<template>
	<view class="oderPage">
		<view v-if="state.list&&state.list.length>0" v-for="(item,index) in state.list" class="details">
			<view class="header">
				<image :src="`${$imgUrl}order/no1.png`" mode=""></image>
				<text>{{item.orderId}}</text>
			</view>
			<view class="hr">

			</view>
			<view class="row">
				<view class="">
					订单车牌号：
				</view>
				<text>{{item.vehiclePlate}}</text>
			</view>
			<view class="row">
				<view class="">
					旧卡号：
				</view>
				<text>{{item.cardId}}</text>
			</view>
			<view class="row">
				<view class="">
					旧卡金额：
				</view>
				<text>{{item.cardBalance / 100}}</text>
			</view>
			<view class="line">
			</view>
            <button v-if="item.refundType === 'WTJTF'">未提交退费</button>
            <button v-if="item.refundType === 'YTJTF'">已提交退费</button>
			<button v-if="item.refundType === 'GLYQR'" @click="refundTypeAction(item)"> 补领申请</button>
			<button v-if="item.refundType === 'YWCTF'">已完成退费</button>
			<button v-if="item.refundType === 'TFYDC'">已导出退费</button>
			<button v-if="item.refundType === 'ECHDTF'">二次核定退费</button>
			<button v-if="item.refundType === 'RFFL'">退费失败</button>
			<button v-if="item.refundType === 'ALRS'">已拒付</button>
			<button v-if="item.refundType === 'FJWQR'">附件未确认</button>
			<button v-if="item.refundType === 'WGZYQ'">未过争议期</button>
			<button v-if="item.refundType === 'REQUESTED'">已申请</button>
			<button v-if="item.refundType === 'BALSUP'">余额补领</button>
			<button v-if="item.refundType === 'BALSUP'" @click="refundTypeAction(item)"> 圈层</button>
			<button v-if="item.refundType === 'BALSUPCOS'"> 余额补领已圈存</button>
		</view>
		<view v-else>
			<empty title='暂无找到该车牌相关余额补领信息' />
		</view>
	</view>

</template>

<script setup lang="ts">
	import {
		reactive,
		ref
	} from "vue"
	import {
		navTo
	} from "@/utils/utils"
	import {
		onLoad,
		onUnload
	} from "@dcloudio/uni-app";
	import {
		queryRefund,
		queryRefundApply,
		quanApply,
		quanCheck,
		quanConfirm,
		quanXf
	} from "@/utils/network/api.js";
	import {
		request
	} from "@/utils/network/request.js";
	import {
		msg
	} from "@/utils/utils";

	import {
		stringToJson
	} from "@/utils/network/encryption";

	//-----蓝牙模块
	const bluetoothUtil = require("../../../static/etcUtil/index.js");
	const cmd = require("../../../static/etcUtil/cmdConfig.js");
	const tools = require("../../../static/etcUtil/tools.js");
	const card = reactive({
		/*卡相关信息*/
		cardId: "",
		netId: "",
		cardType: "",
		startTime: "",
		endTime: "",
		userName: "",
		idNum: "",
		vehiclePlate: "",
		vehiclePlateColor: "",
		color: "",
		version: "",
		type: "",
		favourable: "",
		money: undefined,
		v_userType: "",
	});
	const state = reactive({
		vehicleId: '',
		list: [],
		id: '' ,//退费信息编号
		cardBalance:"",
	});

	/*视图进入后操作*/
	onLoad((option) => {
		state.vehicleId = option.vehicleId

		//根据车牌查询信息
		queryRefundAction().then(val => {
			state.list = val.data
		})
		/*监听蓝牙回调*/
		uni.$on('bluetoothLink', function(status) {
			getCardId()
		})
	});

	onUnload(() => {
		/*移除监听*/
		uni.$off('bluetoothLink')
	});
	//功能跳转入口
	const refundTypeAction = (val: any) => {
		state.cardBalance=val.cardBalance
		if (val.refundType === 'GLYQR') {
			/*余额补领申请*/
			queryRefundApplyAction(val.orderId).then((value: any) => {
				state.id = value.id
				msg('圈层退费申请成功')
				/*查询完刷新状态*/
				queryRefundAction().then((result: any) => {
					state.list = result.data
				})
			})
		} else if (val.refundType === 'BALSUP') {
			/*圈层*/
			//链接蓝牙
			state.id = val.orderId
			uni.navigateTo({
				url: `/pages/bluetooth/bluetooth?routeType=5`,
			});
		}
	}

	//储值卡注销退费查询接口
	const queryRefundAction = () => {
		var data = {
			vehicleId: state.vehicleId
		};
		const options = {
			type: 2,
			data: data,
			method: "POST",
			showLoading: true,
		};

		return new Promise(async (resolve, reject) => {
			const res = await request(queryRefund, options);
			const data = stringToJson(res.bizContent);
			console.log("储值卡注销退费查询接口",data)
			resolve(data);
		}).catch((error) => {
			reject(error);
		});
	}

	//储值卡注销余额补领申请接口
	const queryRefundApplyAction = (id) => {
		var data = {
			orderId: id
		};
		const options = {
			type: 2,
			data: data,
			method: "POST",
			showLoading: true,
		};
		return new Promise(async (resolve, reject) => {
			const res = await request(queryRefundApply, options);
			const data = stringToJson(res.bizContent);
			resolve(data);
		}).catch((error) => {
			reject(error);
		});
	}

	/*读卡*/
	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 {
					console.error("CMD_READBINARY指令长度不符" + res[2]);
					tools.hideLoadingAlert();
				}
			}
			console.error("CMD_READBINARY指令长度不符" + res[2]);
			tools.hideLoadingAlert();
		});
	};

	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).then((confirmResult) => {
						navTo(
							`/subpackage/after-sale/refund-order-balance/result`)
						});
					} 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(applyValue).then((
											confirmResult) => {
											navTo(
												`/subpackage/after-sale/refund-order-balance/result`)
										});
									});
								}
							});
						} else if (fixStatus === 2) {
							uanConfirmSucessAction(value).then((confirmResult) => {
							navTo(
								`/subpackage/after-sale/refund-order-balance/result`)
							});
						} else if (fixStatus === 1) {
							quanCheckActionTrue().then((val) => {
								checkQuanCengEvent(val);
							});
						}
					});
					uni.hideLoading();
				}
			});
		}
	};

	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 quanCheckActionTrue = () => {
		console.log("进行真实圈层检测");
		// msg(card.money)
		// msg(state.list[0].cardBalance)
		var data = {
			cardId: card.cardId,
			orderId: state.id,
			preBalance: card.money,
			fee: state.cardBalance,
			tradeType: 4,
		};
		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 quanApplyAction = (data) => {
		var form = {
			cardId: card.cardId,
			tradeType: 4,
			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: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>
	page {
		width: 100%;
		height: 100%;
		display: flex;
		flex-direction: column;
		background-color: #EEF7F7;
		box-sizing: border-box;
	}
</style>
<style lang="scss" scoped>
	.oderPage {

		.details {
			margin: 30rpx;
			position: relative;
			background: #fff;
			border-radius: 20rpx;
			padding: 30rpx;
			height: 370rpx;
			background: #FFFFFF;
			box-shadow: 0rpx 2rpx 6rpx 0rpx rgba(223, 223, 223, 0.8);
			border-radius: 20rpx;

			.header {
				align-items: center;
				display: flex;
				padding-bottom: 30rpx;
				// border-bottom: 1px solid #DCDCDC;

				image {
					width: 51rpx;
					height: 31rpx;
				}

				text {
					font-size: 30rpx;
					margin-left: 20rpx;
					font-weight: 600;
				}
			}

			.hr {
				height: 1rpx;
				background: #DCDCDC;
				width: 100%;
				position: absolute;
				left: 50%;
				transform: translate(-50%);
			}

			.row {
				display: flex;
				margin: 34rpx 0;
				font-size: 26rpx;
				font-family: Noto Sans S Chinese;
				font-weight: 400;
				color: #333333;
				line-height: 30rpx;

				view {
					font-size: 26rpx;
					font-family: Noto Sans S Chinese;
					font-weight: 400;
					color: #999999;
					line-height: 30rpx;

				}
			}

			.line {
				width: 100%;
				height: 1rpx;
				background: #DCDCDC;

			}

			button {
				// width: 141rpx;
				height: 61rpx;
				background: #FFFFFF;
				border: 1px solid #00B38B;
				border-radius: 30rpx;
				font-size: 26rpx;
				font-family: Noto Sans S Chinese;
				font-weight: 400;
				color: #00B38B;
				line-height: 50rpx;
				position: absolute;
				right: 30rpx;
				bottom: 20rpx;
				padding: 6rpx 10rpx;
				
			}
		}

	}
</style>
