<template>
    <div class="app-container">
        <div style="margin-top:10px">
          <el-input
            v-model="listQuery.search"
            placeholder="输入考试名称进行搜索"
            style="width: 300px;"
            class="filter-item"
            @keyup.enter.native="handleFilter"
          />
          <el-button type="primary" @click="handleAdd" icon="el-icon-plus" v-if ="checkPermission(['exam_create'])">新增</el-button>
          <el-button
            class="filter-item"
            type="primary"
            icon="el-icon-refresh-left"
            @click="resetFilter"
          >刷新重置</el-button>
          </div>
          <el-table
            :data="tableData.results"
            style="width: 100%;margin-top:10px;"
            border
            fit
            v-loading="listLoading"
            highlight-current-row
            max-height="600"
            row-key="id"
            default-expand-all
          >
            <el-table-column label="考试名称">
              <template slot-scope="scope">{{ scope.row.name }}</template>
            </el-table-column>
            <el-table-column label="考试试卷">
              <template slot-scope="scope">
                {{scope.row.paper_.name }}
                <!-- <text v-if="scope.row.paper_">{{scope.row.paper_.name }}</text> -->
              </template>
            </el-table-column>
            <el-table-column label="考试地点">
              <template slot-scope="scope">{{ scope.row.place }}</template>
            </el-table-column>
            <el-table-column label="参考机会">
              <template slot-scope="scope">{{ scope.row.chance }}</template>
            </el-table-column>
            <el-table-column label="开启时间">
              <template slot-scope="scope">{{ scope.row.open_time }}</template>
            </el-table-column>
            <el-table-column label="关闭时间">
              <template slot-scope="scope">{{ scope.row.close_time }}</template>
            </el-table-column>
            <el-table-column label="创建人">
              <template slot-scope="scope">
                <span>{{ scope.row.create_admin_username }}</span>
              </template>
            </el-table-column>
            <el-table-column label="参加人数">
              <template slot-scope="scope">{{ scope.row.user_count }}</template>
            </el-table-column>
            <el-table-column label="完成人数">
              <template slot-scope="scope">{{ scope.row.submit_count }}</template>
            </el-table-column>
            <el-table-column align="center" label="操作" fixed="right">
              <template slot-scope="scope">
                <el-button
                  type="primary"
                  size="small"
                  @click="handleView(scope)"
                  :disabled="!checkPermission(['exam_view'])"
                >详情</el-button>
                <el-button
                  size="small"
                  @click="handleEdit(scope)"
                  :disabled="!checkPermission(['exam_update'])"
                >编辑</el-button>
                <el-button
                  type="danger"
                  size="small"
                  @click="handleDelete(scope)"
                  :disabled="!checkPermission(['exam_delete'])"
                >删除</el-button>
              </template>
            </el-table-column>
          </el-table>
      <pagination
        v-show="tableData.count>0"
        :total="tableData.count"
        :page.sync="listQuery.page"
        :limit.sync="listQuery.limit"
        @pagination="getList"
      />
      <el-dialog :visible.sync="dialogVisible" :title="dialogType==='edit'?'编辑考试':'新增考试'" >
        <el-form :model="exam" label-width="120px" :rules="rule1" ref="examForm">
          <el-form-item label="名称" prop="name">
            <el-input v-model="exam.name" placeholder="名称" />
          </el-form-item>
          <el-form-item label="考试地点" prop="place">
            <el-input v-model="exam.place" placeholder="考试地点" />
          </el-form-item>
          <el-form-item label="参考机会" prop="chance">
            <el-input-number v-model="exam.chance" placeholder="参考机会" :min="1"/>
          </el-form-item>
          <el-form-item label="开启时间" prop="open_time">
            <el-date-picker
              v-model="exam.open_time"
              type="datetime"
              placeholder="开启时间"
              style="width:100%">
            </el-date-picker>
          </el-form-item>
          <el-form-item label="关闭时间" prop="close_time">
            <el-date-picker
              v-model="exam.close_time"
              type="datetime"
              placeholder="关闭时间"
              style="width:100%"
            ></el-date-picker>
          </el-form-item>
          <el-form-item label="监考人姓名" prop="proctor_name" label-width="120px">
            <el-input v-model="exam.proctor_name" placeholder="监考人姓名" />
          </el-form-item>
          <el-form-item label="监考人电话" prop="proctor_phone" label-width="120px">
            <el-input v-model="exam.proctor_phone" placeholder="监考人联系方式" />
          </el-form-item>
          <el-form-item label="选定试卷" prop="paper" >
            <el-select v-model="exam.paper" placeholder="可指定试卷" style="width:100%" clearable>
              <el-option
                v-for="item in paperOptions"
                :key="item.id"
                :label="item.name"
                :value="item.id"
              ></el-option>
            </el-select>
          </el-form-item>
        <el-form-item label = "出具证书"> 
          <el-select v-model="exam.certificate" placeholder="是否出具证书" style="width:100%" clearable>
            <el-option
             label = "是"
             value = 'true'>
            </el-option>
            <el-option 
              label = '否'
              value= 'false'>
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="课程名称" prop="course_name" v-if="exam.certificate==='true'">
          <el-select v-model="exam.course_name"  multiple placeholder = "请选择课程名称">
            <el-option 
            v-for="item in courseOptions"
            :key = "item.id"
            :label = "item.name"
            :value = "item.id">
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="考试部门" prop="participant_dep" style="width:100%" clearable collapse-tags filterable >
          <el-button @click="selectAll">全选部门</el-button>
          <el-select v-model="exam.participant_dep" multiple collapse-tags filterable placeholder = "选择部门" >
            <el-option 
            v-for="item in depOptions"
            :key = "item.id"
            :label = "item.name"
            :value = "item.id">
            </el-option>
          </el-select>
        </el-form-item>
        
        <el-form-item label="考试人员" prop="participant_user" style="width:100%" clearable>
          <el-select v-model="exam.participant_user" multiple filterable placeholder = "请选择人员">
            <el-option 
            v-for="item in userOptions"
            :key = "item.id"
            :label = "item.name"
            :value = "item.id">
            </el-option>
          </el-select>
          <el-pagination
            @size-change="handleSizeChange"
            @current-change="handleCurrentChange"
            :current-page="currentPage"
            :page-sizes="[10, 20, 30, 40]"
            :page-size="pageSize"
            layout="total, sizes, prev, pager, next, jumper"
            :total="total"
          ></el-pagination>
        </el-form-item>
        </el-form>
        <div style="text-align:right;">
          <el-button type="danger" @click="dialogVisible=false">取消</el-button>
          <el-button type="primary" @click="confirmexam('examForm')">确认</el-button>
        </div>
      </el-dialog>
    </div>
  </template>
  <script>
  import { getPaperList,getExamList, createExam, updateExam,deleteExam, getCourse, getDepartment} from "@/api/exam";
  import {getUserList} from "@/api/user";
  import checkPermission from "@/utils/permission";
  import Pagination from "@/components/Pagination"


  const defaultexam = {
          id: "",
          name: "",
          place: "",
          open_time: null,
          close_time: null,
          proctor_name:'',
          proctor_phone:'',
          chance:3,
          paper:'',
          certificate:'',
          course_name:[],
          participant_dep:[],
          participant_user:[],
        };
  const listQuery = {
    page: 1,
    limit: 20,
    search: ""
  };
  export default {
    components: { Pagination },
    data() {
      return {
        selects:[],
        exam: {
          id: "",
          name: "",
        },
        // has_certificate:'true',
        courseOptions:[],
        depOptions:[],
        userOptions:[],
        listQuery:listQuery,
        tableData: {count:0},
        listLoading: true,
        dialogVisible: false,
        dialogType: "new",
        workscopeOptions:[],
        paperOptions:[],
        currentPage: 1, // 当前页码
        pageSize: 10, // 每页显示的条数
        total: 0, // 总条数
        rule1: {
          name: [{ required: true, message: "请输入", trigger: "blur" }],
          place: [{ required: true, message: "请输入", trigger: "change" }],
          workscope: [{ required: true, message: "请选择", trigger: "change" }],
          open_time: [{ required: true, message: "请选择", trigger: "change" }],
          close_time: [{ required: true, message: "请选择", trigger: "change" }],
          proctor_name: [{ required: true, message: "请输入", trigger: "change" }],
          proctor_phone: [{ required: true, message: "请输入", trigger: "change" }],
          chance: [{ required: true, message: "请输入", trigger: "change" }]
        },
      };
    },
    computed: {},
    mounted() {
      this.getPaperOptions();
      this.getList();
      this.getCourseList();
      this.getDepartmentList();
      this.getUser();
    },
    methods: {
      checkPermission,
      getPaperOptions(){
        getPaperList({page:0}).then(res=>{
          debugger;
          this.paperOptions = res.data
        })
      },
      selectAll(){
        this.exam.participant_dep = this.depOptions.map(option => option.id);
      },
      getList() {
        this.listLoading = true;
        debugger;
        getExamList(this.listQuery).then(response => {
          this.tableData = response.data
          this.listLoading = false;
        });
      },
      handleSizeChange(val) {
      // 改变每页显示的条数
        this.pageSize = val;
        this.getUser();
    },
      handleCurrentChange(val) {
        // 改变当前页码
        this.currentPage = val;
        this.getUser();
      },
      getDepartmentList(){
        getDepartment().then(response =>{
          this.depOptions = response.data
          return this.depOptions
        })
      },
      getUser(){
        getUserList({page: this.currentPage, size: this.pageSize}).then(response =>{
          this.userOptions = response.data.results
          this.total = response.data.total;
          // console.log(this.userOptions)
        })
      },
      getCourseList(){
        getCourse(this.listQuery).then(response =>{
          this.courseOptions = response.data.results
          this.listLoading = false;
        })
      },
      resetFilter() {
        this.listQuery = {
          page: 1,
          limit: 20,
          search: ""
        };
        this.getList();
      },
      handleFilter() {
        this.listQuery.page = 1;
        this.getList();
      },
      handleAdd() {
        this.exam = Object.assign({}, defaultexam);
        this.dialogType = "new";
        this.dialogVisible = true;
        this.$nextTick(() => {
          this.$refs["examForm"].clearValidate();
        });
      },
      handleEdit(scope) {
        this.exam = Object.assign({}, scope.row); // copy obj
        this.dialogType = "edit";
        this.dialogVisible = true;
        this.$nextTick(() => {
          this.$refs["examForm"].clearValidate();
        });
      },
      handleDelete(scope) {
        this.$confirm("确认删除该考试吗?将丢失数据!", "警告", {
          confirmButtonText: "确认",
          cancelButtonText: "取消",
          type: "error"
        })
          .then(async () => {
            await deleteExam(scope.row.id);
            this.getList()
            this.$message({
              type: "success",
              message: "成功删除!"
            });
          })
          .catch(err => {
            // console.error(err);
          });
      },
      handleView(scope){
        this.$router.push({ path: "/exam/record", query: { exam: scope.row.id } })
      },
      async confirmexam(form) {
        this.$refs[form].validate(valid => {
          if (valid) {
            this.exam.certificate = this.exam.certificate === 'true';
            const isEdit = this.dialogType === "edit";
            if (isEdit) {
              updateExam(this.exam.id, this.exam).then(() => {
                this.getList();
                this.dialogVisible = false;
                this.$message.success('成功')
              });
            } else {
              createExam(this.exam).then(res => {
                this.getList();
                this.dialogVisible = false;
                this.$message.success('成功')
              });
            }
          } else {
            return false;
          }
        });
      },
    }
  };
  </script>
  