<template>
	<view>
		<view class="top">
			<span class='title'>编辑蓝牙设备</span><span class='id'>设备id</span><span>{{deviceId}}</span><span
				class='startTime'>开始时间</span><span>{{startTime}}</span><span class='totalTime'
				style='font-weight: 700;'>总时长</span><span style='font-weight: 700;'>{{time}}</span>
		</view>
		<view class="type">
			<view class="facilityType">
				<p>设备类型</p>
				<view class="buttonOP" v-if="typeList">
					<view class="item" @click="selectOne('type_sn',index,item)"
						:class="{selectType:index==selectTypeIndex}" v-for="(item,index) in typeList" :key="index">
						<img :src="item.cover_url" alt="">
						<span>{{item.name}}</span>
					</view>
				</view>
			</view>
			<view class="facilityType">
				<p>探头</p>
				<view class="buttonOP" v-if="typeList!=''">
					<view class="item" @click="selectOne('detectors',index,item)"
						:class="{selectType:index==selectDetectorsIndexA}"
						v-for="(item,index) in typeList[selectTypeIndex].detectors" :key="index">
						<img :src="item.cover_url" alt="">
						<span>{{item.detector_name}}</span>
					</view>
				</view>
			</view>
			<!-- mode中的模式 -->
			<view class="pattern">
				<view class="facilityType"
					v-if="typeList!=''&&typeList[selectTypeIndex].detectors[selectDetectorsIndex].config.mode&&typeList[selectTypeIndex].detectors[selectDetectorsIndex].config.mode.list">
					<p>模式</p>
					<view class="buttonOP">
						<button @click="selectOne('mode',index,item)" :class="{selectType:index==selectModeIndexA}"
							v-for="(item,index) in typeList[selectTypeIndex].detectors[selectDetectorsIndex].config.mode.list">{{item.name}}</button>
					</view>
				</view>
				<!-- power中的模式 -->
				<view class="facilityType"
					v-else-if="typeList!=''&&typeList[selectTypeIndex].detectors[selectDetectorsIndex].config.power.list">
					<p>模式</p>
					<view class="buttonOP">
						<button @click="selectOne('mode',index,item)" :class="{selectType:index==selectModeIndexA}"
							v-for="(item,index) in typeList[selectTypeIndex].detectors[selectDetectorsIndex].config.power.list">{{item.name}}</button>
						<button style="margin-left: 100px; background-color: #374b5f;" @click="pqCLick">点击排气</button>
					</view>
				</view>
				<view class="facilityType" v-else>
					<p>强度</p>
					<view class="buttonOPO">
						<button @click="reduce">减少</button>
						<view class="strength">
							{{modeClass}}
						</view><button @click="add">增加</button>
					</view>
				</view>
			</view>
		</view>
		<view class="bottomBox">
			<view class="back">
				<button @click="back">返回蓝牙匹配</button>
			</view>
			<view class="bottomBox-right">
				<button @click="operate('open')" class="open">开始</button>
				<button @click="operate('pause')" class="pause">暂停</button>
				<button @click="operate('finish')" class="finish">结束</button>
			</view>
		</view>
	</view>
</template>

<script>
	import {
		formatDate
	} from '../../utils.js'
	export default {
		data() {
			return {
				deviceId: '', //蓝牙设备ID
				serviceId: '', //服务UUID
				characteristicId: '', //特征值
				typeList: [], //设备数据列表
				selectTypeIndex: 0, //选择中设备类型index
				selectDetectorsIndex: 0, //探头index
				selectDetectorsIndexA: 99, //探头index
				selectModeIndex: 0, //模式index
				selectModeIndexA: 99, //模式index
				TYPE_SN: 'ZK', //设备名称
				PQCODE: "AABB12343838373244363235444138010101010101", //开始排气
				PQCLOSECODE: "AABB12343838373244363235444138010201010101", //关闭排气
				modeClass: 0, //强度等级
				minClass: '', //最小强度等级
				maxClass: '', //小大强度等级
				incrementClass: '', //强度增幅
				START: '01', //开始
				PAUSE: '00', //暂停
				equipmentNum: '', //设备编号
				modeNum: '01', //模式编号
				startTime: "", //开始时间
				time: '00:00:00', //初始展示时间
				timer: '',
				istimer: false, //是否暂停
				hour: 0, //计时(时)
				minutes: 0, //计时(分)
				seconds: 0, //计时(秒)
			};
		},
		onLoad(options) {
			// console.log(options, 333333);
			this.deviceId = options.deviceId
			this.serviceId = options.serviceId
			this.characteristicId = options.characteristicId
			let typeList = uni.getStorageSync('typeList')
			if (!typeList) {
				// 获取设备列表
				this.getTypeList()
			} else {
				this.typeList = typeList
			}
		},
		methods: {
			// -----------蓝牙报错提示
			blueError(code) {
				switch (code) {
					case 10000:
						this.errorToast('未初始化蓝牙适配器,请返回重新连接')
						break
					case 10001:
						this.errorToast('当前蓝牙适配器不可用')
						break
					case 10002:
						this.errorToast('没有找到指定设备')
						break
					case 10003:
						this.errorToast('连接失败')
						break
					case 10004:
						this.errorToast('没有找到指定服务,请返回重新连接')
						break
					case 10005:
						this.errorToast('没有找到指定特征值')
						break
					case 10006:
						this.errorToast('当前连接已断开')
						break
					case 10007:
						this.errorToast('当前特征值不支持此操作')
						break
					case 10008:
						this.errorToast('其余所有系统上报的异常')
						break
					case 10009:
						this.errorToast('Android 系统特有，系统版本低于 4.3 不支持 BLE')
						break
					case 10010:
						this.errorToast('已连接')
						break
					case 10011:
						this.errorToast('配对设备需要配对码')
						break
					case 10012:
						this.errorToast('连接超时')
						break
					case 10013:
						this.errorToast('连接 deviceld 为空或者是格式不正确')
						break
				}
			},
			// -----------统一错误封装
			errorToast(err) {
				uni.showToast({
					title: `${err}`,
					icon: 'none',
					duration: 2500
				})
			},
			// -----------------返回蓝牙匹配
			back() {
				uni.$emit('updateData', true)
				uni.navigateBack({
					delta: 1
				})
			},
			// ------------------获取设备数据列表
			async getTypeList() {
				const {
					data: res
				} = await uni.$http.post('v2/api-device/device/type_list')
				// console.log(JSON.parse(JSON.stringify(res.data.list)), '获取的数据返回');
				// 筛选出无创水光
				for (let key in res.data.list) {
					if (res.data.list[key].id != 1 && res.data.list[key].id != 15 && res.data.list[key].id != 10) {
						this.typeList.push(res.data.list[key])
					}
				}
				// 将数据保存到本地
				uni.setStorageSync('typeList', this.typeList)
			},
			// ------------------选择设备配置
			selectOne(type, index, item) {
				switch (type) {
					case 'type_sn':
						this.selectTypeIndex = index
						this.selectDetectorsIndex = 0
						this.selectModeIndex = 0
						this.selectDetectorsIndexA = 99
						this.selectModeIndexA = 99
						this.equipmentNum = '' //重置探头
						this.modeNum = '' //重置模式或强度
						console.log(item)
						//赋值哪个厂家的设备
						if (item.type_sn.includes('ZK')) {
							this.TYPE_SN = 'ZK'
						} else {
							this.TYPE_SN = 'LD'
						}
						break
					case 'detectors':
						this.selectDetectorsIndex = index
						this.selectDetectorsIndexA = index
						this.selectModeIndexA = 99
						this.equipmentNum = Number(item.detector_sn).toString(16) < 10 ? '0' + Number(item.detector_sn)
							.toString(16) : Number(item.detector_sn).toString(16) //设备探头编号(16进制)
						// console.log(this.equipmentNum)
						console.log(item)
						this.minClass = item.config.power.min //最小值
						this.maxClass = item.config.power.max //最大值
						this.incrementClass = item.config.power.increment //增幅
						this.modeClass = item.config.power.default //默认值
						break
					case 'mode':
						this.selectModeIndex = index
						this.selectModeIndexA = index
						this.modeNum = Number(item.value).toString(16) < 10 ? '0' + Number(item.value).toString(16) :
							Number(item.value).toString(16)
						// console.log(this.modeNum)
						break
				}
			},
			// -----------------开始计时
			begin() {
				if (!this.istimer) {
					this.timer = setInterval(this.startTimer, 1000);
					this.istimer = true
				}
			},
			//------------暂停计时
			pauseTime() {
				if (this.timer) {
					clearInterval(this.timer);
					this.istimer = false
				}
			},
			// -------------结束计时
			finishTime() {
				if (this.timer) {
					clearInterval(this.timer);
					this.istimer = false
					this.time = '00:00:00'
					this.startTime = ''
					this.seconds = 0
					this.minutes = 0
					this.hour = 0
				}
			},
			// -----------------计时器
			startTimer() {
				this.seconds += 1;
				if (this.seconds >= 60) {
					this.seconds = 0;
					this.minutes = Number(this.minutes) + 1;
				}
				if (this.minutes >= 60) {
					this.minutes = 0;
					this.hour = Number(this.hour) + 1;
				}
				this.time = (this.hour < 10 ? '0' + this.hour : this.hour) + ':' + (this.minutes < 10 ? '0' + this
					.minutes :
					this.minutes) + ':' + (this.seconds < 10 ? '0' + this.seconds : this.seconds);
			},
			// ----------------------操作设备开启暂停结束
			operate(type) {
				// 强度编号
				let modeNum = Number(this.modeClass).toString(16) < 10 ? '0' + Number(this.modeClass).toString(16) :
					Number(this.modeClass).toString(16)
				// 设备模式编号
				if (this.typeList[this.selectTypeIndex].detectors[this.selectDetectorsIndex].config.mode?.list || this
					.typeList[this.selectTypeIndex].detectors[this.selectDetectorsIndex].config.power?.list) {
					modeNum = this.modeNum
				}
				// console.log(modeNum);
				// 蓝牙指令操作码
				let code =
					`AABB12343838373244363235444138${this.equipmentNum}03${type=='open'?this.START:this.PAUSE}${modeNum}0101`
				// 判断是否是(中科)厂家的设备
				if (this.TYPE_SN == 'ZK') {
					code = `a9800100${this.equipmentNum}${modeNum}0101${type=='open'?this.START:this.PAUSE}3cc3`
				}
				if (!this.equipmentNum) {
					uni.showToast({
						title: '请选择探头',
						icon: "none"
					})
					return
				}
				if (this.typeList[this.selectTypeIndex].detectors[this.selectDetectorsIndex].config.mode?.list || this
					.typeList[this.selectTypeIndex].detectors[this.selectDetectorsIndex].config.power?.list) {
					if (this.selectModeIndexA == 99) {
						uni.showToast({
							title: '请选择模式',
							icon: "none"
						})
						return
					}
				}
				// 操作 开始 暂停 结束
				if (type == 'open') {
					this.send(code, '启动成功')
				} else if (type == 'pause') {
					this.send(code, '暂停成功')
				} else {
					this.send(code, '结束操作')
				}
			},
			// --------------减少强度
			reduce() {
				this.modeClass = this.modeClass - this.incrementClass
				if (this.modeClass <= this.minClass) {
					this.modeClass = this.minClass
					return
				}
			},
			//---------------增加强度
			add() {
				this.modeClass = Number(this.modeClass) + Number(this.incrementClass)
				if (this.modeClass >= this.maxClass) {
					this.modeClass = this.maxClass
					return
				}
			},
			// --------------排气
			pqCLick() {
				// 判断是否是排气指令（16）进制
				this.send(this.PQCODE, '启动成功')
			},
			// -------------------发送数据
			send(newMsg, title = '执行成功') {
				console.log(newMsg);
				wx.showLoading({
					title: '正在启动',
					mask: true
				})
				// 向蓝牙设备发送一个0x00的16进制数据
				let that = this
				let buffer = new ArrayBuffer(Math.ceil(newMsg.length / 2))
				let dataView = new DataView(buffer)
				var index = 0
				for (var i = 0; i < newMsg.length; i++) {
					if (i % 2 < 1) {
						dataView.setUint8(index, '0x' + newMsg.substr(i, 2))
						index++
					}
				}
				// console.log(that.deviceId, that.serviceId, that.characteristicId);
				// return
				uni.writeBLECharacteristicValue({
					deviceId: that.deviceId, // 设备ID
					serviceId: that.serviceId, // 服务UUID
					characteristicId: that.characteristicId, // 特征值
					value: buffer,
					success(res) {
						if (newMsg != that.PQCODE || newMsg != that.PQCLOSECODE) {
							uni.hideLoading()
							uni.showToast({
								title,
								icon: 'none',
							})
						}
						// ------排气指令
						if (newMsg == that.PQCODE) {
							uni.showLoading({
								title: '正在排气',
								mask: true
							})
							setTimeout(() => {
								console.log(1);
								that.send(that.PQCLOSECODE, '排气完成')
							}, 2000)
						}
						// ------排气指令
						if (newMsg == that.PQCLOSECODE) {
							uni.hideLoading()
							uni.showToast({
								title: '排气完成',
								icon: 'success'
							})
						}
						// 开始计时
						if (title == '启动成功') {
							that.begin()
							if (this.startTime == '') {
								this.startTime = formatDate(new Date(), 'YYYY/MM/DD/hh/mm/ss')
							}
						} else if (title == '暂停成功' || title == '排气完成') {
							that.pauseTime()
						} else {
							that.finishTime()
						}
						console.log(res, '发送数据成功')
					},
					fail(err) {
						uni.hideLoading()
						that.blueError(err.errCode)
						console.error(err)
					}
				})
			},
		}
	}
</script>

<style lang="less" scoped>
	.top {
		padding-left: 30px;

		span {
			font-size: 16px;
		}

		.title {
			font-weight: 700;
			margin-right: 40px;
		}

		.id {
			margin-right: 20px;
		}

		.startTime {
			margin: 0 20px;
		}

		.totalTime {
			margin: 0 20px;
		}
	}

	.type {
		margin-left: 100px;
		margin-top: 40px;
		width: 85%;

		.pattern {
			display: flex;
			overflow-x: scroll;

			.facilityType {
				margin-right: 80px;
			}
		}

		.buttonOP {
			display: flex;

			.item {
				padding-right: 20px;
				padding-left: 6px;
				height: 100px;
				background-color: #b8b8b8;
				margin-right: 20px;
				border-radius: 24px;
				overflow: hidden;
				display: flex;
				justify-content: center;
				align-items: center;

				img {
					width: 90px;
					height: 90px;
					border-radius: 24px;
					margin-right: 20px;
				}
			}

			button {
				flex-shrink: 0;
				margin: 0;
				background-color: #b8b8b8;
				color: #fff;
				margin-right: 50px;
			}

			.selectType {
				background-color: #1e98d7;
			}

		}

		.buttonOPO {
			display: flex;
			align-items: center;

			button {
				flex-shrink: 0;
				margin: 0;
				background-color: #f8c126;
				color: #fff;
			}

			.strength {
				width: 200px;
				background-color: #b8b8b8;
				padding: 14px;
				text-align: center;
				border-radius: 12px;
				margin: 0 4px;
			}
		}

		.facilityType {
			p {
				font-size: 18px;
				margin-bottom: 30px;
				margin-top: 30px;
			}
		}
	}

	.bottomBox {
		width: 90%;
		display: flex;
		margin-top: 100px;
		margin-left: 30px;
		justify-content: space-between;

		.back {
			button {
				background-color: #1e98d7;
				color: #fff;
			}
		}

		.bottomBox-right {
			display: flex;

			button {
				margin-right: 20px;
				width: 120px;
				color: #fff;
			}

			.open {
				background-color: #03bf16;
			}

			.pause {
				background-color: #1e98d7;
			}

			.finish {
				background-color: #d9001b;
			}
		}
	}
</style>