<template>
	<view class="set">
		<uni-nav-bar dark :fixed="true" leftWidth="200rpx" rightWidth="200rpx" :border="false" background-color="#002648" status-bar
			left-icon="left" left-text="返回" @clickLeft="back" title="配 置">
			<block slot="right">
				<!-- @keydownEmit="keydownEmit" -->
				<logout ref="logoutRef" 
				@keydownEmit="keydownEmit" 
				@devicesNameChange="devicesNameChange"
				@BelConnectStatusChange="BelConnectStatusChange"
				@usbConnectStatusChange="usbConnectStatusChange"
				:baudRate="setInfo.baudRate" 
				:dataBits="setInfo.dataBit" 
				:stopBits="setInfo.stopBit"
				:belChecked="setInfo.belChecked"
				:usbChecked="setInfo.usbChecked"
				>
				</logout>
			</block>
		</uni-nav-bar>
		
		<view class="set-content">
			<!-- <view @click="close">
				断开连接
			</view> -->
			<radio-group @change="radioChangeComEye">
				<label class="radio">
					<radio value="电脑验光仪"  class="radio-class" :checked="setInfo.computerChecked">
						<text>电脑验光仪:</text>
					</radio>
					<view class="computer-yg">
						<uni-data-picker style="flex: 1;" v-model="setInfo.computerValue" :localdata="computerYGList" class="picker-scroll"
							popup-title="请选择" @change="computerChange" :clear-icon="false">
						</uni-data-picker>
						<!-- <input type="text" @click="inputComputerClick" :value="setInfo.computerValue">
						<zhilin-cascader
						        v-model="ComputerCascaderFalse"
						        :options="computerYGList"
						        @confirm="computerChange"
						>
						</zhilin-cascader> -->
					</view>
				</label>
				<label class="radio">
					<radio value="眼压仪" class="radio-class" :checked="setInfo.eyeChecked">
						<text>眼压仪:</text>
					</radio>
					<view class="eye-yq">
						<uni-data-picker  style="flex: 1;" v-model="setInfo.eyeValue" :localdata="eyeList" class="picker-scroll"
							popup-title="请选择" @change="eyechange" :clear-icon="false">
						</uni-data-picker>
						<!-- <input type="text" @click="inputEyeClick" :value="setInfo.eyeValue">
						<zhilin-cascader
						        v-model="eyeCascaderFalse"
						        :options="eyeList"
						        @confirm="eyechange"
						>
						</zhilin-cascader> -->
					</view>
				</label>
			</radio-group>
			<view class="ftpReport">
				<view class="ftp-text">
					虚拟设备名称：
				</view>
				<input type="text"  :value="setInfo.DEVICE_CODE" placeholder="请输入虚拟设备名称" @input="deviceCodeInput">
			</view>
			<view class="bel-use">
				<text>连接方式:</text>
				<radio-group @change="radioChangeBelUSB" class="radio-group-two">
					<label class="radio-two">
						<radio value="蓝牙" :checked="setInfo.belChecked" />
						蓝牙
					</label>
					<label class="radio-two">
						<radio value="USB" :checked="setInfo.usbChecked" />
						USB
					</label>
					<label class="radio-two">
						<radio value="VirtualDevice" :checked="setInfo.VirtualDeviceChecked" />
						虚拟设备
					</label>
				</radio-group>
			</view>
			<view class="USB-BEL-Content">
				<view class="reader-card" v-if="setInfo.belChecked" @click="belHandle">
					<text>蓝牙名称:</text>
					<!-- v-if="BelConnectStatus" -->
					<view >
						<text>{{BELInfoName ? BELInfoName : '空'}}</text>
						<text class="bel-text">{{ BelConnectStatus ? '断开连接' : '连接蓝牙'}}</text>
					</view>
					
				</view>
				
				<view class="USB-content" v-if="setInfo.usbChecked">
					<view class="use-LJ">
						<text>连接状态：</text>
						<text class="use-LJ-No" v-if="!usbConnectStatus">
							<text>未连接</text>
							<text @click="USBHandle('连接')">连接USB</text>
						</text>
						<text class="use-LJ-Yes" v-if="usbConnectStatus">
							<text>已连接</text>
							<text @click="USBHandle('断开')">断开USB</text>
						</text>
					</view>
					<view class="port-baud-rate">
						<text>波特率:</text>
						<input type="text" :value="setInfo.baudRate" @input="USBInputChange('baudRate',$event)">
					</view>
					<view class="data-bit">
						<text>数据位:</text>
						<input type="text" :value="setInfo.dataBit" @input="USBInputChange('dataBit',$event)">
					</view>
					<view class="stop-rate">
						<text>停止位:</text>
						<input type="text" :value="setInfo.stopBit" @input="USBInputChange('stopBit',$event)">
					</view>
				</view>
			</view>

			<button type="primary" class="buttons" @click="sureHandle">保存</button>
		</view>
	</view>
</template>

<script>
	var BLE = uni.requireNativePlugin('Zhimi-BLE');
	import logout from '@/components/logout.vue'
	import setData from '@/mixin/setData.js'
	export default {
		data() {
			return {
				setInfo: {
					computerBRAND: '', // 品牌
					computerMODEL: '', // 型号
					eyeBRAND: '', // 品牌
					eyeMODEL: '', // 型号
					DEVICE_CODE:'', // 虚拟设备名称
					computerValue:[],
					eyeValue:[],
					belName: '',
					baudRate: 9600,
					dataBit: 8,
					stopBit: 1,
					computerChecked: true,
					eyeChecked: false,
					belChecked: true,
					usbChecked: false,
					VirtualDeviceChecked:false,
				},
				BelConnectStatus: false,
				usbConnectStatus: false,
				BELInfoName: '',
				ComputerCascaderFalse:false,
				eyeCascaderFalse:false,
				MaskBool:false,
			}
		},
		components: {
			logout
		},
		mixins: [setData],
		onLoad() {
			this.BELInfoName = uni.getStorageSync('BELInfoName') ? JSON.parse(uni.getStorageSync('BELInfoName')) : ''
			uni.getStorageSync('setInfo') ? this.setInfo = JSON.parse(uni.getStorageSync('setInfo')) : ''
			console.log(this.setInfo)
			this.getDeviceList()
			// plus.key.addEventListener('keydown', event => {
			// 	console.log("按键：" + event.keyCode);
			// 	// 扫码
			// 	// if (event.keyCode === 4) {
			// 	// 	uni.navigateTo({
			// 	// 		url: '/pages/scan-code/index'
			// 	// 	});

			// 	// }
			// })
		},
		beforeDestroy() {
			uni.hideLoading()
		},
		onBackPress() {
			console.log('onBackPress')
		   if(this.MaskBool) {  
		     this.MaskBool= false;  
		     return true;  
		   }else{
			  uni.navigateTo({
			  	url: '/pages/scan-code/index'
			  })
		      return true  
		   }  
		},
		methods: {
			keydownEmit(event) {
				console.log('扫码键', event)
				// 返回
				// if (event.keyCode === 27) {
				// 	console.log(event.keyCode)
				// 	// uni.navigateTo({
				// 	// 	url: '/pages/scan-code/index'
				// 	// })
				// }
				// ok
				if (event.keyCode === 13) {
					this.sureHandle()
				}
			},
			deviceCodeInput(e) {
				// console.log(e);
				this.setInfo.DEVICE_CODE = e.detail.value
			},
			async getDeviceList() {
				console.log(123)
				let dataJson = {
					cmd: 'GetDeviceList',
					strXmlorJson: JSON.stringify({
						HM_REQUEST: {
							REQUEST_HEAD: {}
						}
					})
				}
				const res = await this.$baseAPI.request(this.$portAdress.custom, dataJson, 'post')
				let resResult = JSON.parse(res.d)
				console.log(resResult)
				if (resResult.HM_RESPONSE.CODE == 0) {
					let yanyaDevice = resResult.HM_RESPONSE.RESULT.YANYA_LIST.DEVICE
					let yanGuangDevice = resResult.HM_RESPONSE.RESULT.YANGUANG_LIST.DEVICE
					this.setDataFormat(yanyaDevice, 'eyeList')
					this.setDataFormat(yanGuangDevice, 'computerYGList')
				} else {
					uni.showToast({
						title: resResult.HM_RESPONSE.ERROR,
						icon: 'error'
					})
				}
			},
			
			// 封装修改的数据格式
			setDataFormat(Device, name) {
				Device.forEach((resitem, resindex) => {
					if (Device.length - 1 >= resindex) {
						this[name].push({
							text: '',
							value: '',
						})
						this[name][resindex].text = resitem.BRAND
						this[name][resindex].value = resitem.BRAND
						this[name][resindex].children = []
					}
					resitem.MODEL_LIST.MODEL.forEach((resiten, index) => {
						if (resitem.MODEL_LIST.MODEL.length - 1 >= index) {
							this[name][resindex].children.push({
								text: '',
								value: '',
							})
							this[name][resindex].children[index].text = resiten
							this[name][resindex].children[index].value = resiten
							// console.log(this[name])
						}
					})
				})
			},
			// 点击电脑验光仪输入框时
			inputComputerClick() {
				this.ComputerCascaderFalse = true
			},
			// 点击眼压仪输入框时
			inputEyeClick() {
				this.eyeCascaderFalse = true
			},
			// 电脑验光仪改变时 
			computerChange(e) {
				console.log('电脑验光仪改变时',e)
				// this.setInfo.computerValue = `${e[0]} / ${e[1]}`
				// this.setInfo.computerBRAND = e[0]
				// this.setInfo.computerMODEL = e[1]
				uni.setStorageSync('typeCheckbox', '验光')
				this.setInfo.computerValue = e.detail.value
				this.setInfo.computerBRAND = e.detail.value[0].value
				this.setInfo.computerMODEL = e.detail.value[1].value
			},
			// 眼压仪改变时
			eyechange(e) {
				console.log('眼压仪改变时',e)
				// this.setInfo.eyeValue = `${e[0]} / ${e[1]}`
				// this.setInfo.eyeBRAND = e[0]
				// this.setInfo.eyeMODEL = e[1]
				uni.setStorageSync('typeCheckbox', '眼压')
				this.setInfo.eyeValue = e.detail.value
				this.setInfo.eyeBRAND = e.detail.value[0].value
				this.setInfo.eyeMODEL = e.detail.value[1].value
			},
			// 蓝牙连接状态
			BelConnectStatusChange(val) {
				this.BelConnectStatus = val
				console.log(this.BelConnectStatus)
			},
			// usb连接状态
			usbConnectStatusChange(val) {
				this.usbConnectStatus = val
				console.log(this.usbConnectStatus)
			},
			devicesNameChange(val) {
				console.log(val)
				this.BELInfoName = val
			},
			// 波特率/数据位/停止位改变时
			USBInputChange(name,e) {
				// console.log(e);
				this.setInfo[name] = e.detail.value
			},
			// 电脑验光仪和眼压选择
			radioChangeComEye(val) {
				console.log(val)
				if (val.detail.value == '电脑验光仪') {
					this.setInfo.computerChecked = true
					this.setInfo.eyeChecked = false
					uni.setStorageSync('typeCheckbox', '验光')

				} else if(val.detail.value == '眼压仪'){
					this.setInfo.computerChecked = false
					this.setInfo.eyeChecked = true
					uni.setStorageSync('typeCheckbox', '眼压')
				}
			},
			// 蓝牙和USB选择
			radioChangeBelUSB(val) {
				console.log(val)
				if (val.detail.value === '蓝牙') {
					this.setInfo.belChecked = true
					uni.setStorageSync('belChecked', true)
					this.setInfo.usbChecked = false
					this.setInfo.VirtualDeviceChecked = false
				} else if(val.detail.value === 'USB'){
					this.setInfo.belChecked = false
					uni.setStorageSync('belChecked', false)
					this.setInfo.usbChecked = true
					this.setInfo.VirtualDeviceChecked = false
				} else if(val.detail.value === 'VirtualDevice') {
					this.setInfo.belChecked = false
					uni.setStorageSync('belChecked', false)
					this.setInfo.usbChecked = false
					this.setInfo.VirtualDeviceChecked = true
				}
				console.log(this.setInfo.belChecked);
				console.log(this.setInfo.usbChecked);
				console.log(this.setInfo.VirtualDeviceChecked);
			},
			// 点击连接蓝牙
			belHandle() {
				// console.log('连接蓝牙', this.$refs.logoutRef)
				if(this.usbConnectStatus) {
					uni.showToast({
						title:"请先断开USB"
					})
				} else {
					if(this.BelConnectStatus) {
						this.$refs.logoutRef.close()
					} else {
						uni.getStorageSync('BELInfoName') ? uni.showModal({
							title: '提示',
							content: '是否连接默认蓝牙？',
							cancelText:"搜索新设备",
							success: (res) => {
								if (res.confirm) {
									this.$refs.logoutRef.ISdefaultBle = true
									 this.$refs.logoutRef.initBlue()
								} else {
									uni.setStorageSync('belChecked', true)
									this.$refs.logoutRef.ISdefaultBle = false
									 this.$refs.logoutRef.initBlue()
								}
							}
						}) : (this.$refs.logoutRef.ISdefaultBle = false , uni.setStorageSync('belChecked', true) , this.$refs.logoutRef.initBlue())
					}
				}
			},
			// 点击连接USB
			USBHandle(text) {
				console.log('连接usb');
				if(this.BelConnectStatus) {
					uni.showToast({
						title:"请先断开蓝牙"
					})
				} else {
					text === '连接' ? this.$refs.logoutRef.openUSB() : this.$refs.logoutRef.closeUSB()
				}
			},
			// stopHandle() {
			// 	this.$refs.logoutRef.stopDiscovery()
			// },
			// close() {
			// 	console.log('断开')
			// 	this.$refs.logoutRef.close()
			// },
			
			// 保存
			sureHandle() {
				uni.setStorageSync('setInfo', JSON.stringify(this.setInfo))
				if(this.usbConnectStatus && this.setInfo.VirtualDeviceChecked) {
					uni.showToast({
						title:"请先断开USB"
					})
				} else if(this.BelConnectStatus && this.setInfo.VirtualDeviceChecked) {
					uni.showToast({
						title:"请先断开蓝牙"
					})
				} else {
					uni.showToast({
						title: '您已保存成功',
						icon: 'success'
					})
					uni.navigateTo({
						url: '/pages/scan-code/index'
					})
				}
			},
			// 点击返回
			back() {
				uni.navigateTo({
					url: '/pages/scan-code/index'
				});
			},
			
		}
	}
</script>

<style lang="less">
	.set {
		height: 100vh;
		background-color: #002648;
		display: flex;
		flex-direction: column;
		.picker-scroll {
			.uni-data-pickerview  {
				.list {
					overflow-y: scroll;
				}
			}
		}
		.set-content {
			height: 100%;
			margin-top: 50rpx;
			background-color: #fff;
			// border-top-left-radius: 40rpx;
			// border-top-right-radius: 40rpx;
			padding: 50rpx 30rpx;

			.radio {
				margin-bottom: 26rpx;
				display: block;
			}

			.radio-class {
				margin-bottom: 20rpx
			}

			.reader-card {
				display: flex;

				text:nth-child(1) {
					display: inline-block;
					margin-right: 30rpx;
				}

				.bel-text {
					display: inline-block;
					margin-left: 20rpx;
					color: red;
				}
			}
			.use-LJ {
				margin-bottom: 30rpx;
			}
			.use-LJ-No,.use-LJ-Yes {
				text:nth-child(1) {
					margin-right: 20rpx;
				}
				text:nth-child(2) {
					color: red;
				}
			}
			.port-baud-rate,
			.data-bit,
			.stop-rate {
				text {
					width: 220rpx;
				}

				display: flex;
				align-items: center;
				margin-bottom: 26rpx
			}
			.ftp-text {
				margin-bottom:20rpx
			}
			.bel-use {
				display: flex;
				margin-top: 40rpx;
				margin-bottom: 26rpx;
			}

			.radio-group-two {
				margin-left: 14rpx;
			}

			.radio-two {
				margin-right: 10rpx;
			}
		}

		input {
			border: 2px solid #002648;
			flex: 1;
			height: 80rpx;
			line-height: 80rpx;
			padding: 6rpx 14rpx;
			border-radius: 10rpx;
		}

		.input-value-border {
			border: 2px solid #002648;
		}

		.buttons {
			margin-top: 50rpx;
			margin-bottom: 30rpx;
		}
		
	}
</style>
<style lang="less">

</style>
