<!--设备选择 -->
<template>
	<view class="devices">
		<view class="device" v-for="(item, index) in deviceList" :key="index" @click="connectDevice(item)">
			<image :src="`${$imgUrl}bluetooth/card1.png`" class="head" mode="aspectFill"></image>
			<view class="center">
				<view class="name">{{ item._name }}</view>
				<view class="desc">编号 {{ item.name }}</view>
			</view>
			<image :src="item.selected ? selectedUrl : unSelectedUrl" class="icon" mode="aspectFill"></image>
		</view>

		<view class="hint">
			<view class="orange-txt as-layout-horizontal as-gravity-center-start">
				<image :src="`${$imgUrl}common/icon-hint.png`" mode="aspectFill"></image>
				<view>温馨提示：</view>
			</view>
			<view class="grey-txt">&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;
				指令执行过程中，请勿关闭蓝牙，勿将手机远离电子标签，以免导致写卡、写签失败。</view>
		</view>
		<view class="btn">
			<submit-button title="点击重新搜索蓝牙" @submit="load"></submit-button>
		</view>
	</view>


</template>

<script setup lang="ts">
	import { ref, reactive } from "vue";
	import { onLoad, onReady } from "@dcloudio/uni-app";
	import { fileURL } from "@/datas/fileURL.js";

	const imgURL = `${fileURL}image/`;
	const selectedUrl = "common/selected.png`";
	const unSelectedUrl = "common/unselected.png`";
	const jyApi = require("../../static/etc/JYAPI/GenvictBleUtil.js");
	const jlQZApi = require("../../static/etc/JLQZAPI/JLObuSDK.js");
	const atApi = require("../../static/etc/ATAPI/ArtcBleUtil.js");
	const jtApi = require("../../static/etc/JTAPI/BleUtil.js");
	const wqApi = require("../../static/etc/WQAPI/WCDObuSdk.js");
	const cgApi = require("../../static/etc/CGAPI/cguBle.js");
	const tdApi = require("../../static/etc/TDAPI/TDRObuSDK.js");
	const zzApi = require("../../static/etc/WJAPI/wjBleAPI.js");

	const tools = require("../../static/etcUtil/tools.js");
	const datas = require("../../static/etcUtil/datas.js");
	const bluetoothUtil = require("../../static/etcUtil/index.js");
	
	let jlApi = require("../../static/etc/JLAPI/JLObuSDK.js"); //聚力SDK
	let wjApi = require("../../static/etc/WJAPI/wjBleAPI");
	// #ifdef MP-ALIPAY
	// 这部分代码将仅在支付宝小程序平台下执行
	jlApi = require("../../static/etc/JLObuSDK/JLObuSDK.js");
	wjApi = require("../../static/etc/WJBLE/WJBleAPI");
	// 执行支付宝小程序的特定功能
	// #endif

	const state = reactive({
		fee: "",
		cardId: "",
		showPopup: false, //显示激活成功提示
		curDeviceId: "", //当前选中的设备ID
		deviceList: [
			//设备列表
			{
				id: "1",
				image: imgURL + "bluetooth/card1.png`",
				name: "聚力",
				number: "235564444558855",
			},
		],
	});

	const deviceList = ref([]);
	const connectPrefixName = ref(null);
	const routeType = ref(null); //来源 1激活 2圈存 3信息重写 4信息读取

	interface DeviceType {
		name : string; //设备名称
		deviceId : string; //uuid
		prefixName : string; //前缀名称
		selected : boolean; //判断点击次数
		_name : string; //中文名称
	}

	let device : DeviceType = reactive({
		name: "", //设备名称
		deviceId: "", //uuid
		prefixName: "", //前缀名称
		selected: false, //判断点击次数
		_name: "", //中文名称
	});

	onReady(() => {
		load();
	});
	const props = defineProps({
		//手机号
		routeType: {
			type: String,
			default: "",
		},

		//短信模板编码
		cardId: {
			type: String,
			default: "",
		},
	});
	onLoad((option) => {
		routeType.value = props.routeType ? props.routeType : "1";
		state.cardId = props.cardId;
		console.log("props", props)
	});

	/*
	 * 蓝牙初始化
	 */
	const load = () => {
		deviceList.value = [];
		console.log("****************蓝牙getsetting******************");
		uni.getSetting({
			success(res) {
				console.log("****************成功******************");
				console.log("scopebluetooth:" + res.authSetting["scope.bluetooth"]);
				console.log("成功结果：" + JSON.stringify(res));
				if (res.authSetting["scope.bluetooth"] == undefined) {
					//不存在
					uni.authorize({
						scope: "scope.bluetooth",
						success() {
							console.log("扫描蓝牙中");
							tools.showLoadingAlert("扫描蓝牙中");
							openBluetooth();
						},
						fail() {
							uni.showToast({
								title: "蓝牙授权失败",
								icon: "error",
								duration: 1500,
							});
						},
					});
				} else if (!res.authSetting["scope.bluetooth"]) {
					//false
					uni.showModal({
						title: "是否授权读取蓝牙",
						content: "需要获取你的蓝牙，请确认授权，否则无法获取蓝牙",
						success: function (mres) {
							if (mres.confirm) {
								uni.openSetting({
									success(authData) {
										if (authData.authSetting["scope.bluetooth"] == true) {
											tools.showLoadingAlert("扫描蓝牙中");
											openBluetooth();
										} else {
											uni.closeBluetoothAdapter();
											uni.showToast({
												title: "蓝牙授权失败",
												icon: "error",
												duration: 1500,
											});
										}
									},
								});
							} else if (mres.cancel) {
								uni.showToast({
									title: "蓝牙授权失败",
									icon: "error",
									duration: 1000,
								});
							}
						},
					});
				} else {
					tools.showLoadingAlert("扫描蓝牙中");
					openBluetooth();
				}
			},
			fail(res) {
				console.log("****************失败******************");
				console.log("失败结果：" + JSON.stringify(res));
			},
		});
	};

	/*
	 * 打开蓝牙
	 */
	const openBluetooth = () => {
		let foundDevices = []; //扫描到的蓝牙列表
		uni.closeBluetoothAdapter(); //先关闭蓝牙

		//打开蓝牙
		uni.openBluetoothAdapter({
			success: function (res) {
				uni.startBluetoothDevicesDiscovery({
					success: function (res) {
						console.log(res);
						//扫描结果的监听
						uni.onBluetoothDeviceFound(function (res) {
							// console.log(res.devices);
							for (let i = 0; i < res.devices.length; i++) {
								let name = res.devices[i]["name"];
								let prefixName = "";
								let deviceId = res.devices[i]["deviceId"];
								console.log(res.devices[i]["name"]);
								if (name != "" && name != undefined && name != "undefined") {
									if (
										name.indexOf("G-WJ") != -1 ||
										name.indexOf("ETC") != -1 ||
										name.indexOf("G-JL") != -1
									) {
										//前装设备
										prefixName = "ETC";
									} else {
										//聚力临时设备
										if (name.indexOf("5201121") != -1) {
											prefixName = "JL";
										} else {
											prefixName = name.substring(0, 2);
										}
									}
									prefixName = prefixName.toUpperCase();
									if (
										prefixName == "WJ" ||
										prefixName == "JL" ||
										prefixName == "JY" ||
										prefixName == "AT" ||
										prefixName == "JT" ||
										prefixName == "WQ" ||
										prefixName == "CG" ||
										prefixName == "TD" ||
										prefixName == "ZZ" ||
										prefixName == "ETC"
									) {
										// //隐藏加载框
										tools.hideLoadingAlert();

										device.name = name;
										device.deviceId = deviceId;
										device.prefixName = prefixName;
										device.selected = false; //防止重复点击

										let _name = "";
										switch (prefixName) {
											case "WJ":
												_name = "万集";
												break;
											case "JL":
												_name = "聚利";
												break;
											case "JY":
												_name = "金溢";
												break;
											case "AT":
												_name = "埃特斯";
												break;
											case "JT":
												_name = "建投";
												break;
											case "WQ":
												_name = "握奇";
												break;
											case "CG":
												_name = "成谷";
												break;
											case "TD":
												_name = "天地融";
												break;
											case "ZZ":
												_name = "智载";
												break;
											case "ETC":
												_name = "前装";
												break;
											default:
												_name = "未知";
												break;
										}
										device._name = _name;

										if (deviceList.value.length == 0) {
											foundDevices.push(device);
										} else {
											let isHave = false;
											for (let j = 0; j < foundDevices.length; j++) {
												if (name == foundDevices[j].deviceId) {
													isHave = true;
													break;
												}
											}
											if (!isHave) {
												foundDevices.push(device);
											}
										}
										deviceList.value = foundDevices;
										foundDevices = [];
										// console.log(foundDevices);
									}
								}
							}
						});
					},
					fail: function (res) {
						console.log(res);
					},
				});
			},
			fail: function (res) {
				console.log(res);
				alertF("手机蓝牙未打开或不支持蓝牙");
			},
		});
	};

	/**
	 * 连接蓝牙
	 */
	const connectDevice = (e) => {
		console.log(e);
		let item = e;
		//停止扫描蓝牙
		console.info("停止扫描蓝牙");
		uni.stopBluetoothDevicesDiscovery({
			success: function (res) {
				console.log(device);
				if (item.selected == false) {
					console.log("第一次点击了");
					item.selected = true;
					setTimeout(function () {
						if (device.selected == undefined) {
							console.info("selected is undefined");
							linkFail(); //未找到设备, 请重新搜索
							return;
						}
						item.selected = false;
					}, 4000);
				} else {
					console.log("第二次点击了");
					return;
				}

				if (
					item.prefixName == undefined ||
					item.prefixName == "undefined" ||
					item.prefixName == ""
				) {
					console.info("device.prefixName is undefined");
					linkFail(); //未找到设备, 请重新搜索
					return;
				}

				let prefixName = item.prefixName;

				connectPrefixName.value = item.prefixName;
				// delete device.prefixName
				// delete device._name

				console.log(item);

				tools.showLoadingAlert("蓝牙连接中");
				console.info("连接的是" + prefixName);
				switch (prefixName) {
					case "WJ":
						wjApi.connectDevice(
							device,
							function (res) {
								connectSuccess(res);
							},
							function (res) {
								listenStatus(res);
							}
						);
						break;
					case "JL":
						jlApi.connectDevice(
							device,
							function (res) {
								connectSuccess(res);
							},
							function (res) {
								listenStatus(res);
							}
						);
						break;
					case "ETC":
						jlQZApi.connectDevice(
							device,
							function (res) {
								preDevice(res);
							},
							function (res) {
								listenStatus(res);
							}
						);
						break;
					case "JY":
						jyApi.connectDevice(
							device,
							function (res) {
								connectSuccess(res);
							},
							function (res) {
								listenStatus(res);
							}
						);
						break;
					case "AT":
						atApi.connectDevice(
							device,
							function (res) {
								connectSuccess(res);
							},
							function (res) {
								listenStatus(res);
							}
						);
						break;
					case "JT":
						jtApi.connectDevice(
							device,
							function (res) {
								connectSuccess(res);
							},
							function (res) {
								listenStatus(res);
							}
						);
						break;
					case "WQ":
						wqApi.connectDevice(
							device,
							function (res) {
								connectSuccess(res);
							},
							function (res) {
								listenStatus(res);
							}
						);
						break;
					case "CG":
						cgApi.connectDevice(
							device,
							function (res) {
								connectSuccess(res);
							},
							function (res) {
								listenStatus(res);
							}
						);
						break;

					case "TD":
						tdApi.connectDevice(
							device,
							function (res) {
								connectSuccess(res);
							},
							function (res) {
								listenStatus(res);
							}
						);
						break;

					case "ZZ":
						zzApi.connectDevice(
							device,
							function (res) {
								connectSuccess(res);
							},
							function (res) {
								listenStatus(res);
							}
						);
						break;

					default: //未找到设备, 请重新搜索
						linkFail();
						break;
				}
			},
			fail: function (res) {
				console.log(res);
				linkFail(); //未找到设备, 请重新搜索
			},
		});
	};

	/**
	 * 未找到设备, 请重新搜索
	 */
	const linkFail = () => {
		datas.setData("bluLinkStatus", false);
		datas.setData("connectPrefixName", "");

		tools.showModalAlert("未找到设备, 请重新搜索", function successFunc() {
			load();
		});
	};

	/**
	 * 连接成功
	 */
	const emit = defineEmits<{
		(e : "submit", connectSuccess : any, cardId : any) : void;
	}>();
	const connectSuccess = (res) => {
		console.log("连接回调函数func1");
		console.log(res);
		if (res.code == 0) {
			console.log("连接成功");
			datas.setData("bluLinkStatus", true);
			datas.setData("connectPrefixName", connectPrefixName.value);

			//routeType 1.激活（订单来）  2.圈存 （/pages/recharge/recharge来）3.信息重写 4.信息读取  5从哪里来回哪里去监听bluetoothLink
			if (routeType.value == "1") {
				uni.navigateTo({
					url: "/subpackage/after-sale/activation/activate",
				});
			} else if (routeType.value == "2") {
				// uni.navigateTo({
				//   url: `/pages/recharge/recharge?connectSuccess=1&&cardId=${state.cardId}`,
				// });
				emit("submit", 1, state.cardId);
			} else if (routeType.value == "3") {

			} else if (routeType.value == "4") {
				uni.navigateTo({
					url: "/subpackage/after-sale/deviceInfo/deviceInfo",
				});
			}
			else if (routeType.value == "5") {
				uni.$emit('bluetoothLink', { status: true })
				uni.navigateBack({
					delta: 1
				})
			} else {
				return;
			}
		} else {
			alertF(res.msg);
		}
	};

	/**
	 * 前装设备
	 */
	const preDevice = (res) => {
		if (res.code == 0) {
			console.log("连接成功");
			datas.setData("bluLinkStatus", true);
			datas.setData("connectPrefixName", connectPrefixName.value);

			// tools.toUrl(route.preActivateInfo);//跳转 前装设备
		} else {
			alertF(res.msg);
			console.log(res.msg);
		}
	};

	/**
	 * 监听蓝牙状态
	 */
	const listenStatus = (res) => {
		console.log("时时监听蓝牙状态func2");
		console.log(res);
		if (res.code == 0) {
			datas.setData("bluLinkStatus", true);
			datas.setData("connectPrefixName", connectPrefixName.value);
		} else {
			datas.setData("bluLinkStatus", false);
			datas.setData("connectPrefixName", "");
			tools.showToastAlert("蓝牙已断开");
		}
	};

	/**
	 * 提示加关蓝牙
	 */
	const alertF = (msg : string) => {
		//隐藏加载框
		tools.hideLoadingAlert();

		//断开蓝牙
		bluetoothUtil.disconnectDevice();

		//提示对话框
		tools.showModalAlert(msg);
	};
</script>

<style>
	page {
		background-color: #f3f3f3;
	}

	:deep(.u-mode-center-box) {
		border-radius: 20rpx;
	}
</style>

<style lang="scss" scoped>
	.devices {
		.device {
			width: calc(100% - 30rpx);
			margin-left: 30rpx;
			display: flex;
			flex-direction: row;
			align-items: center;
			margin-top: 30rpx;
			background: white;
			padding: 25rpx 20rpx;
			border-top-left-radius: 20rpx;
			border-bottom-left-radius: 20rpx;
			box-shadow: 0px 10px 10rpx 10rpx rgba(223, 223, 223, 0.3);

			.head {
				width: 120rpx;
				height: 120rpx;
				border-radius: 10rpx;
				background-color: #f3f3f3;
			}

			.center {
				flex: 1;
				margin-left: 30rpx;
				margin-right: 30rpx;

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

				.desc {
					font-size: 26rpx;
					color: #666666;
					margin-top: 25rpx;
				}
			}

			.icon {
				width: 43rpx;
				height: 43rpx;
				margin-right: 10rpx;
			}
		}

		.hint {
			margin: 60rpx 30rpx 0px;

			.orange-txt {
				font-size: 26rpx;
				color: #ff8000;

				image {
					width: 30rpx;
					height: 30rpx;
					margin-right: 10rpx;
				}
			}

			.grey-txt {
				font-size: 26rpx;
				color: #666666;
				line-height: 40rpx;
				margin-top: 16rpx;
			}
		}

		.btn {
			margin: 70rpx 40rpx;
		}
	}
</style>