<!--考试管理-->
<template>
  <div class="app-container exam">
    <el-form :model="queryParams" ref="queryForm" :inline="true" v-show="showSearch&&pageType==0" label-width="68px" class="form-box">

      <el-form-item label="考试名称" prop="title">
        <el-input
          v-model="queryParams.title"
          placeholder="请输入考试名称"
          clearable
          size="small"
        />
      </el-form-item>
      <el-form-item label="适用范围" prop="scopeType">
        <el-select v-model="queryParams.scopeType" placeholder="请选择适用范围" clearable size="small">
          <el-option
            v-for="item in scopeTypes"
            :key="item.type"
            :label="item.value"
            :value="item.type"
          >
          </el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="创建时间">
        <el-date-picker
          :clearable="false"
          v-model="createTimeDate"
          size="small"
          style="width: 240px"
          value-format="yyyy-MM-dd"
          type="daterange"
          range-separator="-"
          start-placeholder="开始日期"
          end-placeholder="结束日期"
        ></el-date-picker>
      </el-form-item>
      <el-form-item style="float: right;">
        <el-col :span="1.5" style="margin-right:20px;">
          <p class="add-button-one-120"
             @click="addExam"
             v-hasPermi="['exam:exam:add']"
          ><i class="el-icon-plus"></i>新增考试</p>
        </el-col>
      </el-form-item>
      <el-form-item >
        <p class="inquire-button-one" @click="handleQuery">查询</p>
        <p class="reset-button-one" @click="resetQuery">重置</p>
      </el-form-item>
    </el-form>
    <el-table v-loading="loading" border :data="examList" @selection-change="handleSelectionChange" v-show="pageType==0">
      <el-table-column label="考试名称" align="left" prop="title" />
      <el-table-column label="适用范围" align="left" prop="scopeType">
        <template slot-scope="scope">
          <span v-for="(item,index) in scopeTypes" :key="index" v-if="scope.row.scopeType==item.type">{{item.value}}</span>
        </template>
      </el-table-column>
      <el-table-column label="组题方式" align="left" prop="joinType">
        <template slot-scope="scope">
          <span>{{scope.row.joinType == 1 ?'自动组题':'手动组题'}}</span>
        </template>
      </el-table-column>
      <el-table-column label="创建时间" align="left" prop="createTime"/>
      <el-table-column label="操作" align="left" class-name="small-padding fixed-width" width="350">
        <template slot-scope="scope">
          <div class="button-box">
            <p class="table-min-button"
               style="margin-right:10px;"
               @click="trainingButton(scope.row)"
            >关联学习资源</p>
            <p class="table-min-button"
               style="margin-right:10px;"
               @click="examInfo(scope.row)"
               v-hasPermi="['exam:exam:query']"
            >详情</p>
            <p class="table-min-button"
               style="margin-right:10px;"
               @click="addExam(scope.row)"
               v-hasPermiAnd="['exam:exam:query','exam:exam:edit']"
            >编辑</p>
            <p class="table-min-button"
               @click="handleDelete(scope.row)"
               v-hasPermi="['exam:exam:remove']"
            >删除</p>
          </div>
        </template>
      </el-table-column>
    </el-table>
    <pagination :page-sizes="[20, 30, 40, 50]"
      v-show="total>0&&pageType==0"
      :total="total"
      layout="total, prev, pager, next, sizes, jumper"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />
    <add-exam-page v-if="pageType==1" :repoId="repoId"></add-exam-page>
    <exam-info v-if="pageType==2" :rowData="rowData"></exam-info>
    <!-- 添加或修改考试对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="500px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="80px">
        <div v-if="dialogType==1">
          <el-form-item label="选择学习资源" prop="courseIds" label-width="120px">
            <el-select v-model="form.courseIds" placeholder="选择学习资源">
              <el-option
                v-for="item in optionCourses"
                :key="item.id"
                :label="item.title"
                :value="item.id"
              >
              </el-option>

            </el-select>
          </el-form-item>
        </div>
        <div v-if="dialogType==2" class="exam-dialog-box">
          <el-form-item label="选择证书" prop="examCerts">
            <el-select v-model="form.examCerts" multiple placeholder="请选择证书">
              <el-option
                v-for="item in optionCertificates"
                :key="item.id"
                :label="item.certTitle"
                :value="item.id"
              >
              </el-option>
            </el-select>
          </el-form-item>
        </div>
      </el-form>
      <div slot="footer" class="dialog-footer" v-if="dialogType==1||dialogType==2">
        <el-button @click="cancel">取 消</el-button>
        <el-button type="primary" @click="submitForm">确 定</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { listExam, getExam, delExam, addExam, updateExam, updateSafeTrain, updateCert } from "@/api/exam/exam";
import addExamPage from './addExamPage.vue'
import examInfo from './examInfo.vue'
import { optionTrain } from "@/api/exam/train";
import { certificateOption } from "@/api/exam/certificate";
import { option_course } from "@/api/exam/el_course";

export default {
  components: {
    addExamPage,
    examInfo
  },
  name: "Exam",
  data() {
    return {
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 考试表格数据
      examList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      createTimeDate: [],
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize:20,
        code: null,
        title: null,
        content: null,
        openType: null,
        joinType: null,
        level: null,
        scopeType: null,
        state: null,
        convert: null,
        timeLimit: null,
        startTime: null,
        endTime: null,
        totalScore: null,
        totalTime: null,
        qualifyScore: null,
        userId: null,
        deptId: null,
        deptName: null
      },
      // 表单参数
      form: {},
      // 表单校验
      rules: {
        title: [
          { required: true, message: "考试名称不能为空", trigger: "blur" },
          { required: true, message: "考试名称不能为空", validator: this.spaceJudgment, trigger: "blur" }
        ],
        content: [
          { required: true, message: "考试描述不能为空", trigger: "blur" },
          { required: true, message: "考试描述不能为空", validator: this.spaceJudgment, trigger: "blur" }
        ],
        openType: [
          { required: true, message: "1公开2部门3定员不能为空", trigger: "change" }
        ],
        joinType: [
          { required: true, message: "组题方式1题库,2指定不能为空", trigger: "change" }
        ],
        level: [
          { required: true, message: "难度:0不限,1普通,2较难不能为空", trigger: "blur" }
        ],
        totalScore: [
          { required: true, message: "总分数不能为空", trigger: "blur" },
          { required: true, message: "总分数不能为空", validator: this.spaceJudgment, trigger: "blur" }
        ],
        totalTime: [
          { required: true, message: "总时长不能为空", trigger: "blur" },
          { required: true, message: "总时长不能为空", validator: this.spaceJudgment, trigger: "blur" }
        ],
        qualifyScore: [
          { required: true, message: "及格分数不能为空", trigger: "blur" },
          { required: true, message: "及格分数不能为空", validator: this.spaceJudgment, trigger: "blur" }
        ],
      },
      //弹窗状态
      dialogType:0,
      // 证书
      optionCertificates: [],
      // 安全培训
      optionTrains: [],
      // 学习资源
      optionCourses: [],
      //页面状态
      pageType:0,
      // 学科类别字典
      subClassOptions: [],
      // 选取的id绑定证书和安全培训用
      rowId: '',
      levels: [
        {
          type: 1,
          value: "中等",
        },
        {
          type: 2,
          value: "较难",
        },
        {
          type: 3,
          value: "难",
        },
      ],
      scopeTypes: [
        {
          type: 1,
          value: "安全准入考试",
        },
        {
          type: 2,
          value: "负面清单考试",
        },
        {
          type: 3,
          value: "黑名单考试",
        },
        {
          type: 4,
          value: "模拟考试",
        },
      ],
      rowData:"",
      //考试ID  用于编辑查询
      repoId:"",
    };
  },
  created() {
    this.getList();
    this.getDicts("subject_class").then(response => {
      this.subClassOptions = response.data;
    });
  },
  methods: {
    /** 查询证书列表 */
    getCertificateOption() {
      certificateOption({}).then(response => {
        this.optionCertificates = response.data;
      });
    },
    /** 查询安全培训列表 */
    getOptionTrain(subjectClass) {
      optionTrain({"subjectClass": subjectClass}).then( response => {
        this.optionTrains =  response.data;
      });
    },
    /** 查询学习资源列表 */
    getOptionCourse() {
      option_course({}).then( response => {
        this.optionCourses =  response.data;
      });
    },
    //新增考试
    addExam(row){
      if(row){
        this.repoId = row.id;
      }else{
        this.repoId = "";
      }
      this.pageType = 1;
    },
    examInfo(row){
      this.rowData = row.id;
      this.pageType = 2;
    },
    pageOff(){
      this.pageType = 0;
      this.getList();
    },
    //关联学习资源
    trainingButton(row){
      // this.reset();
      this.reset();
      this.dialogType = 1;
      this.open = true;
      this.title = "关联学习资源";
      this.rowId = row.id;
      if(row.courseIds){
        this.form.courseIds = parseInt(row.courseIds)
      }
      //this.getOptionTrain(row.code);
      this.getOptionCourse()
    },
    //绑定证书
    bindingButton(row){
      this.reset();
      this.dialogType = 2;
      this.open = true;
      this.title = "绑定证书";
      this.rowId = row.id;
      if(row.examCerts){
        console.log(row.examCerts)
        let list = [];
        for(let i=0;i<row.examCerts.length;i++){
          console.log(row.examCerts)
          list.push(row.examCerts[i].certId)
        }
        this.form.examCerts = list
      }
      this.getCertificateOption();
    },
    //考试明细
    detailButton(row){

    },
    /** 查询考试列表 */
    getList() {
      if(this.createTimeDate[0]){
        this.queryParams.inTime = this.createTimeDate[0];
        this.queryParams.outTime = this.createTimeDate[1];
      }else {
        this.queryParams.inTime = null
        this.queryParams.outTime = null
      }
      this.loading = true;
      listExam(this.queryParams).then(response => {
        this.examList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.dialogType = 0;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        id: null,
        title: null,
        content: null,
        openType: null,
        joinType: null,
        level: null,
        scopeType: null,
        state: null,
        convert: null,
        timeLimit: null,
        startTime: null,
        endTime: null,
        createTime: null,
        updateTime: null,
        totalScore: null,
        totalTime: null,
        qualifyScore: null,
        userId: null,
        createBy: null,
        updateBy: null,
        deptId: null,
        deptName: null,
        // 关联学习资源id
        courseIds: null,
        // 关联多个证书
        examCerts: null,

      };
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.queryParams.inTime = null
      this.queryParams.outTime = null
      this.createTimeDate = []
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.id)
      this.single = selection.length!==1
      this.multiple = !selection.length
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
      this.title = "添加考试";
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      const id = row.id || this.ids
      getExam(id).then(response => {
        this.form = response.data;
        this.open = true;
        this.title = "修改考试";
      });
    },
    /** 提交按钮 */
    submitForm() {
      let self = this;
      this.$refs["form"].validate(valid => {
        if (valid) {
          console.log(this.dialogType)

          if(this.dialogType == 1){
              if(!this.form.courseIds){
              this.msgError("请先选择证书！");
              return
            }
            if(this.rowId){
              updateSafeTrain({
                id: this.rowId,
                courseIds: this.form.courseIds
              }).then(response => {
                this.msgSuccess("修改成功");
                this.open = false;
                this.getList();
              });
            } else {
              this.open = false;
            }
          }else if(this.dialogType == 2){

            console.log(this.form.examCerts)

            let list = [];
            for(let i=0;i<self.form.examCerts.length;i++){
              let obj = {
                certId:self.form.examCerts[i]
              }
              list.push(obj)
            }
            // this.form.examCerts = JSON.parse(JSON.stringify(list));
            // console.log("list",list)
            if(this.rowId){
              updateCert({
                id: this.rowId,
                examCerts: list
              }).then(response => {
                this.msgSuccess("修改成功");
                this.open = false;
                this.getList();
              });
            }
          }

        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const ids = row.id || this.ids;
      this.$confirm('是否确认删除考试?', "警告", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning"
        }).then(function() {
          return delExam(ids);
        }).then(() => {
          this.getList();
          this.msgSuccess("删除成功");
        }).catch(() => {});
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download('exam/exam/export', {
        ...this.queryParams
      }, `exam_exam.xlsx`)
    }
  }
};
</script>

<style scoped lang="scss">
  .exam{
    display: flex!important;
    flex-direction: column;
    box-shadow: 0 0 8px 2px rgba(0, 0, 0, 0.1);
    padding:20px!important;
    .button-box{
      width:530px;
      display: flex;
    }
    .form-box{
    }
  }
</style>
