<template>
  <div class="pages">
    <Headside></Headside>
    <div class="pageTitle">
      <em>
        {{ classInfo.endTime }}
      </em>
    </div>
    <div class="progressContainer">
      <div class="valueDisplay">
        <div class="lt">
            <span :style="{'left': Redflag+'%'}">
              <em>CK {{ redSum }}</em>
            </span>
        </div>
        <div class="md">
          <span :style="{'left': BlueFlag+'%'}">
              <em>CK {{ blueSum }}</em>
            </span>
        </div>
        <div class="rt">
              <span :style="{'left': yellowFlag+'%'}">
              <em>CK {{ yellowSum }}</em>
            </span>
        </div>
      </div>
      <div class="lineContianer">
        <div class="vsContainer">
          <img class="leftVs" src="../assets/imgs/pk/vs.png" alt="">
          <img class="rightVs" src="../assets/imgs/pk/vs.png" alt="">
        </div>
        <div class="lt">
            <span :style="{'width':RedProgress+'%'}">
            </span>
          <em>红队{{ redPeron }}人</em>
        </div>
        <div class="md">          
          <span :style="{'width':BlueProgress+'%'}"></span>
          <em>蓝队{{ bluePerson }}人</em>         
        </div>
        <div class="rt">
              <span :style="{'width':yellowProgress+'%'}">
            </span>
          <em>黄队{{ yellowPerson }}人</em>
        </div>
      </div>
    </div>
    <div class="userPart">
      <div class="lt">
        <threestudent :students="students.redUnite"></threestudent>
        <div class="bottomLine redBottom"></div>
      </div>
      <div class="md">
        <threestudent :students="students.blueUnite"></threestudent>
        <div class="bottomLine blueBottom"></div>
      </div>
      <div class="rt">
        <threestudent :students="students.yellowUnite"></threestudent>
        <div class="bottomLine yellowBottom"></div>
      </div>
    </div>
    <!-- <div class="icons">
      <img src="../assets/imgs/pk/icons2.svg" alt="">
    </div> -->
    <!--    突破纪录-->
    <newRecord :toper-info="toperInfo"></newRecord>
    <!--    欢迎新同学-->
    <newStudent :student-info="studentInfo"></newStudent>
  </div>
</template>
<script>
import '../libs/rem';
import Headside from '@/components/Headside'
import newRecord from '@/components/newRecord'
import newStudent from '@/components/newStudent'
import threestudent from '@/components/threestudent'

import
{
  getHello,
  getClassStat,
  getRecordBreak,
  getNewUser
} from '@/api/getApiRes'

import '../Global'

let qs = require('qs');
export default {
  data() {
    return {
      ClassOn: 1,
      trueDate: true,//真实数据 true false
      studentsClassName: [
        {name: 'max'}
      ],
      students: {
        redUnite: [],
        blueUnite: [],
        yellowUnite: [],
      },
      thisClassName: '',
      redSum: 0,
      blueSum: 0,
      yellowSum: 0,
      redPeron: 0,
      bluePerson: 0,
      yellowPerson: 0,
      pkVal: '50%',
      RedstudentsClassName: [
        {name: 'max'}
      ],
      BluestudentsClassName: [
        {name: 'max'}
      ],
      PlanName: '',
      num: 0,
      Teacher: '',
      classInfo: {
        name: '竞技课程',
        num: '0',
        btTime: '2020-11-13 09:00:00',//时间戳
        endTime: '00:00:00',
        redSum: 0,
        blueSum: 0,
      },
      // totalTime: 30,
      // studentTime: 15,
      toperInfo: {
        dialogVisible: false,
        toper: {},
        totalTime: 30,
      },
      studentInfo: {
        dialogVisible: false,
        Rs: [],
        percent: 0,
        studentTime: 15
      },
      Redflag: 0,
      BlueFlag: 0,
      yellowFlag: 0,
      RedProgress: 28,
      BlueProgress: 28,
      yellowProgress: 28,
    }
  },
  mounted() {
    this.init();
  },
  watch: {
    '$route': function (val) {
      let that = this;
      if (val.path == '/threepk') {
        this.init();
      } else {
        clearInterval(this.PkTimer);
        // clearInterval(this.PkEgg);
        clearInterval(this.timer2);
        clearInterval(this.timer3);
        this.PkTimer = null;
        // this.PkEgg = null;
        this.timer2 = null;
        this.timer3 = null;
      }
    }
  },
  beforeDestroy() {
    clearInterval(this.PkTimer);
    // clearInterval(this.PkEgg);
    clearInterval(this.timer2);
    clearInterval(this.timer3);
    this.PkTimer = null;
    // this.PkEgg = null;
    this.timer2 = null;
    this.timer3 = null;
  },
  methods: {
    init() {
      this.GetgetUserList();
      this.createEgg();
      this.createNewStudent();

      this.PkTimer = setInterval(() => {
        this.GetgetUserList();
        this.ClacClassTime();
        this.curgetClassStat();
      }, 1000);
      
      this.timer2 = setInterval(() => {
        this.createEgg();
      }, 25000);
      
      this.timer3 = setInterval(() => {
        this.createNewStudent();
      }, 20000);
    },
    // 启动一个成就彩蛋
    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)
    },
    // 载入课程信息
    ReadLessonInfo(Dp) {
      this.PlanName = Dp.PlanName;
      this.BeginTime = Dp.BeginTime;
      this.Teacher = Dp.Teacher;
    },
    // 分队展示
    UniteBreak(Rs) {
      let that = this;
      that.students.redUnite = [];
      that.students.blueUnite = [];
      that.students.yellowUnite = [];
      if (!Rs) {
        that.students.redUnite = [];
        that.students.blueUnite = [];
        that.students.yellowUnite = [];
      } else {
        Rs.map(function (item, t) {
          item.sportLevel = sportLevel(item.ActivePercent);
          if (item.GroupNo == 1) {
            that.students.redUnite.push(item);
          }
          if (item.GroupNo == 2) {
            that.students.blueUnite.push(item);
          }
          if (item.GroupNo == 3) {
            that.students.yellowUnite.push(item);
          }
        })
      }
      that.giveClassName(that.students.redUnite, 1);
      that.giveClassName(that.students.blueUnite, 2);
      that.giveClassName(that.students.yellowUnite, 3);
      that.calcSumCK(that.students);
    },
    // 计算各队总分
    calcSumCK(Rs) {
      let that = this;
      let redSum = 0;
      let blueSum = 0;
      let yellowSum = 0;

      // that.redSum
      Rs.redUnite.map(function (item, t) {
        redSum += parseFloat(item.Ck.toFixed(1));
      });
      Rs.blueUnite.map(function (item, t) {
        blueSum += parseFloat(item.Ck.toFixed(1));
      });
      Rs.yellowUnite.map(function (item, t) {
        yellowSum += parseFloat(item.Ck.toFixed(1));
      });

      that.redSum = redSum.toFixed(1);
      that.blueSum = blueSum.toFixed(1);
      that.yellowSum = yellowSum.toFixed(1);

      // 进度条 FormatCk
      let redFmtSum = 0;
      let blueFmtSum = 0;
      let yellowFmtSum = 0;
      let pkval = 0;
      Rs.redUnite.map(function (item, t) {
        // redFmtSum += parseFloat(item.FormatCk);
        redFmtSum += parseFloat(item.Ck);
      });
      Rs.blueUnite.map(function (item, t) {
        // blueFmtSum += parseFloat(item.FormatCk);
        blueFmtSum += parseFloat(item.Ck);
      });
      Rs.yellowUnite.map(function (item, t) {
        // yellowFmtSum += parseFloat(item.FormatCk);
        yellowFmtSum += parseFloat(item.Ck);
      });

      let sumMax = 0;
      let maxLength = Rs.redUnite.length;
      if (maxLength < Rs.blueUnite.length) {
        maxLength = Rs.blueUnite.length;        
      }
      if (maxLength < Rs.yellowUnite.length) {
        maxLength = Rs.yellowUnite.length;        
      }
      sumMax = maxLength * 20;

      // 当为0时均分
      if (redFmtSum == 0) {
        that.Redflag = 0;
        that.RedProgress = 28;
      } else {
        // 限制最大
        let redPercent = parseInt((redFmtSum / sumMax) * 100);
        redPercent = redPercent > 100 ? 100 : redPercent;
        that.Redflag = redPercent * 0.71;
        that.RedProgress = that.Redflag + 28
        if (that.RedProgress > 100) {
          that.RedProgress = 100
        }
        // that.Redflag = 72;
        // that.RedProgress = 100;
        // console.log("redFmtSum:" + redFmtSum);
        // console.log("RedProgress:" + that.RedProgress);
      }

      if (blueFmtSum == 0) {
        that.BlueFlag = 0;
        that.BlueProgress = 28;
      } else {
        // 限制最大
        let bluePercent = parseInt((blueFmtSum / sumMax) * 100);
        bluePercent = bluePercent > 100 ? 100 : bluePercent;
        that.BlueFlag = bluePercent * 0.71;
        that.BlueProgress = that.BlueFlag + 28
        if (that.BlueProgress > 100) {
          that.BlueProgress = 100
        }
        // that.BlueFlag = 72;
        // that.BlueProgress = 100;
        // console.log("blueFmtSum:" + blueFmtSum);
        // console.log("BlueProgress:" + that.BlueProgress);
      }

      if (yellowFmtSum == 0) {
        that.yellowFlag = 0;
        that.yellowProgress = 28;
      } else {
        // 限制最大
        let yellowPercent = parseInt((yellowFmtSum / sumMax) * 100);
        yellowPercent = yellowPercent > 100 ? 100 : yellowPercent;
        that.yellowFlag = yellowPercent * 0.725;
        that.yellowProgress = that.yellowFlag + 28
        if (that.yellowProgress > 100) {
          that.yellowProgress = 100
        }
        // that.yellowFlag = 72;
        // that.yellowProgress = 100;
        // console.log("yellowFmtSum:" + yellowFmtSum);
        // console.log("yellowProgress:" + that.yellowProgress);
      }
    },
    // 获取上课学生信息
    GetgetUserList() {
      let that = this;
      let param = {
        token: localStorage.token,
        eqSn: localStorage.eqSn
      };
      let postdata = qs.stringify(param);
      getHello(postdata).then(res => {
        let json = res;
        if (json.Code == 0) {
          if (!json.Dp) {
            // that.$message.error('没有获取到课程信息');
            return false
          } else {
            that.ReadLessonInfo(json.Dp);
          }
          // 学生分队展示
          that.UniteBreak(json.Rs);
          // 人口总数
          that.num = json.Rs.length ? json.Rs.length : 0;
          this.ClacClassTime();
        } else {
          // 已下课
          // console.log("[getHello] 已下课 " + json.Code);
          if (json.Code == '999') {
            // that.$router.push({path: '/2pkRank'});
          } else {
            // 已出错
            that.$message.error(json.Memo);
          }
        }
      })
    },
    giveClassName(res, type) {
      let that = this;
      if (type == 1) {
        that.redPeron = parseInt(res.length);
      } else if (type == 2) {
        that.bluePerson = parseInt(res.length)
      } else if (type == 3) {
        that.yellowPerson = parseInt(res.length)
      }
    },
    // 计算团队竞技课持续时间
    ClacClassTime() {
      let BeginTime = new Date(globalcurrent() + ' ' + this.BeginTime);//结束时间
      let nowDate = new Date();
      let date = new Date(nowDate - BeginTime - 8 * 60 * 60 * 1000);//减掉东八区时区问题

      let h = date.getHours() < 10 ? '0' + date.getHours() + ':' : date.getHours() + ':';
      let m = date.getMinutes() < 10 ? '0' + date.getMinutes() + ':' : date.getMinutes() + ':';
      let s = date.getSeconds() < 10 ? '0' + date.getSeconds() : date.getSeconds();
      this.classInfo.endTime = h + m + s;
    },
    // 当前课程状态
    curgetClassStat() {
      let that = this;
      let param = {
        token: localStorage.token,
        eqSn: localStorage.eqSn
      };
      let postdata = qs.stringify(param);
      getClassStat(postdata).then(res => {
        let json = res;
        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：竞技课3PK
            that.$router.push({path: '/3pkRank'});
            // switch (parseInt(json.dp)) {
            //   case 3:
            //     that.$router.push({path: '/3pkRank'});
            //     break;
            // }
          }
        } else {
          // that.$message.error(json.Memo);
        }
      })
    },
  },
  filters: {
    fmtNum(val) {
      if (val == 0) {
        return '--'
      } else {
        if (parseInt(val) < 0) return 0;
        if (parseInt(val) > 0) return val
      }
    },
    fmtFloat(val) {
      if (val == 0) {
        return '0.0'
      } else {
        return parseFloat(val).toFixed(1);
      }
    },
    fmtInt(val) {
      if (val == 0) {
        return '0'
      } else {
        return parseInt(val);
      }
    },
    max100(val) {
      if (val <= 100) {
        return val
      } else {
        return 100
      }
    }
  },
  components: {
    Headside, newRecord, newStudent, threestudent
  }
}
</script>
<style lang="scss" scoped>

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

@mixin bg {
  height: auto;
  min-height: 100%;
  background-color: #333;
  background-repeat: no-repeat;
  background-position: top center;
  background-size: 100% 100%;
}

.pages {
  background: url("../assets/imgs/three/threeBg.png");
  @include bg;

  .pageTitle {
    background: url("../assets/imgs/pk/pageTitle.svg");
    background-repeat: no-repeat;
    background-position: top center;
    background-size: 100% 100%;
    @include cube;
    width: 98%;
    height: 0.65rem;
    overflow: visible;
    margin-top: -0.36rem;
    margin-right: 2.8rem;
    
    em {
      position: relative;
      top: 0.11rem;
      right: 6.3rem;
      float: right;
      color: white;
      font-size: 0.3rem;
      font-style: normal;
    }
  }

  .progressContainer {

    .valueDisplay {
      @include cube;
      width: 98%;
      overflow: visible;
      margin-top: -0.03rem;

      .lt {
        width: 33.33%;
        float: left;

        span {
          background: url("../assets/imgs/three/redFlag.png");
          background-repeat: no-repeat;
          background-position: top center;
          background-size: 100%;
        }
      }

      .md {
        width: 33.33% !important;
        float: left;

        span {
          background: url("../assets/imgs/three/blueFlag.png");
          background-repeat: no-repeat;
          background-position: top center;
          background-size: 100%;
        }
      }

      .rt {
        width: 33.33%;
        float: left;

        span {
          background: url("../assets/imgs/three/yellowFlag.png");
          background-repeat: no-repeat;
          background-position: top center;
          background-size: 100%;
        }
      }

      span {
        position: relative;
        top: 0.1rem;
        width: 1.9rem;
        height: 0.9rem;
        float: left;

        em {
          @include cube;
          font-size: 0.3rem;
          color: white;
          text-align: center;
          font-style: normal;
          line-height: 0.6rem;
        }
      }
    }
  }
}

.lineContianer {
  position: relative;
  @include cube;
  width: 98%;
  z-index: 222;
  overflow: visible;

  .vsContainer {
    position: absolute;
    width: 100%;
    z-index: 1;

    img {
      position: relative;
      float: left;
      width: 1.2rem;
      left: 5.87rem;
      margin-top: 0.72rem;

      &.rightVs {
        float: left;
        left: 11.33rem;
      }
    }
  }
    
  .lt {
    width: 33.33%;
    float: left;
    background: url("../assets/imgs/three/bar_bg.png");
    background-repeat: no-repeat;
    background-position: top right;
    background-size: 100% 100%;

    span {
      width: 4rem;
      float: left;
      // border-radius: 3px;
      background: linear-gradient(to left, #d11122 0%, rgba(209, 17, 34, 0.23) 100%);
      margin-bottom: 0.03rem;
    }

    em {
      position: absolute;
      float: left;
      left: 1%;
      margin-top: 0.05rem;
      width: 1.6rem;
      color: white;
      text-align: right;
      font-size: 0.3rem;
      font-style: normal;
    }
  }

  .md {
    width: 33.33%;
    float: left;
    overflow: visible;
    background: url("../assets/imgs/three/bar_bg.png");
    background-repeat: no-repeat;
    background-position: top right;
    background-size: 100% 100%;

    span {
      position: relative;
      width: 4rem;
      float: left;
      background: linear-gradient(to left, #4cbbfc 0%, rgba(0, 125, 198, 0.17) 100%);
      margin-bottom: 0.03rem;
    }

    em {
      position: absolute;
      float: left;
      left: 35%;
      margin-top: 0.05rem;
      width: 1.6rem;
      color: white;
      text-align: right;
      font-size: 0.3rem;
      font-style: normal;
    }
  }

  .rt {
    width: 33.33%;
    float: right;
    background: url("../assets/imgs/three/bar_bg.png");
    background-repeat: no-repeat;
    background-position: top right;
    background-size: 100% 100%;

    span {
      width: 4rem;
      float: left;
      // border-radius: 3px;
      background: linear-gradient(to left, #fccd4c 0%, rgba(255, 228, 15, 0.26) 100%);
      margin-bottom: 0.03rem;
    }

    em {
      position: absolute;
      float: left;
      left: 69%;
      margin-top: 0.05rem;
      width: 1.6rem;
      color: white;
      text-align: right;
      font-size: 0.3rem;
      font-style: normal;
    }
  }

  span {
    height: 0.5rem;
  }
}

.userPart {
  @include cube;
  width: 98%;
  position: relative;
  padding-top: 0.3rem;
  padding-bottom: 0.16rem;
  height: 8.2rem;

  .lt {
    @include cube;
    position: relative;
    width: 32.5%;
    height: 100%;
    float: left;

    .bottomLine {
      position: absolute;
      bottom: 0;
      @include cube;
      height: 0.85rem;
      border-radius: 18px;
      opacity: 0.8;
      background: linear-gradient(rgba(0, 0, 0, 0) 0%, rgba(209, 17, 34, 0.62) 100%);

    }
  }

  .md {
    @include cube;
    position: relative;
    width: 32.5%;
    height: 100%;
    float: left;
    margin-left: 0.26rem;

    .bottomLine {
      position: absolute;
      bottom: 0;
      @include cube;
      height: 0.85rem;
      border-radius: 18px;
      opacity: 0.8;
      background: linear-gradient(rgba(0, 0, 0, 0) 0%, rgba(0, 134, 232, 0.62) 100%);
    }
  }

  .rt {
    @include cube;
    position: relative;
    width: 32.5%;
    height: 100%;
    float: right;
    margin-left: 0.02rem;


    .bottomLine {
      position: absolute;
      bottom: 0;
      @include cube;
      height: 0.85rem;
      border-radius: 18px;
      opacity: 0.8;
      background: linear-gradient(rgba(0, 0, 0, 0) 0%, rgba(216, 191, 0, 0.9) 100%);
    }
  }
}

.icons {
  @include cube;
  position: absolute;
  bottom: 0.2rem;

  img {
    @include cube;
    // width: 40%;
    width: 18%;
  }
}

// /*响应式调整*/
// @media(min-width: 320px) and (max-width: 1025px) {
//   .progressContainer {
//     margin-top: 0rem;
//   }
//   .userPart {
//     // height: 10rem;
//     overflow-y: scroll;
//   }
// }
</style>
