<template>
  <div :class="[{'IndexContainer':true}]" :style="{height:ClentHeight}">
    <keep-alive>
      <router-view></router-view>
    </keep-alive>
  </div>
</template>

<script>
import {
  QueryVueFramework,
  DownloadVueFramework,
  getCheckUpdate,
  getUserList
} from '@/api/getApiRes'

import "../../public/mui.js"
import '../Global'
import * as ble from '../ble'
import * as ws from '../webSocket'


let qs = require('qs');

export default {
  name: 'Home',
  data() {
    return {
      testMode: false,      //是否测试模式
      aSideState: false,
      bleEnable: false,     //是否开启BLE广播监听
      wsUrl: "ws://192.168.0.3:9000/websocket",            //webSocket服务器URL
      shopName: "",         //店铺名称 英泓小飞龙
      thisClick: 0,
      tabwildState: 1,
      handleTabsList: [{
        title: '系统首页',
        name: '1',
        clmurl: '/',
      }],
      editableTabsValue: '1',
      localVersion: '2.5',
      isPad: true,// pad 展示版本
      ClentHeight: document.documentElement.clientHeight + 'px',
      testEqsnArr: [
        '939a94d3044f1078', // WZX 手机基座测试
        '7962ad082220d997', // 公司PAD 基座测试
        '1277fcb4c81e29d2', // ?
        // 'e1b37235010cf637', // 公司PAD
        'd104bd6ffec3d5ba', // 公司电视盒(接TV)
        'd76a54a795fb5774', // 公司电视盒2
        '9ecb2cb6cb3bf318', // 公司电视盒2 基座测试
        '30:9C:23:0C:8B:1E', // 默认
      ],
      intervTime_checkUpdate: 600000, //检测升级信息的轮询时间 毫秒
      appRuntime: 0, //APP运行时长 分钟
    }
  },
  mounted() {
    this.sysInit();
  },
  methods: {
    // 获取当前版本号
    sysInit() {
      let that = this;
      //浏览器默认的
      localStorage.eqSn = '30:9C:23:0C:8B:1E';
      // localStorage.eqSn = 'd104bd6ffec3d5ba';
      that.$store.commit('setEqSn', localStorage.eqSn);
      that.$store.commit('setLocalVersion', that.localVersion);

      that.getSysDateTime();

      if (window.plus) {
        that.plusReady();
      } else {
        console.log('>>> plus is not ready');
        // 调试时候关闭
        this.getConfigParam(localStorage.eqSn);
        document.addEventListener('plusready', that.plusReady, false);
      }     
    },
    getSysDateTime() {
      let that = this;
      console.log('[sysInit] getSysDateTime() run!');

      setInterval(() => {
        let date = new Date();
        let curTime = globalGetCurrentTime(date);
        let curDay = globalcurrentByCN(date);
        let curWeek = numberToWeekdays(date.getDay());
        that.$store.commit('setCurTime', curTime);
        that.$store.commit('setCurDay', curDay);
        that.$store.commit('setCurWeek', curWeek);
        // console.log(curTime);
      }, 1000);
    },
    plusReady() {
      let that = this;
      console.log('>>> plus is ready');

      if (typeof plus == 'undefined') return false;
      // 获取本地应用资源版本号
      plus.runtime.getProperty(plus.runtime.appid, function (inf) {
        that.localVersion = inf.version;
        that.$store.commit('setLocalVersion', that.localVersion);
      });

      //   获取手机UUID
      plus.device.getInfo({
        success: function (e) {
          let uuid = JSON.stringify(e.uuid).toString().substr(1);
          uuid = uuid.substring(0, uuid.length - 1);
          localStorage.eqSn = uuid;
          that.$store.commit('setEqSn', uuid);
          
          console.log('>>> [uuid]: ' + uuid);
          console.log('getDeviceInfo success: ' + JSON.stringify(e.uuid));
          // 正式版打开
          // 获取配置参数
          that.getConfigParam(e.uuid);

          // 公司测试机用公司版本升级 
          if (that.testEqsnArr.includes(uuid)) {
            that.testMode = true;                 
          } else {  // 正式版
            that.testMode = false;            
          }

          // 教室版本自动升级，户外版禁用自动升级
          if (runVersion == 'outDoor') {
            console.log('户外版禁用自动升级');
            
            setInterval(() => {
              that.checkAppRuntime();
            }, that.intervTime_checkUpdate);

            return false
          } 
          else if (runVersion == 'localtest') {
            console.log('本机测试禁用自动升级');
            plus.nativeUI.toast("本机测试 禁用自动升级 UUID: " + uuid);

            setInterval(() => {
              that.checkAppRuntime();
            }, that.intervTime_checkUpdate);
            
            return false
          } 
          else {
            that.checkUpdate();

            // 每10分钟检测一下升级信息
            setInterval(() => {
              // console.log("$route.path: " + that.$route.path);
              // console.log("$route.name: " + that.$route.name);

              that.checkAppRuntime();

              if (that.$route.name == "Wait") {
                console.log(">>> checkUpdate");
                that.checkUpdate();
              }
            }, that.intervTime_checkUpdate);
          }
        },
        fail: function (e) {
          console.log('getDeviceInfo failed: ' + JSON.stringify(e));
        }
      });
    },
    checkAppRuntime() {
      let that = this;
      that.appRuntime += that.intervTime_checkUpdate / 1000 / 60; //更新APP运行时长 分钟
      console.log('>>> App Runtime: ' + that.appRuntime + ' 分钟');
      let date = new Date();
      if (date.getHours() == 6 && that.appRuntime >= 720) {  //每天早上6点 且 运行时长大于12小时
      // if (date.getHours() == 13 && that.appRuntime >= 1) {
        plus.nativeUI.toast("APP即将重启，请稍等...");
        that.restartApp();
        that.appRuntime = 0;
      }
    },
    // 是否有新版本
    checkUpdate() {
      let that = this;
      let param = {
        vfType: 3   //新版电视端-Http接口
      };
      let postdata = qs.stringify(param);
      const h = that.$createElement;
      QueryVueFramework(postdata, that.testMode).then(res => {
        let json = res;
        if (json.Code == 0) {
          let remoteVersion = json.VueFramework.Version;
          that.$store.commit('setRemoteVersion', remoteVersion);

          console.log('localVersion: ' + that.$store.state.localVersion);
          console.log('remoteVersion: ' + that.$store.state.remoteVersion);
          if (that.$store.state.localVersion != that.$store.state.remoteVersion) {
            // 正式
            plus.nativeUI.toast("发现新版本 " + that.$store.state.remoteVersion + "，准备升级...");
            let url = DownloadVueFramework(that.testMode);
            that.downWgt(url);
          }
        }
      })
    },
    downWgt(url) {
      let that = this;
      plus.downloader.createDownload(url, {
        // method: "POST",
        // data: "{vfType:3}",
        filename: "_doc/update/"
        }, function (d, status) {
        if (status == 200) {
          console.log(d);
          console.log("下载wgt成功：" + d.filename);
          that.installWgt(d.filename); // 安装wgt包
        } else {
          console.log("下载wgt失败！");
          plus.nativeUI.toast("下载升级包失败！");
        }
        // plus.nativeUI.closeWaiting();
      }).start();
    },
    installWgt(path) {
      plus.nativeUI.showWaiting("正在升级，请稍候...");
      plus.runtime.install(path, {}, function () {
        plus.nativeUI.closeWaiting();
        console.log("安装wgt文件成功！");
        plus.nativeUI.toast("升级完成！");
        plus.runtime.restart();
        // });
      }, function (e) {
        plus.nativeUI.closeWaiting();
        console.log("安装wgt文件失败[" + e.code + "]：" + e.message);
        plus.nativeUI.toast("升级失败[" + e.code + "]：" + e.message);
      });
    },
    // 重启当前的应用
    restartApp() {
      plus.runtime.restart();
    },
    // 获取配置参数
    getConfigParam(eqsn) {
      const that = this;
      let url = '';
      if (runVersion == 'test') {   //演示模式
        headapi = "http://cal.beswell.com:85/DataTransfer/";
        console.log("runVersion = " + runVersion + " headapi = " + headapi);
        that.shopName = "演示模式";
        that.$store.commit('setShopName', that.shopName);
        that.wsUrl = "ws://192.168.0.3:9000/websocket";
        that.$store.commit('setWsUrl', that.wsUrl);
        return false
      }
      if (runVersion == 'localtest') {   //本机测试 TV端映射到本机进行测试
        // headapi = "http://127.0.0.1/";
        headapi = 'http://192.168.0.22/';
        console.log("runVersion = " + runVersion + " headapi = " + headapi);
        that.shopName = "本机测试";
        that.$store.commit('setShopName', that.shopName);
        that.wsUrl = "ws://192.168.0.3:9000/websocket";
        that.$store.commit('setWsUrl', that.wsUrl);

        that.bleEnable = true;
        setTimeout(function() {
          that.bleRcv(that.bleEnable);
        }, 3000);
        
        return false
      }
      // 测试使用0.3心率系统
      // if (eqsn == '7962ad082220d997' || eqsn == '1277fcb4c81e29d2' || eqsn == '30:9C:23:0C:8B:1E') {
      if (that.testEqsnArr.includes(eqsn)) {
        url = "http://192.168.0.3:19096/v1/Sensors/GetShopConfigParam";
      } else {
        url = updateUrl + 'GetShopConfigParam'
      }
      let param = {
        eqSn: eqsn
      };
      let postdata = qs.stringify(param);
      axios.post(url, postdata).then(function (data) {
        console.log(eqsn, url);
        let json = data.data;
        console.log(json);
        if (json.Code == 0) {
          that.bleEnable = json.BltHubSwitch;
          that.shopName = json.ShopName;
          that.$store.commit('setShopName', that.shopName);
          that.wsUrl = json.HubReportIp;
          that.$store.commit('setWsUrl', that.wsUrl);

          // 户外版使用HotsPotDataServiceIP
          if (runVersion == 'outDoor') {
            headapi = json.Rs.HotsPotDataServiceIP;
            // 内网测试版
            // headapi = 'http://192.168.0.3:19096/v1/Sensors/';
            if (!json.Rs.HotsPotDataServiceIP) {
              that.$message.error("未获取到HotsPotDataServiceIP");
              return false
            }
          } else {
            headapi = json.Rs.DataServiceIP;
            // console.log("正式版 headapi = " + headapi);
          }

          that.bleRcv(that.bleEnable);
        } else {
          headapi = 'http://192.168.0.10:8080/';  //树莓派数据转发
          console.log("error: " + json.Memo);
          that.shopName = "设备未授权";
          that.$store.commit('setShopName', that.shopName);
          that.wsUrl = "ws://192.168.0.3:9000/websocket";
          that.$store.commit('setWsUrl', that.wsUrl);
        }
        console.log("headapi = " + headapi);
      }, function (response) {
        console.info(response);
      })
    },
    bleRcv(bleEnable) {
      const that = this;
      if (window.plus && bleEnable == 1) {
        console.log('BLE SET Enabled');
        
        ble.BluetoothAdapter = plus.android.importClass("android.bluetooth.BluetoothAdapter");
        ble.btAdapter = ble.BluetoothAdapter.getDefaultAdapter();
        ble.Toast = plus.android.importClass("android.widget.Toast");
        ble.activity = plus.android.runtimeMainActivity();
        ble.Intent = plus.android.importClass("android.content.Intent");
      
        if (!ble.getBluetoothStatus()) {
          ble.turnOnBluetooth();
        }
        ble.listenerStateChange();      // 监听状态变化
        ble.listenerDeviceFound();      // 监听发现新设备

        let now = 0;
        let diffTime = 0;
        let bleIntvTime = setInterval(() => {
          //已上课
          if (that.$store.state.classOn > 0) {
            if (!ble.getBleDiscovery() && ble.getBluetoothStatus()) {
              ble.startBluetoothDiscovery();  // 开始搜索蓝牙
              console.log('已上课，开始接收心率数据');
              // plus.nativeUI.toast("已上课，开始接收心率数据");
            }            
            else if (ble.getBleDiscovery()) {   //接收心率数据时发生异常
              now = new Date().getTime();       //毫秒
              diffTime = now - ble.lastRcvTime;
              if (diffTime >= 3000) {
                console.log('接收心率数据时间超时，重置蓝牙搜索');
                ble.stopBluetoothDiscovery();   // 停止搜索蓝牙
                ble.setBleDiscovery(false);
                ble.lastRcvTime += 3000;
              }
            }

            ble.uploadBleData();
          }          
          //已下课，停止接收心率数据
          else if (ble.getBleDiscovery() && that.$store.state.classOn == 0) {
            console.log('已下课，停止接收心率数据');
            ble.setBleDiscovery(false);
            ble.stopBluetoothDiscovery();  // 停止搜索蓝牙
            // plus.nativeUI.toast("已下课，停止接收心率数据");
          }
        }, 1500);
      }
    }
  },
  components: {}
}
</script>

<!-- Add "scoped" attribute to limit CSS to this component only -->
<style>
ul, li {
  list-style: none;
  margin: 0;
  padding: 0;
}

.el-header {
  padding: 0 !important;
  height: 72px !important;
}

.shortElaside {
  width: 140px !important;
  overflow: hidden;
  height: 100%;
  float: left;
}

.lognElaside {
  width: 256px !important;
  overflow: hidden;
  height: 100%;
  float: left;
}

/deep/ .nav {
  width: 60px;
}

.IndexContainer {
  position: absolute;
  top: 0;
  bottom: 0;
  left: 0;
  right: 0;
  background: #F0F2F5;
  height: 100%;
  overflow-y: scroll;
}

/*演示版专供*/
.isPad {
  height: 11.2rem;
}

.IndexContainer > .el-container {
  width: 100%;
  height: 100%;
  overflow: hidden;
  display: block;
  margin: 0 auto;
}

.footer {
  position: absolute;
  bottom: 0px;
  width: 100%;
  padding: 10px;
  overflow: hidden;
  display: block;
  margin: 0 auto;
  text-align: center;
  text-indent: -30%;
  font-size: 12px;
  color: #BDBDBD;
  background: #F0F2F5;
  z-index: 222;
}

.el-main {
  width: 100%;
  height: 100%;
  /*min-height: 800px;*/
  overflow: hidden;
  display: block;
  margin: 0 auto;
  overflow-y: hidden;
  padding: 10px 20px;
}

/*ipad only*/
@media only screen and (max-width: 1366px) {
  .lognElaside {
    width: 70px !important;
  }

  .logoContainer img {
    display: none !important;
  }

  .el-main {
    padding: 3px !important;
    overflow-y: scroll;
  }

  .el-main > .context {
    /*height: 640px;*/
    /*overflow-y: scroll;*/
    padding: 6px !important;
  }

  .table {
    /*width: 950px;*/
    /*overflow-x: scroll;*/
  }

  .el-dialog {
    max-width: 960px;
  }

  .el-dialog__body {
    padding: 3px;
  }

  .el-transfer__buttons {
    width: 60px;
    padding: 3px;
  }

  .el-transfer .el-button + .el-button {
    float: right;
  }

  .el-container.is-vertical {
    position: absolute;
    left: 140px;
    top: 0;
    right: 0;
    bottom: 0;
    height: 100%;
  }

  .context {
    border-radius: 12px;
    height: 823px !important;
    overflow-y: scroll;
  }

  .el-dialog {
    padding: 5px;
    padding-bottom: 15px;
  }
}

#__vconsole {
  display: none;
}

#__vconsole.show {
  display: block;
}

</style>
