<template>
	<view class="page">
		<!-- 	<u-navbar  :border-bottom="false" :background="bgc" title-color='#fff' back-icon-color="#fff"
			title-size='36' height='50'></u-navbar> -->
		<view class="title">
			<image src="https://api.ccttiot.com/smartmeter/img/static/uyr6T0Vfkefty2blkDmU" mode="" style="width: 52rpx;height: 52rpx;margin-right: 10rpx;vertical-align: bottom;vertical-align: bottom;" @click="btnshouye"></image>
		    <text style="width: 80%;text-align: center;display: inline-block;">{{deviceobj.deviceName == undefined ? '--' : deviceobj.deviceName}}</text>
			<view class="wz">
				<!-- 该设备还剩余时长：{{expireTimeStr}}分钟 -->
			</view>
			<view class="wz" @click="call" style="text-align: right;padding-right: 20rpx;" v-if="deviceobj.storeContactMobile == null">
				联系客服
				<!-- ：<text >{{deviceobj.userMobile == undefined ? '--' : deviceobj.userMobile}}</text> -->
			</view>
			<view class="wz" @click="call" style="text-align: right;padding-right: 20rpx;" v-else>
				联系客服
				<!-- ：<text >{{deviceobj.storeContactMobile == undefined ? '--' : deviceobj.storeContactMobile}}</text> -->
			</view>
		</view>

		<!-- 检测蓝牙未开启 -->
		<view class="shibai" v-if="lanyaflag">
			<view class="top">
				设备离线
			</view>
			<view class="tishi">
				检测到该设备离线,请打开蓝牙进行蓝牙模式
			</view>
			<view class="li">
				<view class="wz">
					第一：检查手机蓝牙是否打开
				</view>
				<image style="width: 386rpx;height: 263rpx;"
					src="https://api.ccttiot.com/smartmeter/img/static/uM4DY4Ee9AgFHLv4bIDR" mode=""></image>
			</view>
			<view class="li">
				<view class="wz">
					第二：设置小程序蓝牙授权
				</view>
				<image style="width: 368rpx;height: 151rpx;"
					src="https://api.ccttiot.com/smartmeter/img/static/uAj06uo9qysixLrcFHBn" mode=""></image>
				<image style="width: 386rpx;height: 301rpx;"
					src="https://api.ccttiot.com/smartmeter/img/static/ugFSKFZn4mzJJHQx3K2Z" mode=""></image>
				<image style="width: 386rpx;height: 330rpx;"
					src="https://api.ccttiot.com/smartmeter/img/static/uZ4XoCI2KNQzcPKbwGLN" mode=""></image>
			</view>
			<view class="jxcz" @click="btnjxcz">
				我已知晓
			</view>
		</view> 

		<view class="box" v-else>
			<view class="tit">
				选择服务
			</view>
			<view>
				<view :class="indexactive == item.suitId ? 'active':''"
					style="width:100%;height:100%;background: #fff;box-shadow: 0rpx 16rpx 40rpx 0rpx rgba(42,130,228,0.1);border-radius: 30rpx;padding: 20rpx 34rpx;box-sizing: border-box;margin-top: 20rpx;border: 4rpx solid #fff;"
					v-for="(item,index) in deviceobj.suitList" :key="index" @click="btnactive(item)">
					<view class="lt">
						<view class="tc" style="font-weight: 600;font-size: 34rpx;">
							{{item.name}}
						</view>
						<!-- <view class="date">
							{{item.value}} <text v-if="item.timeUnit == 1">日</text>  <text v-if="item.timeUnit == 2">时</text> <text v-if="item.timeUnit == 3">分钟</text> <text v-if="item.timeUnit == 4">秒</text>
						</view> -->
					</view>
					<view class="rt" style="margin-top: 10rpx;font-size: 28rpx;">
						<text v-if="item.feeType == 1">计时收费</text>
						<text v-if="item.feeType == 2">按量收费</text>
						<text v-if="item.feeType == 3">分时段按量收费</text>
						<text v-if="item.feeType == 4">分时段按时收费</text>
						（{{item.feeMode == 1 ? '单次收费' : '智能收费'}}）：
						<text v-if="item.feeType == 1">{{item.value}}<text v-if="item.timeUnit == 2">时</text> <text v-if="item.timeUnit == 3">分钟</text> <text v-if="item.timeUnit == 4">秒</text> {{item.price}}元</text>
						<text v-if="item.feeType == 2">{{item.value}}度{{item.price}}元</text>
						<!-- <text  v-if="item.feeType == 3 || item.feeType == 4">押金{{item.deposit}}元</text> -->
						<text  v-if="item.feeMode == 2">押金{{item.deposit}}元</text>
						
					</view>
					<view class="" style="margin-top: 10rpx;color: #8883F0;font-size: 28rpx;" v-if="item.feeMode == 2">
						完成订单后押金将自动退还
					</view>
					<view class="" style="width: 100%" v-if="item.feeType == 3 || item.feeType == 4">
						<u-collapse>
								<u-collapse-item title="收费详情">
									<view class="" style="margin-bottom: 6rpx;font-size: 24rpx;">
										收费时间段(滑动查看各时段费用)
									</view>
									<view class="ulbox">
										<view class="ulli">
											<view class="li" v-for="(val,gearAmountindex) in item.arr" :key="gearAmountindex">
												{{val}}元
											</view>
										</view>
										<view class="olli">
											<view class="li" v-for="(vals,timeindex) in 24" :key="timeindex">
												{{timeindex + ':00'}}
											</view> 
										</view>
									</view>
								</u-collapse-item>
							</u-collapse>
					</view> 
					<view class="" style="margin-top: 10rpx;">
						套餐说明：{{item.description == null ? '无' : item.description}}
					</view>
					
				</view>
				<view v-if="deviceobj.suitList == null || deviceobj.suitList.length == 0" class="" style="color: #ccc;font-size: 36rpx;">
					该设备暂无套餐...
				</view>
			</view>

			<view class="tongyi" v-if="deviceobj.suitList != null">
				<u-checkbox-group>
					<u-checkbox v-model="checked" @change="checkboxChange" active-color="#8883F0 ">我已同意
					</u-checkbox><text @click="btnyonghu">《用户服务协议》</text> <text @click="btnyinsi">《隐私政策》</text>
				</u-checkbox-group>
				<!-- <view class="zf" v-else>
					立即支付
				</view> -->
				<!-- 获取手机号 -->
				<button class="zf" v-if="telslag" open-type="getPhoneNumber" @getphonenumber="getPhoneNumber">
					立即支付
				</button>
				<view class="zf" @click="btnzhifu" v-else>
					立即支付
				</view>
			</view>
			<view class="mask" v-if="zhifuflag"></view>
			<view class="mask" v-if="czflag"></view>
            
			<view class="czdh"  v-if="jzflag">
                <view class="bj">
                	<view class="tittop">
                		正在充值中,请稍后
                	</view>
                	<view class="bfb">
                		{{progress}} %
                	</view>
                </view>
			</view>

		</view>
		
		<!-- 防诈骗提示 -->
		<view class="fangswindle" v-if="swindleflag">
			<image src="https://api.ccttiot.com/smartmeter/img/static/uvJcZhPixU1trBud6xTa" mode=""></image>
			<view class="zhixiao" @click="btnswindleflag">
				我已知晓
			</view>
		</view>
		<view v-if="swindleflag" class="" style="width: 100%;height: 100vh;position: fixed;top: 0;left: 0;background-color: #000;opacity: .5;z-index: 98;"></view>
		
		
		
	</view>
</template>

<script>
	var xBlufi = require("@/page_components/blufi/xBlufi.js"); 
	export default {
		data() {
			return {
				flags:false,
				jzflag:false,
				progress: 0,
				isLoading: false,
				zhifuflag:false,
				indexactive: -1,
				checked: false,
				lanyaflag: false,
				deviceobj: {},
				timer: null,
				expireTimeStr: '',
				zfobj: {},
				orderno: '',
				id: '',
				czflag: false,
				sytime: 0,
				datetime: 0,
				mac: '',
				deviceId: '',
				name: '',
				ver_data: '',
				devicesList: [],
				onlineStatus: '',
				jine: '',
				dingobj: {},
				suitTimeUnit:'',
				zfflag:true,
				prices:'',
				sceneValue:'',
				suitFeeMode:'',
				suitFeeType:'',
				suitGearAmount:[],
				suitGearTime:[],
				suitPrice:'',
				payNo:'',
				q:'',
				channelId:'',
				swindleflag:true,
				phonenumber:'',
				mchShowBillMobile:'',
				telslag:false,
				userId:''
			}
		},
		onLoad(option) {
			if (option.q) {
				function getQueryParam(url, paramName) {
					let regex = new RegExp(`[?&]${paramName}=([^&]*)`);
					let results = regex.exec(url);
					return results ? decodeURIComponent(results[1].replace(/\+/g, ' ')) : null
				}
				this.sceneValue = option.q
				let decodedValue = decodeURIComponent(this.sceneValue);
				this.id = getQueryParam(decodedValue, 's')
			} else {
				this.id = option.id
			}
		},
		computed: {

		},
		// 分享到好友（会话）
		  onShareAppMessage: function () {  
		    return {  
		      title: '创想物联',  
		      path: '/pages/shouye/index'  
		    }  
		  },  
		  
		  // 分享到朋友圈  
		  onShareTimeline: function () {  
		    return {  
		      title: '创想物联',  
		      query: '',  
		      path: '/pages/shouye/index'  
		    }  
		  },
		onShow() {
			// this.getuserinfo()
			this.getzfqd()
			setTimeout(()=>{
				if (this.id != '') {
					this.$u.get("/app/user/userInfo").then((res) => {
						if (res.code == 200) {
							this.phonenumber = res.data.phonenumber
							this.userId = res.data.userId
					        this.getone()
						} else {
							uni.navigateTo({
								url: '/pages/login/login?id=' + 1
							})
						} 
					})
				}
			},1)
		},
		onUnload: function() {
			if (this.timer) {
				clearInterval(this.timer)
				this.timer = null;
			}
			// xBlufi.listenDeviceMsgEvent(false, this.funListenDeviceMsgEvent);
			// wx.closeBLEConnection({
			//   deviceId: this.deviceId,
			// })
		},
		onHide() {
			xBlufi.listenDeviceMsgEvent(false, this.funListenDeviceMsgEvent);
			xBlufi.notifyStartDiscoverBle({
				'isStart': false
			});
		},
		onBeforeUnmount() {
			xBlufi.listenDeviceMsgEvent(false, this.funListenDeviceMsgEvent);
			xBlufi.notifyStartDiscoverBle({
				'isStart': false
			})
		},
		methods: {
			// 点击我已知晓
			btnswindleflag(){
				this.swindleflag = false
				if(this.userId == this.deviceobj.userId && this.deviceobj.suitList == null || this.deviceobj.suitList.length == 0){
					uni.showModal({
						title: '提示',
						content: '该设备暂无套餐,是否前去配置？',
						success: function(res) {
							if (res.confirm) {
								uni.navigateTo({
									url: '/page_components/newtaocan'
								})
							} else if (res.cancel) {
					
							}
						}
					})
				}
			},
			
			getzfqd(){
				this.$u.get(`/app/channel/recharge/enabledList`).then(res =>{
					if(res.code == 200){
						this.channelId = res.data[0].channelId
						uni.hideLoading()
					}else{
						uni.hideLoading()
						uni.showToast({
							title:res.msg,
							icon: 'none',
							duration:2000
						})
					}
				})
			},
			
			getone(){
				let that = this
				let data = {
					deviceNo: that.id
				}
				that.$u.get(`/app/device/isBind?deviceNo=${that.id}`).then(res => {
					if (res.data == 2) {
						that.$u.get(`/app/device/${that.id}/withSuitList`).then((res) => {
							if (res.code == 200) {
								that.$u.get(`/app/device/${that.id}/bySn`).then((res) => {
									if (res.code == 200) {
										that.mac = 'CTKG-' + res.data.mac
										that.onlineStatus = res.data.onlineStatus
									}
								})
							} 
						})
					} else if (res.data == 1) {
						uni.navigateTo({
							url:'/pages/shouye/index?id=' + this.id
						})
					} else if (res.data == 0) {
						uni.navigateTo({
							url:'/pages/shouye/index?id=' + this.id
						})
					}
				})
				this.gettaoc()
			},
			
			
			
			btnshouye(){
				uni.reLaunch({
					url:'/pages/shouye/index'
				})
			},
			btnjxcz() {
				this.czflag = false
				xBlufi.initXBlufi(1)
				xBlufi.listenDeviceMsgEvent(true, this.funListenDeviceMsgEvent);
				xBlufi.notifyStartDiscoverBle({
					'isStart': true
				})
				setTimeout(() => {
					xBlufi.notifyStartDiscoverBle({
						'isStart': false
					})
					if (this.devicesList.length > 0) {
						xBlufi.notifyConnectBle({
							isStart: true,
							deviceId: this.deviceId,
							name: this.name
						})
					}
				}, 2000)
			},

			call() {
				let phoneNumber = ''
				if (this.deviceobj.storeContactMobile == null) {
					phoneNumber = this.deviceobj.userMobile
				} else {
					phoneNumber = this.deviceobj.storeContactMobile
				}
				uni.makePhoneCall({
					phoneNumber: phoneNumber,
					success: function(res) {
						console.log('拨打电话成功', res)
					},
					fail: function(err) {
						console.error('拨打电话失败', err)
						uni.showToast({
							title: '拨打电话失败',
							icon: 'none'
						})
					}
				})
			},
			
			//
			btnyinsi(){
				uni.navigateTo({
					url: '/page_fenbao/statulist/about/index?tit=' + '隐私政策'
				})
			},
			btnyonghu(){
				uni.navigateTo({
					url: '/page_fenbao/statulist/about/index?tit=' + '用户服务协议'
				})
			},

			gettrue() {
				this.$u.get("/app/device/isBind?deviceNo=" + this.id).then((res) => {
					if (res.data == 0 || res.data == 1) {
						uni.navigateTo({
							url: '/pages/shouye/index?flag=' + true + '&id=' + this.id
						})
					}
				})
			},
			getuserinfo() {
				this.$u.get("/app/user/userInfo").then((res) => {
					if (res.code == 200) {
						// this.gettrue()
					} else {
						uni.navigateTo({
							url: '/pages/login/login?id=' + 1
						})
					}
				})
			},
			getmac() {
				this.$u.get(`/app/device/${this.id}/bySn`).then((res) => {
					if (res.code == 200) {
						// this.mac = 'CTKG-' + res.data.mac
						this.mac = res.data.mac
						this.onlineStatus = res.data.onlineStatus
					}
				})
			},
			gettaoc() {
				this.$u.get(`/app/device/${this.id}/withSuitList`).then((res) => {
					if (res.code == 200) {
						this.deviceobj = res.data
						this.zfobj = res.data.suitList[0]
						let targetDateStr = this.deviceobj.expireTime
						this.mchShowBillMobile = res.data.mchShowBillMobile
						if(this.mchShowBillMobile == true && this.phonenumber == ''){
							this.telslag = true
						}else{
							this.telslag = false
						}
						if(targetDateStr != null){
							let targetParts = targetDateStr.split(/[- :]/)
							let targetDate = new Date(targetParts[0], targetParts[1] - 1, targetParts[2], targetParts[3], targetParts[4], targetParts[5])
							let now = new Date()
							let differenceInMs = targetDate - now
							if (differenceInMs <= 0) {
								this.expireTimeStr = '0'
							} else {
								this.expireTimeStr = '1'
							}
						}
						if(res.data.suitList){
							this.mapGearTimeToGearAmount(res.data.suitList)
						}
						// console.log(res.data.suitList,'1212');
					}
				})
			},
			mapGearTimeToGearAmount(suitList) {
			  // 遍历 suitList 数组
			  suitList.forEach(suit => {
			    const gearTime = suit.gearTime
			    const gearAmount = suit.gearAmount
			    const arr = new Array(gearTime.length).fill(null)
			    gearTime.forEach((time, index) => {
			      if (time >= 0 && time < gearAmount.length) {
			        arr[index] = gearAmount[time]
			      }
			    })
			    suit.arr = arr
			  })
			},
			btnzhifu() {
				if (this.checked == false) {
					uni.showToast({
						title: '请勾选用户服务协议 !',
						icon: 'none',
						duration: 1000
					})
				} else if (this.indexactive == -1) {
					uni.showToast({
						title: '请选择套餐 !',
						icon: 'none',
						duration: 1000
					})
				}else if(this.mchShowBillMobile == true && this.phonenumber == ''){
					this.getPhoneNumber()
				}else {
					this.zhifuflag = true
					this.getzhifu()
				}
			},
			// 获取手机号
			getPhoneNumber(e){
				this.$u.put(`/app/user/bindWxMobile?mobileCode=${e.detail.code}`).then(res =>{
					if(res.code == 200){
						this.zhifuflag = true
						this.getzhifu()
					}else{
						uni.showToast({
							title: res.msg,
							icon: 'none',
							duration: 1000
						})
					}
				})
			},
			// 支付
			getzhifu(){
				if (this.onlineStatus == 1) {
					uni.showLoading({
						title: '准备支付中...'
					})
					this.getzfqd()
					let that = this
					let data = {
						deviceNo: that.id,
						suitId: that.zfobj.suitId,
						money: that.zfobj.price,
						suitDeposit:that.zfobj.deposit,
						suitTime: that.zfobj.value,
						suitTimeUnit:that.suitTimeUnit,
						suitFeeMode:that.suitFeeMode,
						suitFeeType:that.suitFeeType,
						suitGearAmount:that.suitGearAmount,
						suitGearTime:that.suitGearTime,
						suitPrice:that.suitPrice
					}
					that.$u.post('/app/bill/recharge', data).then((res) => {
						if (res.code == 200) {
							that.orderno = res.data
							// console.log(this.prices);
							// if(this.prices == 0){
								// 0元购
							// 	that.$u.put(`/app/bill/${that.orderno}/refreshPayResult`).then(res => {})
							// 	// 支付成功逻辑
							// 	uni.reLaunch({
							// 		url: '/pages/shouye/index'
							// 	})
							// 	uni.setStorageSync('time', that.expireTimeStr)
							// }
							if(this.suitFeeType == 3 || this.suitFeeType == 4){
								let data = {
									billNo:that.orderno,
									channelId:that.channelId
								}
								that.$u.put(`/app/bill/payDeposit`,data).then(res => {
									if(res.code == 200){
										that.payNo = res.data.payBill.payNo
										uni.requestPayment({
											provider: 'wxpay',
											timeStamp: res.data.payParams.timeStamp,
											nonceStr: res.data.payParams.nonceStr,
											package: res.data.payParams.packageVal,
											signType: res.data.payParams.signType,
											paySign: res.data.payParams.paySign,
											success: (res) => {
												this.zhifuflag = false
												// console.log(res, '支付成功')
												if (that.timer) {
													clearInterval(this.timer)
													that.timer = null;
												}
												that.$u.put(`/app/bill/${that.payNo}/refreshPayResult`).then(res => {})
												// 支付成功逻辑
												uni.reLaunch({
													// url: '/pages/shouye/index'
													url:'/page_components/eletj?id=' + that.orderno
												})
												uni.setStorageSync('time', that.expireTimeStr)
											},
											fail(err) {
												that.zhifuflag = false
												// 支付失败逻辑
												uni.showToast({
													title: '支付失败',
													icon: 'none',
													duration: 2000
												})
											}
										})
									}else{
										that.zhifuflag = false
										uni.showToast({
											title: res.msg,
											icon: 'none',
											duration: 2000
										})
									}
								})
							}else{
								let data = {
									billNo:that.orderno,
									channelId:that.channelId
								}
								that.$u.put(`/app/bill/pay`,data).then((res) => {
									if (res.code == 200) {
											uni.requestPayment({
												provider: 'wxpay',
												timeStamp: res.data.payParams.timeStamp,
												nonceStr: res.data.payParams.nonceStr,
												package: res.data.payParams.packageVal,
												signType: res.data.payParams.signType,
												paySign: res.data.payParams.paySign,
												success: (res) => {
													this.zhifuflag = false
													// console.log(res, '支付成功')
													if (that.timer) {
														clearInterval(this.timer)
														that.timer = null;
													}
													that.$u.put(`/app/bill/${that.orderno}/refreshPayResult`).then(res => {})
													// 支付成功逻辑
													uni.reLaunch({
														url:'/page_components/eletj?id=' + that.orderno
													})
													uni.setStorageSync('time', that.expireTimeStr)
												},
												fail(err) {
													that.zhifuflag = false
													// 支付失败逻辑
													uni.showToast({
														title: '支付失败',
														icon: 'none',
														duration: 2000
													})
												}
											})
									}else{
										that.zhifuflag = false
										uni.showToast({
											title: res.msg,
											icon: 'none',
											duration: 2000
										})
									}
								})
							}
						} else if (res.code == 401) {
							uni.reLaunch({
								url: '/pages/login/login'
							})
							that.zhifuflag = false
						}else if(res.code == 500){
							uni.showToast({
								title:res.msg,
								icon: 'none',
								duration: 2000
							})
						}
					})
				} else {
					if (this.ver_data == '') {
						this.czflag = true	
						uni.showLoading({
							title: '蓝牙连接中'
						})
						let that = this
						xBlufi.initXBlufi(1);
						xBlufi.listenDeviceMsgEvent(true, that.funListenDeviceMsgEvent);
						xBlufi.notifyStartDiscoverBle({
							'isStart': true
						})
						setTimeout(() => {
							xBlufi.notifyStartDiscoverBle({
								'isStart': false
							})
							if (that.devicesList.length > 0) {
								xBlufi.notifyConnectBle({
									isStart: true,
									deviceId: that.deviceId,
									name: that.name
								})
							}
						}, 2000)
						uni.showModal({
							title: '温馨提示',
							content: `检测到该设备未联网,为您切换为蓝牙模式,支付的时候靠近该设备,并打开蓝牙`,
							showCancel: false,
						})
						setTimeout(()=>{
							if(this.ver_data == ''){
								uni.showToast({
									title: '未连接成功，如多次失败请点击右上角联系客服咨询',
									icon: 'none',
									duration: 5000
								})
								this.czflag = false
								this.zhifuflag = false
								setTimeout(()=>{
									uni.hideLoading()
								},5000)
							}
						},10000)
					} else {
						uni.showLoading({
							title: '准备支付中...'
						})
						this.getzfqd()
						this.zhifuflag = true
						let that = this
						let data = {
							deviceNo: that.id,
							suitId: that.zfobj.suitId,
							money: that.zfobj.price,
							suitDeposit:that.zfobj.deposit,
							suitTime: that.zfobj.value,
							suitTimeUnit:that.suitTimeUnit,
							suitFeeMode:that.suitFeeMode,
							suitFeeType:that.suitFeeType,
							suitGearAmount:that.suitGearAmount,
							suitGearTime:that.suitGearTime,
							suitPrice:that.suitPrice
						}
						that.$u.post('/app/bill/recharge', data).then((res) => {
							if (res.code == 200) {
								that.orderno = res.data
								if(this.suitFeeType == 3 || this.suitFeeType == 4){
									let data = {
										billNo:that.orderno,
										channelId:that.channelId
									}
									that.$u.put(`/app/bill/payDeposit`,data).then((res) => {
										if (res.code == 200) {
											    that.payNo = res.data.payBill.payNo
												uni.requestPayment({
													provider: 'wxpay',
													timeStamp: res.data.payParams.timeStamp,
													nonceStr: res.data.payParams.nonceStr,
													package: res.data.payParams.packageVal,
													signType: res.data.payParams.signType,
													paySign: res.data.payParams.paySign,
													success: (res) => {
														// console.log(res, '支付成功');
														if (that.timer) {
															clearInterval(this.timer);
															that.timer = null;
														}
														// 111111111111111111111111 
														that.$u.put(`/app/payBill/${that.payNo}/refreshPayResult`).then(res =>{
															// if(res.code == 200){
																that.$u.get(`/app/bill/byNo/${that.orderno}`).then(res => {
																		if (res.code == 200) {
																			if(res.data.status == 9){
																				uni.getNetworkType({
																					success(res) {
																						if (res.networkType !== 'none') {
																							uni.getConnectedBluetoothDevices({
																								success(res) { 
																									that.jzflag = true
																									that.startLoading()
																									setTimeout(()=> {
																										xBlufi.notifySendCustomData({
																												customData: 'open'
																											})
																											xBlufi.notifySendCustomData({
																													customData: '11open'
																												})
																											setTimeout(() => {
																												that.zhifuflag = false
																												uni.reLaunch({
																													// url: '/pages/shouye/index'
																													url:'/page_components/eletj?id=' + that.orderno
																												})
																											},1000)
																									},1500)
																								},
																								fail(err) {
																									console.error('获取已连接蓝牙设备信息失败：',err)
																								}
																							})
																						} else {
																							console.log('手机未连接网络')
																							// this.baiflag = false
																						}
																					}
																				})
																			}else{
																				uni.showToast({
																					title: '支付失败',
																					icon: 'none',
																					duration: 2000
																				});
																			}
																		}else{
																			uni.showToast({
																				title: res.msg,
																				icon: 'none',
																				duration: 2000
																			})
																		}
																	})
															// }
														})
														// 支付成功逻辑
														uni.setStorageSync('time', that.expireTimeStr)
													},
													fail(err) {
														this.zhifuflag = false
														setTimeout(() => {
															this.czflag = false
															uni.hideLoading()
														}, 500)
														// 支付失败逻辑
														uni.showToast({
															title: '支付失败',
															icon: 'none',
															duration: 2000
														});
													}
												})
										}else{
											this.zhifuflag = false
										}
									})
								}else{
								let data = {
									billNo:that.orderno,
									channelId:that.channelId
								}
								that.$u.put(`/app/bill/pay`,data).then((res) => {
										if (res.code == 200) {
												uni.requestPayment({
													provider: 'wxpay',
													timeStamp: res.data.payParams.timeStamp,
													nonceStr: res.data.payParams.nonceStr,
													package: res.data.payParams.packageVal,
													signType: res.data.payParams.signType,
													paySign: res.data.payParams.paySign,
													success: (res) => {
														// console.log(res, '支付成功');
														if (that.timer) {
															clearInterval(this.timer);
															that.timer = null;
														}
														// 111111111111111111111111 
														that.$u.put(`/app/bill/${that.orderno}/refreshPayResult`).then(res =>{
															// if(res.code == 200 || res.code == 500){
																that.$u.put(`/app/bill/rechargeBillDevice?billNo=${that.orderno}`).then(res=>{
																	that.$u.get('/app/bill/recharge/device/fail/list').then(res => { //充值失败调用
																			if (res.code == 200) {
																				console.log('获取订单状态',res);
																				if(res.data.length > 0 && res.data != null){
																					let dingobj = res.data[0].billNo
																					console.log(dingobj,'订单号');
																					uni.getNetworkType({
																						success(res) {
																							if (res.networkType !== 'none') {
																								uni.getConnectedBluetoothDevices({
																									success(res) {
																										that.jzflag = true
																										that.startLoading()
																										setTimeout(()=> {
																											xBlufi.notifySendCustomData({
																													customData: "time@" + that.jine
																												})
																										},1500)
																									},
																									fail(err) {
																										console.error('获取已连接蓝牙设备信息失败：',err)
																									}
																								})
																								that.$u.get(`/app/bill/recharge/${dingobj}/bluetoothSuccess`).then(res => {
																											if (res.code == 200) {
																												that.zhifuflag = false
																												console.log('蓝牙离线充值成功11')
																												setTimeout(() => {
																													uni.reLaunch({
																														url:'/page_components/eletj?id=' + that.orderno
																													})
																												},1000)
																											}else{
																												uni.showToast({
																													title: res.msg,
																													icon: 'none',
																													duration: 2000
																												})
																											}
																										})
																							} else {
																								console.log('手机未连接网络')
																								// this.baiflag = false
																							}
																						}
																					})
																				}else{
																					setTimeout(() => {
																						uni.reLaunch({
																							url:'/pages/shouye/index'
																						})
																					},1000)
																				}
																			}
																		})
																})
															// }
														})
														// 支付成功逻辑
														uni.setStorageSync('time', that.expireTimeStr)
													},
													fail(err) {
														this.zhifuflag = false
														setTimeout(() => {
															this.czflag = false
															uni.hideLoading()
														}, 500)
														// 支付失败逻辑
														uni.showToast({
															title: '支付失败',
															icon: 'none',
															duration: 2000
														});
													}
												})
										}else{
											this.zhifuflag = false
											uni.showToast({
												title: res.msg,
												icon: 'none',
												duration: 2000
											})
										}
									})
								}
							} else if (res.code == 500) {
								uni.showToast({
									title: res.msg,
									icon: 'none',
									duration: 2000
								});
							} else {
								this.czflag = false
							}
						})
					}
				}
			},
			
			 startLoading() {
			    this.isLoading = true;
			    const intervalId = setInterval(() => {
			      this.progress += 100 / 100; // 每次增加 1
			      if (this.progress >= 99) {
			        clearInterval(intervalId);
			        this.isLoading = false;
			        this.progress = 98; // 确保进度条最终达到98
			      }
			    }, 15);
			 },
            //选择套餐
			btnactive(item) {
				// this.zhifuflag = true
				this.prices = item.price
				this.sytime = item.value
				this.zfobj = item
				this.indexactive = item.suitId
				this.suitTimeUnit = item.timeUnit
				this.suitPrice = item.price
				this.suitGearAmount = item.gearAmount
				this.suitGearTime = item.gearTime
				this.suitFeeMode = item.feeMode
				this.suitFeeType = item.feeType
				if(item.timeUnit == 1){
					this.jine = item.value  * 24 * 60 * 60
				}else if(item.timeUnit == 2){
					this.jine = item.value * 60 * 60
				}else if(item.timeUnit == 3){
					this.jine = item.value * 60
				}else if(item.timeUnit == 4){
					this.jine = item.value
				}
				console.log(this.jine);
			},
			checkboxChange(e) {
				this.checked = e.value
			},

            // 获取附近蓝牙设备列表
			funListenDeviceMsgEvent: function(options) {
				switch (options.type) { 
					case xBlufi.XBLUFI_TYPE.TYPE_GET_DEVICE_LISTS:
						if (options.result) {
							let devicesarr = options.data
							console.log(devicesarr,this.mac,'111');
							devicesarr.forEach(device => {
								const mac = device.name.substring(4);
								if (device.name.slice(5, 17) == this.mac.slice(5, 17)) {
									this.deviceId = device.deviceId
									this.name = device.name
									// console.log(device.name,this.mac,'222');
									this.devicesList.push(device);
									let uniqueDevicesList = Array.from(new Set(this.devicesList));
									// 将去重后的数组重新赋值给 this.devicesList
									this.devicesList = uniqueDevicesList;
								} else {
									// uni.showToast({
									// 	title: '未找到该设备，请确认该设备在附近',
									// 	icon: 'none',
									// 	duration: 3000
									// })
								}
							})
						}
						break;
					case xBlufi.XBLUFI_TYPE.TYPE_CONNECTED:
						console.log("连接回调：" + JSON.stringify(options));
						if (options.result) {
							// console.log('125451245')  
							{
								xBlufi.notifyInitBleEsp32({
									deviceId: this.deviceId
								});
								// xBlufi.listenDeviceMsgEvent(true, this.funListenDeviceMsgEvents);
								this.deviceIds = options.data.deviceId
								this.name = this.name
							}
						}else{
							
						}

						break;
					case xBlufi.XBLUFI_TYPE.TYPE_RECIEVE_CUSTON_DATA:
						this.ver_data = this.parseCustomData(options.data)
						console.log("1收到设备发来的自定义数据结果：", this.ver_data);
						setTimeout(()=>{
							this.czflag = false
							this.zhifuflag = false
							uni.hideLoading()
							// uni.showToast({
							// 	title: '切换成功，请点击支付',
							// 	icon: 'none',
							// 	duration: 2000
							// })
						},1000)
						break;
					case xBlufi.XBLUFI_TYPE.TYPE_GET_DEVICE_LISTS_STOP:
						if (options.result) {
							let uniqueDevicesList = Array.from(new Set(this.devicesList));
							let filteredDevices = uniqueDevicesList.filter(device => device.name.substring(0, 4) === "CTKG");
							// 将过滤后的数组重新赋值给 this.devicesList
							this.devicesList = filteredDevices;
						}
						break;
					case xBlufi.XBLUFI_TYPE.TYPE_GET_DEVICE_LISTS_START:
						if (!options.result) {
							this.lanyaflag = true
							uni.showToast({
								title: '蓝牙未开启',
								icon: 'none',
								duration: 3000
							});
							return
						} else {
							this.lanyaflag = false
						}
						break;
				}
			},
            // 从蓝牙拿到数据进行解析
			parseCustomData(data) {
				// 将字符串按照 "@" 分割成数组
				const dataArray = data.split('@');
				const voltage = parseFloat(dataArray[0].substring(1)); // 去除前缀 "V"，并将字符串转换为浮点数
				const switchState = dataArray[1].substring(1); // 去除前缀 "S"
				const current = parseFloat(dataArray[2].substring(1)); // 去除前缀 "A"，并将字符串转换为浮点数
				const power = parseFloat(dataArray[4].substring(1)); // 去除前缀 "P"，并将字符串转换为浮点数
				const remainingPower = parseFloat(dataArray[5].substring(1)); // 去除前缀 "M"，并将字符串转换为浮点数
				const setMode = dataArray[6].substring(1); // 去除前缀 "T"
				// 返回解析后的数据对象
				return {
					voltage,
					switchState,
					current,
					power,
					remainingPower,
					setMode
				};
			},

		}
	}
</script>

<style lang="scss">
	.fangswindle{
		position: fixed;
		top: 500rpx;
		left: 50%;
		transform: translateX(-50%);
		z-index: 99;
		image{
			width: 584rpx;
			height: 456rpx;
		}
		.zhixiao{
			width: 530rpx;
			height: 76rpx;
			background: #8883F0;
			border-radius: 47rpx 47rpx 47rpx 47rpx;
			text-align: center;
			line-height: 76rpx;
			font-size: 32rpx;
			color: #FFFFFF;
			position: fixed;
			top: 340rpx;
			left: 50%;
			transform: translateX(-50%);
			z-index: 99;
		}
	}
	.czdh{
		width: 100%;
		height: 100vh;
		position: fixed;
		top: 0;
		left: 0;
		background-color: rgba(0, 0, 0, .5);
		padding-top: 700rpx;
		.bj{
			width: 500rpx;
			height: 300rpx;
			background-color: #fff;
			margin: auto;
			border-radius: 20rpx;
			.tittop{
				width: 100%;
				text-align: center;
				padding-top: 50rpx;
				box-sizing: border-box;
			}
			.bfb{
				width: 100%;
				text-align: center;
				padding-top: 50rpx;
				box-sizing: border-box;
				font-size: 50rpx;
			}
		}
	}
	.u-icon__icon{
		// margin-right: 20rpx;
	}
	.mask {
		width: 100%;
		height: 100vh;
		position: fixed;
		top: 0;
		left: 50%;
		transform: translateX(-50%);
		background-color: #000;
		opacity: .6;
	}
    .ulbox{
		width: 100%;
		overflow: scroll;
		.ulli{
			display: flex;
			width: 170vh;
			.li{
				flex: 1;
				border: 1rpx solid #ccc;
				text-align: center;
				font-size: 32rpx;
				color: #8883F0;
				height: 88rpx;
				line-height: 88rpx;
			}
		}
		.olli{
			display: flex;
			width: 170vh;
			.li{
				flex: 1;
				border: 1rpx solid #ccc;
				text-align: center;
				font-size: 22rpx;
				color: #262B37;
				height: 88rpx;
				line-height: 88rpx;
			}
		}
	}
	.shibai {
		margin-top: 50rpx;
		text-align: center;
		padding-bottom: 600rpx;
		height: 100vh;
		overflow: scroll;

		.jxcz {
			width: 563rpx;
			height: 100rpx;
			background: #8883F0;
			border-radius: 60rpx 60rpx 60rpx 60rpx;
			text-align: center;
			line-height: 100rpx;
			font-size: 45rpx;
			color: #FFFFFF;
			position: fixed;
			bottom: 62rpx;
			left: 50%;
			transform: translateX(-50%);
		}

		.top {
			font-size: 40rpx;
			color: #3D3D3D;
		}

		.tishi {
			font-size: 31rpx;
			color: #3D3D3D;
			margin-top: 50rpx;
		}

		.li {
			margin-top: 50rpx;
			font-size: 31rpx;
			color: #3D3D3D;

			image {
				margin-top: 30rpx;
			}
		}
	}

	/deep/ .u-title {
		padding-bottom: 22rpx;
	}

	/deep/ .u-checkbox__label {
		margin-right: 0 !important;
	}

	// /deep/ .u-icon__icon{
	// 	padding-bottom: 41rpx;
	// }
	page {
		background: linear-gradient(180deg, #8883F0 0%, rgba(255, 255, 255, 0) 100%);
	}

	.active {
		// background-color: #8883F0 !important;
		// color: #fff !important;
		border: 4rpx solid #8883F0 !important;
		box-sizing: border-box;
	}

	.page {
		width: 750rpx;
		// position: fixed;
		// top: 0;
		// left: 0;
		overflow: hidden;
		height: 100vh;

		.tip_box {
			position: fixed;
			left: 72rpx;
			top: 700rpx;
			width: 610rpx;
			// height: 282rpx;
			background: #F7FAFE;
			border-radius: 30rpx 30rpx 30rpx 30rpx;
			z-index: 10000000;

			.top {
				padding: 52rpx 38rpx 42rpx 36rpx;

				.txt {
					width: 100%;
					text-align: center;
					font-weight: 500;
					font-size: 32rpx;
					color: #3D3D3D;
				}
			}

			.bot {
				border-top: 2rpx solid #D8D8D8;
				display: flex;
				flex-wrap: nowrap;
				height: 100%;

				.bot_left {
					width: 50%;
					height: 98rpx;
					display: flex;
					align-items: center;
					justify-content: center;
					font-weight: 500;
					font-size: 36rpx;
					color: #3D3D3D;
				}

				.bot_right {
					width: 50%;
					height: 98rpx;
					display: flex;
					align-items: center;
					justify-content: center;

					border-left: 2rpx solid #D8D8D8;
					font-weight: 500;
					font-size: 36rpx;
					color: #8883F0;

				}

			}
		}

		.title {
			margin-top: 40rpx;
			padding-left: 32rpx;
			font-weight: 600;
			font-size: 40rpx;
			color: #fff;
			margin-bottom: 30rpx;
			margin-top: 110rpx;
			height: 126rpx;

			.wz {
				font-weight: 400;
				font-size: 32rpx;
				margin-top: 30rpx;
			}
		}

		.box {
			width: 750rpx;
			height: 71vh;
			overflow: scroll;
			background: #F4F5F7;
			border-radius: 0rpx 0rpx 0rpx 0rpx;
			padding: 36rpx 54rpx;
			box-sizing: border-box;
			border-radius: 30rpx 30rpx 0 0;

			.tongyi {
				width: 590rpx;
				position: fixed;
				bottom: 50rpx;
				left: 50%;
				transform: translateX(-50%);

				text {
					color: #638DFF;
					height: 50rpx;
					line-height: 50rpx;
				}

				.zf {
					width: 590rpx;
					height: 84rpx;
					background: #8883F0;
					filter: blur(0px);
					border-radius: 50rpx;
					text-align: center;
					line-height: 84rpx;
					font-size: 36rpx;
					color: #FFFFFF;
					margin-top: 10rpx;
				}
			}

			.shuom {
				width: 648rpx;
				max-height: 100%;
				background: #FFFFFF;
				box-shadow: 0rpx 16rpx 40rpx 0rpx rgba(42, 130, 228, 0.1);
				filter: blur(0px);
				border-radius: 30rpx;
				margin: auto;
				margin-top: 36rpx;
				padding: 20rpx 36rpx;
				box-sizing: border-box;

				.tits {
					font-size: 32rpx;
					font-weight: 600;
					margin-top: 30rpx;
				}


			}

			.wz {
				font-size: 28rpx;
				color: #ccc;
				margin-top: 30rpx;
				font-weight: 400;
			}

			.list_val {
				.tc {
					font-weight: 600;
					font-size: 34rpx;
					color: #525252;
				}

				.date {
					font-size: 26rpx;
					color: #525252;
					margin-top: 10rpx;
				}

				.rt {
					font-size: 40rpx;
					color: #525252;
					padding-top: 20rpx;
				}
			}

			.tit {
				font-size: 40rpx;
				color: #383838;
				font-weight: 600;
				margin-bottom: 32rpx;
			}
		}
	}
</style>