<script>
import game_store from "@/store/game";
import ConnectionScan from "@/components/connection/brains/scan";
import Connecting from "@/components/connection/brains/connecting";
import Connected from "@/components/connection/brains/connected";
import ToySelected from "@/components/connection/toys/selected";
import ToySelection from "@/components/connection/toys/selection";
import Toast from "../../../static/vant/toast/toast";
let $this;
export default {
  name: "ConnectionIndex",
  components: {
    ConnectionScan,
    Connecting,
    Connected,
    ToySelected,
    ToySelection
  },
  data() {
    return {
      // 设备状态 0为未连接，1：连接中，2：已连接 3：连接失败
      device_status: 0,
      // 教具选择弹框
      popup_show: false,
      // 选择的教具
      toy_item: {
        id: 0,
        name: "",
        img: "",
        hex: "",
      },
      // 连接教具 0:未连接 1：连接中 2：已连接 3：连接失败 4:游戏中
      connect_toy: 0,



      // $this.$bluetooth 设置的参数
      // 电量
      device_power: 0,
      device_voltage: 0,
      rssi: 0,
      current_hex:"",
      // 判断是否已经连接教具
      toy_connected: false,
      toy_sn:"",
      toy_power:0,
      toy_voltage:0,
      // 设置图标的颜色
      device_bg: false,
      toy_UUID:"",
      hasUsb:false,

      connect_show: false,
      device:{},

    }
  },
  created() {
    $this = this;
  },
  methods: {
    /**
     * 获取设备扫码连接状态
     */
    getScanStatus($status) {
      // 扫码成功连接中1,失败未连接0
      $this.device_status = $status * 1;
      console.log("接收到设备扫码连接状态:", $status);
    },
    /**
     * 获取设备连接状态
     * @param $status 设备状态 0为未连接，1：连接中，2：已连接 3：连接失败 4:取消連接
     */
    setDeviceStatus($status) {
      $this.device_status = $status * 1;
      console.log("接收到设备连接状态:", $status);
      if ($status * 1 === 2) {
        let $checkServices = setInterval(() => {
          let $serviceId = game_store.getters.getServiceId();
          if ($serviceId) {
            clearInterval($checkServices);
            // 监听数据
            $this.$bluetooth.openNotify($this);
            $this.$bluetooth.notifyDatas($this);
            $this.$bluetooth.watchBLEstatus($this);
          }
        }, 1500);
      } else {
        game_store.setters.setGameStatus(0);
        // todo 清空链接的设备
        $this.connect_toy = $status;
        $this.connect_show = false;
        $this.device_bg = false;
        $this.connect_status = false;
        if ($status * 1 > 0) {
          // 断开脑机
          // 移除搜索到新设备的事件的全部监听函数
          wx.offBluetoothDeviceFound();
          // 停止搜寻附近的蓝牙外围设备。若已经找到需要的蓝牙设备并不需要继续搜索时，建议调用该接口停止蓝牙搜索。
          wx.stopBluetoothDevicesDiscovery();
          $this.$bluetooth.SendOrder("09");
          let deviceId = game_store.getters.getDeviceId();
          //断开蓝牙连接
          wx.closeBLEConnection({
            deviceId: deviceId,
            success() {
              Toast.success({
                message: "断开蓝牙连接成功",
              });
              game_store.setters.clearDeviceToy();
              wx.closeBluetoothAdapter();
            },
            fail(res) {
              console.log("断开蓝牙连接失败error:", res);
            },
            complete() {
              $this.device = {};
              $this.toy_UUID = "";
              $this.$forceUpdate();
            },
          });
        }
      }
    },
    /**
     * 打开教具选择
     */
    openToyList(){
      this.popup_show = true;
      this.toy_sn = "教具";
      if ($this.device_status*1 === 2) {
        // 关闭脑控
        this.$bluetooth.SendOrder("09");
      }
    },
    //关闭窗口
    closePopup() {
      $this.popup_show = false;
    },
    // 选好教具
    chooseOK() {
      $this.popup_show = false;
      $this.toy_item = game_store.getters.getToyItem();
      if($this.toy_item && $this.toy_item.id > 0) {
        $this.setToyStatus(1);
        let $hex = ($this.toy_hex = $this.toy_item["hex"].substr($this.toy_item["hex"].length - 2, 2));
        if ($hex === "80") {
          wx.setStorageSync("report_mode", 2)
        } else {
          wx.setStorageSync("report_mode", 1)
        }
        console.log("连接教具:", `03 00 ${$hex} 00 0a`, JSON.stringify($this.toy_item));
        // 连接教具: 03 00 ${$hex} 00 0a
        $this.$bluetooth.sendConnectOneToMore($hex);
        //2022-5-25 09:07:59 设置10秒后是否已经连接
        setTimeout(() => {
          if ($this.toy_connected === false) {
            $this.setToyStatus(3);
          }
        }, 10000);
      }
    },
    /**
     * 修改教具连接状态 0:未连接 1：连接中 2：已连接 3：连接失败 4:游戏中
     * @param $status
     */
    setToyStatus($status = 0) {
      $this.connect_toy = $status;
    },
    gameStart() {
      $this.game_status = 1;
      $this.connect_toy = 4;
    },
  }
};
</script>

<template>
  <div id="device_container">
    <view>
      <text class="cuIcon-titles text-primary"></text>
      <text class="">我的设备</text>
    </view>
    <div class="device padding">
      <!-- 脑机模块 -->
      <div v-if="connect_toy === 0">
        <!-- 扫码连接 -->
        <div v-if="device_status === 0" class="connect_box">
          <ConnectionScan @scanStatus="getScanStatus"></ConnectionScan>
        </div>
        <!-- 连接中 -->
        <div v-if="device_status === 1" class="connecting_box">
          <Connecting :status="device_status" @deviceStatus="setDeviceStatus"></Connecting>
        </div>
        <!-- 已链接 -->
        <div v-if="device_status === 2" class="connected_box">
          <Connected :device_bg="device_bg" :device_power="device_power" @deviceStatus="setDeviceStatus" @openToys="openToyList"></Connected>
        </div>
      </div>
      <!-- 教具模块 -->
      <div v-else>
        <div class="connecting_toy">
          <ToySelected :connect_toy="connect_toy"
                       :toy="toy_item"
                       :toy_sn="toy_sn"
                       :device_bg="device_bg"
                       :device_power="device_power"
                       :toy_power="toy_power"
                       @openToys="openToyList"
                       @deviceStatus="setDeviceStatus"
                       @gameStart="gameStart"
          ></ToySelected>
        </div>
      </div>
      <!-- 选择教具 -->
      <van-popup :show="popup_show" @close="closePopup" position="bottom" round closeable safe-area-inset-bottom>
        <ToySelection></ToySelection>
        <div class="padding">
          <button class="cu-btn lg cu-btn-primary text-white text-center padding" @click="chooseOK">
            选好了
          </button>
        </div>
      </van-popup>
    </div>
  </div>
</template>

<!--共有样式-->
<style>
.second_device_text {
  position: relative;
  bottom: 5px;
}

.connect_img {
  width: 85px;
  height: 80px;
}

/*教具不同背景*/
.toy_item_normal_bg {
  background-image: url("https://img.shuimuai.com/web/toy_bg.png");
  background-position: center;
  background-size: 100% 100%;
}

/*教具选中背景*/
.toy_item_action_bg {
  background-image: url("https://img.shuimuai.com/web/toy_bg_action.png");
  background-position: center;
  background-size: 100% 100%;
}

.ring_2 {
  width: 199px;
  height: 203px;
  background: rgba(93, 77, 184, 0);
  border: 2px solid #f7f7f7;
  opacity: 0.43;
  border-radius: 50%;
}

.ring_3 {
  width: 158px;
  height: 158px;
  background: rgba(93, 77, 184, 0);
  border: 3px solid #f6f6f6;
  opacity: 0.54;
  border-radius: 50%;
}

.dot_container {
  height: 100px;
}

.dot_wait {
  height: 5px;
  width: 80px;
  background-image: url("https://img.shuimuai.com/web/connect_line.png");
  background-position: center;
  background-size: 100% 100%;
}

.device_phone {
  width: 30px;
  height: 40px;
  bottom: 5px;
}

.device_brain {
  width: 40px;
  height: 40px;
  bottom: 10px;
}

.device_text {
  padding: 3px;
  font-size: 9px;
}

.moving_dot {
  width: 18px;
  height: 18px;
  position: relative;
  left: 15px;
  bottom: 7px;
}

.moving {
  animation: moving 2s linear infinite;
}

/*左右移动动画*/
@keyframes moving {
  0% {
    left: 0px;
  }
  50% {
    left: 35px;
  }
  100% {
    left: 0px;
  }
}

.cut_brain_icon {
  width: 11px;
  height: 11px;
}

.cut_text {
  font-size: 11px;
}

/*设备绿色信号灯*/
.sign_green {
  width: 20px;
  height: 10px;
  position: relative;
  top: 9px;
  left: 0;
}

/*水母男孩*/
.connected_boy {
  width: 110px;
  height: 110px;
  position: absolute;
  right: -60px;
  top: 63px;
}

.boy_session {
  background-image: url("https://img.shuimuai.com/web/boy_session.png");
  background-position: center;
  background-size: 100% 100%;
  width: 120px;
  height: 100px;
  position: absolute;
  top: 18px;
  right: 25px;
  z-index: 4;
}

.boy_session_text {
  font-size: 12px;
  color: #6b6b6b;
}

.device_electric {
  position: relative;
  width: 16px;
  height: 16px;
  top: 0px;
  right: 0px;
  z-index: 5;
}

/*设备连接模块*/
.device_bg {
  width: 90px;
  height: 100px;
  background-position: center;
  background-size: 100% 100%;
  background-image: url("https://img.shuimuai.com/web/device_bg.png");
}

.left {
  line-height: 32px;
}
</style>

<!--私有样式-->
<style scoped>
#device_container {
  position: relative;
  bottom: 80px;
}

</style>
