<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" use-slot auto-start @finish="time_out"
                            @change="watch_time" class="control-count-down"
            >
              <text>{{ timeData.minutes }}:{{ timeData.seconds }}</text>
            </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">停止游玩</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>
    <van-toast id="van-toast"/>

  </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";
import Toast from '../../../static/vant/toast/toast';
import {game_devices, gameAddLine, gameEnd} from "../../requests/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: "您的会员消费时间已用完",
        }
      ],
      timeData: {},
      mode_item: {},
      pop_show: false,
      elc_power: 100,
      // 折线图
      echarts,
      attCharts: initAttChart,
      medCharts: initMedChart,
      user_info: {},
      //设备值
      _deviceId: "",
      _serviceId: "",
      _characteristicId: "",

      toy_index: 0,
      toy_id: 0,
      toy: {},
      toy_hex: "",

      play_time: 0,

      //图标数据集合
      att_list: [],
      med_list: [],
      delta_list: [],
      alpha_list: [],
      beta_list: [],
      theta_list: []
    }
  },
  methods: {
    //游戏结束方法
    game_finished() {
      //停止控制游戏
      bluetooth.sendPause($this._deviceId, $this._serviceId, $this._characteristicId)
      bluetooth.sendEnd($this._deviceId, $this._serviceId, $this._characteristicId)
      const countDown = $this.$mp.page.selectComponent('.control-count-down');
      countDown.pause();
      Toast.success('已成功断开')
      //设置游戏状态为 停止游戏
      game_store.commit('setGameStatus', 0)
      //游戏结束传送一下数据
      $this.post_data()
      $this.game_over()
      $this.to_report()
    },
    //  关闭弹窗
    close_pop() {
      $this.pop_show = false
    },
    // 时间到
    time_out() {
      $this.pop_show = true
      $this.game_finished()
    },
    to_report() {
      mpvue.reLaunch({
        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_hex, 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 $data = bluetooth.get_big_data(hexStr)
        if ($data) {
          $this.att_list.push($data['att'])
          $this.med_list.push($data['med'])
          $this.delta_list.push(Math.round($data['delta'] / 10000))
          $this.alpha_list.push(Math.round($data['alpha'] / 1000000))
          $this.theta_list.push(Math.round($data['theta'] / 10000))
          $this.beta_list.push(Math.round($data['beta']) / 1000000)

          //通过专注放松度 画图
          let $option = util.getLineOption($this.att_list, $this.med_list)
          att_charts.setOption($option)

          //通过基本脑波发送数据
          let $base_option = util.getBaseOption($this.delta_list, $this.theta_list, $this.alpha_list, $this.beta_list)
          med_charts.setOption($base_option)
        }
        //获取设备电量
        let $power = bluetooth.get_device_elc(hexStr)
        if ($power) {
          $this.elc_power = $power
        }

        //连接玩具
        console.log('玩具hexStr', hexStr)
        let $flag = bluetooth.connect_toy(hexStr, $this._deviceId, $this._serviceId, $this._characteristicId)
        //连接不上设备
        if ($flag == false) {
          // $this.game_finished()
          console.log('info', $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('');
    },

    //  监听时间发生变动
    watch_time(e) {
      let $datetime = e.mp.detail
      $this.timeData = $datetime
      //时间倒数
      if ($datetime.seconds == '00') {
        //  时间满一分钟 则提交一次数据
        // 添加折线图的点
        $this.post_data()
      }
    },
    // 往后端推送一次定时数据
    post_data() {
      let $params = {
        game_record_id: game_store.getters.getGameRecordId,
        line: $this.att_list,
        line_med: $this.med_list
      }
      gameAddLine($params).then((res) => {
        let $data = res.data
        if ($data.code == 0) {
          $this.att_list = []
          $this.med_list = []
          $this.delta_list = []
          $this.alpha_list = []
          $this.theta_list = []
          $this.beta_list = []
          console.log('推送数据成功')
        } else {
          console.log('推送数据失败')
        }
      })
    },
    //  结束游戏
    game_over() {
      let $current_time = $this.timeData.minutes * 60 + $this.timeData.seconds
      let $play_time = $this.play_time - $current_time
      if ($this.mode == 2) {
        let $userinfo = wx.getStorageSync('userinfo')
        $play_time = $userinfo['play_time'] - $current_time
      }
      let $params = {
        record_id: game_store.getters.getGameRecordId,
        type: $this.mode,
        play_time: $play_time
      }
      gameEnd($params).then((res) => {
        let $data = res.data
      })
    }
  }
  ,
  mounted() {
  },
  created() {
    $this = this;
  },
  onShow() {
    $this._deviceId = game_store.getters.getDeviceId
    $this.getBLEDeviceServices($this._deviceId)

    //  筛选 玩具id
    $this.toy_hex = game_store.getters.getToyHex
    // bluetooth.sendConnect($this.toy_hex, $this._deviceId, $this._serviceId, $this._characteristicId)


    //筛选模式
    $this.mode = game_store.getters.getMode

    //获取用户游玩时间
    let $play_time = $this.play_time = game_store.getters.getPlayTime
    $this.mode_list.forEach(($val, $index) => {
      $val['time'] = $play_time  * 1000
      if ($val['id'] == $this.mode) {
        $this.mode_item = $val
      }
    })

  },
  onLoad() {
  },
  onUnload() {
    const countDown = $this.$mp.page.selectComponent('.control-count-down');
    countDown.pause();
    bluetooth.sendPause($this._deviceId, $this._serviceId, $this._characteristicId)
    bluetooth.sendEnd($this._deviceId, $this._serviceId, $this._characteristicId)

    let $play_time = $this.timeData.minutes * 60 + $this.timeData.seconds
    console.log($play_time)
    game_store.commit('setPlayTime', $play_time)
  }
}
</script>

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