<template>
	<view class="wrapper" v-if="state.haveData">
		<!-- 背景颜色充满屏 -->
		<view class="bg-color"></view>
		<!-- 补卡额订单列表-->

		<view class="list-wrap">
			<view class="card-info" v-for="(item,index) in state.list" :key="item.id">
				<view class="info-wrap">
					<view class="info-left">
						<view class="info-left-text">
							<text class="label">车牌号：</text>
							<text class="val">{{item.vehiclePlate}}</text>
						</view>
						<view>
							<text class="label">ETC卡号：</text>
							<text class="val">{{item.cardId}}</text>
						</view>
					</view>
					<view class="info-right">
						<view class="price-label">
							交易金额
						</view>
						<view class="price-val">
							<u-icon name="rmb"></u-icon>
							<text class="price-val-text">{{item.cardBalance/100}}</text>
						</view>
					</view>
				</view>
				<view class="btn-wrap">
					<view>
						<text v-if="item.status === 1" class="status-wrap">审核进度：<text>已进行</text></text>
						<text v-if="item.status === 2" class="status-wrap">审核进度：<text
								class="status-text">未进行</text></text>
						<text v-if="item.status === -1" class="status-wrap">审核进度：<text>驳回</text></text>
						<text v-if="item.status === 3" class="status-wrap">审核进度：<text>待审核</text></text>
					</view>
					<view class="btn-1 btn" v-if="item.status === 2" @click="refundTypeAction(item)">圈存</view>
					<!-- <view class="btn-1 btn" v-if="item.status === 1" @click="toApply(item)">补卡额申请</view>
					<view class="btn-1 btn" v-if="item.status === 2" @click="toView(item)">查看进度</view>
					<view class="btn-1 btn" v-if="item.status === 3" @click="toEvaluate(item)">去评价</view> -->
				</view>
			</view>

		</view>
	</view>
	<view class="no" v-if="state.list.length==0">暂无补卡额圈存数据</view>
</template>

<script lang="ts" setup>
	import { reactive, ref } from "vue";
	import { onLoad, onUnload } from "@dcloudio/uni-app";
	import { request } from "@/utils/network/request.js";
	import { queryCardLimit, quanCheck, quanApply, quanConfirm, quanXf } from "@/utils/network/api";
	import { stringToJson } from "@/utils/network/encryption";
	import { msg } from "@/utils/utils";
	const cmd = require("../../static/etcUtil/cmdConfig.js");
	const tools = require("../../static/etcUtil/tools.js");
	const bluetoothUtil = require("../../static/etcUtil/index.js");
	import { navTo } from "@/utils/utils"
	const card = reactive({
		/*卡相关信息*/
		cardId: "",
		netId: "",
		cardType: "",
		startTime: "",
		endTime: "",
		userName: "",
		idNum: "",
		vehiclePlate: "",
		vehiclePlateColor: "",
		color: "",
		version: "",
		type: "",
		favourable: "",
		money: undefined,
		v_userType: "",
	});
	const show = ref(false);
	const dataTime = reactive({
		startDate: "",
		endDate: ""
	})
	const state = reactive({
		vehicleId: "",//车牌号
		id: "",
		list: [],
		cardBalance: "",
		haveData: false,  //是否有数据
		refundBalance: "",
	})
	const listData = reactive(null)
	onLoad((options) => {
		state.vehicleId = options.vehicleId
		//根据车牌查询信息.data
		queryRefundAction().then(val => {
			console.log("val", val)
			if (val.data) {
				state.list = val.data
				state.haveData = true
			}
		})
		/*监听蓝牙回调*/
		uni.$on('bluetoothLink', function (status) {
			getCardId()
		})
	});
	onUnload(() => {
		/*移除监听*/
		uni.$off('bluetoothLink')
	});
	// 补卡额列表查询接口
	const queryRefundAction = () => {
		const options = {
			type: 2,
			data: {
				"vehicleId": state.vehicleId,
				"systemType": "WX"
			},
			method: "POST",
			showLoading: true,
		};
		return new Promise(async (resolve, reject) => {
			const res = await request(queryCardLimit, options);
			const data = stringToJson(res.bizContent);
			console.log("储值卡注销退费查询接口", data)
			resolve(data);
		}).catch((error) => {
			reject(error);
		});
	};
	// 日期修改
	function changeHandle(e) {
		dataTime.startDate = e.startDate;
		dataTime.endDate = e.endDate;

	}

	// 补卡申请
	function toApply(item) {
		uni.navigateTo({
			url: `/subpackage/orders/cardAmount?id=${item.id}`
		});
	}
	// 去评价
	function toEvaluate(item) {
		uni.navigateTo({
			url: `/subpackage/orders/order-evaluate?id=${item.id}`
		});
	}
	// 查看进度
	function toView(item) {
		uni.navigateTo({
			url: `/subpackage/orders/cardAmountDetail?id=${item.id}`
		});
	}
	// 去圈存
	//功能跳转入口
	const refundTypeAction = (val : any) => {
		/*圈存*/
		//链接蓝牙
		console.log("val.id", val.id)
		state.id = val.id;
		state.cardBalance = val.cardBalance
		uni.navigateTo({
			url: `/pages/bluetooth/bluetooth?routeType=5`,
		});
	}
	/*读卡*/
	const getCardId = () => {
		console.log("======获取卡信息======");
		let cmdArr = [
			cmd.HOME_DIRECTORY,
			//选择主目
			cmd.APPLICATION_DIRECTORY,
			//选择文件1001--DF01联网收费应用目录
			cmd.CMD_READBINARY,
			//15文件--卡片发行基本数据文件
			cmd.CMD_GETBALANCE,
			//钱包
		];
		tools.showLoadingAlert("正在执行指令");
		//10：写卡   20：写OBU
		bluetoothUtil.transCmd(cmdArr, "10", function (res) {
			tools.hideLoadingAlert();
			let str = res[2].substring(res[2].length - 4, res[2].length);
			let str3 = res[3].substring(res[3].length - 4, res[3].length);
			if (str == "9000" || str3 == "9000") {
				if (res[2].length > 86 || res[3] >= 12) {
					card.cardId = 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, 19) >= 4 ? "4x" : "2x";
					card.netId = res[2].substring(20, 24);
					card.cardType = res[2].substring(28, 29) == 23 ? 1 : 2;
					card.vehiclePlateColor = parseInt(res[2].substring(82, 84), 16);
					(card.money = parseInt(parseInt(res[3].substring(0, 8), 16), 10)),
						console.log("======卡信息======", card);

					quanCheckActionTrue().then((val) => {
						checkQuanCengEvent(val);
					});
				} else {
					tools.hideLoadingAlert();
				}
			}
			tools.hideLoadingAlert();
		});
	};
	const quanCheckActionTrue = () => {
		console.log("进行真实圈存检测");

		var data = {
			cardId: card.cardId,
			orderId: state.id,
			preBalance: card.money,
			fee: state.cardBalance,
			tradeType: 5,
		};
		const options = {
			type: 2,
			data: data,
			method: "POST",
			showLoading: true,
		};
		return new Promise(async (resolve, reject) => {
			const res = await request(quanCheck, options);
			const data = stringToJson(res.bizContent);
			resolve(data);
		}).catch((error) => {
			reject(error);
		});
	};
	const checkQuanCengEvent = (val : any) => {
		if (val.chargeStatus === 1) {
			let cmdArr = val.command.split(",");
			uni.showLoading({
				title: "写入中",
			});
			bluetoothUtil.transCmd(cmdArr, "10", function (res) {
				let response = res.toString();
				var dic = {
					command: val.command,
					cosResponse: response,
				};
				uni.hideLoading();
				quanApplyAction(dic).then((value) => {
					console.log("圈存申请完后的结果");
					console.log(value);
					//圈存初始化验证通过 , 进行圈存
					if (value.commandType === 2) {
						uanConfirmAction(value)
					} else {
						msg("圈存初始化指令验证失败, 重新初始化");
					}
				});

			});
		} else {
			let cmdArr = val.command.split(",");
			uni.showLoading({
				title: "写入中",
			});
			bluetoothUtil.transCmd(cmdArr, "10", function (res) {
				var status = res[1].substring(res[1].length - 4, res[1].length);
				console.log("打印状态");
				console.log(status);
				if (status === "9000") {
					console.log("修复指令入参");
					let response = res.toString();
					var dic = {
						command: val.command,
						cosResponse: response,
						rechargeId: val.rechargeId,
					};
					quanFixAction(dic).then((value) => {
						console.log(value);
						console.log("修复结果返回");
						var fixStatus = value.fixStatus;
						//圈存修复COS指令Response信息不足,重新进行修复初始化
						if (fixStatus === 3) {
							let xfcmdArr = value.command.split(",");
							bluetoothUtil.transCmd(xfcmdArr, "10", function (resValueData) {
								var status = resValueData[1].substring(
									resValueData[1].length - 4,
									resValueData[1].length
								);
								console.log("打印状态");
								console.log(status);
								if (status === "9000") {
									console.log(resValueData);
									var valueResponse = resValueData.toString();
									console.log(response);

									var applyDic = {
										command: value.command,
										cosResponse: valueResponse,
										rechargeId: value.rechargeId,
									};
									console.log("消费成功");
									quanApplyAction(applyDic).then((applyValue) => {
										uanConfirmAction(value)
									});
								}
							});
						} else if (fixStatus === 2) {
							uanConfirmSucessAction(value).then((confirmResult) => {
								navTo(
									`/subpackage/orders/flowingWater-result`)
							});
						} else if (fixStatus === 1) {
							quanCheckActionTrue().then((val) => {
								checkQuanCengEvent(val);
							});
						}
					});
					uni.hideLoading();
				}
			});
		}
	};
	/*圈存申请*/
	const quanApplyAction = (data) => {
		var form = {
			cardId: card.cardId,
			tradeType: 5,
			command: data.command,
			cosResponse: data.cosResponse,
			orderId: state.id,
			rechargeId: data.rechargeId,
			fee: state.cardBalance,
			preBalance: card.money,
		};
		const options = {
			type: 2,
			data: form,
			method: "POST",
			showLoading: true,
		};
		return new Promise(async (resolve, reject) => {
			console.log("70", options)
			const res = await request(quanApply, options);
			const data = stringToJson(res.bizContent);
			resolve(data);
		}).catch((error) => {
			reject(error);
		});
	};
	/*圈存确认*/
	const uanConfirmAction = (data) => {
		console.log("圈存确认进入");
		let cmdArr = data.command.split(",");
		console.log(cmdArr);
		bluetoothUtil.transCmd(cmdArr, "10", function (res) {
			console.log("圈存透传");
			console.log(res);
			var arraylenth = res.length;
			var status = res[arraylenth - 1].substring(
				res[arraylenth - 1].length - 4,
				res[arraylenth - 1].length
			);
			console.log("打印圈存确认指令状态");
			console.log(status);
			if (status === "9000") {
				var form = {
					command: data.command,
					cosResponse: res.toString(),
					rechargeId: data.rechargeId,
					paidAmount: state.cardBalance,
					giftAmount: 0,
				};
				const options = {
					type: 2,
					data: form,
					method: "POST",
					showLoading: true,
				};
				request(quanConfirm, options).then((res) => {
					const result = stringToJson(res.bizContent);
					navTo(`/subpackage/orders/flowingWater-result`)
				});
			}
		});
	};
	const uanConfirmSucessAction = (data) => {
		var form = {
			command: data.command,
			cosResponse: "9000",
			rechargeId: data.rechargeId,
			paidAmount: data.fee,
			giftAmount: 0,
		};
		const options = {
			type: 2,
			data: form,
			method: "POST",
			showLoading: true,
		};
		return new Promise(async (resolve, reject) => {
			const res = await request(quanConfirm, options);
			const data = stringToJson(res.bizContent);
			resolve(data);
		}).catch((error) => {
			reject(error);
		});
	};
	/*圈存修复*/
	const quanFixAction = (val) => {
		var data = {
			command: val.command, //修复初始化的指令
			cosResponse: val.cosResponse, //修复初始化结果
			rechargeId: val.rechargeId, //充值流水号
		};
		const options = {
			type: 2,
			data: data,
			method: "POST",
			showLoading: true,
		};
		return new Promise(async (resolve, reject) => {
			const res = await request(quanXf, options);
			const data = stringToJson(res.bizContent);
			resolve(data);
		}).catch((error) => {
			reject(error);
		});
	};
</script>

<style lang="scss" scoped>
	.no {
		text-align: center;
		font-size: 32rpx;
		margin: 20rpx auto;
	}

	.bg-color {
		position: fixed;
		top: 0;
		left: 0;
		right: 0;
		bottom: 0;
		background: #EEF7F7;
		z-index: -1;
	}

	.search-box {
		margin: 30rpx 30rpx 20rpx 30rpx;
		height: 72rpx;
		height: 81rpx;
		background: #FFFFFF;
		border: 1px solid #DCDCDC;
		border-radius: 40rpx;
		display: flex;
		justify-content: center;
		align-items: center;
		box-sizing: border-box;
	}

	.search-box .icon {
		width: 48rpx;
		height: 48rpx;
		margin: 0 20rpx;
	}

	.search-box .search {
		flex: 1;
		margin-right: 20rpx;
		height: 100%;
		padding: 0 10rpx;
		font-size: 28rpx;
		color: #00b38b;
	}

	.scroll-view {
		white-space: nowrap;
		position: sticky;
		top: 0;
		background: #ffffff;
		box-shadow: 0rpx 2rpx 6rpx 0rpx rgba(223, 223, 223, 0.8);
	}

	.search-time {
		// width: 100%;
		display: flex;
		padding: 10rpx 30rpx 30rpx;

		.search-time-box {
			flex: 1;
		}

		.time-btn {
			width: 130rpx;
			height: 80rpx;
			background: #00B38B;
			border-radius: 40rpx;
			color: #FFFFFF;
			font-size: 32rpx;
			line-height: 80rpx;
			text-align: center;
			margin-left: 20rpx;
		}

		.show-info {
			// width: 541rpx;
			width: 85%;
			height: 81rpx;
			padding: 0 31rpx;
			background: #FFFFFF;
			border: 1px solid #DCDCDC;
			border-radius: 40rpx;
			display: flex;
			justify-content: space-between;
			align-items: center;

			.show-text {
				display: flex;
				align-items: center;
			}

			.date-text {
				color: #999999;
				font-size: 28rpx;
			}

			.text-val {
				color: #333
			}

			.line {
				width: 25rpx;
				height: 1rpx;
				background: #999999;
				margin: 0 24rpx;
			}
		}
	}

	.total-num {
		font-size: 28rpx;
		color: #999999;
		margin-left: 30rpx;
	}

	.list-wrap {
		margin: 30rpx;
		padding-bottom: 20rpx;
	}

	.card-info {
		background: #FFFFFF;
		box-shadow: 0rpx 2rpx 6rpx 0rpx rgba(223, 223, 223, 0.8);
		border-radius: 20rpx;
		margin-bottom: 30rpx;
		padding: 30rpx 30px 13rpx 30rpx;

		.info-wrap {
			display: flex;
			justify-content: space-between;
			align-items: center;
			border-bottom: 1px solid #dcdcdc;
			padding-bottom: 30rpx;

			.info-left-text {
				margin-bottom: 20rpx;
			}

			.label {
				color: #999999;
				font-size: 26rpx;
				font-weight: 400;
			}

			.val {
				color: #333333;
				font-size: 26rpx;
				font-weight: 400;
			}

			.price-label {
				color: #999999;
				font-size: 24rpx;
				font-weight: 400;
				margin-bottom: 22rpx;
				text-align: center;
			}

			.price-val-text {
				font-size: 36rpx;
				font-weight: 700;
				color: #333333;
				margin-left: 9rpx;
			}

			.price-val {
				font-size: 26rpx;
				color: #333333;
			}

		}

		.card-text-wrap {
			display: flex;
			justify-content: space-between;
			align-items: center;
			margin: 38rpx 0 46rpx 0;

			.text-box {
				display: flex;
				flex-direction: column;
				align-items: center;

				.name-text {
					font-size: 30rpx;
					font-weight: 400;
					color: #333333;
				}

				.time-text {
					font-size: 30rpx;
					color: #333333;
					font-weight: 400;
					margin-top: 8rpx;
				}

				.date-text {
					font-size: 24rpx;
					color: #999999;
					font-weight: 400;
					margin-top: 8rpx;
				}
			}

			.arrow-wrap {
				display: flex;
				flex-direction: column;
				align-items: center;

				.d-img {
					width: 186rpx;
					height: 12rpx;
				}

				.arrow-text {
					color: #666666;
					font-size: 26rpx;
				}
			}
		}

		.btn-wrap {
			margin-top: 30rpx;
			display: flex;
			justify-content: space-between;
			align-items: center;

			.status-wrap {
				color: #999999;
				font-size: 26rpx;
				margin-right: 23rpx;
			}

			.status-text {
				color: #00B38B;
			}

			.btn {
				background: #FFFFFF;
				border: 1px solid #00B38B;
				border-radius: 30rpx;
				line-height: 50rpx;
				text-align: center;
				color: #00B38B;
				font-size: 26rpx;
			}

			.btn-1 {
				width: 140rpx;
				height: 50rpx;
			}

			.btn-2 {
				width: 141rpx;
				height: 50rpx;
			}

			.btn-3 {
				width: 121rpx;
				height: 50rpx;
			}
		}
	}
</style>