<template>
	<scroll-view class="main-container" scroll-y="true"
		:refresher-enabled="false">
		<view v-for="(item, index) in deviceListDataShow" :key="item.id" class="list-item" hover-class="list-item-hover"
			hover-start-time="0" hover-stay-time="100" @click="listViewTap(item.id)">
			<image v-if="item.manufacturer==='eciot'" src="/static/img/ecble.png" class="list-item-img"></image>
			<image v-else src="/static/img/ble.png" class="list-item-img"></image>
			<text class="list-item-name">{{item.name}}</text>
			<image v-if="item.rssi >= -41" src="/static/img/s5.png" mode="aspectFit" class="list-item-rssi-img"></image>
			<image v-else-if="item.rssi >= -55" src="/static/img/s4.png" mode="aspectFit" class="list-item-rssi-img"></image>
			<image v-else-if="item.rssi >= -65" src="/static/img/s3.png" mode="aspectFit" class="list-item-rssi-img"></image>
			<image v-else-if="item.rssi >= -75" src="/static/img/s2.png" mode="aspectFit" class="list-item-rssi-img"></image>
			<image v-else="item.rssi < -75" src="/static/img/s1.png" mode="aspectFit" class="list-item-rssi-img"></image>
			<text class="list-item-rssi">{{item.rssi}}</text>
			<view class="list-item-line"></view>
		</view>
    <u-modal :show="showPwd" @confirm="inputPwd" @cancel="cancel" :showCancelButton="true"  title="请输入操作密码" >
      <view class="slot-content">
        <u--input
            type="number"
            placeholder="6位数字密码"
            border="surround"
            v-model="pwd"
        ></u--input>
      </view>
    </u-modal>
		<view v-if="deviceListDataShow.length==0" class="notice"> - 未发现设备，请确认蓝牙是否打开 -</view>
		<view class="gap"></view>
	</scroll-view>


</template>

<script>
import {getPwd,setPwd,parsePwd,sendPortDetailCmd} from "@/utils/weitiandi/device/device.js";
// #ifdef APP
import ecUI from '@/utils/ecUI.js'
import ecBLE from '@/utils/ecBLE/ecBLE.js'
// #endif
// #ifdef MP
const ecUI = require('@/utils/ecUI.js')
const ecBLE = require('@/utils/ecBLE/ecBLE.js')
// #endif
	let ctx
	let deviceListData = []
	export default {
		data() {
			return {
        showPwd:false,
        rightPwd:"",
        pwd:"",
        timer:"",
        buleid:"",
				deviceListDataShow: [],
        showTimer:null,
			}
		},
		onLoad() {
      ecUI.showLoading('蓝牙初始化中')
			ctx = this
      clearInterval(this.timer);
      this.timer = setInterval(() => {
        ctx.deviceListDataShow = JSON.parse(JSON.stringify(deviceListData))
      }, 800)
		},
    onUnload(){
      ecBLE.stopBluetoothDevicesDiscovery();
      ecBLE.closeBLEConnection()
    },
		onShow() {
      if(this.showTimer!= null){
        clearTimeout(this.showTimer);
      }
			this.showTimer = setTimeout(() => {
				ctx.openBluetoothAdapter()
			}, 100)
		},
		methods: {
      cancel(){
        this.showPwd = false;
        uni.navigateBack({
        });
      },
      inputPwd(){
        if(!this.pwd ){
          this.$modal.showToast("密码不能为空");
        }else{
          if(this.rightPwd && this.rightPwd === this.pwd){
           this.loginSuccess();
          }else{
            this.$modal.showToast("密码有误，请重新输入");
          }

        }
      },
      loginSuccess(){
        this.showPwd = false;
        uni.setStorageSync("pwd",this.rightPwd);
        uni.setStorageSync('blueid', this.buleid);
        this.pwd = "";
        ecBLE.stopBluetoothDevicesDiscovery();
        uni.navigateTo({
          url: '/pages/weitiandi/bluetooth/index'
        });
      },
      getLocalPwd(){
        let pwd = uni.getStorageSync("pwd");
        return pwd;
      },
			listViewTap(id){
        let self = this;
				ecUI.showLoading('设备连接中')
				ecBLE.onBLEConnectionStateChange(res => {
          console.log(res);
					if (res.ok) {
            setTimeout(function(){
              ecUI.hideLoading()
              getPwd();
              self.buleid = id;
            },2500)
            // uni.setStorageSync('blueid', id);
						// ecBLE.stopBluetoothDevicesDiscovery();
            //
					} else {
            ecUI.hideLoading()
            uni.removeStorageSync('blueid');
						ecUI.showModal(
							'提示',
							'连接失败,errCode=' + res.errCode + ',errMsg=' + res.errMsg
						)
					}
				});
        //receive data
        ecBLE.onBLECharacteristicValueChange((str, strHex) => {
			console.log("数据来了")
          let isCheckRevHex = true;
          let data =
              (isCheckRevHex ? strHex.replace(/[0-9a-fA-F]{2}/g, ' $&') : str)
          // console.log(data)
          self.$modal.closeLoading();
          console.log("settting:"+data);
          //AA 67 0D 05 00 00 00 00 00 00 00 00 00 25 E2 00 80
          let pwd =  parsePwd(data);
          let localPwd = self.getLocalPwd()
          console.log("pwd:"+pwd);
          console.log("localPwd:"+localPwd)
          self.rightPwd = pwd;
          if(pwd != localPwd){
            self.showInputPwd();
          }else{
            self.loginSuccess();
          }
        })
				ecBLE.createBLEConnection(id)
			},
      showInputPwd(){
        this.showPwd = true;
      },
			openBluetoothAdapter() {
        let self = this;
				ecBLE.onBluetoothAdapterStateChange(res => {
          ecUI.hideLoading()
					if (res.ok) {
						console.log('Bluetooth adapter ok')
            let blueid = uni.getStorageSync('blueid');
            if(blueid){
              self.listViewTap(blueid);
            }else{
              ctx.startBluetoothDevicesDiscovery()
            }
					} else {
						ecUI.showModal(
							'提示',
							`Bluetooth adapter error | ${res.errCode} | ${res.errMsg}`,
							() => {

							}
						)
					}
				})
				ecBLE.openBluetoothAdapter()
			},
			startBluetoothDevicesDiscovery() {
				console.log('start search')
				ecBLE.onBluetoothDeviceFound(res => {
					// if(res.id==="EC:22:05:13:78:49")
					// console.log(`id:${res.id},name:${res.name},rssi:${res.rssi}`)
					for (const item of deviceListData) {
						if (item.id === res.id) {
							item.name = res.name
							item.rssi = res.rssi
							return
						}
					}
					let manufacturer = ''
					if (res.name.length === 11 && res.name.startsWith('@')) {
						manufacturer = 'eciot'
					}
					if (res.name.length === 15 && res.name.startsWith('BT_')) {
						manufacturer = 'eciot'
					}
					deviceListData.push({
						id: res.id,
						name: res.name,
						rssi: res.rssi,
						manufacturer,
					})
				})
				ecBLE.startBluetoothDevicesDiscovery()
			},
		}
	}
</script>

<style>
	.main-container {
		height: 100vh;
	}

	.list-item {
		height: 57px;
		position: relative;
	}

	.list-item-hover {
		background-color: #e5e4e9;
	}

	.list-item-img {
		position: absolute;
		width: 36px;
		height: 36px;
		left: 20px;
		top: 10px;
	}

	.list-item-name {
		position: absolute;
		font-size: 22px;
		left: 76px;
		top: 0px;
		line-height: 56px;
	}

	.list-item-rssi-img {
		position: absolute;
		width: 20px;
		height: 20px;
		right: 20px;
		top: 13px;
	}

	.list-item-rssi {
		position: absolute;
		width: 40px;
		height: 20px;
		right: 10px;
		top: 33px;
		font-size: 12px;
		font-weight: bold;
		display: flex;
		justify-content: center;
	}

	.list-item-line {
		position: absolute;
		height: 1px;
		width: 100vw;
		left: 20px;
		top: 56px;
		background-color: #c6c6c8;
	}

	.notice {
		display: flex;
		justify-content: center;
		align-items: center;
		margin-top: 10px;
		font-size: 13px;
		color: #909399;
	}

	.gap {
		height: 57px;
	}
</style>
