<template>
	<view class="container-view">
		<view class="open-bg-view">
			<img class="open-bg" src="https://qiniu.bms16.com/FqNzU4Wh2kry5H0EqC5zeM2thRFg" alt="">
		</view>
		<view class="explain-view">
			<view class="explain-num-view flex-row">
				<!-- <text><text class="explain-num">{{empty_door_id}} </text>号仓门已打开</text> -->
				<text>仓门已打开</text>
			</view>
			<view class="explain-text">请存入更换电池,取走满电电池,并关好仓门</view>
			<!-- <view class="explain-text">请 归还 / 取出 电池并关上仓门</view> -->
			<!-- <view class="explain-text">请取出电池并关上仓门</view> -->
			<!-- <view class="explain-text-grap">归还完成后电柜会自动打开可租仓门</view> -->
			<!-- <view class="explain-text-grap">自动为您匹配最高电量电池</view> -->
		</view>
		<!-- 完成弹窗 -->
			<view v-if="isOverModal" class="modal-group">
				<view class="payment-info-main">
					<view class="payment-info-top flex-row">
						<img class="check-icon" :src="showtxt.img" alt="">
						<!-- <img src="https://qiniu.bms16.com/FmGcOOZZm09nx9lH3lez7D3DYHKn" alt=""> -->
					</view>
					<view class="open-result-view">
						<view class="open-result flex-row">{{showtxt.title}}</view>
						<view class="open-result-tip flex-row">{{showtxt.text}}</view>
					</view>
					<view class="over-btn-view">
						<view v-if="status==3" @tap="tapToIndex" class="over-btn flex-row">完成.{{countdown}}</view>
						<view v-if="status==4" @tap="connectStore" class="over-btn flex-row">联系门店</view>
					</view>
				</view>
			</view>
		
	</view>
</template>

<script>
	const http = require('../../common/http.js');
	const config = require('../../common/config.js');
	const common = require('../../common/common.js');
	var bluetooth = require('../../common/bluetooth.js');
	const DF_CAB_INFO_DONE = 10000; //机柜信息传输完成
	const app = getApp();
export default {
		data() {
			return {
				isOverModal:false,
				orderStatusTimer: null,//查询订单状态
				order_sn:'',
				showtxt:{
					img:'',
					title:'',
					text:''
				},
				status:0,
				countdown:5,
				empty_door_id:'', //空仓（归还仓）编号
				full_door_id:'', //满电仓(借出电池仓)编号
				phone:'', //换电失败联系电话
				cabinetInfo:{},
				isShow:false,
				intervalTime:null
			};
		},
		/**
		 * 生命周期函数--监听页面加载
		 */
		onLoad: function(options) {
			const me=this
			const paramsString = decodeURIComponent(options.pdata)
			const cabinetInfoString = decodeURIComponent(options.cabinet_info)
			this.cabinetInfo= JSON.parse(cabinetInfoString)||{}
			const pData=JSON.parse(paramsString)||{}
			this.phone=this.cabinetInfo.link_phone||''
			if(this.cabinetInfo.online_status==1){
				me.order_sn=pData.order_sn
				me.clearTimer()
				//机柜直接下发指令开始换电
				me.orderStatusTimer = setInterval(function () {
				  me.getChangeBatteryStatus(me.order_sn)
				}, 1200)
				setTimeout(function () {
				  wx.showLoading({
				    title: '正在换电中，请稍后',
				  })
				}, 200)
			}else{
				// 离线蓝牙换电
				me.sendExchangeCommand({...pData,...this.cabinetInfo})
			}
		},
		/**
		 * 生命周期函数--监听页面显示
		 */
		onShow: function() {
			
		},
		methods: {
			getChangeBatteryStatus(order_sn){
				const me=this
				//定时查询换电状态
				 http.postApi(config.API_DAY_HIRE_CABINRT_CHANGE_BATTERY_STATUS, { order_sn: order_sn }, resp => {
				      if (resp.data.code === 200) {
				        const statusInfo = resp.data.data.statusInfo
				        const status = statusInfo.status
				        if (status == 0||status == 1 || status == 2) {
				          return;
				        }
						me.empty_door_id=
				        uni.hideLoading();
				        me.clearTimer()
						
				        if (status == 3) {
							const _showtxt = {
									title:'换电成功',
									text:'即将跳转至首页，祝您骑行愉快',
									img:'https://qiniu.bms16.com/Fg5C4OVF17Q8p5-mHu7CoFne0Zqp'
									}
							me.setData({
								isOverModal:true,
								status:3,
								showtxt:_showtxt
							})
							me.startCountdown()
				        } else {
							const _showtxt  = {
								title:'换电失败',
								text:statusInfo.fail_reason,
								img:'https://qiniu.bms16.com/FmGcOOZZm09nx9lH3lez7D3DYHKn'
								}
							me.setData({
								isOverModal:true,
								status:4,
								showtxt:_showtxt
							})
				        }
				      }
				    })
			},
			 // 开始倒计时  
			  startCountdown: function() {  
			    let that = this;  
			    this.intervalTime = setInterval(function() {  
			      if (that.countdown > 1) {  
			        that.setData({  
			          countdown: that.countdown - 1  
			        });  
			      } else {  
			        clearInterval(that.intervalTime); // 清除定时器  
			        that.tapToIndex() 
			      }  
			    }, 1000); // 每隔1000毫秒（1秒）执行一次  
			  },
			tapToIndex(){
				this.isOverModal=false
				this.bluetoothClose()
				this.clearTimer()
				this.clearIntervalTimer()
				uni.reLaunch({
				  url: '/pages/index/index',
				})
			},
			connectStore(){
				const me = this
				const phone = this.phone
				// const phone = 18170410707
				uni.showModal({
					content: `您是否要拨打电话${phone}？`,
					confirmText: '确定',
					success: (res) => {
						if (res.confirm) {
							me.clearTimer()
							uni.makePhoneCall({
								phoneNumber: phone,
								success() {},
								fail() {}
							})
						}
					},
					fail: (res) => {}
				})
			},
			clearTimer () {
			   if (this.orderStatusTimer == null) return
			   clearInterval(this.orderStatusTimer)
			   this.orderStatusTimer = null
			 },
			 clearIntervalTimer () {
			   if (this.intervalTime == null) return
			   clearInterval(this.intervalTime)
			   this.intervalTime = null
			 },
			 sendExchangeCommand(pdata) {
				 console.log(pdata,'pdata');
			 	var device = {};
			 	device.orderNo = pdata.order_sn;
			 	device.battertNum = pdata.cabbatterysn;
			 	device.empityBoxNo = pdata.empty_door_id;
			 	device.fullBoxNo = pdata.full_door_id;
			 	device.dev_id = this.cabinetInfo.dev_id;
			 	device.serialNum = new Date().getTime().toString();
			 	device.key = this.decodeKey(this.cabinetInfo.bt_sec)
			 	device.mac_id = this.cabinetInfo.bt_mac;
			 	app.globalData.reportData = null;
			 	app.globalData.reponseData = null;
			 	const me = this;
			 
			 	if (bluetooth.isConnected(device.mac_id)) {
			 		// me.loadBluetooth()
			 		bluetooth.sendExchangeCommand(
			 			device.mac_id,
			 			device,
			 			function() {
			 				me.clearTimer();
			 				me.orderStatusTimer = setInterval(function() {
			 					if (app.globalData.reponseData !== null) {
			 						var reponseData = app.globalData.reponseData;
			 						if (reponseData.reponse == 1) {
			 							if (reponseData.state != 1) {
			 								if (reponseData.msg != '上次操作未确认') {
			 									uni.hideLoading();
			 									me.clearTimer();
			 									common.simpleToast(reponseData.msg);
			 								} else {
			 									if (bluetooth.isConnected(device.mac_id)) {
			 										bluetooth.sendCancelCommand(
			 											device.mac_id,
			 											reponseData.serialNo,
			 											function() {},
			 											function() {
			 												me.sendExchangeCommand(pdata);
			 											}
			 										);
			 									} else {
			 										// this.loadBluetooth();
													//蓝牙未连接
			 									}
			 								}
			 							}
			 						}
			 					}
			 
			 					if (app.globalData.reportData !== null) {
			 						var reportData = app.globalData.reportData;
			 
			 						if (reportData.report == 1) {
			 							common.simpleToast(reportData.msg);
			 							uni.hideLoading();
			 							me.clearTimer();
			 
			 							if (!me.isShow) {
											if(reportData.msg=='换电成功'||reportData.msg=='成功'){
												// 换电成功
												me.isShow = true;
												me.isOverModal=true
												me.status=3
												me.showtxt = {
													title:'换电成功',
													text:'即将跳转至首页，祝您骑行愉快',
													img:'https://qiniu.bms16.com/Fg5C4OVF17Q8p5-mHu7CoFne0Zqp'
													}
												// countdown
												// 倒计时跳转首页
												me.clearTimer();
												me.bluetoothClose();
												me.startCountdown()	
											}else{
												me.isShow = true;
												me.status=4
												me.isOverModal=true
												me.showtxt  = {
													title:'换电失败',
													text:reportData.msg,
													img:'https://qiniu.bms16.com/FmGcOOZZm09nx9lH3lez7D3DYHKn'
													}
												me.clearTimer();
												me.bluetoothClose();
											}
											
			 							}
			 						}
			 					}
			 				}, 2000);
			 				uni.showLoading({
			 					title: '正在换电中，请稍后'
			 				});
			 			},
			 			function() {
			 				//common.simpleToast('发送失败')
			 				uni.showModal({
			 					title: '提示',
			 					confirmText: '重新发送',
			 					content: '请重新发起换电',
			 					success: function(res) {
			 						if (res.confirm) {
			 							me.sendExchangeCommand(pdata);
			 						} else {
			 							uni.navigateBack({
			 								delta: 1
			 							});
			 						}
			 					}
			 				});
			 			}
			 		);
			 	} else {
			 		// this.loadBluetooth();
					// 重新获取蓝牙
			 	}
			 },
			 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');
			 },
			 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
			 },
		}
	};
</script>

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