<!-- 补考人员 -->
<template>
  <div class="page-container studentsTakingMakeUpExams-addPage">
    <div class="page-container-top-max-big-box">
      <p class="top-1-p">补考安排</p>
      <p class="top-2-p" @click="backPage()">返回</p>
      <p class="top-4-p" @click="submitButton()" v-if="makeupStarted == 0">保存</p>
    </div>
    <div class="content-box">
      <div class="max-add-form-box" v-if="makeupStarted == 0">
        <el-form class="add-form-box" :model="newData" ref="form" label-width="140px" :rules="rules">
          <div class="form-flex-box">
            <el-form-item label="复用原试卷" prop="reuseOriginalPaper">
              <el-switch
                :active-value="1"
                :inactive-value="0"
                v-model="newData.reuseOriginalPaper"
                active-color="#0183FB"
                inactive-color="#AAAAAA"
              >
              </el-switch>
            </el-form-item>
            <p class="checkButton-p" v-if="newData.reuseOriginalPaper == 0" style="margin-left:20px;" @click="openPaperDrawer">选择试卷</p>
            <div class="selected-tag" v-if="newData.paperName && newData.reuseOriginalPaper == 0">
              <span>{{ newData.paperName }}</span>
              <i class="el-icon-close" @click="newData.paperId = null; newData.paperName = ''"></i>
            </div>
          </div>
          <div class="form-flex-box">
            <el-form-item label="补考时间" prop="examTimeRange">
              <el-date-picker
                popper-class="examinationArrange-addPage-date-picker"
                v-model="newData.examTimeRange"
                type="datetimerange"
                range-separator="至"
                format="yyyy-MM-dd HH:mm"
                value-format="yyyy-MM-dd HH:mm"
                start-placeholder="开始日期"
                end-placeholder="结束日期"
                :picker-options="pickerOptions"
              />
            </el-form-item>
          </div>
          <div class="form-flex-box">
            <el-form-item label="可补考次数" prop="attemptLimit">
              <el-input-number
                class="form-input-number"
                style="width:200px"
                :min="1"
                :max="9999"
                :step="1" :precision="0" step-strictly
                v-model="newData.attemptLimit"
              >
              </el-input-number>
            </el-form-item>
            <el-form-item label="考试时长" prop="answerDuration">
              <div class="stepper-row">
                <div class="number-stepper">
                  <div class="number-stepper">
                    <el-input-number
                      class="form-input-number"
                      style="width:160px"
                      :min="0"
                      :max="9999"
                      :step="1" :precision="0" step-strictly
                      v-model="newData.answerDuration"
                    >
                    </el-input-number>
                  </div>
                </div>
                <span class="unit-text">分钟</span>
                <span class="tip-text" style="margin-left:12px;">限制答卷最大时长</span>
              </div>
            </el-form-item>
          </div>
        </el-form>
      </div>
      <div class="page-form-title-box">
        <el-form :model="queryParams" class="form-box" ref="queryForm"
                 :inline="true" style="width:100%;">
          <el-form-item label="" prop="academicYear">
            <el-select v-model="queryParams.academicYear" placeholder="学年" style="width: 140px">
              <el-option
                v-for="dict in optionListB"
                :key="dict.gradeNumber"
                :label="dict.gradeNumber"
                :value="dict.gradeNumber"
              />
            </el-select>
          </el-form-item>
          <el-form-item label="" prop="deptId">
            <el-cascader
              style="width: 180px"
              v-model="queryParams.deptId"
              :options="optionListA"
              :props="{
                    emitPath:false,
                    checkStrictly: true,
                    value: 'deptId',
                    label: 'deptName',
                    children: 'child',
                  }"
              :show-all-levels="false"
              filterable
              placeholder="学院单位"
            ></el-cascader>
          </el-form-item>
          <el-form-item label="" prop="disciplineId">
            <el-select v-model="queryParams.disciplineId" placeholder="专业" style="width: 140px">
              <el-option
                v-for="dict in optionListC"
                :key="dict.id"
                :label="dict.disciplineName"
                :value="dict.id"
              />
            </el-select>
          </el-form-item>
          <el-form-item label="" prop="account">
            <el-input
              maxLength="30"
              v-model="queryParams.account"
              placeholder="姓名/学工号"
              style="width: 140px"
            />
          </el-form-item>
          <p class="page-inquire-common-style-button" @click="handleQuery">查询</p>
          <p class="page-reset-common-style-button" @click="resetQuery">重置</p>
          <p class="page-add-common-style-button" style="float: right;" @click="exportButton()">导出</p>
        </el-form>
      </div>
      <div class="page-content-box">
        <el-table class="table-box"  border :data="dataList">
          <el-table-column label="姓名" prop="userName" show-overflow-tooltip/>
          <el-table-column label="学工号" prop="account" width="140" show-overflow-tooltip/>
          <el-table-column label="专业" prop="disciplineName" width="120" show-overflow-tooltip/>
          <el-table-column label="学年" prop="academicYear" width="100" show-overflow-tooltip/>
          <el-table-column label="学院单位" prop="deptName" width="200" show-overflow-tooltip/>
          <el-table-column label="交卷时间" prop="submitTime" width="140" show-overflow-tooltip>
            <template slot-scope="scope">
              <span>{{ parseTime(scope.row.submitTime,'{y}-{m}-{d} {h}:{i}:{s}') }}</span>
            </template>
          </el-table-column>
          <el-table-column label="用时" prop="durationText" width="100" show-overflow-tooltip/>
          <el-table-column label="成绩" prop="score" width="100" show-overflow-tooltip/>
          <el-table-column label="结果" prop="passStatus" width="100" show-overflow-tooltip>
            <template slot-scope="scope">
              <span v-if="scope.row.resultStatus == 4" class="colorA">缺勤</span>
              <span v-if="scope.row.resultStatus == 3" class="colorB">未通过</span>
            </template>
          </el-table-column>
          <el-table-column label="操作" width="200" show-overflow-tooltip>
            <template slot-scope="scope">
              <div class="table-button-box">
                <p class="table-button-null"></p>
                <p class="table-button-p"
                   @click="lockExam(scope.row)"
                >查看答卷</p>
                <p class="table-button-null"></p>
              </div>
            </template>
          </el-table-column>
        </el-table>
        <pagination :page-sizes="[20, 30, 40, 50]"
                    v-show="total>0"
                    :total="total"
                    :page.sync="queryParams.page"
                    :limit.sync="queryParams.pageSize"
                    @pagination="getList"
        />
      </div>
    </div>
    <el-drawer
      size="100%"
      custom-class="studentsTakingMakeUpExams-addPage"
      :append-to-body="true"
      :title="drawerTitle"
      ref="drawer"
      :visible.sync="drawer"
      direction="rtl"
    >
      <!--选择试卷/选择试题-->
      <selectTestPaper v-if="drawerType === 1&&drawer"></selectTestPaper>
      <examDetails v-if="drawerType === 2&&drawer" :examDetailsPropsData="examDetailsPropsData"></examDetails>
    </el-drawer>
  </div>
</template>

<script>
  import examDetails from '@/views/safetyEducationExaminationNew/components/examDetails.vue'
  import selectTestPaper from './selectTestPaper.vue'
  import {
    systemUserGetAcademicYear,examElExamMakeupResults,
    examElExamMakeupAdd,examElExamMakeupCandidates,
    examElDisciplineTypeList, systemDeptCurrentDept,
    examElExamDetail
  } from '@/api/safetyEducationExaminationNew/index'

  export default {
    name: 'addPage',
    components: {
      selectTestPaper,
      examDetails
    },
    props: {
      propsData: {}
    },
    data() {
      const validateData = (rule, value, callback) => {
        if (value == 0) {
          callback(new Error('总分数不能为0'))
        } else {
          callback()
        }
      }
      return {
        //日期选择范围限制
        pickerOptions: {
          disabledDate(time) {
            return time.getTime() < Date.now() - 8.64e7;
          }
        },
        newData: {
          parentExamId:null,
          reuseOriginalPaper: 1,
          attemptLimit: 1,
          answerDuration: 0,
          paperId: null,
          paperName: '',
          examTimeRange: [],
        },
        rules:{
          reuseOriginalPaper: [
            { required: true, message: "是否复用原试卷", trigger: "blur" },
            { required: true, message: "是否复用原试卷", validator: this.spaceJudgment, trigger: "blur" }
          ],
          attemptLimit: [
            { required: true, message: "请选择可补考次数", trigger: "blur" },
            { required: true, message: "请选择可补考次数", validator: this.spaceJudgment, trigger: "blur" }
          ],
          answerDuration: [
            { required: true, message: '请选择考试时长', trigger: 'change' },
            { validator: validateData, trigger: 'blur' }
          ],
          examTimeRange: [
            { required: true, message: "请选择补考时间", trigger: "blur" },
            { required: true, message: "请选择补考时间", validator: this.spaceJudgment, trigger: "blur" }
          ],
        },
        //下拉列表数据
        optionListA: [],
        optionListB: [],
        optionListC: [],
        //查询条件
        queryParams: {
          page: 1,
          pageSize: 20,
          deptId: null,
          academicYear: null,
          disciplineId: null,
          account: ''
        },
        //列表数据
        dataList: [],
        //数据数量
        total: 0,
        //弹窗相关
        drawerTitle: '',
        drawerType: '',
        drawer: false,
        //补考是否已开始 0未开始 1开始
        makeupStarted:null,
        //补考试卷详情数据
        examDetailsPropsData:null,
      }
    },
    created() {

    },
    mounted() {
      this.$set(this,'makeupStarted',this.propsData.makeupStarted);
      if(this.propsData.makeupExamId&&this.propsData.makeupStarted==0){
        this.examElExamDetail();
      }
      this.$set(this.newData,'parentExamId',this.propsData.id);
      this.examElDisciplineTypeList()
      this.systemDeptCurrentDept()
      this.systemUserGetAcademicYear()
      this.getList()
    },
    methods: {
      //补考详情
      examElExamDetail(){
        examElExamDetail({id:this.propsData.id}).then(response => {
          this.$set(this,'newData',{
            reuseOriginalPaper:response.data.reuseOriginalPaper,
            paperName:response.data.paperName,
            paperId:response.data.paperId,
            examTimeRange:[response.data.startTime.replace("T", "0"),response.data.endTime.replace("T", "0")],
            attemptLimit:response.data.attemptLimit,
            answerDuration:response.data.answerDuration,
          });
        })
      },
      //导出
      exportButton(){
        let self = this;
        self.$confirm(`确认导出数据?`, "提示", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning"
        }).then(async () => {
          let obj = JSON.parse(JSON.stringify(this.queryParams))
          obj.examId = self.newData.parentExamId
          self.download('/exam/elExam/makeup-candidates-export', {...obj}, '补考候选人.xlsx')
        }).catch(() => {})
      },
      //弹窗返回
      drawerReturnButton(){
        //选择试卷
        this.$set(this.newData, 'paperId', data.id)
        this.$set(this.newData, 'paperName', data.name)
        this.$refs.drawer.closeDrawer();
      },
      openPaperDrawer() {
        // TODO: 打开选择试卷弹窗
        this.$set(this, 'drawerTitle', '选择试卷')
        this.$set(this, 'drawerType', 1)
        this.$set(this, 'drawer', true)
      },
      // 返回按钮
      backPage() {
        this.$parent.tableButton(6)
      },
      // 提交按钮
      submitButton() {
        let  self = this;
        this.$refs.form.validate((valid, fields) => {
          if (valid) {
            this.$confirm('是否确认保存?', "提示", {
              confirmButtonText: "确定",
              cancelButtonText: "取消",
              type: "warning"
            }).then(function() {
            }).then(() => {
              self.examElExamMakeupAdd();
            }).catch(() => {});
          }
        })
      },
      examElExamMakeupAdd(){
        let obj = {
          parentExamId:this.newData.parentExamId,
          reuseOriginalPaper:this.newData.reuseOriginalPaper,
          paperId:this.newData.reuseOriginalPaper?this.newData.paperId:'',
          attemptLimit:this.newData.attemptLimit,
          answerDuration:this.newData.answerDuration,
          startTime:this.newData.examTimeRange[0].replace(" ", "T"),
          endTime:this.newData.examTimeRange[1].replace(" ", "T"),
        }
        examElExamMakeupAdd(obj).then(response => {
          this.msgSuccess(response.message)
          this.$parent.tableButton(6)
        })
      },
      lockExam(row){
        this.$set(this, 'drawerTitle', '试卷详情')
        this.$set(this, 'drawerType', 2)
        this.$set(this, 'examDetailsPropsData', row)
        this.$set(this, 'drawer', true)
      },
      //查询按钮
      handleQuery() {
        this.$set(this.queryParams, 'page', 1)
        this.getList()
      },
      //重置按钮
      resetQuery() {
        this.$set(this, 'queryParams', {
          page: 1,
          pageSize: 20,
          deptId: null,
          academicYear: null,
          disciplineId: null,
          account: ''
        })
        this.getList()
      },
      //获取数据列表
      getList() {
        let obj = JSON.parse(JSON.stringify(this.queryParams))
        obj.examId = this.newData.parentExamId
        if(this.makeupStarted == 0){
          examElExamMakeupCandidates(obj).then(response => {
            this.$set(this, 'dataList', response.data.records)
            this.$set(this, 'total', response.data.total)
          })
        }else if (this.makeupStarted == 1){
          examElExamMakeupResults(obj).then(response => {
            this.$set(this, 'dataList', response.data.records)
            this.$set(this, 'total', response.data.total)
          })
        }
      },
      //查询全部专业类别
      examElDisciplineTypeList() {
        examElDisciplineTypeList({}).then(response => {
          this.$set(this, 'optionListC', response.data)
        })
      },
      //学年下拉列表
      systemUserGetAcademicYear(){
        systemUserGetAcademicYear({}).then(response => {
          this.$set(this,'optionListB',response.data);
        });
      },
      //学院列表
      systemDeptCurrentDept() {
        systemDeptCurrentDept({}).then(response => {
          const list = response.data || [];
          this.formatTreeData(list);
          this.$set(this, 'optionListA', list)
        })
      }
    }
  }
</script>

<style scoped lang="scss">
  .studentsTakingMakeUpExams-addPage {
    flex: 1;
    display: flex;
    flex-direction: column;
    overflow: hidden;
    .colorA{
      color:#F6A53C;
    }
    .colorB{
      color:#EF98A2;
    }
    .content-box {
      flex: 1;
      display: flex;
      flex-direction: column;
      overflow: hidden;

      .max-add-form-box {
        padding: 20px 0 0 0;
        border-bottom:1px solid #dedede;

        .form-flex-box {
          display: flex;

          .stepper-row {
            display: flex;
            align-items: center;
          }

          .number-stepper {
            display: inline-flex;
            align-items: center;
            border-radius: 4px;
            overflow: hidden;

            .stepper-btn {
              width: 32px;
              height: 32px;
              background: #f5f7fa;
              border: none;
              cursor: pointer;
              font-size: 16px;
              color: #333;

              &:hover {
                background: #e6f0fe;
              }
            }

            .stepper-val {
              min-width: 44px;
              text-align: center;
              font-size: 14px;
              padding: 0 4px;
            }
          }

          .unit-text {
            margin-left: 8px;
            color: #333;
            white-space: nowrap;
            font-size: 14px;
          }

          .tip-text {
            color: #999;
            font-size: 13px;
          }
        }

        .checkButton-p {
          height: 40px;
          background-color: #0183fa;
          color: #ffffff;
          line-height: 40px;
          border-radius: 4px;
          text-align: center;
          width: 80px;
          cursor: pointer;
        }

        .selected-tag {
          height: 40px;
          margin-left: 20px;
          display: inline-flex;
          align-items: center;
          background: #e6f4ff;
          border: 1px solid #91caff;
          border-radius: 4px;
          padding: 6px 12px;
          color: #0183fa;
          font-size: 13px;
          min-width: 200px;
          max-width: 500px;

          span {
            line-height: 28px;
            flex: 1;
          }

          i {
            margin-left: 8px;
            cursor: pointer;

            &:hover {
              color: #e74c3c;
            }
          }
        }
      }
    }
  }
</style>
<style lang="scss">
  .examinationArrange-addPage-date-picker {
    .el-input--small {
      width: 144px !important;
    }
    .el-time-panel__content::after, .el-time-panel__content::before{
      top:45%!important;
    }
  }
</style>
