<template>
  <div :class="pageStyle">
    <Headside></Headside>
    <!--    学生列表-->
    <div class="userList">
      <student :students="students" :students-class-name="studentsClassName"></student>
    </div>
    <!--图示-->
    <levelIcon></levelIcon>
    <!--    突破纪录-->
    <newRecord :toper-info="toperInfo"></newRecord>
    <!--    欢迎新同学-->
    <newStudent :student-info="studentInfo"></newStudent>
  </div>
</template>

<script>
import Headside from '@/components/Headside'
import newRecord from '@/components/newRecord'
import newStudent from '@/components/newStudent'
import levelIcon from '@/components/levelIcon'
import student from '@/components/student'
import
{
  getHello,
  getClassStat,
  getRecordBreak,
  getNewUser
} from '@/api/getApiRes'

import '../libs/rem';
import '../Global'

let qs = require('qs');

export default {
  data() {
    return {
      ClassOn: 1,
      eqSn: '30:9C:23:0C:8B:1E',
      pageStyle: 'bgStyleMain',
      trueDate: true,//真实数据 true false
      times: 1,
      thisClassName: '',
      studentsClassName: [],
      students: [],
      single: [],
      dialogVisible: false,
      serachBtnStatus: false,
      dialogMsg: '',
      imgsrc: '../static/img/people/',
      // totalTime: 30,
      // studentTime: 15,
      toperInfo: {
        dialogVisible: false,
        toper: {},
        totalTime: 30,
      },
      studentInfo: {
        dialogVisible: false,
        Rs: [],
        percent: 0,
        studentTime: 15
      },
      fakeEgg: {
        Rs: {
          "DuId": 37,
          "UserId": 0,
          "UserName": "郑伟",
          "Sex": 1,
          "Head": "https://img-operation.csdnimg.cn/csdn/silkroad/img/1604989753379.png",
          "Cle": 400,
          "CleTitle": "个人单次卡路里记录",
          "CleUnit": "千卡",
          "CkTitle": "个人单次CK记录",
          "Ck": 99.9,
          "CkUnit": "CK值",
        }
      },
      mainTimer: null,
      timer2: null,
    }
  },
  mounted() {
    this.init();
    //   this.mainTimer = setInterval(() => {
    //     this.init();
    //   }, 3000);
  },
  watch: {
    '$route': function (val) {
      if (val.path == '/main') {
        if (this.trueDate) {
          // console.log("使用真实数据");
          this.init();
        } else {
          console.log("使用假数据");
          this.students = fakeNews(2);
          this.giveClassName(this.students);
          // this.createEgg(this.students[5]);
        }
      } else {
        // console.log("val.path="+val.path);
        clearInterval(this.mainTimer);
        clearInterval(this.timer2);
        clearInterval(this.timer3);
        this.mainTimer = null;
        this.timer2 = null;
        this.timer3 = null;
      }
    }
  },
  beforeDestroy() {
    clearInterval(this.mainTimer);
    clearInterval(this.timer2);
    clearInterval(this.timer3);
    this.mainTimer = null;
    this.timer2 = null;
    this.timer3 = null;
  },
  methods: {
    init() {
      // console.log(headTest);
      this.GetgetUserList();
      this.createEgg();
      this.createNewStudent();
      this.curgetClassStat();

      this.mainTimer = setInterval(() => {
        this.GetgetUserList();
        this.curgetClassStat();
      }, 1000);
      
      this.timer2 = setInterval(() => {
        this.createEgg();
      }, 25000);
      
      this.timer3 = setInterval(() => {
        this.createNewStudent();
      }, 20000);
    },
    alertInfo(info) {
      alert(info);
    },
    // 启动一个成就彩蛋
    createEgg() {
      let that = this;
      let param = {
        token: localStorage.token,
        eqSn: localStorage.eqSn
      };
      let postdata = qs.stringify(param);
      getRecordBreak(postdata).then(res => {
        let json = res;
        if (json.Code == 0) {
          console.log('破纪录了');
          that.OpenEgg(json.Rs);
        } else {
          // 并没有人破记录
          if (json.Code == 999) return false;
          if (json.Code != 999) that.$message.error(json.Memo + '[ 错误码]' + json.Code);
        }
      })
    },
    // 欢迎新同学
    createNewStudent() {
      let that = this;
      let param = {
        token: localStorage.token,
        eqSn: localStorage.eqSn
      };
      let postdata = qs.stringify(param);
      getNewUser(postdata).then(res => {
        let json = res;
        if (json.Code == 0) {
          console.log('来新生了');
          that.OpenStudent(json.Rs);          
        } else {
          // 并没有人破记录
          if (json.Code == 999) return false;
          if (json.Code != 999) that.$message.error(json.Memo + '[ 错误码]' + json.Code);
        }
      })
    },
    OpenEgg(msg, reshowNum=0) {      
      let that = this;
      if (that.ClassOn == 0) {
        console.log('[破纪录] 已下课，取消弹窗 reshowNum: ' + reshowNum);
        return false;
      }
      if (that.studentInfo.dialogVisible == true || that.toperInfo.dialogVisible == true) {
        console.log('[破纪录] 弹出窗口尚未关闭，5秒后重试');
        setTimeout(() => {
          reshowNum++;
          that.OpenEgg(msg, reshowNum);
        }, 5000);
        return false;
      } 
      if (reshowNum > 0) {
        console.log('[破纪录] reshowNum: ' + reshowNum);
      }
      that.toperInfo.toper = msg;
      that.toperInfo.dialogVisible = true;
      // 倒计时20秒自动关闭
      that.toperInfo.totalTime = 20;
      let clock = window.setInterval(() => {
        that.toperInfo.totalTime--;
        if (parseInt(that.toperInfo.totalTime) <= 0) {
          that.toperInfo.dialogVisible = false;// 关闭 自动关闭彩蛋
          clearInterval(clock);
        }
      }, 1000)
    },
    OpenStudent(msg, reshowNum=0) {      
      let that = this;
      if (that.ClassOn == 0) {
        console.log('[欢迎新同学] 已下课，取消弹窗 reshowNum: ' + reshowNum);
        return false;
      }
      if (that.studentInfo.dialogVisible == true || that.toperInfo.dialogVisible == true) {
        console.log('[欢迎新同学] 弹出窗口尚未关闭，5秒后重试');
        setTimeout(() => {
          reshowNum++;
          that.OpenStudent(msg, reshowNum);
        }, 5000);
        return false;
      }
      if (reshowNum > 0) {
        console.log('[欢迎新同学] reshowNum: ' + reshowNum);
      }
      that.studentInfo.Rs = msg;
      that.studentInfo.dialogVisible = true;
      // 倒计时15秒自动关闭
      that.studentInfo.studentTime = 15;
      let clock = window.setInterval(() => {
        that.studentInfo.studentTime--;
        if (parseInt(that.studentInfo.studentTime) <= 0) {
          that.studentInfo.dialogVisible = false; //关闭 自动关闭
          clearInterval(clock);
        }
      }, 1000)
    },
    GetgetUserList() {
      let that = this;
      let param = {
        token: localStorage.token,
        eqSn: localStorage.eqSn
      };
      let postdata = qs.stringify(param);
      // console.log("getHello postdata = " + postdata);
      getHello(postdata).then(res => {
        let json = res;
        if (json == undefined)
          return;
        // console.log("getHello = " + JSON.stringify(json));
        if (json.Code == 0) {
          that.students = json.Rs;
          that.giveClassName(json.Rs);
        } else {
          // 已下课
          if (json.Code == '999') {
            that.students = ""
          } else {
            // 已出错
            that.$message.error(json.Memo);
          }
        }
      })
    },
    curgetClassStat() {
      let that = this;
      let param = {
        token: localStorage.token,
        eqSn: localStorage.eqSn
      };
      let postdata = qs.stringify(param);
      getClassStat(postdata).then(res => {
        let json = res;
        // console.log("[Main] getClassStat: " + JSON.stringify(json));
        if (json.Code == 0) {
          that.$store.commit('setClassOn', json.ClassOn);
          // 没开课
          if (json.ClassOn == 0) {
            that.ClassOn = 0;
            if (that.studentInfo.dialogVisible == true || that.toperInfo.dialogVisible == true) {
              console.log('[getClassStat] 下课了，等待弹出窗口关闭');
              return false
            } 

            console.log("下课了");
            // 0: 下课 团课/私教 排名
            // 1：团课/私教 todo
            // 2：竞技课2PK
            // 3：竞技课threepk
            switch (parseInt(json.dp)) {
              case 0:
                that.$router.push({path: '/rank'});
                break;
              case 1:
                that.$router.push({path: '/'});
                break;
              case 2:
                that.$router.push({path: '/pk'});
                break;
              case 3:
                that.$router.push({path: '/threepk'});
                break;
            }
          }
        } else {
          console.log("已上课");
        }
      })
    },
    // 给每一个数据加类名，一次遍历全部赋值
    giveClassName(res) {
      let that = this;
      let numberClass = '';
      let colorClass = '';
      let resLength = parseInt(res.length);
      for (let i = 0; i < resLength; i++) {
        switch (true) {
          case  resLength == 1:
            numberClass = 'max';
            break;
          case  resLength == 2:
            numberClass = 'two';
            break;
          case  resLength <= 4 && resLength > 2:
            numberClass = 'four';
            break;
          case  resLength <= 9 && resLength > 4:
            numberClass = 'nine';
            break;
          // case  resLength <= 9 && resLength > 6:
          //   numberClass = 'nine';
          //   break;
          case resLength <= 16 && resLength > 9:
            numberClass = 'sixteen';
            break;
          case resLength <= 25 && resLength > 16:
            numberClass = 'twentyFive';
            break;
          case resLength >= 26:
            numberClass = 'twentyFive';
            break;
        }
        let per = parseInt(res[i].ActivePercent);
        switch (true) {
          case per >= 90:
            colorClass = 'red';
            break;
          case per <= 89 && per > 79:
            colorClass = 'brown';
            break;
          case per <= 79 && per > 69:
            colorClass = 'yellow';
            break;
          case per <= 69 && per > 54:
            colorClass = 'green';
            break;
          case per <= 54 && per > 39:
            colorClass = 'violet';
            break;
          case per <= 39:
            colorClass = 'blue';
            break
        }

        that.studentsClassName[i] = {
          name: numberClass + ' ' + colorClass,
        }
      }
    },
  },
  components: {
    Headside, levelIcon, newRecord, newStudent, student
  }
}
</script>

<style lang="scss" scoped>
//@import "../assets/css/bg.css";
@import "../assets/css/bg.scss";


@mixin cube {
  width: 100%;
  overflow: hidden;
  display: block;
  margin: 0 auto;
}

* {
  font-family: vista;
}

.pages {
  position: absolute;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  width: 100%;
  overflow: hidden;
  display: block;
  margin: 0 auto;
  font-family: vista;
  overflow-y: scroll;
}

.userList {
  @include cube;
  padding-bottom: 0.5rem;
  // max-height: 9.4rem;
  overflow-y: scroll;
}

// /*响应式调整*/
// @media(min-width: 320px) and (max-width: 1025px) {
//   .userList {
//     max-height: inherit;
//   }
// }

</style>
