<template>
  <view style="height: 100vh">
	<view v-if="!connected">
    <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-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>
  </view>

  <view v-if="connected">
    <view class="text-area">
      <u--form  v-if="isCompanyUser()" style="width: 100%;"
               labelPosition="left"
               ref="uForm"
      >
        <u-form-item
            label="WIFI名称:"
            borderBottom
            labelWidth="auto"
            @click="openChooseWifi"
            ref="item1"
        >
          <u--input
              v-model="SSID"
              disabled
              disabledColor="#ffffff"
              placeholder="请选择wifi:"
              border="none"
          ></u--input>
          <u-icon
              slot="right"
              name="arrow-right"
          ></u-icon>
        </u-form-item>
        <u-form-item
            label="密码:"
            borderBottom
            ref="item1"
        >
          <u--input
              v-model="password"
              border="none"
          ></u--input>
        </u-form-item>

      </u--form>
      <u--form  v-else style="width: 100%;"
                labelPosition="left"
                ref="uForm"
      >
        <u-form-item
            label="WIFI名称:"
            borderBottom
            labelWidth="auto"
            @click="openChooseWifi"
            ref="item1"
        >
          <u--input
              v-model="SSID"
              disabled
              disabledColor="#ffffff"
              placeholder="请选择wifi:"
              border="none"
          ></u--input>
          <u-icon
              slot="right"
              name="arrow-right"
          ></u-icon>
        </u-form-item>
        <u-form-item
            label="密码:"
            borderBottom
            ref="item1"
        >
          <u--input
              v-model="password"
              border="none"
          ></u--input>
        </u-form-item>


        <u-form-item
            label="二维码ID:"
            borderBottom
            ref="item1"
            labelWidth="auto"
        >
          <u--input
              v-model="qrcodeid"
              border="none"
          ></u--input>
        </u-form-item>

        <u-form-item
            @click="showProductList = true"
            label="产品类型:"
            borderBottom
            ref="item1"
            labelWidth="auto"
        >
          <u--input disabled
                    v-model="productName"
                    border="none"
          ></u--input>
        </u-form-item>

      </u--form>
    </view>
    <view style="margin:10px">
      <u-button text="开始配网" v-if="isCompanyUser()" @click="doConnectUser(1)" size="small" type="primary"></u-button>

      <u-button text="开始配网" v-else @click="doConnect(2)" size="small" type="primary"></u-button>

    </view>
    <u-picker @cancel="showWiftList=false" @confirm="chooseWifi"  :show="showWiftList" :columns="wifiList"></u-picker>

    <u-picker @cancel="showProductList=false" keyName="text" @confirm="chooseProduct"  :show="showProductList" :columns="chooseProductList"></u-picker>

  </view>
  </view>
</template>

<script>
import authObj from '@/plugins/auth.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'
import {getDevcieByQrcodeID} from "@/api/device/device";
	let ctx
	let deviceListData = []
	export default {
    data() {
			return {
        showProductList:false,
        showPwd:false,
        rightPwd:"",
        pwd:"",
        timer:"",
        buleid:"",
				deviceListDataShow: [],
        showTimer:null,
        connected:false,
        uuid:"",
        showDeviceNo:false,
        inputDeviceNo:"",
        commonCode:"",
        showSendData:false,
        sendData:"",
        qrcodeid:"",
        productName:"",
        deviceno:"",
        SSID:"",
        password:"",
        showWiftList:false,
        productId:56,
        chooseProductList:[[      {
          id:56,text:"3"
        },
          {
            id:56,text:"4"
          },
          {
            id:57,text:"5"
          }
          ]],
        wifiList: [
          []
        ],

			}
		},
		onLoad() {
      uni.setNavigationBarTitle({
        title: "蓝牙配网"
      })
      this.deviceno  = this.generateTimestamp();
      ecUI.showLoading("正在初始化蓝牙模块")
			ctx = this
      clearInterval(this.timer);
      this.timer = setInterval(() => {
        ctx.deviceListDataShow = JSON.parse(JSON.stringify(deviceListData))
      }, 800)
      console.log(this.commonCode)
      this.productName = this.chooseProductList[0][0].text;
		},
    onUnload(){
      ecBLE.stopBluetoothDevicesDiscovery();
      ecBLE.closeBLEConnection()
    },
		onShow() {
      if(this.showTimer!= null){
        clearTimeout(this.showTimer);
      }
			this.showTimer = setTimeout(() => {
				ctx.openBluetoothAdapter()
			}, 100)
		},
		methods: {
      isCompanyUser(){
        return authObj.authRoleAdmin(["companymgr"]) || authObj.authRoleAdmin(["companyuser"]);
      },
      chooseProduct(e){
        this.productId = e.value[0].id;
        this.productName = e.value[0].text;
        this.showProductList= false;
      },
      generateTimestamp() {
  const date = new Date();
  const year = date.getFullYear().toString().substr(2);
  const month = date.getMonth() + 1;
  const day = date.getDate();
  const hours = date.getHours();
  const minutes = date.getMinutes();

  // 生成6位随机数字
  const randomNum = Math.floor(Math.random() * 900000) + 100000;

  // 将数字拼接成字符串
  const timestamp = `${year}${month < 10 ? '0' + month : month}${day < 10 ? '0' + day : day}${hours}${minutes < 10 ? '0' + minutes : minutes}${randomNum}`;

  return timestamp;
},
      getAuth(){
        wx.getSetting({
          success(res) {
            if (!res.authSetting['scope.userLocation']) {
              wx.authorize({
                scope: 'scope.userLocation',
                success () {
                  // 用户已经同意小程序使用录音功能，后续调用 wx.startRecord 接口不会弹窗询问

                }
              })
            }
          }
        })
      },
      chooseWifi(e){
        this.SSID = e.value[0];
        this.showWiftList= false;
      },
      openChooseWifi(){
        if(this.wifiList[0].length == 0){
          this.getWifiList();
        }else{
          this.showWiftList = true;
        }
      },
      openWifi(){
        let self = this;
        // #ifdef MP-WEIXIN
        wx.startWifi({
          success(res) {
            console.log(res);
            // self.getWifiList();
          },
          fail(res) {
            console.log(res)
            uni.showToast({
              title: '请打开WIFI',
              icon: 'none',
              duration: 3000
            });

          },
        })
        // #endif

      },
      getWifi(){
        // #ifdef MP-WEIXIN
        var that = this
        wx.getConnectedWifi({
          success(res) {
            console.log(res)
            that.BSSID = res.wifi.BSSID
            that.WIFIName = res.wifi.SSID
          },
          fail(res) {
            console.log(res)
            //报错的相关处理
          },
        })
        // #endif

      },
      getWifiList(){
        // #ifdef MP-WEIXIN
        var that = this
        uni.showLoading();
        wx.getWifiList({
          success(res) {
            console.log(res)
            wx.onGetWifiList(function(res) {
              that.showWiftList = true;
              uni.hideLoading();
              console.log("获取wifi列表");
              that.wifiList = [[]];
              console.log(res.wifiList); //在这里提取列表数据
              //通过遍历将WIFI名字存入集合，以便下卡框等组件使用
              for (var i = 0; i < res.wifiList.length; i++) {
                that.wifiList[0].push(res.wifiList[i].SSID)
              }
            })
          },
          fail(res) {
            console.log(res)
            uni.showToast({
              title: '获取wifi失败，请检查wifi',
              icon: 'none',
              duration: 2000
            });
          },
        })
        // #endif

      },
      doConnectUser(){
        if(this.SSID == ""){
          uni.showToast({
            title: '请选择WIFI',
            icon: 'none',
            duration: 3000
          });
          return;
        }
        if(this.password == ""){
          uni.showToast({
            title: '请输入wifi密码',
            icon: 'none',
            duration: 3000
          });
          return;
        }

        /**
         * ID:XXX+回车换行(设备编号)
         * QR:XXXX+回车换行(二维码ID)
         * ssid:WiFi名字+回车换行
         * psd:wifi密码+回车换行
         * 最后+OK
         */
        let self = this;
        let endStr = "$$";
        ecUI.showLoading("正在配置网络信息")

        setTimeout(function(){
          self.sendBlueData("ssid:"+self.SSID+endStr);
        },400);

        setTimeout(function(){
          self.sendBlueData("psd:"+self.password+endStr);
        },600);


        setTimeout(function(){
          self.sendBlueData("OK");
        },800);



      },
      doConnect(){
        if(this.SSID == ""){
          uni.showToast({
            title: '请选择WIFI',
            icon: 'none',
            duration: 3000
          });
          return;
        }
        if(this.password == ""){
          uni.showToast({
            title: '请输入wifi密码',
            icon: 'none',
            duration: 3000
          });
          return;
        }

        if(this.qrcodeid == ""){
          uni.showToast({
            title: '请输入二维码ID',
            icon: 'none',
            duration: 3000
          });
          return;
        }


        if(this.deviceno == ""){
          uni.showToast({
            title: '请输入设备编号',
            icon: 'none',
            duration: 3000
          });
          return;
        }


        /**
         * ID:XXX+回车换行(设备编号)
         * QR:XXXX+回车换行(二维码ID)
         * ssid:WiFi名字+回车换行
         * psd:wifi密码+回车换行
         * 最后+OK
         */
        let self = this;
        getDevcieByQrcodeID(this.qrcodeid).then(res=>{
          if(res.data != null){
            self.$modal.showToast("当前二维码已经配置设备");
          }else{
            let endStr = "$$";
            ecUI.showLoading("正在配置网络信息")
            setTimeout(function(){
              self.sendBlueData("ID:"+self.deviceno+endStr);
            },200);
            setTimeout(function(){
              self.sendBlueData("QR:"+self.qrcodeid+endStr);
            },400);

            setTimeout(function(){
              self.sendBlueData("ssid:"+self.SSID+endStr);
            },600);

            setTimeout(function(){
              self.sendBlueData("psd:"+self.password+endStr);
            },800);

            setTimeout(function(){
              self.sendBlueData("pid:"+self.productId+endStr);
            },1000);

            setTimeout(function(){
              self.sendBlueData("OK");
            },1200);
          }
        })




      },
      stringToHex(str) {
          let hex = '';
          for (let i = 0; i < str.length; i++) {
            const char = str.charCodeAt(i);
            const hexChar = char.toString(16).padStart(2, '0');
            hex += hexChar;
          }
          return hex;
      },
      doByTime(func,time){
        setTimeout(function (){
          func();
        },time);
      },
      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){
       tempSendData = this.stringToHex(tempSendData);
        let data = tempSendData
            .replace(/\s*/g, '')
            .replace(/\n/g, '')
            .replace(/\r/g, '')
        console.log("写入数据："+data);
        ecBLE.writeBLECharacteristicValue(data, true)
      },
			listViewTap(id){
        let self = this;
				ecUI.showLoading("正在连接蓝牙")
				ecBLE.onBLEConnectionStateChange(res => {
          console.log(res);
					if (res.ok) {
            self.connected = true;
            self.openWifi();
            ecUI.hideLoading()
            self.showSendData = true;
						ecBLE.stopBluetoothDevicesDiscovery();
            //
					} else {
            ecUI.hideLoading()
            this.$modal.showToast("请检查是否配置成功");
					}
				});
        //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);

        })
        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;
	}
  .text-area {
    display: flex;
    justify-content: center;
    background: white;
    width: 100%;
    height: 100%;
  }
</style>
