<template>
	<view class="containers">
		<view class="sec_info">
			<view class="info_txt">信息确认</view>
			<view class="info_plate">
				<text>车牌号码</text>
				<text>{{ fileDataStrings.vehiclePlate }}</text>
			</view>
			<view class="info_plate">
				<text>车牌颜色</text>
				<text>{{ fileDataStrings.vehiclePlateColorStr }}</text>
			</view>
			<view class="info_plate">
				<text>手机号码</text>
				<text>{{ fileDataStrings.customerTel }}</text>
			</view>
			<view class="info_plate" style="border: none" v-if="fileDataStrings.cardId">
				<text>卡号</text>
				<text>{{ fileDataStrings.cardId }}</text>
			</view>
			<view class="info_plate" v-if="fileDataStrings.obuId">
				<text>OBU号</text>
				<text>{{ fileDataStrings.obuId }}</text>
			</view>
			<view class="info_plate">
				<text>收费车型</text>
				<text>{{ fileDataStrings.vehicleClassStr }}</text>
			</view>
		</view>
		<view class="up_btn" v-if="state.showBtn">
			<button aria-disabled="true" @click="btn" v-if="!state.isSuccess" :class="state.disabled?'button':'hui'">
				点击开始激活
			</button>
			<button aria-disabled="true" @click="back" v-else>
				点击返回首页
			</button>
		</view>
	</view>
	<!-- 激活成功popup -->
	<view v-if="state.showPopup" class="mask">
		<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>
	import {
		reactive,
		ref
	} from "vue";
	import {
		formatTime,
		formatTime2,
		expireDate,
		expireDate2,
		getFormatDate,
		msg,
		navTo
	} from "@/utils/utils";
	import {
		onLoad,
		onUnload
	} from '@dcloudio/uni-app'
	import {
		getItem
	} from "@/utils/storage";
	import {
		requestNew,
		corefn
	} from "@/utils/network/request.js";
	import {
		IntegerToHexString,
	} from "@/utils/util/fileData.js";
	import {
		issueApply,
		issueCallback,
		orderDetailQuery,
		errorLogAdd,
		cardObuQuery,
		cardObuQueryinLog,
		obuFileDataDecrypt,
		vfjObuActive
	} from "@/utils/network/api";
	import {
		agentId
	} from "@/utils/network/difference";
	import {
		startHeartbeat,
		stopHeartbeat
	} from "@/pages/bluetooth/heartbeatService"
	const cmd = require("../../../static/etcUtil/cmdConfig.js");
	const tools = require("../../../static/etcUtil/tools.js");
	const bluetoothUtil = require("../../../static/etcUtil/index.js");

	import activeSuccess from "./components/popup-device-active-success";
	const datas = require("../../../static/etcUtil/datas.js");
	import {
		getVehicleType
	} from "@/subpackage/after-sale/js/vehicleType.js"
	import {
		getVehiclePlateColor
	} from "@/datas/vehiclePlateColor";
	import {
		searchVehicleInfoQuery
	} from "@/subpackage/after-sale/js/publicRequest";
	import {
		decryptCardVehicleInformation
	} from "@/datas/publicRequest";
	import {
		channelId
	} from "@/utils/network/difference";
	import {
		getCodeName, getDicWithType
	} from "@/datas/queryKey.js";
	const state = reactive({
		orderId: "",
		id: "",
		cardStatus: "",
		obuStatus: "",
		isSuccess: false, //是否激活成功
		showPopup: false,
		transfer: 0, //0  是原来的激活   1  是过户激活
		showBtn: true,
		disabled: true,
		progressNum: 0,
		CardVersion: "",
		ObuVersion: "",
		ChipSn: ""
	})
	
	const getCurrentActivateData = () => {
		let activateData = getItem('currentActivateData');
		if(activateData) {
			fileDataStrings.vehiclePlate = activateData.vehiclePlate;
			fileDataStrings.vehicleId = activateData.vehicleId;
			fileDataStrings.vehiclePlateColorStr = activateData.vehiclePlateColorStr;
			fileDataStrings.customerTel = activateData.customerTel;
			fileDataStrings.vehicleClass = activateData.vehicleType;
			fileDataStrings.vehicleClassStr = getCodeName('VEHICLE_TYPE', activateData.vehicleType);
			fileDataStrings.obuId = activateData.obuId;
			fileDataStrings.cardId = activateData.cardId;
		}
	}

	onLoad((option) => {
		//读取传入 存储的数据orderInfo
		getCurrentActivateData()
		let orderData = getItem("orderInfo");
		state.id = orderData.id;
		console.log(state);
		state.transfer = Number(option.transfer)
		//获取订单详情
		if (option.transfer == '1') {
			getOrderDetails(orderData.orderId);
		} else {
			getObuId();
		}
		
		
		console.log("state.transfer", state.transfer, state.transfer == 0, state.transfer == 1, getItem(
			"orderInfo"))
	})

	// ====================== 页面卸载时清理资源 ======================
	onUnload(() => {
		stopHeartbeat();
		// 实际项目中需调用 uni.closeBLEConnection 断开连接
		console.log('页面卸载，清理资源');
	});

	const card = reactive({
		cardId: "",
		cardNo: "",
		startTime: "",
		endTime: "",
		userName: "",
		userNameStr: "",
		idNum: "",
		idNumStr: "",
		vehiclePlate: "",
		vehiclePlateColor: "",
		color: "",
		colorStr: "",
		version: "",
		type: "",
		typeStr: "",
		favourable: "",
		favourableStr: "",
		money: "",
		v_userType: ""
	});
	const obu = reactive({
		obuId: "",
		num: "",
		startTime: "",
		endTime: "",
		version: "",
		approvedCount: "",
		axleCount: "",
		axleDistance: "",
		engineNum: "",
		type: "",
		typeStr: "",
		userType: "",
		userTypeStr: "",
		vehiclePlate: "",
		vehiclePlateColor: "",
		vehiclePlateColorStr: "",
		vin: "",
		wheelCount: "",
		isJH: "",
		isJHStr: "",
		outsideDimensions: "",
		loadStatus: ""
	});
	let cmdRandNum = '';
	let orderInfo = {};

	const fileDataStrings = reactive({
		approvedCount: 0, //核载人数
		cardId: "", //卡号
		obuId: "", //obu号
		packageNum: "", //套餐编号
		axleCount: 0, //轴数
		axleDistance: "", //轴距
		engineNum: "", //发动机
		vehicleVin: "",
		vehicleEngineNum: "",
		cardStatus: "",
		obuStatus: "",
		type: 0, //类型
		userType: 0, //用户类型
		vehiclePlate: "", //车牌
		vehiclePlateColor: 0, //车牌颜色
		vehicleDimensions: "",
		wheelCount: 0, //车轮数
		vehicleIdNo: "", //车牌号
		vehiclePlateColorStr: "",
		customerTel: "",
		customerId: "",
		orderId: "",
		vehicleType: '',
		vehicleClass: '',
		vehicleClassStr: "",
		vehicleId: '',
	});

	function cmdResult1() {
		// tools.showLoadingAlert('正在激活，请等待')
		state.progressNum = 10
		const options = {
			type: 2, //type: 2,JSON格式提交数据(默认表单形式提交)
			showLoading: false,
			data: {
				orderNo: orderInfo.orderNo,
				issueType: state.transfer ? 2 : 1, //1正常激活   2 过户激活
				cardId: card.cardId,
				cardVersion: state.CardVersion,
				obuVersion: obu.version,
				obuId: obu.obuId
			}, //请求参数
			method: "POST", //提交方式(默认POST)
		};
		console.log("options==", options)
		console.log("二发指令申请==前,/iaw/issue/order/issueApply", new Date(), options)
		//BDS-二发指令申请  
		requestNew(issueApply, options)
			.then((res) => {
				console.log("在线激活 请求");
				console.log(res);
				const datas = res;
				console.log("二发指令申请==后,/iaw/issue/order/issueApply", new Date(), res)
				bluetoothUtil.transCmd(datas.cmd.split(','), datas.cmdType == 'CARD' ? '10' : '20', function(res) {
					implementCmd(datas.transOrderId, datas.cmd, res.toString(), datas.stepNo)
				}, (err) => {
					showModals(err.msg)
					console.log("err", err)
					errorLog(datas.cmd, JSON.stringify(err), datas.stepNo)
					tools.hideLoadingAlert();

					state.disabled = true
				});
			})
			.catch((err) => {
				console.log(err);
				tools.hideLoadingAlert();

				state.disabled = true
			});
	}

	function implementCmd(transOrderId, cmd, cmdResult, stepNo) {
		console.log("datas.stepNo1", stepNo)
		if (state.progressNum > 100) {
			state.progressNum = Number(stepNo) * 10 + 10
		} else {
			state.progressNum = 100
		}
		const options = {
			type: 2, //type: 2,JSON格式提交数据(默认表单形式提交)
			showLoading: false,
			data: {
				transOrderId, //步骤号
				cmd,
				cmdResult,
				stepNo,
				mpOpenId: getItem('mpOpenId') //公众号openid
			}, //请求参数
			method: "POST", //提交方式(默认POST)
		};
		console.log("options2222", options)
		console.log("二发指令回传==前,/iaw/issue/order/issueCallback", new Date(), options)
		//BDS-二发指令回传 
		requestNew(issueCallback, options)
			.then((res) => {
				console.log("BDS-二发指令回传 ", res);
				const datas = res;
				console.log("二发指令回传==后,/iaw/issue/order/issueCallback", new Date(), res)
				console.log("在线激活 请求", datas);
				if (datas.stepNo == 100) {
					state.disabled = true
					tools.hideLoadingAlert();
					state.progressNum = 100
					setTimeout(() => {
						state.showPopup = false
					}, 1000)
					setTimeout(() => {
						msg("激活成功", {
							'icon': 'success',
							'duration': 3000
						})
					}, 2000)
					setTimeout(() => {
						getCardIdCommit()
					}, 5000)
				} else {
					console.log("datas.stepNo", datas.stepNo)
					bluetoothUtil.transCmd(datas.cmd.split(','), datas.cmdType == 'CARD' ? '10' : '20', function(res) {
						implementCmd(transOrderId, datas.cmd, res.toString(), datas.stepNo)
					}, (err) => {
						console.log("err", err)
						state.showPopup = false
						state.disabled = true
						errorLog(datas.cmd, JSON.stringify(err), datas.stepNo)
						showModals(err.msg)
					});
				}
			})
			.catch((err) => {
				console.log(err);
				tools.hideLoadingAlert();
				state.showPopup = false
				state.disabled = true
			});
	}

	//开始激活 按钮事件
	const btn = () => {
		console.log('activateBtn', state)
		
		if (!state.disabled) {
			return;
		}
		if (state.CardVersion == '48' || state.CardVersion == '49' || state.ObuVersion == '48' || state.ObuVersion == '49') {
			// 是48,49 先密钥升级再激活
			obuUpdate();
		} else {
			// 不是48,49直接激活
			activateQuqet()
		}

	};
	const activateQuqet = () => {
		state.disabled = false
		console.log('orderInfo参数', orderInfo, state.disabled)
		stopHeartbeat();
		if(state.transfer == '1') {
			cmdResult1()
		} else {
			cmdResult2()
		}
		// cmdResult1()
	}
	
	const cmdResult2 = () => {
		let cmdArr = [cmd.HOME_DIRECTORY, cmd.RANDOM_NUMBER];
		bluetoothUtil.transCmd(cmdArr, '20', function (res) {
			var str = res[1].substring(res[1].length - 4, res[1].length);
			if (str == "9000") {
				let cmdRandNum = res[1].substring(0, res[1].length - 4);
				getObuActivation(cmdRandNum);
			} else {
				tools.alertF("RANDOM_NUMBER指令长度不符" + res[1]);
			}
		})
		
	}
	
	const getObuActivation = (cmdRandNumSecond) => {
		const options = {
			type: 2,
			data: {
				"cardId": card.cardId,
				"obuId": obu.obuId,
				"random": cmdRandNumSecond,
				"vehicleId": fileDataStrings.vehicleId,
				"vehicleType": fileDataStrings.vehicleClass
			},
			method: "POST",
			showLoading: false,
		}
		tools.showLoadingAlert("执行指令");
		requestNew(vfjObuActive, options)
			.then((res) => {
				tools.hideLoadingAlert();
				console.log("在线激活 请求");
				console.log(res);
				const datas = res;
				let cmdArr = datas.apdu.split(',')
				tools.showLoadingAlert("执行指令");
				bluetoothUtil.transCmd(cmdArr, "20", function (res) {
					tools.hideLoadingAlert();
					console.log(res);
					if (res[0] == "9000") {
						msg('激活成功');
						// navTo(`/pages/order/order?index=${0}`);
						uni.switchTab({
							url: '/pages/index/index'
						}).then(res => {
							navTo(`/pages/order/order?index=${0}`)
						})
					} else {
						msg(`激活失败，提示码：${res[0]}`);
					}
				});
			})
			.catch((err) => {
				tools.hideLoadingAlert();
			});
	}
	
	//获取订单详情
	const getOrderDetails = (orderId) => {
		console.log('======获取订单信息======')
		const options = {
			type: 2,
			data: {
				orderNo: orderId
			},
			method: "POST",
			showLoading: false,
		};
		state.disabled = false
		requestNew(orderDetailQuery, options).then((res) => {
			console.log("orderInfo", res);
			orderInfo = res;
			console.log("orderInfores", res);
			if (orderInfo) {
				fileDataStrings.userType = orderInfo.userType; //用户类型
				fileDataStrings.cardId = orderInfo.cardId;
				fileDataStrings.packageNum = orderInfo.packageNum;
				fileDataStrings.obuId = orderInfo.obuId;
				fileDataStrings.customerTel = orderInfo.customerTel;
				fileDataStrings.customerId = orderInfo.customerId;
				fileDataStrings.orderId = orderInfo.orderNo;
				fileDataStrings.vehiclePlateColorStr = getVehiclePlateColor(orderInfo
					.vehiclePlateColor);
				fileDataStrings.vehiclePlate = orderInfo.vehiclePlate; //车牌
				fileDataStrings.vehicleClass = orderInfo.vehicleClass;
				fileDataStrings.vehicleClassStr = getCodeName('VEHICLE_TYPE', activateData.vehicleClass);
			}
		});
		getObuId();
	};

	/**
	 * 获取OBU号 读OBU
	 */
	const getObuId = () => {
		console.log('======获取OBU号======')
		let cmdArray = [cmd.HOME_DIRECTORY, cmd.OBU_SYSTEM_FILE, cmd.RANDOM_NUMBER];
		bluetoothUtil.transCmd(cmdArray, "20", function(res) {
			var status = res[1].substring(res[1].length - 4, res[1].length);
			console.log('获取OBU号执行结果' + status, res)
			//第一次获取随机数
			if (status == "9000") {
				state.disabled = true
				obu.obuId = res[1].substring(20, 36);
				if(fileDataStrings.obuId && fileDataStrings.obuId != obu.obuId ) {
					showModals('车牌obuId与设备obuId不符，请重新选择')
					return;
				}
				// obu.obuId = '5201250802001105';
				obu.vin = res[1].substring(18, 20);
				obu.version = res[1].substring(18, 20);
				state.ObuVersion = res[1].substring(18, 20)
				state.ChipSn = res[1].substring(0, 8)
				cmdRandNum = res[2].substring(0, res[2].length - 4);
				getCardId()
				
			} else {
				showModals('获取设备信息错误！')
			}
		}, () => {
			showModals('获取设备信息错误')
		});
	};

	function showModals(msg) {
		uni.showModal({
			title: '提示',
			content: msg,
			showCancel: false,
			success: function(res) {
				if (res.confirm) {
					uni.navigateBack()
					console.log('用户点击确定1');
				} else if (res.cancel) {
					console.log('用户点击取消1');
				}
			}
		});
	}
	const back = () => {
		uni.switchTab({
			url: "/pages/index/index"
		});
	}
	const getCardId = () => {
		//执行0015文件
		tools.showLoadingAlert("执行指令");

		let cmdArr = [cmd.HOME_DIRECTORY, cmd.APPLICATION_DIRECTORY, cmd.CMD_READBINARY, cmd.CMD_GETBALANCE];
		console.log(cmdArr);
		console.log(bluetoothUtil);
		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);
					if(fileDataStrings.cardId && fileDataStrings.cardId != card.cardId ) {
						showModals('车牌cardId与设备cardId不符，请重新选择')
						return;
					}
					// card.cardId = '52012511110201724155';
					state.CardVersion = res[2].substring(18, 20),
						tools.hideLoadingAlert();
					state.showBtn = true
					startHeartbeat()
				} else {
					alertF("CMD_READBINARY指令长度不符" + res[2]);
				}
				return;
			}
			alertF("CMD_READBINARY指令长度不符" + res[2]);

		})
	};
	const errorLog = (cmd, error, step) => {
		console.log('激活异常提交')
		const options = {
			type: 2,
			data: {
				cardId: card.cardId,
				obuId: obu.obuId,
				orderType: "1",
				factory: datas.getData("deviceName") + "_" + datas.getData("deviceNameZW"),
				orderNo: orderInfo.orderNo,
				cmd,
				error,
				step
			},
			method: "POST",
			showLoading: false,
		};
		requestNew(errorLogAdd, options).then((res) => {
			console.log("错误提交成功", res);

		});
	};
	/**
	 * 获取卡号
	 */
	const getCardIdCommit = () => {
		//执行0015文件
		tools.showLoadingAlert("执行指令");
		let cmdArr = [cmd.HOME_DIRECTORY, cmd.APPLICATION_DIRECTORY, cmd.CMD_READBINARY, cmd.CMD_GETBALANCE];
		console.log(cmdArr);
		console.log(bluetoothUtil);
		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) {
					console.log("res[2]", res[2].substring(84, 86), getVehiclePlateColor(parseInt(res[2]
						.substring(82, 84), 16)), res[2].substring(18, 19))
					card.cardNo = res[2].substring(20, 40);
					card.startTime = res[2].substring(40, 48);
					card.endTime = res[2].substring(48, 56);
					card.version = res[2].substring(18, 20);
					card.money = res[3].substring(0, 8);
					card.v_userType = parseInt(res[2].substring(80, 82), 16);
					console.log("card.v_userType", card.v_userType)
					decryptCardVehicleInformation(res[2].substring(56, 80), function(res) {
						card.vehiclePlate = res;
					});
					console.log("res[2].substring(18, 19)", res[2].substring(18, 20))
					if (res[2].substring(18, 19) >= 4) {
						//4x卡
						card.type = parseInt(res[2].substring(84, 86), 16);
						card.typeStr = getVehicleType(parseInt(res[2].substring(84, 86), 16));
						card.color = parseInt(res[2].substring(82, 84), 16)
						card.colorStr = getVehiclePlateColor(parseInt(res[2].substring(82, 84), 16))
					} else {
						//2x卡--获取车牌颜色
						card.type = "--";
						card.color = parseInt(res[2].substring(82, 84), 16)
						card.colorStr = getVehiclePlateColor(parseInt(res[2].substring(82, 84), 16))
						card.typeStr = getVehicleType(parseInt(res[2].substring(84, 86), 16));
					}
					state.vehicleId = card.vehiclePlate + "_" + parseInt(res[2].substring(82, 84), 16)
					// 读卡信息
					//执行0016文件
					let arr = [cmd.HOME_DIRECTORY, cmd.PERSONAL_INFORMATION]
					bluetoothUtil.transCmd(arr, '10', function(res) {
						let str2 = res[1].substring(res[1].length - 4, res[1].length);
						if (str2 == "9000") {
							if (res[1].length > 108) {
								console.log("res====", res)
								decryptCardVehicleInformation(res[1].substring(4, 44), function(res) {
									card.userName = res; //姓名
									card.userNameStr = card.userName[0] + '*'.repeat(card
										.userName.length - 1)
								});


								decryptCardVehicleInformation(res[1].substring(44, 108), function(
									res) {
									card.idNum = res; //身份证号码		
									card.idNumStr = res.replace(/^\d{14}/, '**************')
								});

								//获取是否有优惠
								let cmdArr3 = [cmd.HOME_DIRECTORY, cmd.APPLICATION_DIRECTORY, cmd
									.CMD_00B08E0000
								];
								bluetoothUtil.transCmd(cmdArr3, '10', function(res) {
									let str3 = res[2].substring(res[2].length - 4, res[2]
										.length);
									if (str3 == "9000") {
										if (res[2].length > 131) {
											let _str = parseInt(res[2].substring(129, 130),
												16);
											card.favourable = _str
											switch (_str) {
												case 0:
													card.favourableStr = "否";
													break;
												case 1:
													card.favourableStr = "是";
													break;
												default:
													card.favourableStr = '未知' + "_" + _str;
													break;
											}
											//回调读取OBU指令
											getObuIdCommit()
											tools.hideLoadingAlert();

										} else {
											alertF("CMD_00B08E0000指令长度不符" + res[2]);
										}
										return;
									}
									alertF(cmd.PERSONAL_INFORMATION + "_" + str);
								})
							} else {
								alertF("PERSONAL_INFORMATION指令长度不符" + res[1]);
							}
							return;
						}
						alertF("PERSONAL_INFORMATION指令长度不符" + res[1]);
					})
				} else {
					alertF("CMD_READBINARY指令长度不符" + res[2]);
				}
				return;
			}
			alertF("CMD_READBINARY指令长度不符" + res[2]);

		})
	};
	/**
	 * 获取OBU号
	 */
	const getObuIdCommit = () => {
		tools.showLoadingAlert("执行指令");
		let cmdArr = [cmd.HOME_DIRECTORY, cmd.OBU_SYSTEM_FILE];
		bluetoothUtil.transCmd(cmdArr, '20', function(res) {
			let str = res[1].substring(res[1].length - 4, res[1].length);
			if (str == "9000") {
				if (res[1].length > 52) {

					obu.num = res[1].substring(20, 36);
					obu.startTime = res[1].substring(36, 44);
					obu.endTime = res[1].substring(44, 52);
					obu.version = res[1].substring(18, 20);
					obu.isJH = res[1].substring(53, 54)
					obu.isJHStr = res[1].substring(53, 54) == "1" ? "是" : res[1].substring(53, 54) == "0" ?
						"否" : "其他：" + res[1].substring(53, 54);
					obu.loadStatus = res[1].substring(52, 54) == '01' ? '正常' : '已拆卸',

						console.log("开始执行车辆信息识读");
					let rand = res[1].substring(18, 20) >= 50 ? '40' : '00';
					var arr = [cmd.OBU_DF01, '00B400000A000000000000000045' + rand];
					bluetoothUtil.transCmd(arr, '20', function(res) {
						console.log(res);
						console.log("开始执行车辆信息识读成功");
						let str2 = res[1].substring(res[1].length - 4, res[1].length);
						let obuVersion = res[1].substring(18, 20);
						let keyIndex = obuVersion > 50 ? '40' : '00';
						let reqType = '00';
						let proviceCode = '5201';
						if (str2 == "9000") {
							console.log("===========", obu.num, res[1].substring(0, res[1].length - 4))
							decryptObuVehicleInfo(obu.num, res[1].substring(0, res[1].length - 4),
								obuVersion, rand, reqType, proviceCode,
								function(res) {

									obu.approvedCount = res.approvedCount;
									obu.axleCount = res.axleCount;
									obu.axleDistance = res.axleDistance;
									obu.engineNum = res.engineNumber.replace(/\u0000/g, '');
									obu.type = res.collectionType;
									obu.typeStr = getVehicleType(res.collectionType);
									obu.userType = res.userType;
									if (res.userType == 0) {
										obu.userTypeStr = "普通车";
									} else if (res.userType == 6) {
										obu.userTypeStr = "公务车";
									}
									obu.vehiclePlate = res.vehiclePlate.replace(/\u0000/g, '');
									//获取车牌颜色
									obu.vehiclePlateColor = res.vehiclePlateColor;
									obu.vehiclePlateColorStr = getVehiclePlateColor(res
										.vehiclePlateColor);
									obu.vin = res.vin.replace(/\u0000/g, '');
									obu.wheelCount = res.wheelsCount;
									obu.outsideDimensions = res.carLong + "x" + res.carWidth +
										"x" + res.carHeight
									getObuList();


									tools.hideLoadingAlert();
								});
							//断开蓝牙
							bluetoothUtil.disconnectDevice();
							tools.showToastAlert("蓝牙已断开");
							console.log('蓝牙已断开=========')
							return;
						}
						alertF("OBU_00B400000A+rand+OBU_4F00指令长度不符" + res[1]);
					})

				} else {
					alertF("OBU_SYSTEM_FILE指令长度不符" + res[1]);
				}
				return;
			}
			alertF("OBU_SYSTEM_FILE指令长度不符" + res[1]);
		})
	};
	const getObuList = () => {
		var data = {
			obuId: obu.num,
			cardId: card.cardNo,
		};
		const options = {
			type: 2,
			data: data,
			method: "POST",
			showLoading: true,
		};
		requestNew(cardObuQuery, options).then((res) => {
			tools.hideLoadingAlert();
			let result = res;
			state.obuStatus = result.obuStatus ? result.obuStatus : ""
			state.cardStatus = result.cardStatus
			if (result.cardType == 1 && result.debitType == 1) {
				state.cardTypeName = "预存卡"
				card['cardTypeName'] = 3
			} else if (result.cardType == 2) {
				state.cardTypeName = "储值卡"
				card['cardTypeName'] = 2
			} else {
				state.cardTypeName = "记账卡"
				card['cardTypeName'] = 1
			}
			// 卡签提交得信息
			card['cardStatus'] = result.cardStatus
			obu['obuStatus'] = result.obuStatus ? result.obuStatus : ""
			cardObuMsgUp()
		})
	}
	// 签信息提交日志记录
	const cardObuMsgUp = () => {
		var data = {
			cardLogInfo: card,
			obuLogInfo: obu,
			type: "active"
		};
		const options = {
			type: 2,
			data: data,
			method: "POST",
			showLoading: true,
		};
		requestNew(cardObuQueryinLog, options).then((res) => {
			tools.hideLoadingAlert();
			navTo(`/subpackage/after-sale/activation/result`)
			console.log("提交成功")
		})
	}
	/**
	 * 解密OBU车辆信息
	 */
	const decryptObuVehicleInfo = (num, data, obuVersion, keyIndex, reqType, proviceCode, func) => {
		const options = {
			type: 2,
			data: {
				contractSN: num,
				cipherData: data,
				reqType: reqType,
				keyIndex: keyIndex,
				proviceCode: proviceCode
			},
			method: "POST",
			showLoading: true,
		};
		requestNew(obuFileDataDecrypt, options).then((res) => {
			console.log("obuFileDataDecrypt", res)
			const data = res
			func(data)
		});
	};
	//提示对话框
	const alertF = (msg) => {

		//隐藏加载框
		tools.hideLoadingAlert();

		//提示对话框
		tools.showModalAlert(msg);
		stopHeartbeat();
	}
	async function obuUpdate() {
		tools.showLoadingAlert('升级中');
		//升级类OBU
		const applyData = await apply4Upgrade({
			contractSn: obu.obuId, //OBU合同序列号 16位
			chipSn: state.ChipSn, //OBU晶片序列号 8位
			issueMode: 'UPG', //发行模式
			issueType: 'SCOBU', //发行发行类型
			cardVersion: state.CardVersion, //卡版本号
			obuVersion: state.ObuVersion //OBU版本号
		});
		if (!applyData) return false;
		console.log("applyData", applyData)
		if (state.CardVersion == '48' || state.CardVersion == '49') {
			const updateEsDat = await updateEs('GEN_OBEIC_UPG', applyData);
			if (!updateEsDat) return false;
		}
		if (state.ObuVersion == '48' || state.ObuVersion == '49') {
			const updateEsDatTwo = await updateEs('GEN_OBESAM_UPG', applyData);
			if (!updateEsDatTwo) return false;
		}
		const upgradeDoneData = await upgradeDone({
			issueSerialNo: applyData.issueSerialNo, //发行订单号
		});
		if (!upgradeDoneData) return false;
		connectPrefixName = datas.getData("connectPrefixName");
		console.log(connectPrefixName);
		activateQuqet();
	}

	function apply4Upgrade(params) {
		return new Promise((resolve) => {
			corefn('IF01001202504281152', params, function(res) {
				console.log("成功1", res)
				if (res.rc != "00") {
					tools.alertF(res.rm);
					return;
				}
				console.log("成功", res)
				resolve(res.rd)
			})
		})
	}
	//获取发行脚本指令
	async function updateEs(type, applyData) {
		console.log('------updateEs------');
		tools.showLoadingAlert('升级中');
		//获取发行脚本指令
		const getCommanData = await getCommands({
			cardNo: applyData.cardNo, //卡片序列号
			wareId: type, //OBU的物料代码 OBE-SAM通道 GEN_OBESAM_UPG     OBE-IC通道 GEN_OBEIC_UPG
			issueSerialNo: applyData.issueSerialNo, //发行订单号
		});
		if (!getCommanData) return false;
		//指令解析
		const result = getCommanData.commands;
		const array = result.split('~');
		let cmdType = type == 'GEN_OBESAM_UPG' ? '20' : '10';
		for (const element of array) {
			console.log('updateEs', element, cmdType);
			tools.showLoadingAlert('升级中');
			// 让出主线程，确保UI更新
			await new Promise(resolve => setTimeout(resolve, 0));
			console.log("进来了", element.charAt(0), )
			if (element.charAt(0) === 'D' || element.charAt(0) === 'R') {
				await processDirectCommand(element, cmdType);
			} else if (element.charAt(0) === 'K') {
				await processKeyExchange(element, cmdType, applyData);
			} else if (element.charAt(0) === 'E') {
				await processExtAuth(element, cmdType, applyData);
			} else if (element === 'SESAM') {
				cmdType = '20';
			} else {
				cmdType = '10';
			}
		}
		return true;
	}

	function getCommands(params) {
		return new Promise((resolve, reject) => {
			corefn('IF01001202504281153', params, function(res) {
				console.log("成功1", res)
				if (res.rc != "00") {
					tools.alertF(res.rm);
					return;
				}
				console.log("成功", res)
				resolve(res.rd)
			})
		})
	}
	// 提取出来的子函数
	async function processDirectCommand(element, cmdType) {
		// 添加随机延迟，避免连续请求
		return bluetoothUtil.transCmdArrAfter(element.substring(1), cmdType);
	}
	async function processKeyExchange(element, cmdType, applyData) {
		const ranData = await bluetoothUtil.transCmdArrAfter('0084000004', cmdType);
		console.log("ranData", ranData)
		const exchangeKeyData = await exchangeKey({
			key: element.substring(1),
			random: ranData['0084000004'][0].substring(0, 8),
			issueSerialNo: applyData.issueSerialNo
		});

		if (!exchangeKeyData) throw new Error('密钥置换失败');
		console.log("exchangeKeyData", exchangeKeyData)
		return bluetoothUtil.transCmdArrAfter(exchangeKeyData.apdu, cmdType);
	}
	async function processExtAuth(element, cmdType, applyData) {
		const ranData = await bluetoothUtil.transCmdArrAfter('0084000004', cmdType);

		const extAuth4IssData = await extAuth4Iss({
			keyType: element.substring(1),
			random: ranData['0084000004'][0].substring(0, 8),
			issueSerialNo: applyData.issueSerialNo,
		});
		console.log("extAuth4IssData", extAuth4IssData)
		if (!extAuth4IssData) throw new Error('外部认证失败');
		return bluetoothUtil.transCmdArrAfter(extAuth4IssData.apdu, cmdType);
	}

	function extAuth4Iss(params) {
		console.log("params", params)
		return new Promise((resolve) => {
			corefn('IF01001202504281156', params, function(res) {
				console.log("成功1", res)
				if (res.rc != "00") {
					tools.alertF(res.rm);
					return;
				}
				console.log("成功", res)
				resolve(res.rd)
			})
		})
	}

	function exchangeKey(params) {
		return new Promise((resolve) => {
			corefn('IF01001202504281154', params, function(res) {
				console.log("成功1", res)
				if (res.rc != "00") {
					tools.alertF(res.rm);
					return;
				}
				console.log("成功", res)
				resolve(res.rd)
			})
		})
	}

	function upgradeDone(params) {
		return new Promise((resolve) => {
			corefn('IF01001202504281155', params, function(res) {
				console.log("成功1", res)
				if (res.rc != "00") {
					tools.alertF(res.rm);
					return;
				}
				console.log("成功", res)
				resolve(res.rd)
			})
		})
	}
</script>

<style>
	.containers {
		height: 100%;
		display: flex;
		flex-direction: column;
		align-items: center;
		justify-content: space-between;
		box-sizing: border-box;
	}

	.sec_info {
		width: 90%;
		height: auto;
		margin: 0 auto;
		box-shadow: 0rpx 6rpx 25rpx 0rpx rgba(0, 0, 0, 0.2);
		margin-top: 50rpx;
		border-radius: 20rpx;
	}

	.info_txt {
		width: 100%;
		height: 120rpx;
		line-height: 120rpx;
		text-align: center;
		color: #000;
		font-size: 36rpx;
		margin-bottom: 20rpx;
	}

	.info_plate {
		display: flex;
		flex-direction: row;
		width: 94%;
		height: 100rpx;
		margin: 0 auto;

		border-bottom: 2rpx solid #f2f2f2;
	}

	.info_plate text:nth-child(1) {
		height: 100rpx;
		text-align: left;
		line-height: 100rpx;
		font-size: 32rpx;
		color: #999;
	}

	.info_plate text:nth-child(2) {
		flex: 1;
		height: 100rpx;
		line-height: 100rpx;
		font-size: 32rpx;
		color: #333;
		margin-left: 50rpx;
		text-align: right;
	}

	/*提交按钮样式*/
	.up_btn {
		width: 85%;
		height: 100rpx;
		margin: 0 auto;
		margin-top: 50rpx;
		margin-bottom: 100rpx;
	}

	.up_btn button {
		width: 100%;
		height: 80rpx;
		line-height: 80rpx;
		color: white;
		font-size: 32rpx;
		text-align: center;
		background: linear-gradient(to right, #01243A, #004576);
		border-radius: 40rpx;
		outline: none;
		border: #4cd95f;
	}

	.button {
		width: 100%;
		height: 80rpx;
		line-height: 80rpx;
		color: white;
		font-size: 32rpx;
		text-align: center;
		background: linear-gradient(to left, #43a1e0 0%, #13e7c1 100%);
		border-radius: 40rpx;
		outline: none;
		border: #4cd95f;
	}

	.hui {
		width: 100%;
		height: 80rpx;
		line-height: 80rpx;
		color: white;
		font-size: 32rpx;
		text-align: center;
		background: linear-gradient(to left, #b9b9b9 0%, #e7e7e7 100%) !important;
		border-radius: 40rpx;
		outline: none;
		border: #4cd95f;
	}

	.up_btn button[disabled] {
		background-color: rgba(0, 191, 112, 0.5);
		color: white;
		font-size: 34rpx;
		border-radius: 20rpx;
	}

	.mask {
		width: 100%;
		height: 100vh;
		background: rgba(0, 0, 0, 0.63);
		position: fixed;
		left: 0;
		top: 0;
		right: 0;
		bottom: 0;
		z-index: 999;
		display: flex;
		align-items: center;
		justify-content: center;
	}
</style>