<template>
  <div class="app-container">
    <div class="filter-container">
      <el-input v-model="KEYWORDS" placeholder="搜索" class="filter-item" style="width: 200px;"/>
      <el-button v-waves class="filter-item" type="primary" icon="el-icon-search" @click="getQuery">
        搜索
      </el-button>
      <el-button v-waves class="filter-item" type="success" icon="el-icon-refresh" @click="goKeyReset">
        重置
      </el-button>
    </div>
    <el-table
      v-loading="listLoading"
      :data="varList"
      :row-key="getRowKey"
      :header-cell-style="{
        'font-weight': 'bold',
        'color': '#000'
      }"
      tooltip-effect="dark"
      border
      fit
      highlight-current-row
    >
      <el-table-column type="index" label="序号" width="50" align="center" />
      <el-table-column prop="EXAMNAME" label="阶段试卷" />
      <el-table-column prop="EXAMTIME" label="考试时间" align="center" />
      <el-table-column prop="ANSWERSHEETTIME" label="答卷时间" align="center" />
      <el-table-column prop="STAGEEXAMSCORE" label="阶段考试成绩" width="100" align="center" >
        <template slot-scope="{row}">
          <div v-if="row.STAGEEXAMSTATE === '3'">{{ row.STAGEEXAMSCORE }}</div>
          <div v-else-if="row.STAGEEXAMSTATE === '4'">未参加</div>
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" width="260">
        <template slot-scope="{row}">
          <div v-if="row.STAGESTEP === '1'" >{{ row.LASTTIME }}</div>
          <div v-else-if="row.STAGESTEP === '2'" >
            <el-button type="success" icon="el-icon-document-add" size="mini" @click="handleStageExam(row)">阶段考试</el-button>
            <div>剩余：{{ row.LASTTIME }}</div>
          </div>
        </template>
      </el-table-column>
    </el-table>
    <div class="page-btn-group">
      <pagination :total="total" :page.sync="listQuery.page" :limit.sync="listQuery.limit" @pagination="getList" />
    </div>
  </div>
</template>
<script>
import Pagination from '@/components/Pagination' // 通过 el-pagination二次打包
import { requestFN } from '@/utils/request'
import waves from '@/directive/waves' // waves directive
export default {
  components: { Pagination },
  directives: { waves },
  data() {
    return {
      listLoading: true,
      listQuery: {
        page: 1,
        limit: 10
      },
      total: 0,
      config: config,
      KEYWORDS: '',
      varList: [],
      pd: [],
      form: {
        CURRICULUMNAME: '', // 课程名称
        CURRICULUMINTRODUCE: '', // 课程介绍
        CURRICULUMAIM: '', // 课程目的
        STARTTIME: '', // 开始时间
        ENDTIME: '', // 结束时间
        CURRICULUMUSERS: '', // 适用人员
        VIDEOCOURSEWARES: '', // 视频课件组
        DATACOURSEWARES: ''// 资料课件组
      },
      multipleSelectionAll: [], // 所有选中的数据包含跨页数据
      multipleSelection: [], // 当前页选中的数据
      LearnerCategoryList: []
    }
  },
  created() {
    // console.info('加载list')
    this.getList()
  },
  destroyed() {
    // 清除定时器
    this.varList.forEach((ele) => {
      if (ele.STAGEEXAMSTATE === '1' && ele.STAGEEXAMPAPER_ID != null) {
        clearInterval(ele.countDown)
      }
    })
  },
  methods: {
    getRowKey(row) {
      return row.STAGEEXAMPAPER_ID
    },
    // 搜索
    getQuery() {
      this.getList()
    },
    goKeyReset() {
      this.KEYWORDS = ''
      this.getList()
    },
    // 获取列表
    getList() {
      this.listLoading = true
      requestFN(
        '/stagestudentrelation/pageDataByUser?showCount=' + this.listQuery.limit + '&currentPage=' + this.listQuery.page,
        {
          KEYWORDS: this.KEYWORDS
        }
      ).then((data) => {
        this.listLoading = false
        this.varList = data.varList
        this.total = data.page.totalResult
        this.pd = data.pd

        // 从后端获取的数据，将这一步骤放到异步获取后端数据的地方，对后端返回的数据进行处理
        this.varList.forEach((ele) => {
          // 调用定时器传递
          this.timeInterval(ele)
          // 如果数据不更新的话，增加下面代码
          this.varList.splice(1, 0)
        })
      }).catch((e) => {
        this.listLoading = false
      })
    },
    // 阶段考试
    handleStageExam(row) {
      this.$parent.STAGEEXAMPAPER_ID = row.STAGEEXAMPAPER_ID
      this.$parent.STAGESTUDENTRELATION_ID = row.STAGESTUDENTRELATION_ID
      this.$parent.activeName = 'Edit'
    },
    // 倒计时定时器
    timeInterval(row) {
      if (row.STAGEEXAMSTATE === '1' && row.STAGEEXAMPAPER_ID != null) {
        // 绑定定时器
        row.countDown = setInterval(() => {
          const nowDate = new Date().getTime()
          // 计算剩余时间戳
          const beginTime = new Date(row.EXAMTIME + ':00').getTime()
          const endTime = beginTime + row.ANSWERSHEETTIME * 60 * 1000
          if (beginTime - nowDate > 0) {
            // 对每行的剩余时间进行设置
            row.lastTime = beginTime - nowDate
            row.stagestep = '1' // 未考试
            this.$set(row, 'LASTTIME', this.timeFormat(row.lastTime))
            this.$set(row, 'STAGESTEP', row.stagestep)
          } else if (beginTime <= nowDate && nowDate <= endTime) {
            if (row.EXAMSTATE == '0') {
              // 考试时间开始后，锁定试卷
              this.$set(row, 'EXAMSTATE', '1')
              requestFN(
                '/stageexampaper/updateExamState',
                {
                  EXAMSTATE: '1',
                  STAGEEXAMPAPER_ID: row.STAGEEXAMPAPER_ID
                }
              ).then((data) => {
              }).catch((e) => {
              })
            }
            // 对每行的剩余时间进行设置
            row.lastTime = endTime - nowDate
            row.stagestep = '2' // 已开考
            this.$set(row, 'LASTTIME', this.timeFormat(row.lastTime))
            this.$set(row, 'STAGESTEP', row.stagestep)
            // console.info('EXAMNAME:' + row.EXAMNAME + ' -> row.STAGEEXAMSTATE:' + row.STAGEEXAMSTATE)
          } else {
            row.stagestep = '3' // 已结束
            this.$set(row, 'STAGESTEP', row.stagestep)
            // 清除定时器
            clearInterval(row.countDown)
            // console.info('计时结束row.STAGEEXAMSTATE:' + row.STAGEEXAMSTATE)
            if (row.STAGEEXAMSTATE == '1') { // 到时后自动更新学员状态为未参加考试
              requestFN(
                '/stagestudentrelation/updateStudentState',
                {
                  // TYPE: '3',
                  STAGEEXAMSTATE: '4',
                  STAGESTUDENTRELATION_ID: row.STAGESTUDENTRELATION_ID
                }
              ).then((data) => {
              }).catch((e) => {
              })
            }
            if (row.EXAMSTATE == '0') { // 考试超期的做未参加处理，试卷做锁定
              this.$set(row, 'EXAMSTATE', '1')
              requestFN(
                '/stageexampaper/updateExamState',
                {
                  EXAMSTATE: '1',
                  STAGEEXAMPAPER_ID: row.STAGEEXAMPAPER_ID
                }
              ).then((data) => {
              }).catch((e) => {
              })
            }
          }
        }, 1000)
      } else if (row.STAGEEXAMSTATE === '3' || row.STAGEEXAMSTATE === '4') {
        this.$set(row, 'STAGESTEP', '3')
      }
    },
    // 剩余时间格式化
    timeFormat(times) {
      if (times > 0) {
        const days = this.addZero(
          Math.floor(times / 1000 / 60 / 60 / 24)
        ) // 天
        const hours = this.addZero(
          Math.floor((times / 1000 / 60 / 60) % 24)
        ) // 时
        const minutes = this.addZero(
          Math.floor((times / 1000 / 60) % 60)
        ) // 分
        const seconds = this.addZero(Math.floor((times / 1000) % 60)) // 秒
        var html = days !== '00' ? days + '天' : ''
        html += hours !== '00' ? hours + '小时' : ''
        html += minutes !== '00' ? minutes + '分钟' : ''
        html += seconds + '秒'
        return html
      } else {
        return '已超时'
      }
    },
    // 个位补零
    addZero(d) {
      return parseInt(d) < 10 ? '0' + d : d
    }
  }
}

</script>
