<template>
	<view class="content">
		<view class="deviceDetail">
			<view class="imgContent">
				<image src="/static/images/BLEAdd/addBleDevice.png" class="titleIco" mode="aspectFit">
				</image>
			</view>
			<view class="deviceName">
				蓝牙名:{{serverDevice?serverDevice['bluetoothName']: device.name}}
			</view>
			<view class="deviceName">
				状态:{{deviceStatu}}
			</view>
			<view class="deviceName">
				设备名:{{serverDevice?serverDevice['deviceName']:device.deviceName}}
			</view>
			<view class="deviceId">
				设备Mac:{{serverDevice?serverDevice['deviceMac']:device.macAddress}}
			</view>
			<view class="deviceId">
				设备IMEI:{{serverDevice?serverDevice['deviceImei']:device.imei}}
			</view>
			<view class="bound" :class="boundStatu">
				{{Statu.boundRemark}}
			</view>
		</view>
		<view class="btnLink" @click="Link()">
			绑定
		</view>

		<global-loading ref="loading" />
	</view>
</template>

<script>
	import request from '@/utils/request.js';
	import bleTool from '@/utils/BleHelper.js';
	import {
		showLoading,
		hideLoading,
		updateLoading
	} from '@/utils/loading.js';

	const pagePath = "pages/common/addBLE/LinkBle";

	var these = null;
	var eventChannel = null;
	var ble = null;
	var inteval=null;
	export default {
		data() {
			return {
				Statu: {
					bound: null,
					timeInteval: null,
					isSearch: false,
					pageHide:false,
					isBind:false
				},
				device: {
					"deviceId": "",
					"name": "",
					"deviceName": "",
					"RSSI": -37,
					"localName": "",
					"advertisServiceUUIDs": [

					],
					"linkStatu": true,
					"macAddress": "",
					"communicationMode": "",
					"imei": ""
				},
				serverDevice: null
			}
		},
		computed: {
			boundStatu: function() {
				if (this.Statu.bound === null) {
					return "displayNone"
				}
				if (this.Statu.bound) {
					return "green"
				} else {
					return "red";
				}
			},
			deviceStatu: function() {
				debugger;
				if (!this.device.name && !this.device.macAddress) {
					return "";
				}
				if (!this.device.linkStatu && !this.device.macAddress) {
					return "蓝牙未连接";
				}
				if (!this.device.macAddress) {
					return '等待设备上报Mac地址';
				}

				if (!this.device.deviceName && !(this.serverDevice && this.serverDevice.deviceName)) {
					if (this.Statu.isSearch) {
						return "无效设备";
					} else {
						if (this.Statu.timeInteval === null) {
							return "等待查询设备"
						} else {
							return "正在查询设备";
						}
					}
				} else {
				
						return "找到有效设备"
					
					
				}

				return "";
			}
		},
		onShow() {
			this.Statu.pageHide=false;
		},
		onHide() {
			this.Statu.pageHide=true;
		},
		onUnload() {
			console.log("返回取消订阅");
			clearInterval(inteval);
			ble.removeAllCallback(pagePath);
			
			if(!this.Statu.isBind && these.device.deviceId){
				ble.disconnectDevice(these.device.deviceId).catch(ex=>{
					console.error("无法断开蓝牙连接");
				});
			}
		},
	
		onLoad(option) {
			these = this;
			ble = bleTool.getBleTool();

			ble.addStateBreakCallback(res => {
				if(this.Statu.pageHide){
					return;
				}
				these.device.linkStatu = false;
				hideLoading(these);
				uni.showToast({
					icon:'fail',
					title:'蓝牙已不可用'
				})
			},pagePath);
			
			ble.addStateRecoveryCallback(res => {
				if(this.Statu.pageHide){
					return;
				}
				if (these.device.deviceId) {
					showLoading(these, {
						text: '蓝牙已恢复正在连接设备'
					});

					these.reLinkdevice();
				}
			},pagePath);
			ble.addDisposeCallback(res => {
				if(this.Statu.pageHide){
					return;
				}
				console.log("处理蓝牙断开连接");
				these.device.linkStatu = false;
				if (these.device.deviceId == res.deviceId) {

					showLoading(these, {
						text: '蓝牙已断开,正在重连'
					});
					these.reLinkdevice();
				}
			},pagePath);

			ble.addReceiveCallback((receive, f, path) => {
				if(this.Statu.pageHide){
					return;
				}
				console.log("收到设备消息，", receive);
				if (these.device.deviceId == receive.deviceId) {
					console.log("11111:", receive);
					these.device.imei = f.imei;
					let flag=false;
					if (receive.bytes && receive.bytes.length && receive.bytes[0] == 0xFC)   {//6155 7305
						if (f && f.macAddress) {
							 flag=true;							
						}						
					}
					else if(receive.str.indexOf('mac address:') == 0){//650 670
						if (f && f.macAddress) {
							 flag=true;							
						}	
					}
					else{
						try{
							console.log("str=",receive.str)
							let json=JSON.parse(receive.str);
							let key = "sta_address"; 
							if (key in json) {//100
								if (f && f.macAddress) {
									 flag=true;
								}
							}
						}catch(err){
							console.log("出现异常,",err);
						}
					}
					
					
					if(flag){
						these.device.macAddress = f.macAddress;
						console.log("222222");
						these.Statu.isSearch = false;
						these.initDevice();
					}
					
				}
			}, pagePath);
			eventChannel = this.getOpenerEventChannel();
			
			if(option.mac){
				this.device.macAddress=option.mac;
				these.initDevice();
			}
			else{
				eventChannel.on('LinkItem', function(data) {
					console.log("data=", data);
					let f = ble.data.LinkedList.find((v) => {
						return v.deviceId == data.deviceId;
					});
					if (f) {
						let keys = Object.keys(f);
						keys.forEach((v, index) => {
							these.device[v] = f[v];
						})
						// console.log("LinkedList=", ble.data.LinkedList)
						// console.log("f=", f);
						// console.log("获取到设备", these.device);
						if (f.macAddress) {
							these.device.macAddress = f.macAddress;
				
							these.initDevice();
						}
					} else {
						console.log("未获取到设备");
					}
				})
				
				 inteval = setInterval(this.initDevice, 10000);
			}
			
			
		},
		methods: {
			reLinkdevice() {
				ble.LinkBlue(these.device.deviceId).then(res => {
					updateLoading(these, {
						text: '连接成功'
					});
					these.device.linkStatu = true;
					setTimeout(() => {
						hideLoading(these);
					}, 2000);
				}).catch(ex => {
					updateLoading(these, {
						text: ex.msg
					});
					setTimeout(() => {
						hideLoading(these);
					}, 2000);
				});
			},
			initDevice: function() {
				if (!these.device.macAddress) {
					return;
				}
				//无效的设备回调
				let deviceInvalid = () => {
										
						these.$set(these.device, "deviceName", "");						
					
				}
				clearTimeout(this.Statu.timeInteval);

				this.Statu.timeInteval = setTimeout(() => {
					this.Statu.isSearch = true;
					showLoading(these, {
						text: '正在获取设备信息'
					});
					console.log("these.device=", these.device);
					request({
						url: '/app/device/getDeviceInfoByDeviceMac',
						method: 'GET',
						data: {
							deviceMac: these.device.macAddress
						}
					}).then(res => {

						console.log("获取设备信息", res);
						if (res && res.code == 200) {
							console.log("res=", res);
							let data = res.data;
							this.serverDevice = data;
							if (data) {
								let keys = Object.keys(data);
								ble.data.LinkedList.find((v) => {
									if (v.deviceId == these.device.deviceId) {
										for (var i = 0; i < keys.length; i++) {
											let key = keys[i];
											these.$set(these.device, key, data[key]);
										}
									}
								});
								clearInterval(inteval);
							} else {
								deviceInvalid();
							}
						} else {
							this.serverDevice =null;
							deviceInvalid();
						}

					}).catch((ex) => {
						console.error("获取设备出现异常:", ex);
					}).finally(() => {
						this.Statu.timeInteval = null;
						this.Statu.isSearch = false;
						hideLoading(these);
					});

				}, 500);

			},
			Link() {
				// 调用绑定设备接口
				
				// let f = ble.data.LinkedList.find((v) => {
				// 	return v.deviceId == these.device.deviceId;
				// });
				// if (!f) {
				// 	these.Statu.bound = false;
				// 	these.Statu.boundRemark = "蓝牙连接不成功";
				// 	return;
				// }
				if (!this.device.macAddress) {
					these.Statu.bound = false;
					these.Statu.boundRemark = "获取设备Mac地址异常";
					return;
				}
				if (!this.serverDevice) {
					these.Statu.bound = false;
					these.Statu.boundRemark = "设备未入库";
					return;
				}
				these.Statu.bound = null;
				these.Statu.boundRemark = "";
				showLoading(these, {

					text: "绑定中..."
				})
				let promise = request({
					url: '/app/device/bind',
					method: 'POST',
					data: {
						deviceImei: '',
						deviceMac: these.device.macAddress,
						communicationMode: 1, //0是4g,1是蓝牙,2蓝牙&4G
					}
				});
				promise.then((res) => {
					console.log("1111" + JSON.stringify(res));
					if (res.code == 200) {
						these.Statu.bound = true;
						these.Statu.boundRemark = "设备绑定成功!";
						let data = these.serverDevice;
						let keys = Object.keys(data);
						ble.data.LinkedList.find((v) => {
							if (v.deviceId == these.device.deviceId) {
								for (var i = 0; i < keys.length; i++) {
									let key = keys[i];
									if (!v.device) {
										v.device = {};
									}
									v.device[key] = data[key];
								}

								ble.updateCache();
							}
						});

						ble.removeReceiveCallback(pagePath);
						clearTimeout(this.Statu.timeInteval);
						this.device.macAddress = null;
						this.Statu.timeInteval = null;
						this.Statu.isBind=true;
						uni.$emit("refreshDeviceList");
						setTimeout(() => {
							uni.switchTab({
								url: "/pages/common/index/index"
							});
						}, 500);
					} else {
						these.Statu.bound = false;
						these.Statu.boundRemark = res.msg;
					}
				}).catch((ex) => {
					these.Statu.bound = false;
					these.Statu.boundRemark = '出现了未知的异常,操作失败';
					console.log("ex=", ex);
				}).finally(() => {
					hideLoading(this);
				});
			}
		}
	}
</script>

<style>
	.content {
		background-color: #1d1d1d;
		color: #ffffffde;
		box-sizing: border-box;
		overflow: hidden;
		width: 100%;
		min-height: 100vh;
		height: auto;
		font-family: "PingFang SC";
	}

	.deviceDetail {
		margin: 200rpx auto;
		display: flex;
		flex-direction: column;
		flex-wrap: nowrap;
		align-content: center;
		justify-content: center;
		align-items: center;
	}

	.imgContent,
	.titleIco {
		width: 120rpx;
		height: 120rpx;
	}

	.deviceId {
		color: rgba(255, 255, 255, 0.87);
		font-size: 32rpx;

		line-height: 44rpx;
		letter-spacing: 0.14rpx;
		margin-top: 5rpx;
	}

	.btnLink {
		position: fixed;
		bottom: 30rpx;
		left: 30rpx;
		right: 30rpx;
		width: calc(100% - 60rpx);
		border-radius: 91px;
		height: 90rpx;
		background: rgba(187, 230, 0, 1);
		color: rgba(35, 35, 35, 1);


		font-size: 32rpx;
		line-height: 90rpx;
		letter-spacing: 12rpx;
		text-align: center;
	}

	.bound,
	.deviceName {
		font-size: 32rpx;
		font-weight: 400;
		line-height: 44rpx;
		letter-spacing: 0.14rpx;
		margin-top: 5rpx;
	}

	.displayNone {
		display: none !important;
	}

	.green {
		color: rgba(187, 230, 0, 1);
	}

	.red {
		color: rgba(245, 80, 80, 1);
	}
</style>