<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">
            <text class="count_down_text">{{ countdown_text }}</text>
          </view>
        </van-col>
        <van-col span="10" offset="4">
          <view class="text-sm">
            <text class="title">计费模式</text>
            <text v-if="mode===1" class="type padding-left-sm">次卡(10分钟)</text>
            <text v-else-if="mode===2" class="type padding-left-sm">会员时间消费</text>
            <text v-else class="type padding-left-sm">未选择</text>
          </view>
          <button class="cu-btn bg-red text-white margin-top-sm" @click="clickToEnd()" :disabled="end_loading">
            <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="8">
          <div class="flex flex-direction align-center justify-center" v-if="device_bg">
            <img src="https://img.shuimuai.com/web/touhuanzhuangtai_2.png" alt="" class="device_img"/>
            <text class="text-default">已经正确佩戴</text>
          </div>
          <div class="flex flex-direction align-center justify-center" v-else>
            <img src="https://img.shuimuai.com/web/touhuanzhuangtai_3.png" alt="" class="device_img"/>
            <text class="text-default">未正确佩戴</text>
          </div>
        </van-col>
        <van-col span="8">
          <div class="flex flex-direction align-center justify-center">
            <view class="elc_power_container">
              <img src="https://img.shuimuai.com/web/dianchi_3.png" alt="" :style="{ width: device_power + '%' }"
                   class="device_elc"/>
            </view>
            <text class="text-default">脑机电量</text>
          </div>
        </van-col>
        <van-col span="8">
          <div class="flex flex-direction align-center justify-center">
            <view class="elc_power_container">
              <img src="https://img.shuimuai.com/web/dianchi_3.png" alt="" :style="{ width: toy_power + '%' }"
                   class="device_elc"/>
            </view>
            <text class="text-default">教具电量</text>
          </div>
        </van-col>
        <van-col span="8">
          <div class="flex flex-direction align-center justify-center">
            <text style="color:white;">{{ RSSI }}dBm</text>
            <text class="text-default">脑机信号值</text>
          </div>
        </van-col>
      </van-row>
    </div>
    <!--  环形实时数据  -->
    <div class="circle_container">
      <van-circle :value="online_att" layer-color="#49465E" color="#FFB400" stroke-width="7" :speed="0">
        <view class="circle_text">
          <text class="online_att_txt">{{ online_att }}</text>
          <view class="online_desc">{{ online_att_desc }}</view>
        </view>
      </van-circle>
      <van-circle :value="online_med" layer-color="#49465E" color="#40FF31" stroke-width="7" :speed="0">
        <view class="circle_text">
          <text class="online_med_txt">{{ online_med }}</text>
          <view class="online_desc">{{ online_med_desc }}</view>
        </view>
      </van-circle>
    </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-med"></view>
              <view class="name">Med(放松度)</view>
            </view>
            <view>
              <view class="dot dot-amp"></view>
              <view class="name">Amp (和谐度)</view>
            </view>
          </view>
        </view>
        <view class="chart">
          <mpvue-echarts
            :echarts="echarts"
            :onInit="attCharts"
            canvasId="canvasId-demo1"
          />
        </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">
            <van-row>
              <van-col span="8">
                <view>
                  <view class="dot dot-delta"></view>
                  <view class="name">Delta</view>
                </view>
              </van-col>
              <van-col span="8">
                <view>
                  <view class="dot dot-theta"></view>
                  <view class="name">Theta</view>
                </view>
              </van-col>
              <van-col span="8">
                <view>
                  <view class="dot dot-low-beta"></view>
                  <view class="name">Low_Beta</view>
                </view>
              </van-col>
              <van-col span="8">
                <view>
                  <view class="dot dot-high-beta"></view>
                  <view class="name">High_Beta</view>
                </view>
              </van-col>
              <van-col span="8">
                <view>
                  <view class="dot dot-low-alpha"></view>
                  <view class="name">Low_Alpha</view>
                </view>
              </van-col>
              <van-col span="8">
                <view>
                  <view class="dot dot-high-alpah"></view>
                  <view class="name">High_Alpha</view>
                </view>
              </van-col>
            </van-row>
          </view>
        </view>
        <view class="chart">
          <mpvue-echarts
            :echarts="echarts"
            :onInit="medCharts"
            canvasId="canvasId-demo2"
          />
        </view>
      </view>
    </div>
    <van-dialog id="van-dialog"/>
    <van-toast id="van-toast"/>
    <van-notify id="van-notify"/>
  </div>
</template>

<script>
import ble_store from "@/store/bluetooth";
import util from "../../../utils";
import game_store from "@/store/game";
import Toast from "../../../../static/vant/toast/toast";
import {gameAddLine, gameEnd} from "../../../requests/game";
import mpvueEcharts from "mpvue-echarts";
import echarts from "../../../../static/echarts.min";
import {formatPlaySeconds, get_big_data} from "../../../utils/game";
import {LOG_DEBUG, LOG_WECHAT} from "../../../utils/log";

let att_charts, med_charts, $this, $timeout;

// 大脑图表初始化
function initAttChart(canvas, width, height) {
  att_charts = echarts.init(canvas, null, {
    width: width,
    height: height,
  });
  canvas.setChart(att_charts);
  let option = {}; // 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);
  let option = {}; // ECharts 配置项
  med_charts.setOption(option);
  return med_charts; // 返回 chart 后可以自动绑定触摸操作
}

export default {
  name: "StartGames",
  components: {
    mpvueEcharts,
  },
  created() {
    $this = this;
  },
  data() {
    return {
      // 折线图
      echarts,
      attCharts: initAttChart,
      medCharts: initMedChart,
      // 检测佩戴是否正确
      device_bg: true,
      // 脑机电量
      device_power: 0,
      // 教具电量
      toy_power: 0,
      //  蓝牙信号强度
      RSSI: 0,
      // 监听到的蓝牙数据
      hexStr: "",
      //实时的专注值和放松度
      online_att: 0,
      online_att_desc: "",
      online_med: 0,
      online_med_desc: "",
      //图标数据集合
      att_list: [],
      med_list: [],
      //和谐度
      amp_list: [],
      delta_list: [],
      theta_list: [],
      low_alphas: [],
      high_alphas: [],
      low_betas: [],
      high_betas: [],
      //保存的数据集合
      game_data: [],
      save_index: [
        "att",
        "med",
        "delta",
        "theta",
        "low_alpha",
        "high_alpha",
        "low_beta",
        "high_beta",
        "low_gamma",
        "middle_gamma",
        "delta_basic",
        "theta_basic",
        "low_alpha_basic",
        "high_alpha_basic",
        "low_beta_basic",
        "high_beta_basic",
        "low_gamma_basic",
        "middle_gamma_basic"
      ],
      // 计费模式： 1:次数 2:时间 0:未选择
      mode: 0,
      // 结束游戏loading
      end_loading: false,
      // 判断是否已经结束游戏
      is_end: false,
      // 该局总时间:30分钟或10分钟
      total_time: 0,
      // 该局游戏剩余可以游玩的时间
      play_time: 0,
      // 本次游玩时间倒计时
      countdown_text: "--:--",
    };
  },
  onLoad(options) {
    if (options.end === 1) {
      $this.is_end = true;
      $this.executed = true
    }
  },
  mounted() {
    let game_status = game_store.getters.getGameStatus()*1;
    if (game_status === 1) {
      $this.is_end = false;
      $this.end_loading = false;
      $this.total_time = game_store.getters.getOverPlayTime();
      // 筛选模式
      $this.mode = game_store.getters.getMode() * 1;
      // 可玩时间 (剩余时长)
      $this.play_time = game_store.getters.getPlayTime();
      // 开始游戏
      $this.startTheGame();
      // 打开蓝牙监听
      $this.$connection.watchBLEstatus($this);
    }
    if (game_status === 3) {
      $this.endTheGame();
    }
  },
  // 加载完成后、后台切到前台或重新进入页面时触发
  onShow() {
    game_store.setters.setHideStatus(false);
    $this.countdown_text = "--:--";
    let game_status = game_store.getters.getGameStatus()*1;
    if (game_status === 2) {
      // 获取 拉到后台得时间
      let $hide_time = game_store.getters.getHideTime()*1;
      if ($hide_time) {
        let store_time = game_store.getters.getPlayedTime()*1;
        // 获取当前时间差
        let $now = Math.round(new Date() / 1000) - $hide_time;
        // 实际游玩时间
        let played_time =  store_time + $now;
        if (played_time >= $this.total_time) {
          $this.endTheGame();
        } else {
          //重新设置游玩时间
          game_store.setters.setPlayedTime(played_time);
          // 可玩时间 (剩余时长)
          $this.play_time = $this.total_time - played_time;
          // 重新倒计时
          $this.countdownInterval($this.play_time);
        }
      }
    }
  },
  // // 页面从前台切换到后台或者去别的页面时候触发的
  // onHide() {
  //   game_store.setters.setHideStatus(true);
  //   let game_status = game_store.getters.getGameStatus()*1;
  //   if (game_status === 2) {
  //     // 存储时间
  //     game_store.setters.setPlayedTime($this.total_time - $this.play_time);
  //     // 四舍五入取整
  //     game_store.setters.setHideTime(Math.round(new Date() / 1000));
  //     clearInterval($timeout);
  //   }
  // },
  // 页面卸载时候触发的生命周期
  onUnload() {
    LOG_DEBUG("训练页面被卸载！is_end:", $this.is_end, ",end_loading", $this.end_loading);
    if (!$this.is_end) {
      // 存储时间
      game_store.setters.setPlayedTime($this.total_time - $this.play_time);
      // 设置未结束游戏
      $this.is_end = false;
      $this.end_loading = false;
    }
    game_store.setters.setHideStatus(true);
    let game_status = game_store.getters.getGameStatus()*1;
    if (game_status === 2) {
      // 存储时间
      game_store.setters.setPlayedTime($this.total_time - $this.play_time);
      // 四舍五入取整
      game_store.setters.setHideTime(Math.round(new Date() / 1000));
    }
    // clearInterval($timeout);
  },
  methods: {
    /**
     * 实时分析游戏数据
     */
    analysisGameData: function (hexStr) {
      let $data = get_big_data(hexStr);
      this.onlineAttMed($data);
      this.doChartsData($data);
    },
    /**
     * 实时的专注值和放松度
     */
    onlineAttMed: function ($data) {
      $this.online_att = $data["att"];
      if ($this.online_att >= 1 && $this.online_att < 40) {
        $this.online_att_desc = "专注力不足";
      } else if ($this.online_att < 60) {
        $this.online_att_desc = "一般专注";
      } else if ($this.online_att < 80) {
        $this.online_att_desc = "高度专注";
      } else if ($this.online_att <= 100) {
        $this.online_att_desc = "深度专注";
      }
      $this.online_med = $data["med"];
      if ($this.online_med >= 1 && $this.online_med < 40) {
        $this.online_med_desc = "放松度不足";
      } else if ($this.online_med < 60) {
        $this.online_med_desc = "一般放松";
      } else if ($this.online_med < 80) {
        $this.online_med_desc = "高度放松";
      } else if ($this.online_med <= 100) {
        $this.online_med_desc = "深度放松";
      }
    },
    /**
     * 大脑状态数据 与 基本脑波数据
     */
    doChartsData: function ($data) {
      // 显示的数据
      $this.att_list.push($data["att"]);
      $this.med_list.push($data["med"]);
      $this.amp_list.push(100 - Math.abs($data["att"] - $data["med"]));
      $this.delta_list.push($data['delta']);
      $this.theta_list.push($data['theta']);
      $this.low_alphas.push($data['low_alpha']);
      $this.high_alphas.push($data['high_alpha']);
      $this.low_betas.push($data['low_beta']);
      $this.high_betas.push($data['high_beta']);
      game_store.setters.setGameDataLength($this.att_list.length);
      if ($this.att_list.length > 15) {
        // 图表显示数据过长时从第一个开始删除
        $this.att_list.shift();
        $this.med_list.shift();
        $this.amp_list.shift();
        $this.delta_list.shift();
        $this.theta_list.shift();
        $this.low_alphas.shift();
        $this.high_alphas.shift();
        $this.low_betas.shift();
        $this.high_betas.shift();
      }
      //判断是否隐藏 隐藏则不绘画
      let $hide_status = game_store.getters.getHideStatus();
      if (!$hide_status) {
        if (att_charts) {
          // 通过专注放松度 画图
          let $option = util.getLineOption($this.att_list, $this.med_list, $this.amp_list);
          att_charts.setOption($option);
        }
        if (med_charts) {
          // 通过基本脑波发送数据
          let $base_option = util.getBaseOption($this.delta_list, $this.theta_list, $this.low_alphas, $this.high_alphas, $this.low_betas, $this.high_betas);
          med_charts.setOption($base_option);
        }
      }
      // 保存的数据
      for (let i = 0; i < $this.save_index.length; i++) {
        if ($this.game_data[$this.save_index[i]] === undefined) {
          $this.game_data[$this.save_index[i]] = [];
        }
        $this.game_data[$this.save_index[i]].push($data[$this.save_index[i]])
      }
    },
    /**
     * 开始游戏
     */
    startTheGame() {
      LOG_DEBUG("开始游戏");
      game_store.setters.setGameStatus(2);
      wx.setKeepScreenOn({
        keepScreenOn: true,
      });
      // 打开重连功能,自动发送RF重连教具
      $this.$connection.sendAutoConnectRf(true, Math.round($this.total_time / 60));
      $this.$connection.notifyDatas($this);
      setTimeout(() => {
        // 获取LED灯状态并设置
        let led_status = game_store.getters.getLED();
        LOG_DEBUG("开始游戏获取LED灯状态", led_status)
        if (led_status) {
          $this.$connection.SendLedOrder("01");
        } else {
          $this.$connection.SendLedOrder("00");
        }
      }, 500);
      setTimeout(() => {
        let $toy_sn = ble_store.getters.getToySn().toUpperCase();
        // 获取教具类型 发送陀螺仪开关指令
        if ($toy_sn.includes("SW") || $toy_sn.includes("KL") || $toy_sn.includes("SC")) {
          // 设置教具为无运动状态 AA CC 03 00 00 00 34 CKS
          $this.$connection.SendMotionOrder("01");
        } else {
          $this.$connection.SendMotionOrder("00");
        }
      }, 1000);
      // 开始倒计时
      $this.countdownInterval();
    },
    countdownInterval(){
      clearInterval($timeout)
      $timeout = setInterval(() => {
        //判断是否游戏中
        let game_status = game_store.getters.getGameStatus()*1;
        if (game_status === 2 && $this.play_time > 0) {
          // 自定义定时器
          $this.play_time -= 1;
          game_store.setters.setPlayedTime($this.total_time-$this.play_time);
          $this.countdown_text = formatPlaySeconds($this.play_time);
          console.log("%c游戏倒计时", "color:red;", $this.countdown_text);
        } else {
          clearInterval($timeout);
          $this.endTheGame();
        }
      }, 1000);
    },
    /**
     * 点击结束游戏按钮
     */
    clickToEnd() {
      if (!$this.end_loading && !$this.is_end) {
        $this.endTheGame();
      }
    },
    /**
     * 游戏结束
     */
    endTheGame() {
      if($this.end_loading || $this.is_end){
        return;
      }
      $this.end_loading = true;
      $this.is_end = true;
      clearInterval($timeout);
      game_store.setters.setGameStatus(3);
      LOG_DEBUG("正在结束游戏->endTheGame()");
      // 关闭脑控
      $this.$connection.sendControlClose();
      // 结束游戏提交数据
      $this.postGameData();
      // 跳转到报告页
      Toast.loading({
        forbidClick: true,
        mask: true,
        message: "正在生成报告...",
        duration: 2000,
        onClose() {
          $this.toReportPage();
          $this.end_loading = false;
        }
      });
      let $code = ble_store.getters.getDeviceSn();
      LOG_WECHAT($code, "结束训练record_id:", game_store.getters.getGameRecordId());
    },
    /**
     * 往后端推送一次数据
     */
    postGameData() {
      let post_data = [];
      for (let i = 0; i < this.save_index.length; i++) {
        post_data[this.save_index[i]] = this.game_data[this.save_index[i]].join(',');
      }
      //判断数据长度大于理想状态 需要对数组进行切割 逐个提交数据
      let $dataParams = {
        game_record_id: game_store.getters.getGameRecordId(),
        //数据段长度小于65 单个提交
        line: this.game_data['att'].join(','),
        line_med: this.game_data['med'].join(','),
        ...post_data,
        sn: ble_store.getters.getDeviceSn()
      };
      if (!$dataParams.line) {
        return false;
      }
      gameAddLine($dataParams).then((res) => {
        let $data = res.data;
        if ($data.code*1 === 0) {
          $this.game_data = [];
        }
      });
      let $params = {
        game_record_id: game_store.getters.getGameRecordId(),
        type: $this.mode,
        play_time: $this.total_time - Math.abs($this.play_time),
      };
      gameEnd($params).then(() => {
        $this.resetGameData();
      });
    },
    /**
     * 重置游戏数据
     */
    resetGameData(){
      //游戏结束重置游戏时间
      wx.removeStorageSync("play_time");
      //删除隐藏时间
      game_store.remover.rmHideTime();
      //游戏结束重置游戏模式
      game_store.setters.setMode(0);
      //设置游戏状态为 停止游戏
      let game_status = game_store.getters.getGameStatus() * 1;
      if (game_status === 1 || game_status === 2) {
        game_store.setters.setGameStatus(3);
      }
      // 重置状态
      $this.is_end = false;
      $this.end_loading = false;
      $this.att_list = [];
      $this.med_list = [];
      $this.amp_list = [];
      $this.delta_list = [];
      $this.theta_list = [];
      $this.low_alphas = [];
      $this.high_alphas = [];
      $this.low_betas = [];
      $this.high_betas = [];
      //游戏结束重置游戏卡卷类型时间和卡卷类型
      $this.play_time = game_store.getters.getPlayTime();
      game_store.setters.setPlayedTime(0);
      game_store.setters.setOverPlayTime(0);
      game_store.setters.setMode(0);
      $this.countdown_text = "--:--";
    },
    /**
     * 跳转到报告页
     */
    toReportPage() {
      mpvue.redirectTo({
        url: "/pages/games/report/main?id=" + game_store.getters.getGameRecordId() + "&size=" + game_store.getters.getGameDataLength(),
        success() {
          $this.attList = [];
          $this.medList = [];
          $this.ampList = [];
          LOG_DEBUG("生成报告成功")
        },
      });
    },
  },
};
</script>

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

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

/* 节标题  */
.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 {
  width: 250px;
  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;
}

/*弹窗模块*/
.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;
}

/*倒计时样式*/
.count_down_text {
  font-size: 35px;
  font-family: PingFang SC;
  font-weight: 400;
  color: #fff;
  line-height: 28px;
}

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

/* 提高dialog提示的层级 */
#van-dialog {
  z-index: 10000001 !important;
}

.dot-amp {
  background: #D4327A;
}

.dot-med {
  background: #40FF31;
}

.circle_container {
  width: 100%;
  height: 150px;
  background: #302D43;
  opacity: 0.6;
  border-radius: 20px;
  display: flex;
  justify-content: space-around;
  align-items: center;
}

.circle_text {
  width: 100%;
}

.online_att_txt {
  font-size: 40px;
  font-family: Arial, serif;
  font-weight: bold;
  color: #FAB615;
}

.online_med_txt {
  font-size: 40px;
  font-family: Arial, serif;
  font-weight: bold;
  color: #40FF31;
}

.online_desc {
  font-size: 12px;
  font-weight: 400;
  color: #FFFFFF;
}

.dot-delta {
  background-color: #FF77B3;
}

.dot-theta {
  background-color: #FFE838;
}

.dot-low-beta {
  background-color: #0060F1;
}

.dot-high-beta {
  background-color: #00CCFF;
}

.dot-low-alpha {
  background-color: #38FF49;
}

.dot-high-alpah {
  background-color: #00AD0E;
}
</style>
