<template>
  <view class="content">
    <image class="img" :src="productUrl" mode="aspectFit" />
    <view class="hint mt1">
      <image
        class="img1"
        :src="stateIcon"
        mode="aspectFit"
        v-if="showStateIcon"
      />
      <text class="text1">{{ hintText }}</text>
    </view>
    <view class="hint mt1" v-if="showLink">
      <image
        class="img2"
        src="../../../static/common/ic_smile.svg"
        mode="aspectFit"
      />
      <text class="text2">{{ productHint }}</text>
    </view>
    <view class="bottom content">
      <button :loading="isloading" :class="buttonClass" @click="btnClick">
        {{ buttonText }}
      </button>
    </view>
    <bt-alert v-if="showAlert" @close="btAlertClose" />
  </view>
</template>

<script>
import BleConfigNet from "../../../Lib/BleConfigNet.js";
import BtAlert from "../../../components/btAlert/btAlert.vue";
export default {
  components: { BtAlert },
  data: () => ({
    /** 产品型号*/
    model: "MW-M3",
    /** 产品名称 */
    productName: "",
    /** 是否显示界面上提示的icon*/
    showStateIcon: true,
    /** 界面上提示icon的图片*/
    stateIcon: "../../../static/common/ic_green_success.svg",
    /** 界面上提示文字内容*/
    hintText: "正在扫描设备，请保持设备开机状态",
    /** 是否显示如何连接设备的提示*/
    showLink: true,
    /** 按钮的name*/
    btnName: "scan",
    /** 是否显示蓝牙开关弹窗 */
    showAlert: false,
    /** 超时扫描的定时器*/
    stopScanTimer: null,
    /** 要连接的设备*/
    device: null,
  }),
  computed: {
    buttonText() {
      if (this.btnName == "scaning") {
        return "正在搜索设备...";
      } else if (this.btnName == "rescan") {
        return "重新搜索";
      } else if (this.btnName == "connect") {
        return "连接";
      } else if (this.btnName == "reconnect") {
        return "重新连接";
      } else if (this.btnName == "finish") {
        return "完成";
      } else if (this.btnName == "connecting") {
        return "正在连接...";
      } else if (this.btnName == "scan") {
        return "搜索";
      } else {
        return this.btnName;
      }
    },
    buttonClass() {
      if (this.btnName == "scaning" || this.btnName == "connecting") {
        return "btn disabled";
      } else if (this.btnName == "finish") {
        return "btn finish";
      } else {
        return "btn";
      }
    },
    productUrl() {
      return `https://airsmart-photo1.oss-cn-shanghai.aliyuncs.com/wx/productModel/3X/${this.model}.png`;
    },
    productHint() {
      return `如何连接${this.productName}设备？`;
    },
    isloading() {
      return this.btnName == "scaning" || this.btnName == "connecting";
    },
  },
  methods: {
    //关闭弹窗
    btAlertClose() {
      this.showAlert = false;
    },
    /**
     * 按钮点击事件
     */
    btnClick() {
      if (this.btnName == "rescan" || this.btnName == "scan") {
        //搜索
        this.init();
      } else if (this.btnName == "connect" || this.btnName == "reconnect") {
        //连接
        this.btnName = "connecting";
        if (this.device) {
          BleConfigNet.connectBle(this.device.mac, this.bleConfigNetCallback);
        } else {
          that.hintText = "沒有搜索到设备";
          that.btnName = "rescan";
          that.showStateIcon = false;
          that.showLink = true;
        }
      } else if (this.btnName == "finish") {
        //完成
        if (this.device && this.device.uuid) {
          //添加设备
          this.$store.dispatch({
            type: "moduleMqtt/addDevice",
            clientId: `wx_${getApp().globalData.uid}`,
            device: {
              devName: this.productName,
              uuid: this.device.uuid,
              ProdModel:this.model
            },
          });
          //返回上上一级页面
          uni.navigateBack({
            delta: 2,
          });
        } else {
          uni.showToast({
            title: "iccid获取失败",
            icon: "none",
          });
        }
      }
    },
    //初始化蓝牙
    init() {
      const that = this;
      uni.openBluetoothAdapter({
        success: (res) => {
          console.log(`初始化蓝牙模块成功 ${res}`);
          that.startBleScan();
        },
        fail: (error) => {
          if (error.errCode === 10001) {
            //在用户蓝牙开关未开启或者手机不支持蓝牙功能的情况下
            this.showAlert = true;

            //蓝牙状态监听
            that.lisenBtState();
          } else {
            //其他错误
            uni.showToast({
              title: `查看手机蓝牙是否打开`,
              icon: "none",
            });
            console.log(error);
          }
        },
      });
    },
    //蓝牙开关的监听
    lisenBtState() {
      //监听蓝牙是否打开
      let that = this;
      uni.onBluetoothAdapterStateChange(function (res) {
        console.log(
          `onBluetoothAdapterStateChange available = ${res.available}`
        );
        //console.log(res);
        if (res.available) {
          //蓝牙已打开
          //开始扫描设备
          that.startBleScan();
        }
      });
    },
    //扫描蓝牙设备
    startBleScan() {
      this.showAlert = false;
      this.btnName = "scaning";
      this.hintText = "正在扫描设备，请保持设备开机状态";
      this.showStateIcon = false;
      this.showLink = true;
      this.device = null;
      const that = this;
      clearTimeout(this.stopScanTimer);
      //开始扫描
      uni.startBluetoothDevicesDiscovery({
        success: (res) => {
          //设置扫描的超时时间
          that.setStopScanTimeout();
          //扫描到的设备的回调
          uni.onBluetoothDeviceFound(function (res) {
            let devices = res.devices;
            for (var i = 0; i < devices.length; i++) {
              console.log(devices[i]);
              //todo 到时候要更具名称/型号来判断
              if (
                devices[i].name &&
                devices[i].name.startsWith("AIrSMArT") &&
                that.device == null
              ) {
                //停止扫描
                that.stopScan();
                that.device = {
                  name: devices[i].name,
                  mac: devices[i].deviceId,
                };
                that.showStateIcon = false;
                that.hintText = "以搜索到MW-M4设备";
                that.showLink = true;
                that.btnName = "connect";
                break;
              }
            }
          });
        },
        fail: (err) => {
          console.warn(err);
          that.hintText = "搜索设备失败";
          that.btnName = "rescan";
          that.showStateIcon = false;
          that.showLink = true;
        },
      });
    },
    //设置超时扫描的定时器
    setStopScanTimeout() {
      const that = this;
      //N秒之后停止扫描
      that.stopScanTimer = setTimeout(() => {
        //停止扫描
        uni.stopBluetoothDevicesDiscovery({
          complete() {
            if (that.device == null) {
              that.hintText = "沒有搜索到设备";
              that.btnName = "rescan";
              that.showStateIcon = false;
              that.showLink = true;
            }
          },
        });
      }, 15 * 1000);
    },
    //停止蓝牙的扫描
    stopScan() {
      uni.stopBluetoothDevicesDiscovery({});
      clearTimeout(this.stopScanTimer);
    },
    //ble配网的回调
    bleConfigNetCallback(res) {
      console.log(res);
      if (res.errCode == 0) {
        if (this.device) {
          this.device.uuid = res.iccid;
        }
        //配网成功
        this.hintText = "连接成功";
        this.btnName = "finish";
        this.showStateIcon = true;
        this.showLink = false;
        this.stateIcon = "../../../static/common/ic_green_success.svg";
      } else {
        this.hintText = "连接失败，请确保设备开机状态";
        this.btnName = "reconnect";
        this.showStateIcon = true;
        this.showLink = true;
        this.stateIcon = "../../../static/common/ic_red_fail.svg";
      }
    },
  },
  watch: {},

  // 页面周期函数--监听页面加载
  onLoad(options) {
    this.model = options.model;
    this.productName = options.name;
    if (this.productName && this.productName.length > 0) {
      uni.setNavigationBarTitle({
        title: `连接${this.productName}`,
      });
    }
    this.init();
  },
  // 页面周期函数--监听页面初次渲染完成
  onReady() {},
  // 页面周期函数--监听页面显示(not-nvue)
  onShow() {},
  // 页面周期函数--监听页面隐藏
  onHide() {},
  // 页面周期函数--监听页面卸载
  onUnload() {
    this.stopScan();
    BleConfigNet.closeBLEConnection();
  },
};
</script>

<style>
.content {
  display: flex;
  flex-direction: column;
  justify-content: flex-start;
  align-items: center;
}
.img {
  margin-top: 19.79vh;
  width: 37.33vw;
  height: 34.4vw;
}
.img1 {
  width: 32rpx;
  height: 32rpx;
  margin-right: 8rpx;
}
.img2 {
  width: 24rpx;
  height: 22rpx;
  margin-right: 8rpx;
}
.hint {
  height: 40rpx;
  display: flex;
  flex-direction: row;
  justify-content: center;
  align-items: center;
}
.mt1 {
  margin-top: 30rpx;
}
.text1 {
  font-size: 24rpx;
  font-weight: 700;
  color: #353535;
}
.text2 {
  font-size: 24rpx;
  font-weight: 500;
  color: #684bbe;
}
.btn {
  background-color: #353535;
  width: 69.33vw;
  border-radius: 50rpx;
  color: white;
  padding-top: 24rpx;
  padding-bottom: 24rpx;
  font-size: 32rpx;
  line-height: 1;
}

.disabled {
  background-color: #999999;
  cursor: not-allowed;
}
.finish {
  background-color: #684bbe;
}
.bottom {
  position: fixed;
  top: 73.8vh;
  left: 0;
  right: 0;
  bottom: 0;
}
</style>
