<template>
	<view class="container-view">
		<view @tap="sacnBtn" class="refund-btn"><text>扫码换电</text></view>
		<view v-if="isModelCenter" class="model_center">
			<image class="pack_model" src="https://zxappfile.bms16.com/zx_client/buy_pack_model.png" />
			<view v-if="packType==0" class="pack_model_text">您还未购买换电套餐，需先完成购买后再扫码领取电池</view>
			<view v-if="packType==2" class="pack_model_text">您还未完成押金授权，现在前往押金授权?</view>
			<view v-if="packType==0" class="look_package" @tap="clickLookPackage">查看套餐</view>
			<view v-if="packType==2" class="look_package" @tap="clickMyPackage">去押金认证</view>
			<view class="line_view"></view>
			<image @tap="clickClosePackage" class="close_package"
				src="https://zxappfile.bms16.com/zx_client/close_package.png"></image>
		</view>
	</view>
</template>

<script>
	// var http = require('../../common/http.js');
	var http = require('../../common/request.js');
	// var config = require('../../common/config.js');
	var config = require('../../common/config_gyq.js');
	var common = require('../../common/common.js');
	var storage = require('../../common/storage.js')
	var user = require('../../common/user.js');
	var bluetooth = require('../../common/bluetooth.js');
	// var IndexImpl = require('../../pages/index/model/indexImpl.js');
	const DF_CAB_INFO_DONE = 10000; //机柜信息传输完成
	var subscribeTimer = null;
	var app = getApp();
	export default {
		props: {
			listData:{
				type: null,
				validator: val => typeof val === 'object' || val === null,
				required: true
			},
			cab_info: {
				type: null,
				validator: val => typeof val === 'object' || val === null,
				required: true
			},
			dev_id: {
				type: String,
				required: true
			},
			is_my: {
				type: Boolean,
				required: false
			}
		},
		data() {
			return {
				car_info:{},
				isModelCenter: false,
				packType:0,
				is_battery: false,
				free_price: 0,
				battery_info: {},
				packInfo: {},
				reservation_info: [],
				myPackageInfo: {},
				countdownTimer: {},
				blueInfo: {}, //连接蓝牙需要数据
				isBluetooth: false, //缓存蓝牙连接状态
				cabinetInfo: {}, //机柜信息
				num: 0, //免费换电次数
				payType: 0, //支付方式
				scan_dev_id: '', //扫码机柜编号
				online_status: '', //机柜在线状态
				isOpenBluetooth: false,
				license_plate_number: '',
				isShowToBuy: false,
				isShowAppoint: false,
				wallet_money: 0,
				payResp: {},
				myLocation: {},
				orderInfo: {},
				carInfo: {},
				is_retuen_battery: false, //判断按钮点击还电还是换电操作
				orderStatusTimer: null, //定时查询还电状态
				showScanBtn: false,
			}
		}
		/**
		 * 生命周期函数--监听页面加载
		 */
		,
		watch: {
			cab_info: {
				handler: function(newVal) {
					if (newVal) {
						console.log(newVal, "newVal")
						this.setData({
							reservation_info: JSON.stringify(newVal) == '{}' ? [] : newVal
								.reservation_info
						});
						// this.updateCountdown();
					}
				},
				immediate: true
			}
		},
		mounted: function(options) {
			this.loadMyPackageInfo()
			const car_list = uni.getStorageSync('user_car_list') || null
			const storedLocation = uni.getStorageSync('user_current_location');
			this.car_info =  uni.getStorageSync('car_info') || {};
			if (car_list) {
				// this.license_plate_number = car_list.plate_number
				this.carInfo = car_list
			}
			if (app.globalData.showScanBtn) {
				this.showScanBtn = true
			} else {
				this.showScanBtn = false
			}
			if (storedLocation && storedLocation.longitude && storedLocation.latitude) {
				// 如果本地有存储的定位信息，则直接使用
				this.setData({
					myLocation: storedLocation,
					// license_plate_number: car_list.plate_number
				});
			}
			//#ifdef MP-ALIPAY
			this.payType = 2
			//#endif
			//#ifdef MP-WEIXIN
			this.payType = 0
			//#endif
			bluetooth.initBluetooth()
			this.bluetoothClose()
			this.loadBatteryInfo()
			//this.loadExchangeInfo()
		},
		/**
		 * 生命周期函数--监听页面显示
		 */
		onShow: function() {

		},
		methods: {
			clickLookPackage() {
				wx.switchTab({
					url: '/pages/packageCenter/packageCenter'
				})
			},
			clickMyPackage() {
				wx.navigateTo({
					url: '/pages/my/myPackage/myPackage'
				})
			},
			
			// 更新倒计时
			// updateCountdown() {
			// 	if (this.reservation_info.length > 0) {
			// 		console.log(this.reservation_info[0])
			// 		const remainingTime = common.calculateRemainingTime(this.reservation_info[0]
			// 			.lock_expire_time);
			// 		if (remainingTime >= 0) {
			// 			this.setData({
			// 				countdownTimer: common.formatTimeScan(remainingTime)
			// 			})
			// 		}
			// 		if (remainingTime > 0) {
			// 			subscribeTimer = setTimeout(() => this.updateCountdown(), 1000); // 每秒更新一次
			// 		}
			// 	}
			// },

			loadMyPackageInfo() {
				// IndexImpl.loadMyPackageInfo(
				// 	(resp) => {
				// 		this.setData({
				// 			isShowAppoint: resp.isShowAppoint,
				// 			myPackageInfo: resp.myPackageInfo,
				// 			packInfo: resp.packInfo
				// 		})
				// 		this.$emit(
				// 			'popPackageModel', this.packInfo
				// 		);
				// 	},
				// 	(failMsg) => {
				// 		//common.simpleToast(failMsg)
				// 	}
				// )
			},

			// navToGuild() {
			// 	const url = this.is_battery ? '/pages/my/leadReturnBattery/leadReturnBattery' :
			// 		'/pages/exchangeGuide/exchangeGuide'
			// 	uni.navigateTo({
			// 		url: url
			// 	});
			// },
			isTagCodeFn(){
				let userBattery = []
				let boxBattery = []
				
				let tagCode = []
				for (let index = 0; index < this.listData.user_battery_list.length; index++) {
					let item = this.listData.user_battery_list[index];
					userBattery.push(item.tag_info)
				}
				for (let index = 0; index < this.listData.boxList.length; index++) {
					let item = this.listData.boxList[index];
					if(item.tag_info) boxBattery.push(item.tag_info)
				}
				console.log(userBattery)
				console.log(boxBattery)
				for (let index = 0; index < userBattery.length; index++) {
					let item = userBattery[index];
					for (var i = 0; i < boxBattery.length; i++) {
						var items = boxBattery[i];
						if(item.child_tag_code == items.child_tag_code && item.child_tag_code){
							tagCode.push(item.child_tag_code)
						}else if(item.main_tag_code == items.main_tag_code && item.main_tag_code){
							tagCode.push(item.main_tag_code)
						}
					}
				}
				console.log(tagCode)
				return tagCode
			},
			async sacnBtn() {
				if(this.listData.can_exchange_num == 0){
					this.isModelCenter = true
					this.packType = 2
					return
				}
				if((this.listData.user_battery_list.length - this.listData.can_exchange_num) >= 0 && this.listData.can_exchange_num != -1){
					common.simpleToast('您的次数不足无法换电！')
					return
				}
				if(this.isTagCodeFn().length < 1){
					common.simpleToast('未找到和您匹配的电源！')
					return
				}
				let res = await uni.scanCode({
					onlyFromCamera: true,
					scanType: ['qrCode'],
				});
				var cabinet_dev_id = '';
				if(res[0]) return
				res = res[1]
				this.loadGeneralQRData(res)
				
				if ('path' in res && res.path) {
					if (res.path.split('%26devid%3D').length > 1) {
						cabinet_dev_id = res.path.split('%26devid%3D')[1].split('%26')[0];
					} else if (res.path.split('&devid=').length > 1) {
						cabinet_dev_id = res.path.split('&devid=')[1].split('&')[0];
					}
				}
				if (cabinet_dev_id != '') {
					this.scan_dev_id = cabinet_dev_id
					this.loadNowCabinetDetail(cabinet_dev_id)
				} else {
					//common.simpleToast("未找到相应的机柜")
				}
				
			},
			sacnBtnReturn() {
				const me = this
				uni.showModal({
					cancelText: '取消',
					confirmText: '确定',
					content: '您确定要归还电池吗？',
					showCancel: true,
					title: '提示',
					success: (result) => {
						if (result.confirm) {
							me.is_retuen_battery = true
							uni.scanCode({
								onlyFromCamera: true,
								scanType: [],
								success: function(res) {
									var cabinet_dev_id = '';
									me.loadGeneralQRData(res)
									if ('path' in res && res.path) {
										if (res.path.split('%26devid%3D').length > 1) {
											cabinet_dev_id = res.path.split('%26devid%3D')[1]
												.split('%26')[0];
										} else if (res.path.split('&devid=').length > 1) {
											cabinet_dev_id = res.path.split('&devid=')[1].split(
												'&')[0];
										}
									}

									if (cabinet_dev_id != '') {
										me.scan_dev_id = cabinet_dev_id
										me.loadNowCabinetDetail(cabinet_dev_id)
									} else {
										//common.simpleToast("未找到相应的机柜")
									}
								},
								fail: function(res) {},
								complete: function(res) {}
							});
						}
					},
				})
			},

			loadGeneralQRData(options, stash_sn) {
				let qrCode = getApp().globalData.qrCode;
				var url = ''
				if (qrCode.indexOf("https://zx.uwenya.cc/xcx/s") != -1) {
					getApp().globalData.qrCode = ''
					url = qrCode
				}
				if (('result' in options) && options.result.indexOf("https://zx.uwenya.cc/xcx/s") != -1) {
					url = decodeURIComponent(options.result);
				}
				if (url == '') return
				var obj = this.getUrlParams(url)
				if (('t' in obj) && ('d' in obj)) {
					if (obj.t == 1) {
						this.scan_dev_id = obj.d
						this.loadNowCabinetDetail(obj.d)
						return
					}
				}
			},
			getUrlParams(url) {
				// 通过 ? 分割获取后面的参数字符串
				let urlStr = url.split('?')[1]
				// 创建空对象存储参数
				let obj = {};
				// 再通过 & 将每一个参数单独分割出来
				let paramsArr = urlStr.split('&')
				for (let i = 0, len = paramsArr.length; i < len; i++) {
					// 再通过 = 将每一个参数分割为 key:value 的形式
					let arr = paramsArr[i].split('=')
					obj[arr[0]] = arr[1];
				}
				return obj
			},

			cancelReservation(reservation_order_sn) {
				const pData = {
					order_sn: reservation_order_sn
				}
				http.postApi(config.API_DAYHIRE_RESERVATION_CANCEL, pData, (resp) => {
					if (resp.data.code === 200) {
						common.simpleToast("取消预约成功")
						this.$emit(
							'refreshCabinet'
						);
						// this.loadCabinetDetail()
					} else {
						common.simpleToast(resp.data.msg)
					}
				})
			},

			tapReservation() {
				// 预约换电
				if (this.packInfo.packType === 0||this.packInfo.packType === 2) {
					const notShow = 1
					this.$emit(
						'popPackageModel', this.packInfo,notShow
					);
					return
				}
				if (this.myPackageInfo.effective.list.length === 0) {
					common.simpleToast("暂无可预约的电池")
					return
				}
				const pData = {
					dev_id: this.dev_id,
					battery_sn: this.myPackageInfo.effective.list[0].current_battery_sn
				}
				if (this.packInfo.packType === 0||this.packInfo.packType === 2) {
					const notShow = 1
					this.$emit(
						'popPackageModel', this.packInfo,notShow
					);
				} else{
					http.postApi(config.API_DAYHIRE_CABINET_EXCHANGE_RESERVATION, pData, (resp) => {
						if (resp.data.code === 200) {
							common.simpleToast("预约成功")
							this.$emit(
								'refreshCabinet'
							);
						} else if (resp.data.code === 181102) {
							const me = this
							uni.showModal({
								cancelText: '关闭',
								confirmText: '取消预约',
								content: '您当前已存在预约其它机柜，是否要取消之前的预约操作？',
								showCancel: true,
								title: '提示',
								success: (result) => {
									if (result.confirm) {
										me.cancelReservation(resp.data.data.order_sn)
									}
								},
							})
						} else {
							common.simpleToast(resp.data.msg)
						}
					})
				}
			},

			async loadNowCabinetDetail(dev_id) {
				this.dev_id = dev_id
				let battery_sn_list = this.listData.user_battery_list.map(item=>{
					return item.battery.battery_sn
				})
				let {data} = await http.postApi(config.API_FLK_CABINET_CHANGE_BATTERY,{
					car_sn:this.car_info.car_sn,
					dev_id,
					pay_type:0,
					battery_sn_list,
				})
				if(data.code == 200){
					uni.navigateTo({
						url:`/pages/openCabinet/openCabinet?order_sn=${data.data.order_sn}`
					})
				}else{
					common.simpleToast(data.msg)
				}
				console.log(data)
				
				// await http.postApi(config.API_FLK_CABINET_CHANGE_BATTERY,{
				// 	car_sn:'',
				// 	dev_id:'',
				// 	pay_type:'',
				// 	from:'',
				// 	battery_sn_list:'',
				// })
				// const timeNow = Date.now()
				// this.scan_dev_id = dev_id
				// //扫码机柜信息
				// const me = this
				// const pData = {
				// 	longitude: this.myLocation.longitude,
				// 	latitude: this.myLocation.latitude,
				// 	dev_id: dev_id || '',
				// 	service: "reservation",
				// 	time: timeNow
				// }
				// http.postApi(config.API_DAYHIRE_CABINRT_CABINRT_INFO, pData, (resp) => {
				// 	if (resp.data.code === 200) {
				// 		this.online_status = resp.data.data.cabinetInfo.online_status
				// 		const device = {
				// 			device_type: "LSCabinet",
				// 			bt_type: "",
				// 			mac_id: resp.data.data.cabinetInfo.bt_mac,
				// 			btid: resp.data.data.cabinetInfo.bt_mac,
				// 			dev_id: resp.data.data.cabinetInfo.dev_id,
				// 			key: me.decodeKey(resp.data.data.cabinetInfo.bt_sec),
				// 			btkey: resp.data.data.cabinetInfo.bt_mac,
				// 			bt_sec: me.decodeKey(resp.data.data.cabinetInfo.bt_sec),
				// 			bt_mac: resp.data.data.cabinetInfo.bt_mac
				// 		}
				// 		me.setData({
				// 			blueInfo: device,
				// 			cabinetInfo: resp.data.data.cabinetInfo
				// 		})
				// 		// me.updateCountdown()
				// 		me.bluetoothClose()
				// 		if (me.online_status == 1) {
				// 			if (me.is_retuen_battery) {
				// 				//机柜还电流程
				// 				me.noBluetoothBack()
				// 			} else {
				// 				if (me.packInfo.last_num == 0&&me.packInfo.num != 0) {
				// 					if (me.free_price != 0) {
				// 						me.setData({
				// 							isShowToBuy: true
				// 						})
				// 						me.walletInfo()
				// 					} else{
				// 						const pData = {
				// 							from: from,
				// 							battery_sn: this.is_battery ? this.battery_info.battery_sn : this.packInfo.current_battery_sn,
				// 							dev_id: this.scan_dev_id,
				// 							pay_type: 9
				// 						}
				// 						const me = this
				// 						//#ifdef MP-ALIPAY
				// 						const from = 'ali'
				// 						//#endif
				// 						//#ifdef MP-WEIXIN
				// 						const from = 'wx'
				// 						//#endif
				// 						http.postApi(config.API_CABINET_CHANGE_BATTERY2, pData, (resp) => {
				// 							if (resp.data.code === 200) {
				// 								// 钱包支付不需要支付直接换电 有换电次数可以直接换电
				// 								if (!resp.data.data.need_pay) {
				// 									me.orderInfo = {
				// 										order_sn: resp.data.data.order_sn,
				// 										empty_door_id: resp.data.data.empty_door_id,
				// 										full_door_id: resp.data.data.full_door_id,
				// 										cabbatterysn: resp.data.data.rtn_battery_sn || ''
				// 									};
				// 									me.navOpenCabinet(me.orderInfo)
				// 								} else {
				// 									me.setData({
				// 										isShowToBuy: false
				// 									})
				// 									me.wxPayPrice = resp.data.data.price
				// 									me.payResp = resp
				// 									me.doPayBattery({})
				// 								}
				// 							} else {
				// 								common.simpleToast(resp.data.msg)
				// 							}
				// 						})
				// 					}
				// 				} else {
				// 					me.toPayOrFreeExchange()
				// 				}
				// 			}

				// 		} else {
				// 			me.setData({
				// 				isOpenBluetooth: true
				// 			})
				// 		}

				// 	} else {
				// 		common.simpleToast(resp.data.msg)
				// 	}
				// })
			},
			walletInfo() {
				const me = this
				http.postApi(config.API_DAYHIRE_USER_WALLET_INFO, {}, function(resp) {
					if (resp.data.code === 200) {
						me.wallet_money = (resp.data.data.balance / 100).toFixed(2)
					} else {
						common.simpleToast(resp.data.msg)
					}
				})
			},
			toPayOrFreeExchange() {
				//购买单次换电次数进行换电或者有免费次数直接换电
				const me = this
				//#ifdef MP-ALIPAY
				const from = 'ali'
				//#endif
				//#ifdef MP-WEIXIN
				const from = 'wx'
				//#endif
				const pData = {
					from: from,
					battery_sn: this.is_battery ? this.battery_info.battery_sn : this.packInfo.current_battery_sn,
					dev_id: this.scan_dev_id,
					pay_type: this.payType
				}
				//如果在线用机柜换电 不在线用蓝牙换电
				http.postApi(config.API_CABINET_CHANGE_BATTERY2, pData, (resp) => {
					if (resp.data.code === 200) {
						// 钱包支付不需要支付直接换电 有换电次数可以直接换电
						if (!resp.data.data.need_pay) {
							me.orderInfo = {
								order_sn: resp.data.data.order_sn,
								empty_door_id: resp.data.data.empty_door_id,
								full_door_id: resp.data.data.full_door_id,
								cabbatterysn: resp.data.data.rtn_battery_sn || ''
							};
							me.navOpenCabinet(me.orderInfo)
						} else {
							me.setData({
								isShowToBuy: false
							})
							me.wxPayPrice = resp.data.data.price
							me.payResp = resp
							me.doPayBattery({})
						}

					} else {
						common.simpleToast(resp.data.msg)
					}
				})
			},

			async loadBatteryInfo() {
				console.log("加载电池信息")
				const me = this
				console.log(2222);
				
				let resp = await http.postApi(config.API_CAR_DEVICE_LIST, {})
				if (resp.data.code === 200) {
					console.log(resp.data)
					if (resp.data.data !== null) {
						me.setData({
							battery_info: resp.data.data.list,
							is_battery: true
						})
						// me.$emit(
						// 	'updateBatteryInfo', resp.data.data
						// );
					} else {
						me.setData({
							// battery_info: resp.data.data,
							is_battery: false
						})
					}
				} else {
					common.simpleToast(resp.data.msg)
				}
			},

			doPayBattery: function(pData) {
				const me = this
				//#ifdef MP-WEIXIN
				var payParams = JSON.parse(this.payResp.data.data.payParams);
				var order_sn = this.payResp.data.data.order_sn;
				user.wxPay(order_sn, payParams, function(isSuccess) {
					if (isSuccess) {
						common.simpleToast('支付成功')
						//跳转换电流程页面
						me.orderInfo = {
							order_sn: me.payResp.data.data.order_sn,
							empty_door_id: me.payResp.data.data.empty_door_id,
							full_door_id: me.payResp.data.data.full_door_id,
							cabbatterysn: me.payResp.data.data.rtn_battery_sn || ''
						};
						me.navOpenCabinet(me.orderInfo)
					} else {
						user.cancelCabExPay(order_sn)
						// 取消支付
					}
				});
				//#endif
				//#ifdef MP-ALIPAY
				my.tradePay({
					tradeNO: me.payResp.data.data.trade_no,
					success: function(res) {
						if (res.resultCode == 9000) {
							common.simpleToast('支付成功')
							me.orderInfo = {
								order_sn: me.payResp.data.data.order_sn,
								empty_door_id: me.payResp.data.data.empty_door_id,
								full_door_id: me.payResp.data.data.full_door_id,
								cabbatterysn: me.payResp.data.data.rtn_battery_sn || ''
							};
							me.navOpenCabinet(me.orderInfo)
						} else {
							user.cancelCabExPay(order_sn)
						}
					},
				});
				//#endif
			},
			tapOpenBluetooth(time = null) {
				const me = this
				const device = me.blueInfo
				// 蓝牙换电按钮	加载蓝牙
				console.log(111111111);
				this.loadBluetooth()
			},
			loadBluetooth() {
				const me = this;
				console.log(this.blueInfo,'this.blueInfo');
				const device = this.blueInfo;
				if (bluetooth.acceptDevice(device)) {
					// 打开蓝牙连接
					bluetooth.openBluetoothAdapter((res) => {
						common.loading()
						bluetooth.connectDevice(device, () => {
								bluetooth.onCharacteristicStateChange(device.mac_id, 'index', (data) => {
									if (JSON.stringify(data) != '{}') {
										if (data.state === DF_CAB_INFO_DONE) {
											me.reportCabintInfo(me.cabinetInfo.dev_id, data
												.commandList);
											uni.hideLoading();
											common.simpleToast('蓝牙连接成功')
											me.setData({
												isOpenBluetooth: false,
												isBluetooth: true
											});
											me.bindReturnOrExchange() //还电or换电

										}
									}
								});
								bluetooth.onConnectionStateChange(device.mac_id, 'index', (res) => {
									uni.hideLoading();
									if (!res.connected) {
										// 蓝牙未连接
										// common.simpleToast('蓝牙连接断开',2000)
										me.setData({
											isOpenBluetooth: true,
											isBluetooth: false
										});
									} else {
										common.simpleToast('蓝牙连接成功', 2000)
										// 蓝牙已连接
										me.setData({
											isOpenBluetooth: false,
											isBluetooth: true
										});
										me.bindReturnOrExchange() //还电or换电

									}
								});
								bluetooth.sendGetCabinetInfoCommand(
									device.mac_id,
									device,
									(res) => {
										common.loading();
									},
									(res) => {
										console.log(res,"蓝牙连接1")
										me.setData({
											isOpenBluetooth: false
										});
										
										uni.showModal({
											title: '提示',
											confirmText: '重新连接',
											content: '连接失败，请尝试重新连接',
											success: function(res) {
												if (res.confirm) {
													me.loadBluetooth();
												} else {
													// uni.navigateBack({
													// 	delta: 1
													// });
												}
											}
										});
									}
								);
							},
							(res) => {
								uni.hideLoading();
								var showContent = ""
								var text;
								//#ifdef MP-ALIPAY
								text = '支付宝'
								//#endif
								//#ifdef MP-WEIXIN
								text = '微信'
								//#endif
								if (res && ("errCode" in res)) {
									if (res.errCode == 9000001) {
									   var showContent= "观察周围是否有其他骑手连接，请等待对方完成 或 "+ text +"是否开启了蓝牙权限！！"
									} else {
										console.log(res,"蓝牙连接2")
										var showContent = "连接失败，请尝试重新连接"
									}
								} else {
									console.log(res,"蓝牙连接3")
									var showContent = "连接失败，请尝试重新连接"
								}
								me.setData({
									isOpenBluetooth: false,
									isBluetooth: false
								});
								uni.showModal({
									title: '提示',
									confirmText: '重新连接',
									content: showContent,
									success: function(res) {
										if (res.confirm) {
											me.loadBluetooth();
										} else {
											// uni.navigateBack({
											// 	delta: 1
											// });
										}
									}
								});
							}, (res) => {
								uni.hideLoading();
								me.setData({
									isOpenBluetooth: false
								});
								uni.showModal({
									title: '提示',
									confirmText: '我知道了',
									content: '蓝牙未打开或请在右上角设置授权小程序使用蓝牙',
									success: function(res) {
										if (res.confirm) {
											me.loadBluetooth();
										} else {
											// uni.navigateBack({
											// 	delta: 1
											// });
										}
									}
								});
							}
						);
					}, );
				} else {
					//蓝牙连接未成功
					uni.hideLoading();
					uni.showModal({
						confirmText: '我知道了',
						content: '当前机柜未找到符合的蓝牙类型',
						showCancel: false,
						title: '提示',
						complete: (res) => {
							// uni.navigateBack({
							// 	delta: 1
							// });
						}
					});
				}
			},
			
			reportCabintInfo(dev_id, list) {
				var pushList = []
				for (var i = 0; list.length > i; i++) {
					var sublist = []
					for (var j = 0; list[i].length > j; j++) {
						sublist.push(parseInt(list[i][j]))
					}
					pushList.push(sublist)
				}
				const pData = {
					dev_id: dev_id,
					data: JSON.stringify(pushList)
				}
				const me = this
				http.postApi(config.API_CABINET_BLUETOOTH_INFO, pData, function(response) {
					if (response.data.code === 200) {
						// me.setData({
						//   cabinetInfo: response.data.data.cabinetInfo
						// })
					} else {
						simpleToast(response.data.msg)
					}
				})
			},
			navOpenCabinet(pdata, battery_type) {
				const me = this
				const paramsString = JSON.stringify(pdata)
				const cabinetInfoString = JSON.stringify(me.cabinetInfo)
				// 跳转机柜换电页面-展示换电流程和结果
				uni.navigateTo({
					url: '/pages/openCabinetBind/openCabinetBindSn?pdata=' + encodeURIComponent(paramsString) +
						'&cabinet_info=' + encodeURIComponent(cabinetInfoString) + '&battery_type=' + battery_type,
					success: function(res) {},
					fail: function(res) {},
					complete: function(res) {},
				})
			},
			// loadExchangeInfo() {
			// 	// 查询免费换电次数/换电价格
			// 	const pData = {
			// 		license_plate_number: this.license_plate_number
			// 	}
			// 	http.postApi(config.API_DAYHIRE_CABINRT_BATTERY_EXCHANGE_INFO, pData, (resp) => {
			// 		if (resp.data.code === 200) {
			// 			this.setData({
			// 				num: resp.data.data.last_free_number,
			// 				free_price: (resp.data.data.price / 100).toFixed(2),
			// 			})
			// 		} else {
			// 			common.simpleToast(resp.data.msg)
			// 		}
			// 	})
			// },
			bluetoothClose: function() {
				bluetooth.closeBluetoothAdapter();
				bluetooth.closeDevice(
					this.cabinetInfo.bt_mac,
					() => {
						// this.setData({
						// 	bt_loading: false
						// });
					},
					() => {}
				);
				bluetooth.offCharacteristicStateChange(this.cabinetInfo.bt_mac, 'home');
				bluetooth.offConnectionStateChange(this.cabinetInfo.bt_mac, 'home');
			},
			changePayType(e) {
				const type = e.currentTarget.dataset.type
				if (this.wallet_money < this.free_price) {
					common.simpleToast('钱包余额不足')
					return
				}
				this.setData({
					payType: type
				})
				console.log(this.free_price, 'free_price');
			},
			close() {
				this.setData({
					isOpenBluetooth: false
				})
			},
			claseShowToBuy() {
				this.setData({
					isShowToBuy: false
				})
			},
			decodeKey(str) {
				var val = []
				for (var i = 0; i < str.length / 2; i++) {
					val.push(parseInt(str.substring(0 + i * 2, 2 + i * 2), 16))
				}
				var str = ""
				for (var i = 0; val.length > i; i++) {
					str += String.fromCharCode(~val[i] & 0xff)
				}
				return str
			},
			noBluetoothBack() {
				common.loading();
				const me = this
				const pData = {
					battery_sn: this.battery_info.battery_sn,
					dev_id: this.scan_dev_id
				}
				http.postApi(config.API_CABINET_RETURN_HIRE_BATTERYI, pData, resp => {
					uni.hideLoading()
					if (resp.data.code === 200) {
						const pData = {
							order_sn: resp.data.data.order_sn,
							battery_sn: me.battery_info.battery_sn,
						}
						me.navOpenCabinet(pData, 1)
					} else {
						common.alert('提示', resp.data.msg);
					}
				})
			},
			bindReturnOrExchange() {
				const me = this
				console.log(me.is_retuen_batterym, 'is_retuen_battery');
				if (me.is_retuen_battery) {
					common.loading();
					const me = this
					const pdata = {
						battery_sn: this.battery_info.battery_sn,
						dev_id: this.scan_dev_id
					}
					console.log(pdata, 'pdatapdata');
					http.postApi(config.API_CABINET_BLUETOOTH_RETURN, pdata, resp => {
						wx.hideLoading()
						console.log(resp.data, 'resp.data');
						if (resp.data.code === 200) {
							console.log(resp.data.data, '1314');
							const pData = {
								order_sn: resp.data.data.order_sn,
								empty_door_id: resp.data.data.empty_door_id,
								rtn_battery_ca: resp.data.data.rtn_battery_ca || ''
							}
							//还电
							me.navOpenCabinet(pData, 1)
						} else {
							common.alert('提示', resp.data.msg);
						}
					})

				} else {
					//换电
					if (me.packInfo.last_num == 0&&me.packInfo.num != 0) {
						if (me.free_price != 0) {
							me.setData({
								isShowToBuy: true
							})
							me.walletInfo()
						} else{
							const pData = {
								from: from,
								battery_sn: this.is_battery ? this.battery_info.battery_sn : this.packInfo.current_battery_sn,
								dev_id: this.scan_dev_id,
								pay_type: 9
							}
							const me = this
							//#ifdef MP-ALIPAY
							const from = 'ali'
							//#endif
							//#ifdef MP-WEIXIN
							const from = 'wx'
							//#endif
							http.postApi(config.API_CABINET_CHANGE_BATTERY2, pData, (resp) => {
								if (resp.data.code === 200) {
									// 钱包支付不需要支付直接换电 有换电次数可以直接换电
									if (!resp.data.data.need_pay) {
										me.orderInfo = {
											order_sn: resp.data.data.order_sn,
											empty_door_id: resp.data.data.empty_door_id,
											full_door_id: resp.data.data.full_door_id,
											cabbatterysn: resp.data.data.rtn_battery_sn || ''
										};
										me.navOpenCabinet(me.orderInfo)
									} else {
										me.setData({
											isShowToBuy: false
										})
										me.wxPayPrice = resp.data.data.price
										me.payResp = resp
										me.doPayBattery({})
									}
								} else {
									common.simpleToast(resp.data.msg)
								}
							})
						}
					} else {
						me.toPayOrFreeExchange()
					}
				}

			},
			
		}
	};
</script>

<style>
	@import './scanBtn.css';
</style>