<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/images/new/starts/ble.png" class="list-item-img"></image>
      <image v-else src="/static/images/new/starts/bleof.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-modal :show="showDeviceNo" :confirmText="i18('确认')" :cancelText="i18('取消')" @confirm="resetPwd" @cancel="cancel" :showCancelButton="true"  :title="i18('重置密码')" >
      <view class="slot-content">
        <view>
          <u--input
              type="number"
              :placeholder="i18('请输入序列号')"
              border="surround"
              v-model="inputDeviceNo"
          ></u--input>
        </view>
        <view style="margin:10px;text-decoration: underline;margin-bottom: 0px" @click="forgetDeviceNo">
          {{i18('忘记序列号')}}？
        </view>
      </view>
    </u-modal>
    <view v-if="deviceListDataShow.length==0" class="notice"> - {{ $t('buletooth.nodevice') }} -</view>
    <view class="gap"></view>
  </scroll-view>


</template>

<script>
import {getPwd,setPwd,parsePwd,sendPortDetailCmd,getUUID,parseDataObj} from "@/utils/weitiandi/device/device.js";
import w_md5 from "@/js_sdk/zww-md5/w_md5.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
import i18 from '@/utils/i18.js'
let ctx
let deviceListData = []
export default {
  data() {
    return {
      showPwd:false,
      rightPwd:"",
      pwd:"",
      timer:"",
      buleid:"",
      deviceListDataShow: [],
      showTimer:null,
      connected:false,
      uuid:"",
      showDeviceNo:false,
      inputDeviceNo:"",
      commonCode:""
    }
  },
  onLoad() {
    uni.setNavigationBarTitle({
      title: this.$t('page.bluetooth')
    })
    ecUI.showLoading(this.$t('buletooth.init'))
    ctx = this
    clearInterval(this.timer);
    this.timer = setInterval(() => {
      ctx.deviceListDataShow = JSON.parse(JSON.stringify(deviceListData))
    }, 800)
    this.commonCode = this.generateUniqueNumber(this.getBeijingTime());
    console.log(this.commonCode)
  },
  onUnload(){
    ecBLE.stopBluetoothDevicesDiscovery();
    ecBLE.closeBLEConnection()
  },
  onShow() {
    if(this.showTimer!= null){
      clearTimeout(this.showTimer);
    }
    this.showTimer = setTimeout(() => {
      ctx.openBluetoothAdapter()
    }, 100)
  },
  methods: {
    forgetDeviceNo(){
      this.$modal.showToast("请截图该页面联系售后部门");
    },
    i18(text){
      return i18(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({
      });
    },
    inputPwd(){
      if(!this.pwd ){
        this.$modal.showToast(this.$t('buletooth.nopwd'));
      }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;
    },
    listViewTap(id){
      let self = this;
      ecUI.showLoading(this.$t('buletooth.connecting'))
      ecBLE.onBLEConnectionStateChange(res => {
        console.log(res);
        if (res.ok) {
          self.connected = true;
          setTimeout(function(){
            ecUI.hideLoading()
            getPwd();
            self.buleid = id;
          },500)
          // uni.setStorageSync('blueid', id);
          // ecBLE.stopBluetoothDevicesDiscovery();
          //
        } else {
          let msg = res.errMsg;
          console.log(msg);
          if(msg.indexOf("already") != -1){
            self.connected = true;
            setTimeout(function(){
              ecUI.hideLoading()
              getPwd();
              self.buleid = id;
            },500)
            return;
          }
          ecUI.hideLoading()
          uni.removeStorageSync('blueid');
          ecUI.showModal(
              this.$t('buletooth.tip'),
              'error,errCode=' + res.errCode + ',errMsg=' + i18(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)
        data = parseDataObj(data);
        console.log(data);
        let type = data.type;
        if(type == 253){
          self.$modal.closeLoading();
          self.messageCallback(data)
        }else if(type == 172){
          self.$modal.closeLoading();
          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) {
          let blueid = uni.getStorageSync('blueid');
          console.log('Bluetooth adapter ok,blueid:'+blueid)
          if(blueid){
            self.listViewTap(blueid);
          }else{
            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 => {
        // if(res.id==="EC:22:05:13:78:49")
        // console.log(`id:${res.id},name:${res.name},rssi:${res.rssi}`)
        let isRight = false;
        if(res.name.startsWith('BT_') || res.name.startsWith('WGD')){
          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;
  background-image: url('../../../static/images/new/starts/bg1.jpg');
  background-size: cover;
  background-repeat: no-repeat;
}

.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;
  color: #e5e4e9;
}

.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;
  color: aliceblue;
}

.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>
