<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 v-if="checkPermission(['exam_create'])" type="primary" icon="el-icon-plus" @click="handleAdd">新增</el-button>
      <el-button
        class="filter-item"
        type="primary"
        icon="el-icon-refresh-left"
        @click="resetFilter"
      >刷新重置</el-button>
    </div>

    <el-table
      v-loading="listLoading"
      :data="tableData.results"
      style="width: 100%;margin-top:10px;"
      border
      fit
      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.code }}</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.workscope_name }}</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.opentime }}</template>
      </el-table-column>
      <el-table-column label="关闭时间">
        <template slot-scope="scope">{{ scope.row.closetime }}</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 align="center" label="操作" fixed="right">
        <template slot-scope="scope">
          <el-button
            type="primary"
            size="small"
            :disabled="!checkPermission(['exam_view'])"
            @click="handleView(scope)"
          >详情</el-button>
          <el-button
            size="small"
            :disabled="!checkPermission(['exam_update'])"
            @click="handleEdit(scope)"
          >编辑</el-button>
          <el-button
            type="danger"
            size="small"
            :disabled="!checkPermission(['exam_delete'])"
            @click="handleDelete(scope)"
          >删除</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 ref="examForm" :model="exam" label-width="80px" :rules="rule1">
        <el-row>
          <el-col :span="12">
            <el-form-item label="名称" prop="name">
              <el-input v-model="exam.name" placeholder="名称" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="考试地点" prop="place">
              <el-input v-model="exam.place" placeholder="考试地点" />
            </el-form-item>
          </el-col>
        </el-row>

        <el-row>

          <el-col :span="12">
            <el-form-item label="工作类别" prop="workscope">
              <el-select v-model="exam.workscope" placeholder="请选择工作类别" style="width:100%">
                <el-option
                  v-for="item in workscopeOptions"
                  :key="item.id"
                  :label="item.name"
                  :value="item.id"
                />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <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-select>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="开启时间" prop="opentime">
              <el-date-picker
                v-model="exam.opentime"
                type="datetime"
                placeholder="开启时间"
                style="width:100%"
              />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="关闭时间" prop="closetime">
              <el-date-picker
                v-model="exam.closetime"
                type="datetime"
                placeholder="关闭时间"
                style="width:100%"
              />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="参考机会" prop="chance">
              <el-input-number v-model="exam.chance" placeholder="参考机会" :min="1" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="仅培训班学员" prop="only_vip" label-width="100px">
              <el-switch v-model="exam.only_vip" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="自动发证" prop="auto_issue">
              <el-switch v-model="exam.auto_issue" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="证书模板">

              <el-select v-if=" uploadUrl=='https://qw.ctc-zc.com/api'" v-model="exam.cert_template" placeholder="证书模板" clearable>
                <el-option
                  v-for="item in certTemplateOptionsqw"
                  :key="item.value"
                  :label="item.label"
                  :value="item.value"
                />

              </el-select>
              <el-select v-else v-model="exam.cert_template" placeholder="证书模板" clearable>
                <el-option
                  v-for="item in certTemplateOptions"
                  :key="item.value"
                  :label="item.label"
                  :value="item.value"
                />
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>

        <el-divider />
        <el-row>
          <el-col :span="12">
            <el-form-item label="监考人姓名" prop="proctor_name" label-width="120px">
              <el-input v-model="exam.proctor_name" placeholder="监考人姓名" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="监考人联系方式" prop="proctor_phone" label-width="120px">
              <el-input v-model="exam.proctor_phone" placeholder="监考人联系方式" />
            </el-form-item>
          </el-col>
        </el-row>

        <el-form-item label="培训名称" prop="train_name">
          <el-input v-model="exam.train_name" placeholder="培训名称" />
        </el-form-item>
        <el-row>
          <el-col :span="12">
            <el-form-item label="培训开始" prop="train_start_date">
              <el-date-picker
                v-model="exam.train_start_date"
                type="date"
                placeholder="培训开始"
                value-format="yyyy-MM-dd"
                style="width:100%"
              />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="培训结束" prop="train_end_date">
              <el-date-picker
                v-model="exam.train_end_date"
                type="date"
                placeholder="培训结束"
                value-format="yyyy-MM-dd"
                style="width:100%"
              />
            </el-form-item>
          </el-col>
        </el-row>

      </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 { getexamlist, createexam, deleteexam, updateexam } from '@/api/exam'
import { getWorkScopeAll, getPaperList } from '@/api/examtest'
import { deepClone } from '@/utils'
import checkPermission from '@/utils/permission'
import Pagination from '@/components/Pagination'

const defaultexam = {
  id: '',
  name: '',
  place: '',
  opentime: null,
  closetime: null,
  chance: 3,
  only_vip: false,
  cert_template: null,
  auto_issue: false
}
const listQuery = {
  page: 1,
  limit: 20,
  search: ''
}
export default {
  components: { Pagination },
  data() {
    return {
      uploadUrl: process.env.VUE_APP_BASE_API,
      selects: [],
      exam: {
        id: '',
        name: ''
      },
      certTemplateOptionsqw: [
        { value: 3, label: '气味评价证书' },
        { value: 4, label: '气味检验证书' }
      ],
      certTemplateOptions: [
        { value: 1, label: '模板1' },
        { value: 2, label: '模板2' }
      ],
      listQuery: listQuery,
      tableData: { count: 0 },
      listLoading: true,
      dialogVisible: false,
      dialogType: 'new',
      workscopeOptions: [],
      paperOptions: [],
      rule1: {
        name: [{ required: true, message: '请输入', trigger: 'blur' }],
        place: [{ required: true, message: '请输入', trigger: 'change' }],
        workscope: [{ required: true, message: '请选择', trigger: 'change' }],
        opentime: [{ required: true, message: '请选择', trigger: 'change' }],
        closetime: [{ 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: {},
  created() {
    this.getList()
    this.getworkscopeOptions()
    this.getPaperOptions()
  },
  methods: {
    checkPermission,
    getworkscopeOptions() {
      getWorkScopeAll({ can_exam: true }).then(res => {
        this.workscopeOptions = res.data
      })
    },
    getPaperOptions() {
      getPaperList({ pageoff: true }).then(res => {
        this.paperOptions = res.data
      })
    },
    getList() {
      this.listLoading = true
      getexamlist(this.listQuery).then(response => {
        this.tableData = response.data
        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({ name: 'ExamTest2', params: { exam: scope.row.id }})
    },
    async confirmexam(form) {
      this.$refs[form].validate(valid => {
        if (valid) {
          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.exam = res.data
              // this.tableData.unshift(this.exam)
              this.getList()
              this.dialogVisible = false
              this.$message.success('成功')
            })
          }
        } else {
          return false
        }
      })
    }
  }
}
</script>
