<!-- 连接设备对设备进行注销 -->
<template>
	<vehicleDetail ref="vehicleDetailRef" :vehicleId="state.vehicleId"></vehicleDetail>
	
	<view class="log-off-content" v-if="state.showProgress">
		<piaoyi-progress-bar
			canvasId="progressCanvas4"
			:progress="state.progressNum"
			progressBackgroundColor="#07C160"
			:showText="true"
			textColor="#fff"
			:textSize="28"
			:height="22"
			:isCircular="true"
			:diameter="300">
		</piaoyi-progress-bar>
	</view>
</template>

<script setup lang="ts">
	import { msg } from "@/utils/utils";
	import { reactive } from 'vue'
	import vehicleDetail from '@/components/vehicle-detail/vehicle-detail.vue'
	import { onLoad, onUnload } from '@dcloudio/uni-app'
	import { requestNew } from "@/utils/network/request.js";
	import { logOffInstAppy, logOffInstCallBack } from '@/utils/network/api.js'
	import { invokeCmd, getObuIdAfter, getCardIdAfter } from '@/static/etcUtil/command'
	
	import { startHeartbeat, stopHeartbeat } from "@/pages/bluetooth/heartbeatService"
	import { logOffOver } from './js/log-off.js'
	const cmd = require("../../../static/etcUtil/cmdConfig.js");
	const tools = require("../../../static/etcUtil/tools.js");
	const bluetoothUtil = require("../../../static/etcUtil/index.js");
	
	const state = reactive({
		vehicleId: '',
		progressNum: 0,
		isSuccess: false,
		showProgress: false
	})
	
	const card = reactive({
		cardId: "",
		cardNo: "",
		startTime: "",
		endTime: "",
		userName: "",
		userNameStr: "",
		idNum: "",
		idNumStr: "",
		vehiclePlate: "",
		vehiclePlateColor: "",
		color: "",
		colorStr: "",
		version: "",
		type: "",
		typeStr: "",
		favourable: "",
		favourableStr: "",
		money: "",
		v_userType: "",
		cardBalance: ""
	});
	
	// OBU
	const obu = reactive({
		obuId: "",
		startTime: "",
		endTime: "",
		version: "",
		approvedCount: "",
		axleCount: "",
		axleDistance: "",
		engineNum: "",
		type: "",
		userType: "",
		contractNo: "",
		vehiclePlate: "",
		vehiclePlateColor: "",
		vin: "",
		wheelCount: "",
		isJH: ""
	});
	
	let progressNumInter = null
	
	onLoad(({vehicleId}) => {
		if (vehicleId) state.vehicleId = vehicleId
		getObuId().then(res => {
			getCardId().then(res => {
				tools.hideLoadingAlert();
				getLogOffInstAppy()
			})
		})
	})

	/**
	 * 获取OBU号 读OBU
	 */
	const getObuId = () => {
		return new Promise(resolve => {
			console.log('======获取OBU号======')
			let cmdArray = [cmd.HOME_DIRECTORY, cmd.OBU_SYSTEM_FILE, cmd.RANDOM_NUMBER];
			tools.showLoadingAlert("正在执行指令");
			bluetoothUtil.transCmd(cmdArray, "20", function (res) {
				tools.hideLoadingAlert();
				var status = res[1].substring(res[1].length - 4, res[1].length);
				console.log('获取OBU号执行结果' + status)
				//第一次获取随机数
				if (status == "9000") {
					obu.obuId = res[1].substring(20, 36);
					obu.vin = res[1].substring(18, 20);
					obu.version = res[1].substring(18, 19) >= 4 ? "4x" : "2x";
					resolve(obu)
					return
				} else {
					alertF("CMD_READBINARY指令长度不符" + res[2]);
					tools.hideLoadingAlert()
				}
				alertF("CMD_READBINARY指令长度不符" + res[2]);
				tools.hideLoadingAlert()
			});
		})
	};
	
	const getCardId = () => {
		return new Promise(resolve => {
			//执行0015文件
			tools.showLoadingAlert("执行指令");
			let cmdArr = [cmd.HOME_DIRECTORY, cmd.APPLICATION_DIRECTORY, cmd.CMD_READBINARY, cmd.CMD_GETBALANCE];
			bluetoothUtil.transCmd(cmdArr, '10', function(res) { //10：写卡   20：写OBU
				console.log("5201", res)
				let str = res[2].substring(res[2].length - 4, res[2].length); //判断是否为9000
				let str3 = res[3].substring(res[3].length - 4, res[3].length); //判断是否为9000
				if (str == "9000" || str3 == "9000") {
					if (res[2].length > 86 || res[3] >= 12) {
						card.cardId = res[2].substring(20, 40);
						// startHeartbeat()
						resolve(card)
					} else {
						alertF("CMD_READBINARY指令长度不符" + res[2]);
						tools.hideLoadingAlert()
					}
					return;
				}
				alertF("CMD_READBINARY指令长度不符" + res[2]);
				tools.hideLoadingAlert()
			})
		})
	};
	
	//提示对话框
	const alertF = (msg) => {
		//隐藏加载框
		tools.hideLoadingAlert();
		//提示对话框
		tools.showModalAlert(msg);
		stopHeartbeat();
	}
	
	interface command {
		cmd: string,
		cmdType: string,
		stepNo: number,
		transOrderId: string
	}
	
	// 初始化指令
	const getLogOffInstAppy = () => {
		let options = {
			data: {
				cardId: card.cardId,
				obuId: obu.obuId,
				cancelOrRestore: '1' // 1 注销 2 恢复
			}
		}
		state.showProgress = true
		setProgressNum()
		requestNew(logOffInstAppy, options).then((res: command) => {
			const datas = res;
			invokeCmd(logOffInstCallBack, datas, bluetoothUtil, async (result) => {
				// 注销完成
				state.isSuccess = true
				clearProgressNum()
				state.progressNum = 100
				uni.showToast({
					title: '执行完成'
				})
				setTimeout(() => {
					logOffOver()
				}, 1500)
			})
		}).catch(() => {
			clearProgressNum()
			stopHeartbeat()
			state.showProgress = false
		})
	}
	
	const setProgressNum = () => {
		progressNumInter = setInterval(() => {
			if (state.isSuccess) {
				clearProgressNum()
			} else {
				if (state.progressNum < 90) {
					state.progressNum += 1
				} else {
					clearProgressNum()
				}
			}
		}, 1000)
	}
	
	const clearProgressNum = () => {
		clearInterval(progressNumInter)
		progressNumInter = null
	}
	
	
	const showModals = (msg) => {
		uni.showModal({
			title: '提示',
			content: msg,
			showCancel: false
		});
	}
	
	onUnload(() => {
		clearProgressNum()
	})
	
</script>
<style lang="scss" scoped>
	.log-off-content{
		position: fixed;
		top: 0;
		left: 0;
		right: 0;
		bottom: 0;
		background-color: rgba(0, 0, 0, 0.25);
		display: flex;
		align-items: center;
		justify-content: center;
	}
</style>