<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="chart_view_first margin-tb-xl">

        <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">Med(放松度)</view>
            </view>
          </view>
        </view>
        <view class="chart">
          <mpvue-echarts :echarts="echarts" :onInit="attCharts" canvasId="demo-canvas"/>
        </view>
      </view>

      <view class="chart_view_second margin-tb-xl">

        <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>
      </view>

    </div>

    <!--    窗口弹出-->
    <van-popup :show="pop_show" @close="close_pop" round :close-on-click-overlay="false"
               overlay
               z-index="99">
      <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, {formatSeconds} from '../../utils/index'
import bluetooth from "../../utils/bluetooth";
import game_store from "@/store/game";
import Toast from '../../../static/vant/toast/toast';
import {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,

      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: [0],
      med_list: [0],
      delta_list: [],
      alpha_list: [],
      beta_list: [],
      theta_list: [],
      //判断是否结束游戏
      is_end: false,
      //  消耗的时间
      played_time: 0,
      played_time_text: ""
    }
  },
  methods: {
    //游戏结束方法
    game_finished() {

      //停止传输数据
      bluetooth.sendPause($this._deviceId, $this._serviceId, $this._characteristicId)
      bluetooth.sendEnd($this._deviceId, $this._serviceId, $this._characteristicId)
      //停止控制游戏
      bluetooth.shutdownSendControl($this._deviceId, $this._serviceId, $this._characteristicId)
      const countDown = $this.$mp.page.selectComponent('.control-count-down');
      countDown.pause();
      //取消监听低功耗蓝牙设备
      wx.offBLECharacteristicValueChange()
      Toast.success('已成功断开')
      //设置游戏状态为 停止游戏
      game_store.setters.setGameStatus(3)
      //游戏结束重置游戏时间
      wx.removeStorageSync('play_time')
      //游戏结束重置游戏模式
      game_store.setters.setMode(0)
      //删除游戏得id
      game_store.setters.removeToyHex()
      //游戏结束传送一下数据
      $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"
      })
    },
    start_game() {

      wx.onBLECharacteristicValueChange((characteristic) => {
        console.log('监听蓝牙时间获取数据')
        // 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
        }
        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('');
    },

    //  监听时间发生变动
    watch_time(e) {
      let $datetime = e.mp.detail
      if ($datetime.seconds.length == 1) {
        $datetime.seconds = '0' + $datetime.seconds
      }
      $this.timeData = $datetime
      $this.played_time += 1
      console.log("玩了:" + $this.played_time + "秒")
      //时间倒数
      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
      }
      if (!$params.line && !$params.line_med) {
        return false
      }
      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 $params = {
        game_record_id: game_store.getters.getGameRecordId(),
        type: $this.mode,
        play_time: $this.played_time
      }
      console.log("结束游戏参数", $params)
      //
      gameEnd($params).then((res) => {
        let $data = res.data
        $this.played_time = 0
        //设置未结束游戏
        $this.is_end = false
      })
    }
  }
  ,
  mounted() {

    let $deviceId = $this._deviceId = game_store.getters.getDeviceId()
    let $serviceId = $this._serviceId = game_store.getters.getServiceId()
    let $cId = $this._characteristicId = game_store.getters.getCharacterId()
    console.log("游戏开始:", $deviceId, $serviceId, $cId)

    //判断是否结束游戏
    if ($this.is_end == true) {
      $this.game_finished()
    } else {
      //  筛选 玩具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 mode_list = [
        {
          id: 1,
          name: "次卡(10分钟)",
          time: 10 * 60 * 1000,
          err_title: "您的会员消费时间已用完",
        },
        {
          id: 2,
          name: "会员时间消费",
          time: 30 * 60 * 1000,
          err_title: "本次游玩时间已用完"
        }

      ]
      //获取用户游玩时间
      let $played_time = $this.play_time = game_store.getters.getPlayTime() ? game_store.getters.getPlayTime() : 0
      $this.mode_item = mode_list[$this.mode - 1]
      let $origin_time = mode_list[$this.mode - 1]['time']
      $this.mode_item['time'] = $origin_time - ($played_time * 1000)
      $this.start_game()

      //打开蓝牙监听
      bluetooth.watch_bluetooth_status($this)
    }

  },
  created() {
    $this = this;
  },
  onShow() {
  },
  onLoad(options) {
    if (options.end == 1) {
      $this.is_end = true
    }
  },
  onUnload() {
    if (!$this.is_end) {
      // 返回 的时候 暂停
      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)
      wx.offBLECharacteristicValueChange()
      //存储时间
      game_store.setters.setPlayTime($this.played_time)
      this.pop_show = false
      //设置未结束游戏
      $this.is_end = false
    }

  }
}
</script>

<style>
.van-count-down {
  font-weight: bold;
  font-size: 30px !important;
  color: white !important;
}

</style>
<style scoped>
#playing_container {
  width: 100%;
  background: linear-gradient(0deg, rgba(40, 157, 206, 0.51), rgba(135, 145, 226, 0.26));
  background-color: #46425E;
  padding: 5px;
  height: 750px;

}

.game_panel {
  width: 100%;
  height: 76px;
  background: #46425E;
  box-shadow: 0px 3px 4px 0px #302D43;
  border-radius: 11px;
  margin: 0px auto;
}

.game_panel .title {
  color: #9A96B7;
}

.game_panel .type {
  color: #FFFFFF;
}

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

.device_img {
  width: 36px;
  height: 36px;
}

.text-default {
  color: #9A95B7;
  font-size: 10px;
}

/*电量显示*/
.elc_power_container {
  width: 28px;
  border: #9A95B7 3px solid;
  border-radius: 5px;
  height: 22px;
}

.device_elc {
  height: 22px;
  width: 4px;
}

/* 节标题  */
.bar {
  width: 100%;
  height: 15px;
  display: flex;
  align-items: center;
  justify-content: space-between;
  padding: 0 7px;
  box-sizing: border-box;
  margin: 11px 0;
}

.bar view {
  display: flex;
  align-items: center;
  justify-content: start;
}

.bar .line {
  width: 4px;
  height: 15px;
  background-color: #FFB400;
  margin-right: 7px;
}

.bar .title {
  color: #fff;
  font-size: 15px;
}

.label {
  color: #9A95B7;
  font-size: 10px;
}

/*点图*/
.dot {
  width: 8px;
  height: 8px;
  border-radius: 50%;
  margin-right: 4px;
  margin-left: 15px;
}

.dot-orange {
  background: #FFB400;
}

.dot-pink {

  background: #D4327A;
}

.dot-blue {

  background: #00CCFF;
}

.dot-green {

  background: #0CDA2E;
}

.dot-yellow {

  background: #D1D310;
}

.dot-orange-yellow {

  background: #F8A117;
}

/* 图表 */
#mychart-dom-multi-line {
  width: 100%;
  height: 175px;
}

#mychart-dom-multi-line-med {
  width: 100%;
  height: 100px;
}

.chart {
  width: 360px;
  height: 193px;
  background: #302D43;
  opacity: 0.6;
  border-radius: 10px;
}

/*弹窗模块*/
.err_container {
  width: 260px;
  height: 300px;
  border-radius: 5px;
}

/*标题*/
.err_container .title {
  font-size: 20px;
  font-weight: bold;
  color: #4C4C4C;
  line-height: 24px;
}

/*子标题*/
.err_container .sub-title {
  font-size: 12px;
  font-family: Microsoft YaHei;
  font-weight: 400;
  color: #4B4B4B;
  line-height: 24px;
}

.err_img {
  width: 73px;
  height: 83px;
}

.chart_view_first {
  position: relative;
  bottom: 10px;
}

.chart_view_second {
  position: relative;
  bottom: 5px;
}
</style>
