<template>
    <view class="container-view-contril">
		<scroll-view class="scroll-view flex-row" scroll-x="true">
			<view @tap="tapOpen" v-for="(item,index) of contrilList" :key="index" :data-item="item" class="contril-item flex-row">
				<img class="contril-item-img"  :src="item.isTurnOn==0?item.offUrl:item.iconUrl" alt="">
				<text >{{item.name}}</text>
			</view>
			<view class="contril-item flex-row" @tap="toMoreFunctionSet">
				<img class="contril-item-img" src="https://qiniu.bms16.com/Ft3pNyStT22LP8Ds1Mru2LoTHadx" alt="">
				<text>{{$t("更多功能")}}</text>
			</view>
		</scroll-view>
		<view class="flex-row power-view">
			<!-- <view class="power-on-off flex-row" >
				<view :style="sliderStyle" @touchstart="touchStart" @touchmove="touchMove" @touchend="touchEnd" class="power-on-btn"><image style="width: 52rpx;height: 52rpx;" src="https://qiniu.bms16.com/Fkovrpq1bexe-Unal_VJREbLUhdu" mode=""></image></view>
				<view class="power-on-text" >{{ $t('滑动启动') }}</view>
			</view> -->
			<custom-switch @changEnd='changEnd'  :width="'400rpx'"
				:height="'96rpx'"  :modelValue="switchValue" :fetchData="loadData"></custom-switch>
				
				
			<!-- <custom-switch :defaultPosition="'right'" :width="'400rpx'" 
			    :height="'96rpx'"  v-model="switchValue" :fetchData="loadData"></custom-switch> -->
			<view v-if="authority_list.indexOf(5) == -1" @tap="navToInputPages" class="car-change-battery flex-row">
				<view class="car-change-btn"><image style="width: 80rpx;height: 80rpx;" src="https://qiniu.bms16.com/FgvnT-msLbL5RHjl6fvNlM0kab5N" mode=""></image></view>
				<view class="car-change-text">{{ $t('车辆换电') }}</view>
			</view>
		</view>
		<view v-if="popupControlShow" class="show-modal">
			<view class="modal-info">
				<view class="popup-title">{{($t(popText)==$t('开机'))?$t('开启车辆'):($t(popText)==$t('关机')?$t('关闭车辆'):$t(popText))}}</view>
				<view class="popup-content">{{$t("您确认")+(($t(popText)==$t('开机'))?$t('开启车辆'):($t(popText)==$t('关机')?$t('关闭车辆'):$t(popText)))+$t("吗")}}</view>
				<view class="flex-row modal-footer">
					<view class="show-btn cencel-btn-pop" @tap="closePopup">{{$t("取消")}}</view>
					<view class="show-btn ok-btn-pop" @tap="tapBlueToothCmd">{{$t("确定")}}</view>
				</view>
			</view>
		</view>
		<!-- <u-popup v-model="popupControlShow" mode="center" border-radius="30" height="30%" length="60%">
			<view class="popup-title">{{ $t('开启车辆') }}</view>
			<view class="popup-content">{{ $t('确定打开') }}</view>
			<view class="flex-row">
				<view class="sure-btn cencel-btn" @tap="closePopup">{{ $t('取消') }}</view>
				<view class="sure-btn ok-btn" >{{ $t('确定') }}</view>
			</view>
		</u-popup> -->
		<!-- <view v-if="isShowMore" class="show-more">
			<view class="more-info">
				<view class="flex-row flex-between model-title">
					<view>{{$t("{{ $t('更多功能') }}")}}</view>
					<view>
						<image style="width: 32rpx;height: 32rpx;" @tap="isShowMore = false"
							src="https://qiniu.bms16.com/FtoTEHOJiUf_gjPCJGGHMsAtHI5M" />
					</view>
				</view>
				<view style="height: 300rpx;">
					<view data-url="test" @tap="navUrl" class="more-item flex-row">
						<img class="more-img" src="https://qiniu.bms16.com/FgxiD-W96FGvgyLI_kXUfWVDYLQ9" alt="">
						<text>{{$t("{{ $t('胎压') }}")}}</text>
					</view>
					<view class="more-item flex-row">
						<img class="more-img" src="https://qiniu.bms16.com/FgxiD-W96FGvgyLI_kXUfWVDYLQ9" alt="">
						<text>{{$t("{{ $t('电池信息') }}")}}</text>
					</view>
					<view @tap="navCarLocation" class="more-item flex-row">
						<img class="more-img" src="https://qiniu.bms16.com/FgxiD-W96FGvgyLI_kXUfWVDYLQ9" alt="">
						<text>{{$t("{{ $t('导航') }}")}}</text>
					</view>
				</view>
				<view class="lift-btn-view">
					<view class="lift-btn">{{$t("{{ $t('解除绑定') }}")}}</view>
				</view>
			</view>
		</view>
   -->
	</view>
</template>

<script>
	var bluetooth = require('@/common/bluetooth.js');
	var config = require('@/common/config.js');
	var common = require('@/common/common.js');
	var http = require('@/common/http.js');
	import CustomSwitch from '@/component/customSwitch.vue'; // 引入组件
	
	import controlMixin from '@/mixin/index';
	import i18n from '@/locale/index.js'
	import {
			getFunctionTag,
			setFunctionTag
		} from '@/common/storage.js';
export default {
	mixins: [controlMixin],
	components:{CustomSwitch},
	props:{
		contrilList: {
			type: Array,
			default: () => []
		},
		online: {
			type: Boolean,
			default: false
		},
	},

    data() {
        return {
			// popText:'',
			// popupControlShow:false,
			// controlType:null,//选择的车辆控制
			switchValue: {state:false,time:0},
			isShowMore:false,
			car_line:false,
			authority_list:[]
			// startX: 0, // 滑块开始滑动的初始位置
			// moveX: 0, // 滑块滑动的距离
			// unlocked: false, // 是否解锁成功的标志
			
		};
    },
	computed: {
	    // 计算滑块的样式
	    sliderStyle() {
	      return {
	        transform: `translateX(${this.moveX}px)`
	      };
	    },
	},
	mounted() {
		// this.contrilList = getFunctionTag().activeTag
		// setTimeout(()=>{
			this.authority_list=uni.getStorageSync('car_info').authority_list
			this.switchValue.state=uni.getStorageSync('car_info').acc_state==1
		// },50)
		
		// setTimeout(()=>{
		// 	console.log(this.switchValue)
		// },5000)
		
	},
 
    /**
     * 组件的方法列表
     */
    methods: {
		changEnd(e){
			this.switchValue = JSON.parse(e)
			if(this.switchValue.type==1){
				this.callApiThreeTimes()
			}
			console.log(this.switchValue)
		},
		callApiThreeTimes() {
			const apiCall = (attempt) => {
				const car_sn= uni.getStorageSync('car_info').car_sn
				this.$emit('loadCarDetail',car_sn)
			};

			apiCall(1);
			// setTimeout(() => apiCall(2), 200);
			// setTimeout(() => apiCall(3), 200);
		},
		tapOpen(e){
				const item = e.currentTarget.dataset.item;
				this.changClick(item)
		},
		toMoreFunctionSet() {
			uni.navigateTo({
				url: '/pages/carFunctionSet/more?online='+this.online
			})
		},
		trunOn(type){
			
			if (this.carOnline) {
				//开机1 关机0
				const car_sn= uni.getStorageSync('car_info').car_sn;
				const pData = {
					car_sn,
					switch: switchType
				}
				const me=this
				common.loading();
				http.postApi(config.API_FLK_CAR_SWITCH, pData, (resp) => {
					uni.hideLoading();
					if (resp.data.code === 200) {
						common.simpleToast(me.popText + this.$t('成功'));
						const activeTag = me.contrilList.map(item => {
							if('isLock' in item){
								item.isTurnOn = (item.isTurnOn == 1) ? 0 : 1
								item.name = i18n.t((item.isTurnOn == 1) ? this.$t('关机') : this.$t('开机'))
							}
							return item
						})
						const tag = getFunctionTag().tag
						setFunctionTag({
							activeTag,
							tag
						})
						me.$emit('loadCarDetail',pData,car_sn)
					} else {
						common.simpleToast(resp.data.msg);
					}
				});
			}else{
				//车辆离线
				const car_sn= uni.getStorageSync('car_info').car_sn;
				common.loading();
				if (type==1) {
					bluetooth.turnOnCar(car_sn, () => {
						uni.hideLoading();
					});
				}else{
					bluetooth.turnOffCar(car_sn, () => {
						uni.hideLoading();
					});
				}
			}
		},
		async navToInputPages() {
			const me = this
			const exchange_need_package=uni.getStorageSync('car_info').exchange_need_package;
			if(exchange_need_package==0){
				uni.scanCode({
					scanType:['qrCode'],
					success(res) {
						me.loadGeneralQRData(res.result)
					},
					fail() {
						me.$msg(this.$t('扫码失败，请重新扫码'))
					}
				})
			}else if(exchange_need_package==1){
				uni.showModal({
					title: this.$t('温馨提示'),
					content: this.$t('您还未购买换电套餐，是否前往购买换电套餐？'),
					showCancel: true,
					cancelText: this.$t('取消'),
					confirmText: this.$t('前往购买'),
					success: function(res) {
						if (res.confirm) {
							uni.navigateTo({
								url: `/pages/batteryPackage/batteryPackage`
							})
							
						}
					},
					fail: function(res) {},
					complete: function(res) {},
				})
			}else if(exchange_need_package==-1){
				this.$msg(this.$t('当前车辆暂未绑定电池'))
			}
			
		},
		loadGeneralQRData(options) {
			console.log(options)
			let objOpt = this.$paramsObj(options)
			
			if (objOpt.d) {
				uni.navigateTo({
					url: `/pages/cabinetDetail/cabinetDetail?dev_id=${objOpt.d}`,
				})
				return
			} else {
				this.$msg(this.$t('请扫描机柜二维码'))
				return
			}
		},
		
		async loadData(state) {
			// console.log(state,'state');
			return new Promise((resolve,reject) => {
				if (uni.getStorageSync('car_info').online==1) {
								//开机1 关机0
								const car_sn= uni.getStorageSync('car_info').car_sn;
								const switchType= state?0:1;
								const pData = {
									car_sn,
									switch: switchType
								}
								const me=this
								http.postApi(config.API_FLK_CAR_SWITCH, pData, (resp) => {
									if (resp.data.code === 200) {
										//const textStr = (this.switchValue==0)?this.$t('开机'):this.$t('关机')
	
										// const activeTag = me.contrilList.map(item => {
										// 	if('isLock' in item){
										// 		item.isTurnOn = (item.isTurnOn == 1) ? 0 : 1
										// 		item.name = i18n.t((item.isTurnOn == 1) ? this.$t('关机') : this.$t('开机'))
										// 	}
										// 	return item
										// })
										// const tag = getFunctionTag().tag
										// setFunctionTag({
										// 	activeTag,
										// 	tag
										// })
										
										setTimeout(() => {
										
											resolve(JSON.stringify({
												state:!state,
												type:1,
												time: Math.floor(Date.now() / 1000)
											}))
											console.log(132);
											
											// me.switchValue = JSON.stringify({
											// 	state:!state,
											// 	time: Math.floor(Date.now() / 1000)
											// })
										}, 1000)
										
									} else {
										 setTimeout(() => {
										 	resolve(JSON.stringify({
										 		state:state,
												type:2,
										 		time:Math.floor(Date.now() / 1000)
										 	}))
										 	//this.switchValue=!this.switchValue
										 	// this.switchValue = JSON.stringify({
										 	// 	state:this.switchValue.state,
										 	// 	time:Math.floor(Date.now() / 1000)
										 	// })
											// common.simpleToast(resp.data.msg);
										 }, 1000)
										//setTimeout(resolve, 1000);
										
									}
								});
							}else{
								//车辆离线
								const car_sn= uni.getStorageSync('car_info').car_sn;
								const switchType= state;
								common.loading();
								const app=getApp()
								//调用蓝牙连接 
								// if()
								if (!switchType) {
									bluetooth.turnOnCar(car_sn, () => {
										uni.hideLoading();
									});
								}else{
									bluetooth.turnOffCar(car_sn, () => {
										uni.hideLoading();
									});
								}
							}
				// console.log(me.switchValue,'this.switchValue');
				// // this.trunOn()
				// setTimeout(resolve, 1000); // 模拟 5 秒请求时间
			});
		}
		// tapOpen(e){
		// 	this.carOnline=this.online
		// 	console.log( getFunctionTag().activeTag, getFunctionTag());
		// 	const {name,type} = e.currentTarget.dataset.item;
		// 	this.setData({
		// 		popText:name,
		// 		cmdType:type,
		// 		popupControlShow:true
		// 	})
		// },
		// tapBlueToothCmd(){
		// 	const car_info= uni.getStorageSync('car_info');
		// 	const me=this
		// 	// 判断车辆是否在线状态 true 在线调用接口 不在线提示连接蓝牙
		// 	if (this.online) {
		// 		if(this.cmdType=='batteryInfo'){
		// 			uni.navigateTo({
		// 				url:`/pages/batteryDetail/batteryDetail`
		// 			})
		// 		}else if(this.cmdType=='navigation'){
		// 			const {
		// 				address,
		// 				latitude,
		// 				longitude,
		// 				car_name
		// 			} =car_info
		// 			uni.openLocation({
		// 				latitude: latitude - 0,
		// 				longitude: longitude - 0,
		// 				scale: 15,
		// 				name: car_name,
		// 				address: address,
		// 				success: function (res) {},
		// 			})
		// 		}else if(this.cmdType=='turnOnOrOff'){
		// 			const switchType=this.contrilList.find(item => item.isTurnOn)
		// 			const pData={
		// 				car_sn:car_info.car_sn,
		// 				switch:switchType
		// 			}
		// 			const me=this
		// 			common.loading();
		// 			http.postApi(config.API_FLK_CAR_SWITCH, pData, (resp) => {
		// 				uni.hideLoading();
		// 				if (resp.data.code === 200) {
		// 					common.simpleToast(me.popText + this.$t('成功'));
		// 					const activeTag=me.contrilList.map(item=>{
		// 						item.isTurnOn=(item.isTurnOn==1)?0:1
		// 						item.name=i18n.t((item.isTurnOn==1)?this.$t('关机'):this.$t('开机'))
		// 						return item
		// 					})
		// 					const tag=getFunctionTag().tag
		// 					setFunctionTag({activeTag,tag})
							
		// 				} else {
		// 					common.simpleToast(resp.data.msg);
		// 				}
		// 			});
		// 		}else{
		// 			const testArr=[
		// 				{type:'findCar',opt_type:1},
		// 				{type:'openSeatBag',opt_type:0},
		// 				{type:'openTailBox',opt_type:2},
		// 				]
		// 			const pData = testArr.find(i=>i.type===this.cmdType)
		// 			const me=this
		// 			common.loading();
		// 			http.postApi(config.API_FLK_CAR_REMOTE_CONTROL, pData, (resp) => {
		// 				uni.hideLoading();
		// 				if (resp.data.code === 200) {
		// 					common.simpleToast(me.popText + this.$t('成功'));
		// 				} else {
		// 					common.simpleToast(resp.data.msg);
		// 				}
		// 			});
		// 		}
		// 	} else {
		// 		//蓝牙是否已经连接 未连接提示去连接 已连接下发对应指令
		// 		const isBluetoothConnect = app.globalData.connectionStateChangeFunc[car_info.car_sn]
		// 		if(isBluetoothConnect){
		// 			const isTurnOn=this.contrilList.find(item => item.isTurnOn).isTurnOn==1
		// 			console.log(isTurnOn,this.cmdType,this.contrilList);
		// 			const bluetoothCommands = {
		// 				'turnOnOrOff': isTurnOn?bluetooth.turnOnCar:bluetooth.turnOffCar,
		// 				'findCar': bluetooth.findCarCmd,
		// 				'openSeatBag': bluetooth.openCarSeat,
		// 				'openTailBox': bluetooth.openCarTrunk,
		// 				'tirePressure': bluetooth.getCarPressure
		// 			};
		// 			common.loading();
		// 			const command = bluetoothCommands[this.cmdType];
		// 			if (command) {
		// 				command('900000997', () => {
		// 					uni.hideLoading();
		// 					if(this.cmdType=='openSeatBag'||this.cmdType=='openTailBox'){
		// 						common.simpleToast(this.$t('操作成功'));
		// 					}
		// 					console.log(`发送${this.popText}指令结束`);
		// 				});
		// 			}
		// 		}else{
		// 			uni.showModal({
		// 				title: this.$t('提示'),
		// 				content: this.$t('当前车辆处于离线，是否前往开启蓝牙配对操作车辆？'),
		// 				showCancel: true,
		// 				cancelText: this.$t('取消'),
		// 				confirmText: this.$t('确定'),
		// 				success: function(res) {
		// 					if (res.confirm) {
		// 						me.$emit('toBluetooth')
		// 					}
		// 				},
		// 				fail: function(res) {},
		// 				complete: function(res) {},
		// 			})
		// 		}
				
		// 	}
		// 	this.popupControlShow=false

		// },
		// // closePopup(){
		// 	this.popupControlShow=false
		// },
		// tapOpenMore(){
		// 	// this.isShowMore=true
		// },
		// closeMore(){
		// 	this.isShowMore=false
		// },
		// navUrl(url){
		// 	// ifconsole.log(url,'sj');
		// },
		// navCarLocation(){
		// 	//前往配置更多功能
		// 	uni.navigateTo({
		// 		url:'/pages/carLocation/carLocation'
		// 	})
		// },
		
	}
};
</script>
<style>
@import './control.css';
</style>
