<!--设备选择 -->
<template>
	<view class="devices">
		<view class="hint">
			<view class="orange-txt as-layout-horizontal as-gravity-center-start tishi">
				<image :src="`${$imgUrl}common/icon-hint.png`" mode="aspectFill"></image>
				<view>温馨提示：</view>
			</view>
			<view>1、请在手机设置中打开NFC功能。</view>
			<view>2、请将ETC储值卡对准手机NFC天线位置（手机背部顶端），不灵敏或无响应时，请及时调整卡片位置。</view>
			<view>3、充值过程请保证卡片在手机背部，请勿移开。</view>
		</view>
		<view class="btn">
			<submit-button title="点击重新扫描NFC标签" @submit="load"></submit-button>
		</view>
	</view>
</template>
<script setup lang='ts'>
	import {
		onLoad,
		onReady
	} from "@dcloudio/uni-app";
	import {
		getItem,
		setItem
	} from "@/utils/storage";
	import {
		ref,
		reactive
	} from "vue";
	import * as NFCAPI from "../../static/nfc/NFCAPI.js";
	const tools = require("../../static/etcUtil/tools.js");
	// const NFCAPI = require('../../static/nfc/NFCAPI.js');
	const cmd = require("../../static/etcUtil/cmdConfig.js");
	const routeType = ref(null); //来源 1激活 2圈存 3信息重写 4信息读取  7消费明细修复
	const state = reactive({
		fee: "",
		cardId: "",
		rechargeMoney: "", //消费明细圈存传过来的金额
		orderNum: 0, //消费明细 传orderNum说明去支付
		payMoney: 0, //0 修复  1 支付
	});

	onLoad((option) => {

		routeType.value = option.routeType ? option.routeType : "1";
		setItem("routeType", option.routeType)
		state.cardId = option.cardId;
		if (option.fee) {
			state.fee = option.fee;
		}
		if (option.rechargeMoney) {
			state.rechargeMoney = option.rechargeMoney
		}
		if (option.orderNum) {
			state.orderNum = option.orderNum
		}
		if (option.payMoney) {
			state.payMoney = option.payMoney
		}
		console.log("传过来的参数", option, routeType.value)
	});

	//已准备
	onReady(() => {
		scanNfc();
	})

	function load() {
		scanNfc();
	}

	function scanNfc() {
		console.log("routeType.value1", routeType.value)
		tools.showLoadingAlert("扫描NFC中");


		//先断开所有设备
		NFCAPI.remove(() => {
			console.log("routeType.value2=======", routeType.value)
			//开始扫描设备
			// NFCAPI.startScanDeviceNfc(routeType.value, function(res, routeType) {
			// routeType.value = routeType
			const ConRouteType = routeType.value
			NFCAPI.startScanDevice((res) => {
				tools.hideLoadingAlert();
				console.log("routeType.value3===123===1111", ConRouteType, res.code)
				if (res.code != 0) {
					console.log("1111111")
					if (res.code == 1203) {
						tools.showModalAlert("扫描超时请重新扫描NFC标签", function(res) {
							if (res.confirm) {
								scanNfc();
							}
						}, null, "", true)
					} else {
						tools.showToastAlert(res.msg);
					}
					return;
				} else {
					console.log("2222", routeType.value)
					NFCAPI.connectDevice(function() {
						if (res.code != 0) {
							tools.showToastAlert(res.msg);
							return;
						}
						//获取卡信息
						transCmd(function(items) {
							getCardId(items, function() {
								console.log("routeType.value", routeType.value)
								if (getItem('routeType') == "2") {
									tools.toUrl(
										`/pages/recharge/recharge-weixin?connectSuccess=1&&cardId=${state.cardId}&&fee=${state.fee}&&transWay=nfc`
									); //跳转到圈存界面
								} else if (getItem('routeType') ==
									"7") { //7消费明细去修复nfc
									tools.toUrl(
										`/subpackage/personal-center/trapping-and-repairing/recharge-two?rechargeMoney=${state.rechargeMoney}&&orderNum=${state.orderNum}&&payMoney=${state.payMoney}&&transWay=nfc`
									); //跳转到圈存界面
								}
							})
						})
					});
				}
			})
		})
	}

	function getCardId(resultCmdArr: any, callback: any) {
		var that = this;
		console.log(resultCmdArr, '==============123')
		if (resultCmdArr.length == 4) {
			var str = resultCmdArr[2].substring(resultCmdArr[2].length - 4, resultCmdArr[2].length); //判断是否为9000
			var str3 = resultCmdArr[3].substring(resultCmdArr[3].length - 4, resultCmdArr[3].length); //判断是否为9000
			if (str == "9000" || str3 == "9000") {
				if (resultCmdArr[2].length > 86 || resultCmdArr[3] >= 12) {
					var card = {
						cardNo: resultCmdArr[2].substring(20, 40),
						startTime: resultCmdArr[2].substring(40, 48),
						endTime: resultCmdArr[2].substring(48, 56),
						version: resultCmdArr[2].substring(18, 19) >= 4 ? "4x" : "2x",
						money: hex2int(resultCmdArr[3].substring(0, 8)),
						v_userType: parseInt(resultCmdArr[2].substring(80, 82), 16)
					};
					console.log("写命令拿到卡号：" + JSON.stringify(card))
					var jizhangka = card.cardNo.substring(8, 10);
					if (jizhangka == '23') {
						console.log('记账卡');
						tools.alertFback("不支持记账卡圈存", function() {
							//返回首页
							uni.reLaunch({
								url: 'pages/index/index'
							})
						})
						return;
					}
					// that.setData({
					// 	cardNo: card.cardNo,
					// 	cardMoney: card.money > 0 ? card.money : 0,
					// })
					callback(card.cardNo);
				} else {
					tools.showToastAlert("CMD_READBINARY指令长度不符" + resultCmdArr[2]);
				}
				return;
			}
		} else {
			tools.showToastAlert("回包长度不符");
		}
	}

	/**
	 * 十六进制字符串转十进制
	 */
	function hex2int(hex) {
		var len = hex.length,
			a = new Array(len),
			code;
		for (var i = 0; i < len; i++) {
			code = hex.charCodeAt(i);
			if (48 <= code && code < 58) {
				code -= 48;
			} else {
				code = (code & 0xdf) - 65 + 10;
			}
			a[i] = code;
		}
		return a.reduce(function(acc, c) {
			acc = 16 * acc + c;
			return acc;
		}, 0);
	}

	function transCmd(callback: any) {
		tools.showLoadingAlert('透传指令中');
		var cmdArr = [cmd.HOME_DIRECTORY, cmd.APPLICATION_DIRECTORY, cmd.CMD_READBINARY, cmd.CMD_GETBALANCE];
		NFCAPI.transCmd(cmdArr, function(res) {
			tools.hideLoadingAlert();
			console.log(res);
			if (res.code == 0) {
				callback(res.data);
			} else {
				tools.showToastAlert(res.msg);
			}
		});
	}
</script>
<style lang='scss' scoped>
	image {
		width: 40rpx;
		height: 40rpx;
		margin-right: 20rpx;
	}

	.devices {
		padding: 30rpx;
	}

	.btn {
		margin-top: 30rpx;
	}

	.tishi {
		margin-bottom: 20rpx;
	}
</style>