<template>
  <div id="device_container">
    <view>
      <text class="cuIcon-titles text-primary"></text>
      <text class="">我的设备</text>
    </view>
    <div class="device padding-lr">
      <!--      <div class="head flex justify-between">-->

      <!--        <div class="my_msg" @click="get_toy_list">-->
      <!--          <text class="cuIcon-mark"></text>-->
      <!--          <text class="under_line">获取设备列表</text>-->
      <!--        </div>-->
      <!--      </div>-->
      <div v-if="connect_toy == 0">
        <!--      未连接部分-->
        <div class="connect_box" v-if="status == 0">
          <device_unconnect @open_scan="open_scan"></device_unconnect>
        </div>

        <!--      连接中-->
        <div class="connecting_box" v-if="status != 0 && connect_show == false">
          <device_connecting :status="status"></device_connecting>
        </div>

        <!-- 已链接 -->
        <div class="connected_box" v-if="connect_show">
          <device_connected
            @open_choose_toy="open_choose_toy"
            @change_brain_status="change_device_status"
          ></device_connected>
        </div>
      </div>
      <div v-else>
        <!--      玩具模块-->
        <!--      玩具连接中-->
        <div class="connecting_toy">
          <toy_connecting
            :connect_toy="connect_toy"
            :deviceId="_deviceId"
            :toy_id="toy_action"
            :toy="toy_list[toy_action - 1]"
            @open_choose_toy="open_choose_toy"
            @change_toy_connect_status="change_toy_connect_status"
            @change_status="change_device_status"
            @game_start="game_start"
          ></toy_connecting>
        </div>
      </div>
    </div>
    <!--      选择玩具-->
    <van-popup
      :show="choose_toy_window.show"
      @close="on_close"
      position="bottom"
      round
      closeable
      safe-area-inset-bottom
    >
      <!-- 标题 -->
      <div class="head padding">
        <div>
          <div class="line"></div>
          <div class="title">选择玩具</div>
        </div>
      </div>
      <!-- 内容 -->
      <div class="padding toy_list">
        <van-row gutter="14" class="toy_list_content">
          <van-col span="8" v-for="(toy, index) in toy_list" :key="index">
            <div
              class="toy_item flex flex-direction justify-center align-center"
              @click="choose_toy(index)"
              :class="
                toy_action == toy.id
                  ? 'toy_item_action_bg'
                  : 'toy_item_normal_bg'
              "
            >
              <img :src="toy.img" alt="" class="toy_img"/>
              <text class="toy_text padding-top">{{ toy.name }}</text>
            </div>
          </van-col>
        </van-row>
      </div>
      <!-- 结尾 -->
      <div class="toy_actions padding text-center">
        <view class="text-gray toy_action_text padding"
        >选择你最感兴趣的项目，点击“选好了”以后将会自动连接
        </view
        >
        <button
          class="cu-btn lg cu-btn-primary text-white text-center padding"
          @click="choose_ok"
        >
          选好了
        </button>
      </div>
    </van-popup>
    <van-toast id="van-toast"/>
    <van-dialog id="van-dialog"/>

  </div>
</template>

<script>
//蓝牙未连接
import device_unconnect from "@/components/device/unconnect";
//蓝牙连接中
import device_connecting from "@/components/device/connecting";
//蓝牙完成链接
import device_connected from "@/components/device/connected";
//连接玩具
import toy_connecting from "@/components/device/toy/connecting";
//获取个人信息
import Toast from "../../../static/vant/toast/toast";
import {game_devices} from "../../requests/game";
import game_store from "@/store/game";
import bluetooth from "@/utils/bluetooth";
import Dialog from '../../../static/vant/dialog/dialog';


let $this;
export default {
  name: "device",
  components: {
    device_unconnect,
    device_connecting,
    device_connected,
    toy_connecting,
  },
  data() {
    return {
      //设备状态 0为未连接，1：连接中，2：已连接 3：连接失败
      status: 0,
      connect_show: false,

      choose_toy_window: {
        show: false,
        // show: true,
      },
      //'水柱音箱', '喷雾恐龙（大）', '喷雾恐龙（小）', '轨道车', '碰碰车', '小车（大）', '小车（中）', '小车（小）', '飞行器（大）', '飞行器（小）', '水母灯'
      toy_list: [],
      toy_action: 1,
      // connect_show: true,
      //连接玩具 0:未连接 1：连接中 2：已连接 3：连接失败 4:游戏中
        connect_toy: 0,
      code: "jellyfish1234",
      device: {},
      _deviceId: "",
      _device_index: false,
      toy_id: 0
    };
  },
  watch: {
    status($new, $old) {
      //成功连接的方法
      if ($new == 2) {
        $this.connect_show = true;
      } else if ($new == 0) {
        $this.connect_show = false;
      }
    },
  },
  methods: {
    //打开 扫描二维码
    open_scan() {
      //
      wx.scanCode({
        onlyFromCamera: true,
        success: (res) => {
          let $data = res;
          if ($data.result) {
            let url = decodeURIComponent($data.result);
            let $code = url.match(/\?code=(.*)/)[1];
            // 判断新的标识值
            if (!$code) {
              $code = url.match(/\?ring=(.*)/)[1];
            }
            $this.code = $code;
            //打开蓝牙设备
            wx.openBluetoothAdapter({
              success(res) {
                //判断已经打开连接了
                if (res["errMsg"] == "openBluetoothAdapter:ok") {
                  console.log("openBluetoothAdapter success", res);
                  $this.startBluetoothDevicesDiscovery();
                }
              },
              fail(err) {
                if (err["errCode"] == 10001) {
                  Toast.fail({
                    message: "请打开手机蓝牙，并启动脑环！"
                  })
                } else {
                  Toast.fail({
                    message: "蓝牙连接失败",
                  });
                }
              },
            });
          }
        },
      });
    },
    //关闭窗口的方法
    on_close() {
      $this.choose_toy_window.show = false;
    },
    //选择玩具
    choose_toy($index) {
      $this.toy_action = $this.toy_list[$index].id;
    },
    // 打开选择玩具窗口
    open_choose_toy() {
      // $this.choose_toy_window.show = false;
      $this.choose_toy_window.show = true;
    },
    // 选好玩具
    choose_ok() {
      $this.on_close();
      $this.change_toy_connect_status(1);
      $this._device_index = $this.toy_action - 1;
      //获取玩具
      let $toy = $this.toy_list[$this.toy_action - 1];
      $this.toy_id = $toy.id
      let $hex = $toy["hex"].substr($toy["hex"].length - 2, 2);
      let toy_hex = "0x" + $hex;
      game_store.commit("setToyHex", toy_hex);

      //连接玩具
      bluetooth.getBLEDeviceServices($this._deviceId)
      setTimeout(() => {
        console.log($this._deviceId, bluetooth.serviceId, bluetooth.cid)
        bluetooth.sendConnect(toy_hex, $this._deviceId, bluetooth.serviceId, bluetooth.cid, Toast)
        setTimeout(() => {
          bluetooth.watching_toy($this, $this._deviceId, bluetooth.serviceId, bluetooth.cid, Toast)
        }, 800)

      }, 1000)

    },
    //修改玩具连接状态
    change_toy_connect_status($status = 0) {
      $this.connect_toy = $status;
      if ($status == 1) {
        $this.connect_show = true
      } else {
        $this.connect_show = false
      }
    },
    //  修改设备连接状态
    change_device_status($status = 0) {
      $this.status = $status;
      //当蓝牙连接已断开
      if ($status == 0) {
        $this.connect_toy = $status;
        $this.connect_show = false;
        wx.closeBLEConnection({
          deviceId: $this._deviceId,
          success(res) {
            Toast.success({
              message: "已成功断开"
            });
          },

        });


      }
    },

    //开始蓝牙被发现
    startBluetoothDevicesDiscovery() {
      wx.startBluetoothDevicesDiscovery({
        allowDuplicatesKey: true,
        success: (res) => {
          console.log("startBluetoothDevicesDiscovery success", res);
          $this.onBluetoothDeviceFound();
          $this.change_device_status(1);
        },
        fail(err) {
          $this.change_device_status(3);
        },
      });
    },
    //打开蓝牙搜索
    onBluetoothDeviceFound() {
      wx.onBluetoothDeviceFound((res) => {
        res.devices.forEach((device) => {
          if (!device.name && !device.localName) {
            return;
          }
          if (device.localName && (device.localName != '')) {
            device.name = device.localName
          }
          console.log(device["name"]);
          if (device["name"] == $this.code) {
            $this.stopBluetoothDevicesDiscovery();
            $this.device = device;
            game_store.commit("setDeviceId", device.deviceId);
            $this._deviceId = device.deviceId;
            $this.createBLEConnection();
          }
        });
      });
      setTimeout(() => {
        if (!$this.device.deviceId) {
          $this.stopBluetoothDevicesDiscovery();
          $this.status = 0;
          $this.connect_show = false;
          Toast.fail("未连接到设备");
        }
      }, 7000);
    },
    // 停止蓝牙搜索
    stopBluetoothDevicesDiscovery() {
      wx.stopBluetoothDevicesDiscovery();
    },
    //连接低功耗蓝牙设备。
    createBLEConnection() {
      wx.createBLEConnection({
        deviceId: $this.device.deviceId,
        success: (res) => {
          console.log("成功连接");
          //成功连接脑环蓝牙
          $this.change_device_status(2);
          bluetooth.watch_bluetooth_status($this)
          // $this.getBLEDeviceServices($this.device.deviceId)
        },
        fail(err) {
          console.log("err", err);
        },
      });
    },
    //  获取游戏设备玩具
    get_toy_list() {
      //      清空toy_list
      $this.toy_list = [];
      //       device_id: "1"
      // name: "音响"
      // img: "penquan.png"
      // bluetooth: "aadd0a0001"
      game_devices().then((res) => {
        let $data = res.data;
        let $toylist = $data.data;
        let _item = {};
        $toylist.forEach(($val, $index) => {
          _item = {
            id: parseInt($val["device_id"]),
            name: $val["name"],
            img: "https://img.shuimuai.com/" + $val["img"],
            hex: $val["bluetooth"],
          };
          $this.toy_list.push(_item);
        });
        game_store.commit("setToyList", $this.toy_list);
      });
    },

    //  开始游戏的方法
    game_start() {
      game_store.commit("setToyIndex", $this.toy_action - 1);
      console.log("device.vue", $this._deviceId);
    },
  },
  mounted() {

    $this.get_toy_list();
  },
  created() {
    $this = this;
  },
  onShow() {
    //判断是否游戏中
    let $game_status = game_store.getters.getGameStatus;
    if ($game_status == 1) {
      Dialog.confirm({
        title: '系统提示',
        message: '确认要退出游戏了吗？',
      }).then(() => {
        // on confirm
        mpvue.navigateTo({
          url: "/pages/start/main?end=1",
        });
      }).catch(() => {
        // on cancel
        mpvue.navigateTo({
          url: "/pages/start/main",
        });
      });
      $this.change_toy_connect_status(4)
    } else if ($game_status == 3) {
      //不在游戏状态
      $this.change_toy_connect_status(0)
      $this.connect_show = true
      bluetooth.watch_bluetooth_status($this)
    }
  },
  onLoad(options) {
    // 原有的code
    let $_code = wx.getStorageSync("code");
    if (options.q) {
      let url = decodeURIComponent(options.q);
      let $code = url.match(/\?code=(.*)/)[1];
      //判断新的code 和 旧的code 是否一致 不一致则重新登录
      console.log("1---" + $_code, "2---" + $code);
      if ($_code && $_code != $code) {
        Toast.fail("该用户已绑定邀请码");
      }
    }
  },
};
</script>

<!--共有样式-->
<style>

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

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

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

.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: 12px;
}

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

/*水母男孩*/
.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;
}

/*玩具模块*/
.uav_toy {
  width: 40px;
  height: 40px;
}

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

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

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

.head .line {
  width: 4px;
  height: 14px;
  background-color: #5d4db8;
  margin-right: 7px;
}

.head view {
  display: flex;
  justify-self: start;
  align-items: center;
}

/*玩具列表*/
.toy_list {
  overflow-x: scroll;
}

.toy_item {
  width: 120px;
  height: 130px;
}


/*玩具图片*/
.toy_img {
  width: 65px;
  height: 65px;
}

.toy_text {
  font-size: 12px;
}

.toy_action_text {
  font-size: 11px;
  width: 100%;
}

/* 选择玩具 */
.toy_list {
  width: 100%;
  overflow-x: auto;
}

.toy_list_content {
  width: 120%;
  display: inline-block;
  display: flex;
  flex-wrap: wrap;
}

</style>
