<template>
  <div id="playing_container">
    <!--    计费面板模块-->
    <div class="game_panel padding-top-sm">
      <van-row gutter="16">
        <van-col span="8" offset="2">
          <view class="text-sm">
            <text class="title">已游玩时间</text>
          </view>
          <view class="text-lg   padding-top">
            <van-count-down :time="mode_item.time" format="mm:ss" auto-start @finish="time_out"></van-count-down>
          </view>
        </van-col>
        <van-col span="10" offset="4">
          <view class="text-sm">
            <text class="title">计费模式</text>
            <text class="type padding-left-sm">{{ mode_item.name }}</text>
          </view>
          <button class="cu-btn bg-red text-white margin-top-sm" @click="game_finished">
            <img src="https://img.shuimuai.com/m_duankainaohuan.png" class="cut_brain_icon" alt="">
            <text class="padding-lr cut_text text-sm" @click="game_finished">停止游玩</text>
          </button>
        </van-col>
      </van-row>
    </div>

    <!--    设备状态-->
    <div class="game_status padding-tb">
      <van-row>
        <van-col span="10" offset="2">
          <div class="flex flex-direction align-center justify-center">
            <img src="https://img.shuimuai.com/web/touhuanzhuangtai_2.png" alt="" class="device_img">
            <text class="text-default">已经正确佩戴</text>
          </div>
        </van-col>
        <van-col span="10">
          <div class="flex flex-direction align-center justify-center">
            <van-row class="elc_power_container text-center">
              <van-col v-for="(item,index) in elc_power/25" :key="index" span="6">
                <img src="https://img.shuimuai.com/web/dianchi_3.png" alt="" class="device_elc">
              </van-col>
            </van-row>
            <text class="text-default">{{ elc_power }}%</text>
            <text class="text-default">设备电量</text>
          </div>
        </van-col>
      </van-row>
    </div>


    <!--    图标模块-->
    <div class="ec_container">
      <view class="bar">
        <view>
          <view class="line"></view>
          <view class="title">大脑状态</view>
        </view>
        <view class="label">
          <view>
            <view class="dot dot-orange"></view>
            <view class="name">Att(专注度)</view>
          </view>
          <view>
            <view class="dot dot-pink"></view>
            <view class="name">Att(放松度)</view>
          </view>
        </view>
      </view>
      <view class="chart">
        <mpvue-echarts :echarts="echarts" :onInit="attCharts" canvasId="demo-canvas"/>

      </view>
      <view class="bar">
        <view>
          <view class="line"></view>
          <view class="title">基本脑波</view>
        </view>
        <view class="label">
          <view>
            <view class="dot dot-blue"></view>
            <view class="name">Delta</view>
          </view>
          <view>
            <view class="dot dot-green"></view>
            <view class="name">Theta</view>
          </view>
          <view>
            <view class="dot dot-yellow"></view>
            <view class="name">Beta</view>
          </view>
          <view>
            <view class="dot dot-orange-yellow"></view>
            <view class="name">Alpha</view>
          </view>
        </view>
      </view>
      <view class="chart">
        <mpvue-echarts :echarts="echarts" :onInit="medCharts" canvasId="demo-canvas-1"/>
      </view>
    </div>

    <!--    窗口弹出-->
    <van-popup :show="pop_show" @close="close_pop" round :close-on-click-overlay="false">
      <div class="err_container flex flex-direction align-center justify-around">
        <view>
          <text class="title">
            本次游玩时间已到
          </text>
        </view>
        <view>
          <text class="sub-title">
            您的{{ mode_item.name }}消费已用完
          </text>
        </view>
        <img src="https://img.shuimuai.com/web/sign_notimeJfish.png" class="err_img" alt="">
        <button class="cu-btn lg bg-primary text-white" @click="game_finished">查看报告</button>
      </div>
    </van-popup>
  </div>
</template>

<script>
import mpvueEcharts from 'mpvue-echarts'
import echarts from '../../../static/echarts.min';
import util from '../../utils/index'
import bluetooth from "../../utils/bluetooth";
import game_store from "@/store/game";

var att_charts,
  med_charts,
  $this

// 大脑图表初始化
function initAttChart(canvas, width, height) {
  att_charts = echarts.init(canvas, null, {
    width: width,
    height: height
  });
  canvas.setChart(att_charts);

  var option = util.getLineOption([0], [0]); // ECharts 配置项

  att_charts.setOption(option);

  return att_charts; // 返回 chart 后可以自动绑定触摸操作
}

// 我的设备图表初始化
function initMedChart(canvas, width, height) {
  med_charts = echarts.init(canvas, null, {
    width: width,
    height: height
  });
  canvas.setChart(med_charts);

  var option = util.getBaseOption([0], [0], [0], [0]); // ECharts 配置项

  med_charts.setOption(option);

  return med_charts; // 返回 chart 后可以自动绑定触摸操作
}

export default {
  name: "index_container",
  components: {
    mpvueEcharts
  },
  data() {
    return {
      // 使用类型 1次数 2时间 0未选择
      mode: 0,
      mode_list: [
        {
          id: 2,
          name: "会员时间消费",
          time: 20 * 60 * 1000,
          err_title: "本次游玩时间已用完"
        },
        {
          id: 1,
          name: "次卡(10分钟)",
          time: 10 * 60 * 1000,
          err_title: "您的会员消费时间已用完",
        }
      ],
      mode_item: {},
      pop_show: false,
      elc_power: 100,
      // 折线图
      echarts,
      attCharts: initAttChart,
      medCharts: initMedChart,
      user_info: {},
      _deviceId: "",
      _serviceId: "",
      _characteristicId: "",
      toy_index: 0
    }
  },
  methods: {
    //游戏结束方法
    game_finished() {
      let $deviceId = game_store.getters.getDeviceId
      let $serviceId = game_store.getters.getServiceId
      let $charatorId = game_store.getters.getCharacterId
      //停止控制游戏
      bluetooth.sendEnd($deviceId, $serviceId, $charatorId)
      //关闭脑环
      wx.closeBLEConnection({
        deviceId: $deviceId,
        success(res) {
          Toast.success('已成功断开')
          //设置游戏状态为 停止游戏
          game_store.commit('setGameStatus', 0)
          $this.to_report()
        }
      })

    },
    //  关闭弹窗
    close_pop() {
      $this.pop_show = false
    },
    // 时间到
    time_out() {
      $this.pop_show = true
    },
    to_report() {
      mpvue.navigateTo({
        url: "/pages/report/main"
      })
    },
    //获取蓝牙设备服务
    getBLEDeviceServices(deviceId) {
      wx.getBLEDeviceServices({
        deviceId,
        success: (res) => {
          for (let i = 0; i < res.services.length; i++) {
            if (res.services[i].isPrimary) {
              this.getBLEDeviceCharacteristics(deviceId, res.services[i].uuid)
              return
            }
          }
        }
      })
    },
    //获取蓝牙设备某个服务中所有特征值
    getBLEDeviceCharacteristics(deviceId, serviceId) {
      wx.getBLEDeviceCharacteristics({
        deviceId,
        serviceId,
        success: (res) => {
          console.log('getBLEDeviceCharacteristics success', res.characteristics)
          for (let i = 0; i < res.characteristics.length; i++) {
            let item = res.characteristics[i]
            if (item.properties.read) {
              wx.readBLECharacteristicValue({
                deviceId,
                serviceId,
                characteristicId: item.uuid,
              })
            }
            if (item.properties.write) {
              $this.canWrite = true
              $this._deviceId = deviceId
              $this._serviceId = serviceId
              $this._characteristicId = item.uuid
              game_store.commit('setDeviceId', deviceId)
              game_store.commit('setServiceId', serviceId)
              game_store.commit('setCid', item.uuid)
              bluetooth.sendPause(deviceId, serviceId, item.uuid)
              bluetooth.sendConnect($this.toy_index, deviceId, serviceId, item.uuid)
            }

            if (item.properties.notify || item.properties.indicate) {
              wx.notifyBLECharacteristicValueChange({
                deviceId,
                serviceId,
                characteristicId: item.uuid,
                state: true,
              })
            }
          }
        },
        fail(res) {
          console.error('getBLEDeviceCharacteristics', res)
        }
      })
      // 操作之前先监听，保证第一时间获取数据
      wx.onBLECharacteristicValueChange((characteristic) => {
        console.log("收到" + $this.ab2hex(characteristic.value));
        let hexStr = $this.ab2hex(characteristic.value)
        let $flag = bluetooth.connect_toy(hexStr)
        if ($flag) {
          bluetooth.sendControl($this._deviceId, $this._serviceId, $this._characteristicId)
        }
      })
    },

    // ArrayBuffer转16进度字符串示例
    ab2hex(buffer) {
      var hexArr = Array.prototype.map.call(
        new Uint8Array(buffer),
        function (bit) {
          return ('00' + bit.toString(16)).slice(-2)
        }
      )
      return hexArr.join('');
    }
  }
  ,
  mounted() {
    $this._deviceId = game_store.getters.getDeviceId
    $this.toy_index = game_store.getters.getToyIndex
    $this.getBLEDeviceServices($this._deviceId)

    //  模拟蓝牙输入值
    //55 55 20 01 00 02 1b 03 33 04 18 00 15 d7 00 75 37 00 0d da 00 0d 9b 00 10 c2 00 0a f9 00 01 fb 00 04 5a 39
    let hex = "5555200100021b033304180015d7007537000dda000d9b0010c2000af90001fb00045a39"
    let $data = bluetooth.get_big_data(hex)
    console.log($data)

  },
  created() {
    $this = this;
  },
  onLoad($option) {
    $this.userinfo = wx.getStorageSync('userinfo')
    $this.mode_list.forEach(($val, $index) => {
      if ($val['id'] == 2) {
        $val['time'] = parseInt($this.userinfo['play_time']) * 60 * 1000
      }
    })
    console.log($this.mode_list)
    $this.mode = $option.mode
    $this.mode_list.forEach(($val, $index) => {
      if ($option.mode == $val['id']) {
        $this.mode_item = $val
      }
    })
  }
}
</script>

<style scoped>
@import "index.css";
</style>
