<template>
	<view>
		
	</view>
</template>
<script>
var xBlufi = require("@/utils/blufi/xBlufi.js");

export default {
  name: 'bluetooth-control',
  props: {
    mac: {
      type: String,
      default: ''
    }
  },
  data() {
    return {
      devicesList: [],
      carstause: false, // 蓝牙连接状态
      buleclose: false,
      buleopen: false,
      bulering: false,
      bulerebort: false
    }
  },
  watch: {
    carstause(newVal) {
      this.$emit('changeCarstause', newVal);
    }
  },
  methods: {
    // 蓝牙连接
    Binddevice() {
      // uni.getBluetoothAdapterState({
      //   success: (res) => {
      //     if (!res.available) {
      //       uni.showToast({
      //         title: '请打开蓝牙',
      //         icon: 'none'
      //       });
      //       return;
      //     }

      //   },
      //   fail: () => {
      //     uni.showToast({
      //       title: '获取蓝牙状态失败',
      //       icon: 'none'
      //     });
      //   }
      // });
      console.log(this.mac, 'this.mac');

      this.startBluetoothConnection();
    },

    startBluetoothConnection() {
      this.devicesList = [];
      xBlufi.initXBlufi(1);
      xBlufi.listenDeviceMsgEvent(true, this.funListenDeviceMsgEvent);
      xBlufi.notifyStartDiscoverBle({
        'isStart': true
      });

      // 5秒超时处理
      setTimeout(() => {
        this.handleSearchTimeout();
      }, 5000);
    },

    handleSearchTimeout() {
      xBlufi.notifyStartDiscoverBle({
        'isStart': false
      });

      setTimeout(() => {
        if (this.devicesList.length === 0) {
          uni.showToast({
            title: '未找到设备',
            icon: 'none'
          });
          return;
        }

        let deviceFound = false;
        this.devicesList.forEach(device => {
          let macFromName = device.name.substring(device.name.length - 12);
          console.log(macFromName, this.mac);
          if (macFromName == this.mac) {
            deviceFound = true;
            this.createBLEConnection(device);
          }
        });

        if (!deviceFound) {
          uni.showToast({
            title: '未找到匹配设备',
            icon: 'none'
          });
        }
      }, 200);
    },

    // 蓝牙控制方法
    reboot() {
      if (this.carstause) {
        this.sendBluetoothCommand("11reboot");
      } else {
        this.bulerebort = true;
        this.Binddevice();
      }
    },

    open() {
      if (this.carstause) {
        this.sendBluetoothCommand("11open");
      } else {
        this.buleopen = true;
        this.Binddevice();
      }
    },

    close() {
      if (this.carstause) {
        this.sendBluetoothCommand("11close");
      } else {
        this.buleclose = true;
        this.Binddevice();
      }
    },

    ring() {
      if (this.carstause) {
        this.sendBluetoothCommand("11play1@");
      } else {
        this.bulering = true;
        this.Binddevice();
      }
    },

    // 统一的蓝牙命令发送方法
    sendBluetoothCommand(command) {
      uni.getNetworkType({
        success: (res) => {
          if (res.networkType === 'none') {
            uni.showToast({
              title: '请检查网络连接',
              icon: 'none'
            });
            return;
          }

          uni.getConnectedBluetoothDevices({
            success: () => {
              xBlufi.notifySendCustomData({
                customData: command
              });
              this.$emit('operation-complete');
            },
            fail: () => {
              uni.showToast({
                title: '蓝牙连接失败',
                icon: 'none'
              });
            }
          });
        }
      });
    },

    // 蓝牙事件监听
    funListenDeviceMsgEvent(options) {
      switch (options.type) {
        case xBlufi.XBLUFI_TYPE.TYPE_GET_DEVICE_LISTS:
          if (options.result) {
            this.devicesList = Array.from(new Set([...this.devicesList, ...options.data]));
          }
          break;


        case xBlufi.XBLUFI_TYPE.TYPE_CONNECTED:
          console.log("连接回调：" + JSON.stringify(options));
          if (options.result) {
            // uni.hideLoading();


            xBlufi.notifyInitBleEsp32({
              deviceId: options.data.deviceId
            });


            let systemInfo = uni.getSystemInfoSync();
            if (systemInfo.platform === 'android') {
              // 当前设备是 Android  

            } else if (systemInfo.platform === 'ios') {

            }
          }
          if (options.result == false) {
            // this.loadingmask=false
            this.carstause = false

          }
          break;
        case xBlufi.XBLUFI_TYPE.TYPE_RECIEVE_CUSTON_DATA:
          if (options.data) {
            this.carstause = true;
            console.log('蓝牙连接成功');
            // 执行待执行的操作
            setTimeout(() => {
              if (this.buleclose) {
                this.close();
                this.buleclose = false;
              } else if (this.buleopen) {
                this.open();
                this.buleopen = false;
              } else if (this.bulering) {
                this.ring();
                this.bulering = false;
              } else if (this.bulerebort) {
                this.reboot();
                this.bulerebort = false;
              }
            }, 500);
          } else {
            this.carstause = false
            uni.showToast({
              title: '设备初始化失败',
              icon: 'none'
            });
          }
          break;
      }
    },

    createBLEConnection(device) {
      xBlufi.notifyStartDiscoverBle({
        'isStart': false
      });
      xBlufi.notifyConnectBle({
        isStart: true,
        deviceId: device.deviceId,
        name: device.name
      });
    },

    // 清理蓝牙连接
    cleanupBluetooth() {
      xBlufi.listenDeviceMsgEvent(false, this.funListenDeviceMsgEvent);
      xBlufi.notifyStartDiscoverBle({
        'isStart': false
      });
    }
  },

  // 生命周期钩子
  onUnload() {
    this.cleanupBluetooth();
  },
  onHide() {
    this.cleanupBluetooth();
  },
  onBeforeUnmount() {
    this.cleanupBluetooth();
  }
}
</script>