<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" :confirmText="i18('确认')" :cancelText="i18('取消')" @confirm="inputPwd" @cancel="cancel" :showCancelButton="true"  :title="$t('buletooth.pwdinput')" >
      <view class="slot-content">
        <view>
          <u--input
              type="number"
              :placeholder="$t('buletooth.pwdtip')"
              border="surround"
              v-model="pwd"
          ></u--input>
        </view>

        <view style="margin:10px;text-decoration: underline;margin-bottom: 0px" @click="forgetPwd">
          {{i18('忘记密码')}}？
        </view>
      </view>
    </u-modal>

    <u-popup :show="showSendData"  >
      <view class="slot-content">
        <view>
          <u--input
              :placeholder="i18('请输入值')"
              border="surround"
              v-model="sendData"
          ></u--input>
        </view>
        <view style="margin:10px;text-decoration: underline;margin-bottom: 0px" @click="sendLanyaData">
            <u-button>发送</u-button>
        </view>
      </view>
    </u-popup>
		<view v-if="deviceListDataShow.length==0" class="notice"> - {{ $t('buletooth.nodevice') }} -</view>
		<view class="gap"></view>
	</scroll-view>


</template>

<script>

// #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
import i18 from '@/utils/i18.js'
import UButton from "../../../uni_modules/uview-ui/components/u-button/u-button";
import UPopup from "../../../uni_modules/uview-ui/components/u-popup/u-popup";
	let ctx
	let deviceListData = []
	export default {
    components: {UPopup, UButton},
    data() {
			return {
        showPwd:false,
        rightPwd:"",
        pwd:"",
        timer:"",
        buleid:"",
				deviceListDataShow: [],
        showTimer:null,
        connected:false,
        uuid:"",
        showDeviceNo:false,
        inputDeviceNo:"",
        commonCode:"",
        showSendData:false,
        sendData:"",
			}
		},
		onLoad() {
      uni.setNavigationBarTitle({
        title: "蓝牙控制"
      })
      ecUI.showLoading("正在初始化蓝牙模块")
			ctx = this
      clearInterval(this.timer);
      this.timer = setInterval(() => {
        ctx.deviceListDataShow = JSON.parse(JSON.stringify(deviceListData))
      }, 800)
      console.log(this.commonCode)
		},
    onUnload(){
      ecBLE.stopBluetoothDevicesDiscovery();
      ecBLE.closeBLEConnection()
    },
		onShow() {
      if(this.showTimer!= null){
        clearTimeout(this.showTimer);
      }
			this.showTimer = setTimeout(() => {
				ctx.openBluetoothAdapter()
			}, 100)
		},
		methods: {
      sendLanyaData(){
        this.$modal.showToast("正在发送");
       this.sendBlueData(this.sendData);
      },
      i18(text){
        return text;
      },
      cancel(){
        this.showPwd = false;
        uni.navigateBack({
        });
      },
      resetPwd(){
        let self = this;
        if(!this.inputDeviceNo){
          self.$modal.showToast("请输入序列号");
          return;
        }
        let uuidRight = false;
        if(this.inputDeviceNo == this.commonCode || this.uuid == this.inputDeviceNo){
          uuidRight = true;
        }
        if(!uuidRight){
          self.$modal.showToast("序列号有误");
          return;
        }
        if(uuidRight){
          this.$modal.confirm("密码将被重置为123456").then(res=>{
            setPwd("123456")
            self.$modal.showToast("密码修改成功");
            this.rightPwd = "123456";
            self.loginSuccess();
          });
        }
      },
       getBeijingTime() {
         const date = new Date();
         const utcTime = date.getTime() + (date.getTimezoneOffset() * 60 * 1000);
         const beijingTime = new Date(utcTime + (8 * 60 * 60 * 1000));
         return beijingTime;
      },
       generateUniqueNumber(date) {
         let dateString = date.toISOString().slice(0, 10).replace(/-/g, '');
         console.log(dateString)
         let hash = w_md5.hex_md5_32(dateString);
         console.log(hash);//32位小写
         let str = "";
         for (let i = 0; i < 6; i++) {
           const c = hash.charCodeAt(i);
           str  = str+""+c+""
         }
         return str.substr(0,6);
},
      goBack(){
        uni.navigateBack({
        });
      },
      $t(title){
        return title;
      },
      inputPwd(){
        if(!this.pwd ){
          this.$modal.showToast(this.$t('buletooth.errpwd'));
        }else{
          if(this.rightPwd && this.rightPwd === this.pwd){
           this.loginSuccess();
          }else{
            this.$modal.showToast(this.$t('buletooth.errpwd'));
          }

        }
      },
      loginSuccess(){
        this.showPwd = false;
        this.showDeviceNo = false;
        uni.setStorageSync("pwd",this.rightPwd);
        uni.setStorageSync('blueid', this.buleid);
        this.pwd = "";
        ecBLE.stopBluetoothDevicesDiscovery();
        uni.navigateTo({
          url: '/pages/weitiandi/bluetooth/status'
        });
      },
      getLocalPwd(){
        let pwd = uni.getStorageSync("pwd");
        return pwd;
      },
     sendBlueData(tempSendData){
        let data = tempSendData
            .replace(/\s*/g, '')
            .replace(/\n/g, '')
            .replace(/\r/g, '')
        console.log("写入数据："+data);
        ecBLE.writeBLECharacteristicValue(data, false)
      },
			listViewTap(id){
        let self = this;
				ecUI.showLoading(this.$t('buletooth.connecting'))
				ecBLE.onBLEConnectionStateChange(res => {
          console.log(res);
					if (res.ok) {
            self.connected = true;
            ecUI.hideLoading()
            self.showSendData = true;
						ecBLE.stopBluetoothDevicesDiscovery();
            //
					} else {
            ecUI.hideLoading()
						ecUI.showModal(
                this.$t('buletooth.tip'),
							'error,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();
          data = parseDataObj(data);
		  console.log(data);
          let type = data.type;
          if(type == 253){
            self.messageCallback(data)
          }else{
            let pwd =  data.real_data;
            let localPwd = self.getLocalPwd()
            console.log(pwd);
            console.log("localPwd:"+localPwd)
            self.rightPwd = pwd;
            if(pwd != localPwd){
              self.showInputPwd();
            }else{
              self.loginSuccess();
            }
          }

        })
        self.connected = false;
				ecBLE.createBLEConnection(id);
        setTimeout(function (){
          if(!self.connected){
            self.$modal.showToast(i18('连接失败'));
            self.startBluetoothDevicesDiscovery()
          }
        },10000);
			},
      showInputPwd(){
        this.showPwd = true;
      },
      messageCallback(data){
        let self = this;
        console.log(data);
        let type = data.type;
        let real_data = data.real_data;
        if(type == 253){
          self.$modal.closeLoading();
          self.uuid = real_data.substr(0,6);
        }
        self.$forceUpdate();
        console.log('收到服务器内容：' + JSON.stringify(data));
      },
      forgetPwd(){
        this.$modal.loading("正在读取设备ID");
        getUUID()
        this.showDeviceNo = true;
      },
			openBluetoothAdapter() {
        let self = this;
				ecBLE.onBluetoothAdapterStateChange(res => {
          ecUI.hideLoading()
					if (res.ok) {
              ctx.startBluetoothDevicesDiscovery()
					} else {
						ecUI.showModal(
                this.$t('buletooth.tip'),
							`Bluetooth adapter error | ${res.errCode} | ${res.errMsg}`,
							() => {

							}
						)
					}
				})
				ecBLE.openBluetoothAdapter()
			},
			startBluetoothDevicesDiscovery() {
        ecBLE.stopBluetoothDevicesDiscovery();
				console.log('start search')
				ecBLE.onBluetoothDeviceFound(res => {
          let isRight = true;
          // if(res.name.startsWith('BT_') || res.name.startsWith('FC41D')){
          //   isRight = true;
          // }
          if(!isRight){
            return;
          }
					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'
					}
          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>
