<template>
	<view class="container-view">
		<view class="cabinet-bottom">
			<view @tap="navToGuild" class="guide-view flex-row">
				<img class="battery-img" src="https://qiniu.bms16.com/FkJlBRAxbGzR85wOO8WB_bAUTp-i" alt="">
				<view class="guide-text">{{$t('电池换电指南')}}</view>
				<img class="arrow-img" src="https://qiniu.bms16.com/FtC9Hb8y1QEOidsI2UySz85iUQHy" alt="">
			</view>
			<view class="scan-btn-view">
				<view v-if="num>0" class="free-num-view">
					{{$t('免费换电')}}<text class="free-num"> {{num}} </text>次
				</view>
				<view @tap="sacnBtn" class="scan-btn"><text>{{$t('扫码换电')}}</text></view>
			</view>
		</view>
		
	<!-- 购买换电次数弹窗 -->
		<view v-if="isShowToBuy" class="modal-group">
			<view class="fee-rules-main">
				<view class="fee-rules-top flex-row">
					<view @tap="claseShowToBuy" class="fee-rules-close">
						<img class="close-icon" src="https://qiniu.bms16.com/FtoTEHOJiUf_gjPCJGGHMsAtHI5M" alt="">
					</view>
					<view class="pay-moneu-view">
						<view class="pay-money-text">{{$t('付款金额')}}/￥</view>
						<view class="pay-money">{{free_price}}</view>
					</view>
				</view>
				<view class="fee-rules-view">
					<view class="fee-rules flex-row flex-between">
						<view class="fee-rules-title flex-row">
							<img class="fee-rules-icon" src="https://qiniu.bms16.com/FjJ70vT8ydLEGfeABSFYWFe-zosV"
								alt="">
							<text style="margin-left:16rpx;">{{$t('换电收费规则')}}</text>
						</view>
						<view class="fee-rules-money-view">
							<text class="fee-rules-money">￥{{free_price}}</text>
							<text>/1次</text>
						</view>
					</view>
					<view class="open-result-tip">{{$t('您的免费换电次数已用完，后续换电需要支付')}}</view>
				</view>
				<view class="pay-type-view">
					<!-- #ifdef MP-WEIXIN  -->
					<view class="pay-view flex-row">
						<img class="pay-icon" src="https://qiniu.bms16.com/FkmtlfJrmGfAh9n1138KC1WloQkZ" alt="">
						<view class="pay-view-text">{{$t('微信支付')}}</view>
						<img @tap="changePayType" :data-type="0" class="wx-pay-icon"
							:src="payType==0?'https://qiniu.bms16.com/FhWimtmWybKlYMB6mgIReVWArbfq':'https://qiniu.bms16.com/FkmDjxBNZhFGFU5inza2usdtDlX8'"
							alt="">
					</view>
					<!-- #endif  -->
					<!-- #ifdef MP-ALIPAY-->
					<view class="pay-view flex-row">
						<img class="pay-icon" src="https://qiniu.bms16.com/Fk4YmG_RbdH0LNo1s8qHKDtpCTXl" alt="">
						<view class="pay-view-text">{{$t('支付宝支付')}}</view>
						<img @tap="changePayType" :data-type="2" class="wx-pay-icon"
							:src="payType==2?'https://qiniu.bms16.com/FhWimtmWybKlYMB6mgIReVWArbfq':'https://qiniu.bms16.com/FkmDjxBNZhFGFU5inza2usdtDlX8'"
							alt="">
					</view>
					<!-- #endif  -->
					<view class="pay-view flex-row">
						<img class="pay-icon" src="	https://qiniu.bms16.com/FiGNLQ5lqhEK5im_mUVgRrE8PJMB" alt="">
						<view class="pay-view-text">{{$t('钱包余额支付')}}(¥{{wallet_money}})</view>
						<img @tap="changePayType" :data-type="9" class="wx-pay-icon"
							:src="payType==9?'https://qiniu.bms16.com/FhWimtmWybKlYMB6mgIReVWArbfq':'https://qiniu.bms16.com/FkmDjxBNZhFGFU5inza2usdtDlX8'"
							alt="">
					</view>
				</view>
				<view class="over-btn-view">
					<view class="over-btn flex-row" @tap="toPayOrFreeExchange">{{$t('立即支付')}}</view>
				</view>
			</view>
		</view>
		<!-- 打开蓝牙连接弹窗 -->
		<view v-if="isOpenBluetooth" class="modal-group">
			<view class="def-alert-bluetooth">
				<view class="close-view flex-row"><img @tap="close" class="close-icon"
						src="https://qiniu.bms16.com/FtoTEHOJiUf_gjPCJGGHMsAtHI5M" alt=""></view>
				<view class="bluetooth-view flex-row"><img class="bluetooth-icon"
						src="https://qiniu.bms16.com/FjWK8ZBtxCmspiOtHJWrNEoPRA0M" alt=""></view>
				<view class="need-bluetooth-text">{{$t('本次换电需要连接蓝牙')}}</view>
				<view class="need-bluetooth-tip">{{$t('请开启手机蓝牙，点击 (蓝牙换电) 按钮')}}</view>
				<view class="bluetooth-connect-view">
					<view class="bluetooth-connect-btn" @tap="tapOpenBluetooth">{{$t('蓝牙换电')}}</view>
				</view>
			</view>
		</view>
		
	</view>
</template>

<script>
	var http = require('../../common/http.js');
	var config = require('../../common/config.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');
	const DF_CAB_INFO_DONE = 10000; //机柜信息传输完成
	export default {
		props: {
			car_info: {
				type: Array,
				required: true //必填项
			},
		},
		data() {
			return {
				blueInfo:{},//连接蓝牙需要数据
				isBluetooth:false,//缓存蓝牙连接状态
				cabinetInfo:{},//机柜信息
				num:0,//免费换电次数
				payType:0,//支付方式
				scan_dev_id:'',//扫码机柜编号
				online_status:'',//机柜在线状态
				isOpenBluetooth:false,
				license_plate_number:'',
				isShowToBuy:false,
				wallet_money:0,
				payResp:{},
				myLocations:{},
				orderInfo:{},
				carInfo:{}
			}
		}
		/**
		 * 生命周期函数--监听页面加载
		 */
		,
		mounted: function(options) {
			const car_list = uni.getStorageSync('user_car_list') || null
			const storedLocation = uni.getStorageSync('user_current_location');
			if (car_list){
				this.license_plate_number=car_list.plate_number
				this.carInfo=car_list
			}
			
			if (storedLocation && storedLocation.longitude && storedLocation.latitude) {
				// 如果本地有存储的定位信息，则直接使用
				this.setData({
					myLocations: 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.loadExchangeInfo()
		},
		/**
		 * 生命周期函数--监听页面显示
		 */
		onShow: function() {

		},
		methods: {
			navToGuild() {
				uni.navigateTo({
					url: '/pages/exchangeGuide/exchangeGuide'
				});
			},
			sacnBtn() {
				const me = this
				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
							if(me.carInfo.battery_sn&&me.carInfo.remain){
								me.loadNowCabinetDetail(cabinet_dev_id)
							}else if(!me.carInfo.battery_sn){
								common.simpleToast(me.$t('车辆未绑定电池'))
							}else if(!me.carInfo.remain){
								common.simpleToast(me.$t('车辆已到期，请及时前往续费'))
							}
							
						}
					},
					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)
					}
				}
			},
			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
			},
			loadNowCabinetDetail(dev_id){
				const timeNow=Date.now()
				this.scan_dev_id=dev_id
				//扫码机柜信息
				const me=this
				const pData={
					longitude:this.myLocations.longitude,
					latitude:this.myLocations.latitude,
					dev_id:dev_id||'',
					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.bluetoothClose()
						
						if(me.online_status == 1){
							 if(me.num==0){
								 me.setData({
									  isShowToBuy:true
								 })
							 	 me.walletInfo()
							 }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) 
						if(me.free_price <= (resp.data.data.balance / 100).toFixed(2)){
							me.payType=9
						}
						me.setData({
							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={
					dev_id:this.scan_dev_id,
					license_plate_number:this.license_plate_number,
					pay_type:this.payType,
					from:from
				}
				//如果在线用机柜换电 不在线用蓝牙换电
				const url = this.online_status == 1 ? config.API_DAYHIRE_CABINRT_CHANGE_BATTERY : config.API_DAYHIRE_CABINRT_BLUETOOTH_EXCHANGE
				http.postApi(url,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)
					}
				})
			},
			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.$t('支付成功'))
					//跳转换电流程页面
					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.cancelHirePay(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.$t('支付成功'))
			   			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.cancelHirePay(order_sn)
			   		}
			   	},
			   });
			   //#endif
			 },
			tapOpenBluetooth(time = null) {
				const me = this
				const device = me.blueInfo
				// 蓝牙换电按钮	加载蓝牙
				this.loadBluetooth()
			},
			loadBluetooth() {
				const me = this;
				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.$t('蓝牙连接成功'))
												me.setData({
													isOpenBluetooth: false,
													isBluetooth:true
												});
												// 进行机柜蓝牙换电 API_DAYHIRE_CABINRT_BLUETOOTH_CHANGE_BATTERY
												if(me.num==0){
													 me.setData({
													 	isShowToBuy:true
													 })
													 me.walletInfo()
												}else{
													me.toPayOrFreeExchange()
												}
											}
										}
									});
									bluetooth.onConnectionStateChange(device.mac_id, 'index', (res) => {
										uni.hideLoading();
										if (!res.connected) {
											// 蓝牙未连接
											// common.simpleToast('蓝牙连接断开',2000)
											me.setData({
												isOpenBluetooth: true,
												isBluetooth:false
											});
										} else {
											common.simpleToast(me.$t('蓝牙连接成功'),2000)
											// 蓝牙已连接
											me.setData({
												isOpenBluetooth: false,
												isBluetooth:true
											});
											if(me.num==0){
												 me.setData({
												 	isShowToBuy:true
												 })
												 me.walletInfo()
											}else{
												me.toPayOrFreeExchange()
											}
										}
									});
									bluetooth.sendGetCabinetInfoCommand(
										device.mac_id,
										device,
										(res) => {
											common.loading();
										},
										(res) => {
											me.setData({
												isOpenBluetooth: false
											});
											uni.showModal({
												title: me.$t('提示'),
												confirmText: me.$t('重新连接'),
												content: me.$t('连接失败，请尝试重新连接'),
												success: function(res) {
													if (res.confirm) {
														me.loadBluetooth();
													} else {
														// uni.navigateBack({
														// 	delta: 1
														// });
													}
												}
											});
										}
									);
								},
								(res) => {
									uni.hideLoading();
									var showContent = ""
									if (res && ("errCode" in res)) {
										if (res.errCode == 9000001) {
										   var showContent= me.$t('观察周围是否有其他骑手连接，请等待对方完成') + me.$t('或') + me.$t('微信是否开启了蓝牙权限')！！
										}else{
											var showContent= me.$t('连接失败，请尝试重新连接')
										}
									  }
									  else {
										 var showContent= me.$t('连接失败，请尝试重新连接')
									  }
									me.setData({
										isOpenBluetooth: false,
										isBluetooth:false
									});
									uni.showModal({
										title: me.$t('提示'),
										confirmText: me.$t('重新连接'),
										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: me.$t('提示'),
											confirmText: me.$t('我知道了'),
											content: me.$t('蓝牙未打开或请在右上角设置授权小程序使用蓝牙'),
											success: function(res) {
												if (res.confirm) {
													me.loadBluetooth();
												} else {
													// uni.navigateBack({
													// 	delta: 1
													// });
												}
											}
										});
									}
							);
						},
					);
				} else {
					//蓝牙连接未成功
					uni.hideLoading();
					uni.showModal({
						confirmText: me.$t('我知道了'),
						content: me.$t('当前机柜未找到符合的蓝牙类型'),
						showCancel: false,
						title: me.$t('提示'),
						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){
				const me=this
				const paramsString = JSON.stringify(pdata)
				const cabinetInfoString = JSON.stringify(me.cabinetInfo)
				// 跳转机柜换电页面-展示换电流程和结果
				uni.navigateTo({
					url: '/pages/openCabinet/openCabinet?pdata=' + encodeURIComponent(paramsString)+ '&cabinet_info=' + encodeURIComponent(cabinetInfoString),
					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(this.$t('钱包余额不足'))
					return
				}
				this.setData({
					payType: type
				})
			},
			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
			},
		}
	};
</script>

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