<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="考试名称" prop="examName">
        <el-input v-model="queryParams.examName" placeholder="请输入考试名称" clearable
                  @keyup.enter.native="handleQuery"/>
      </el-form-item>
      <!-- <el-form-item label="年度" prop="examYear">
        <el-input
          v-model="queryParams.examYear"
          placeholder="请输入年度"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="报名截止时间" prop="deadline">
        <el-date-picker clearable
          v-model="queryParams.deadline"
          type="date"
          value-format="yyyy-MM-dd"
          placeholder="请选择报名截止时间">
        </el-date-picker>
      </el-form-item>
      <el-form-item label="考试开始时间" prop="startTime">
        <el-date-picker clearable
          v-model="queryParams.startTime"
          type="date"
          value-format="yyyy-MM-dd"
          placeholder="请选择考试开始时间">
        </el-date-picker>
      </el-form-item>
      <el-form-item label="考试结束时间" prop="endTime">
        <el-date-picker clearable
          v-model="queryParams.endTime"
          type="date"
          value-format="yyyy-MM-dd"
          placeholder="请选择考试结束时间">
        </el-date-picker>
      </el-form-item> -->
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button type="primary" plain icon="el-icon-plus" size="mini" @click="handleAdd">新增
        </el-button>
      </el-col>
      <!-- <el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="el-icon-edit"
          size="mini"
          :disabled="single"
          @click="handleUpdate"
          v-hasPermi="['system:exam:edit']"
        >修改</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="el-icon-delete"
          size="mini"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['system:exam:remove']"
        >删除</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="el-icon-download"
          size="mini"
          @click="handleExport"
          v-hasPermi="['system:exam:export']"
        >导出</el-button>
      </el-col> -->
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="examList" @selection-change="handleSelectionChange">
      <el-table-column label="序号" type="index" width="55" align="center"/>
      <el-table-column label="考试名称" align="center" show-overflow-tooltip prop="examName" min-width="150"/>
      <el-table-column label="年度" align="center" prop="examYear" min-width="80"/>
      <el-table-column label="报名截止时间" align="center" prop="deadline" min-width="120">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.deadline, '{y}-{m}-{d} {h}:{i}:{s}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="考试开始时间" align="center" prop="startTime" min-width="100">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.startTime, '{y}-{m}-{d}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="考试结束时间" align="center" prop="endTime" min-width="100">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.endTime, '{y}-{m}-{d}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="状态" align="center" prop="status" min-width="100">
        <template slot-scope="scope">
          <el-link type="primary" :underline="false" @click="registration(scope.row)">
            <dict-tag :options="dict.type.registration_status" :value="scope.row.status"></dict-tag>
          </el-link>
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" min-width="120" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button size="mini" type="text" v-show="scope.row.status == '0'" icon="el-icon-edit"
                     @click="handleUpdate(scope.row)">修改
          </el-button>
          <el-button size="mini" type="text" v-show="scope.row.status == '0'" icon="el-icon-delete"
                     @click="handleDelete(scope.row)">删除
          </el-button>
          <el-button size="mini" type="text" icon="el-icon-view" v-show="scope.row.status != '0'"
                     @click="handleView(scope.row)">查看
          </el-button>
        </template>
      </el-table-column>
    </el-table>
    <pagination v-show="total > 0" :total="total" :page.sync="queryParams.pageNum" :limit.sync="queryParams.pageSize"
                @pagination="getList"/>
    <el-dialog :title="title" :visible.sync="open" width="850px" append-to-body @close="bigDialogClose">
      <el-form ref="form" :model="form" :rules="rules" label-width="110px" class="mr10">
        <el-form-item label="考试名称" prop="examName">
          <el-input v-model="form.examName" placeholder="请输入考试名称" :readOnly="isHandle"/>
        </el-form-item>
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="年度" prop="examYear">
              <el-date-picker style="width:100%;" :readonly="isHandle" v-model="form.examYear" type="year"
                              value-format="yyyy" placeholder="选择年度">
              </el-date-picker>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="报名截止时间" prop="deadline">
              <el-date-picker style="width:100%;" clearable v-model="form.deadline" type="datetime"
                              value-format="yyyy-MM-dd HH:mm"
                              format="yyyy-MM-dd HH:mm" placeholder="请选择报名截止时间" :readonly="isHandle">
              </el-date-picker>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="考试开始时间" prop="startTime">
              <el-date-picker
                v-model="form.startTime"
                :readonly="isHandle"
                type="date"
                style="width: 100%"
                placeholder="选择日期">
              </el-date-picker>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="考试结束时间" prop="endTime">
              <el-date-picker
                v-model="form.endTime"
                type="date"
                :readonly="isHandle"
                :picker-options="pickerOptionsEnd"
                style="width: 100%"
                placeholder="选择日期">
              </el-date-picker>
            </el-form-item>
          </el-col>
        </el-row>

        <!--        <el-form-item label="测试项目" prop="projectName" v-if="!isHandle">-->
        <!--          <el-input v-model="form.projectName" placeholder="请选择测试项目" @click.native="selectProjectList"/>-->
        <!--        </el-form-item>-->
        <!--        <el-form-item label="测试项目" prop="projectName" v-if="isHandle">-->
        <!--          <el-input v-model="form.projectName" placeholder="请选择测试项目" readOnly/>-->
        <!--        </el-form-item>-->
        <el-form-item label="测试项目" prop="projectName">
          <el-input v-model="form.projectName" :readonly="isHandle" @click.native="selectProjectList"
                    placeholder="请选择测试项目"/>
        </el-form-item>
        <div v-if="!isHandle">
          <el-form-item label="考试安排" prop="examArrange">
            <Editor v-model="form.examArrange" :min-height="150"></Editor>
          </el-form-item>
          <el-form-item label="注意事项" prop="notice">
            <Editor v-model="form.notice" :min-height="150"></Editor>
          </el-form-item>
        </div>
      </el-form>
      <div v-if="isHandle">
        <el-form :model="form" :rules="rules" label-width="110px">
          <el-form-item label="考试安排">
            <Editor v-model="form.examArrange" :min-height="150" readOnly></Editor>
          </el-form-item>
          <el-form-item label="考试注意事项">
            <Editor v-model="form.notice" :min-height="150" readOnly></Editor>
          </el-form-item>
        </el-form>
      </div>
      <div slot="footer" class="dialog-footer" style="text-align:center ;">
        <el-button type="primary" @click="submitForm" v-if="!isHandle">保 存</el-button>
        <el-button @click="publish" type="success" style="margin-left:26px ;" v-if="!isHandle">发 布</el-button>
        <el-button @click="cancel" style="margin-left:26px ;">取 消</el-button>
      </div>
    </el-dialog>

    <el-dialog title="测试项目" :visible.sync="openSelect" width="800px" append-to-body>
      <el-table ref="table-project" @row-click="rowClick" size="small" height="400px" :data="projectList"
                @selection-change="handleSelectionChange" :row-key="getRowId">
        <el-table-column type="selection" width="55" reserve-selection align="center"/>
        <el-table-column label="序号" min-width="100" type="index" align="center"/>
        <el-table-column label="项目名称" min-width="100" align="center" prop="project"/>
        <el-table-column label="项目类型" min-width="100" align="center" prop="type">
          <template slot-scope="scope">
            <dict-tag :options="dict.type.professional_category" :value="scope.row.type"></dict-tag>
          </template>
        </el-table-column>
        <el-table-column label="项目创建时间" min-width="100" align="center" prop="createTime"/>
      </el-table>
      <div slot="footer">
        <el-button type="primary" @click="selectConfirm">确 定</el-button>
        <el-button @click="selectClose">取 消</el-button>
      </div>
    </el-dialog>


  </div>
</template>

<script>
import {
  listExam,
  getExam,
  delExam,
  addExam,
  updateExam,
  addPub,
  listProject,
  edit
} from "@/api/smartSchool/examinationManage";

export default {
  name: "Exam",
  dicts: ['professional_category', 'registration_status'],
  data() {

    return {
      isFirst: true,
      handle: undefined,
      tableSelection: [],
      openSelect: false,
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 【请填写功能名称】表格数据
      examList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 是否修改
      isHandle: false,
      // 测试项目
      projectList: [],
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        examName: null,
        // examYear: null,
        // deadline: null,
        // startTime: null,
        // endTime: null,
        // examArrange: null,
        // notice: null,
        // status: null,
      },
      pickerOptionsEnd: {
        disabledDate: (time) => {
          return new Date(time) < new Date(this.form.startTime)
        },
      },
      // 表单参数
      form: {},
      // 表单校验
      rules: {
        examName: [
          {required: true, message: "考试名称不能为空", trigger: "blur"}
        ],
        examYear: [
          {required: true, message: "考试年度不能为空", trigger: "blur"}
        ],
        deadline: [
          {required: true, message: "报名截止时间不能为空", trigger: "blur"}
        ],
        // time: [
        //   {required: true, message: "考试时间不能为空", trigger: "change"}
        // ],
        type: [
          {required: true, message: "测试项目不能为空", trigger: "blur"}
        ],

        projectName: [
          {required: true, message: "测试项目不能为空", trigger: "blur"}
        ],
        startTime: [
          {required: true, message: "开始时间不能为空", trigger: "blur"}
        ],
        endTime: [
          {required: true, message: "结束时间不能为空", trigger: "blur"}
        ],
        examArrange: [
          {required: true, message: "考试安排不能为空", trigger: "blur"}
        ],
        notice: [
          {required: true, message: "考试注意事项不能为空", trigger: "blur"}
        ],
      }
    };
  },
  created() {
    this.getList();
    this.getTestList()
  },
  methods: {

    /** 查询【请填写功能名称】列表 */
    getList() {
      // this.loading = false;
      this.loading = true;
      listExam(this.queryParams).then(response => {
        this.examList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    getRowId(row) {
      return row.id;  // row-key绑定的必须为唯一值
    },
    selectClose() {
      this.openSelect = false
    },
    rowClick(row) {
      this.$refs["table-project"].toggleRowSelection(row)
    },

    /**测试项目列表弹框--确定按钮*/
    selectConfirm() {
      this.form.projectIdList = this.tableSelection.map(item => item.id);
      let projectName = this.tableSelection.map(item => item.project);
      this.$set(this.form, 'projectName', projectName.join(','))
      this.$nextTick(() => {
        this.$refs["form"].validateField('projectName');
      })
      this.openSelect = false;
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        id: null,
        examName: null,
        examYear: null,
        deadline: null,
        time: null,
        startTime: null,
        endTime: null,
        examArrange: null,
        notice: null,
        status: "0",
        createTime: null,
        createBy: null,
        updateTime: null,
        updateBy: null,
      };
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    /** 多选框选中数据发生改变*/
    handleSelectionChange(selection) {
      this.tableSelection = selection
      this.ids = selection.map(item => item.id)
      this.single = selection.length !== 1
      this.multiple = !selection.length
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
      this.isHandle = false
      this.handle = "add"
      this.title = "考试新增";
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.handle = "edit"
      this.isHandle = false
      this.reset();
      const id = row.id || this.ids
      getExam(id).then(response => {
        this.form = response.data;
        this.open = true;
        this.title = "考试编辑";
        this.form.examYear = this.form.examYear + ''
      });
    },


    /** 查看按钮操作 */
    handleView(row) {
      this.isHandle = true
      this.reset();
      const id = row.id || this.ids
      getExam(id).then(response => {
        this.form = response.data;
        this.open = true;
        this.title = "查看";
        this.form.examYear = this.form.examYear.toString()
      });
    },


    /** 查询所有的测试项目列表 */
    getTestList() {
      this.loading = true;
      listProject().then(response => {
        this.projectList = response.rows;
        this.loading = false;
      });
    },
    bigDialogClose() {
      this.isFirst = true
      console.log(this.isFirst, 'isFirst')
    },

    /** 点击测试项目触发*/
    selectProjectList() {
      if (this.isHandle) return
      this.openSelect = true
      this.getTestList() //获取所有项目列表
      if (this.handle == 'add' && this.isFirst) {
        this.isFirst = false
        this.$nextTick(() => {
          this.$refs["table-project"].clearSelection()
        })
      }

      if (this.handle == 'edit') {
        this.form.projectIdList.map(item => {
          this.projectList.map(itemData => {
            if (itemData.id == item) {
              this.$nextTick(() => {
                this.$refs["table-project"].toggleRowSelection(itemData, true)
              })
            }
          });
        });
      }


    },


    /** 保存按钮 */
    submitForm() {
      this.$refs['form'].validate(valid => {
        if (valid) {
          if (this.form.id != null) {
            edit(this.form).then(response => {
              this.$modal.msgSuccess("保存修改成功");
              this.open = false;
              this.getList();
            });
          } else {
            addExam(this.form).then(response => {
              this.$modal.msgSuccess("保存新增成功");
              this.open = false;
              this.getList();
            });
          }


        }
      });
    },


    /** 发布按钮 */
    publish() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          if (this.form.id != null) {
            updateExam(this.form).then(response => {
              this.$modal.msgSuccess("发布修改成功");
              this.open = false;
              this.getList();
              this.$emit("sendStatus")
            });
          } else {
            addPub(this.form).then(response => {
              this.$modal.msgSuccess("发布新增成功");
              this.open = false;
              this.getList();
              this.$emit("sendStatus")
            });
          }
        }
      });
    },

    /** 报名流程按钮 */
    registration(row) {
      this.$router.push({
        path: '/exam/examManage/registeProcess',
        query: {
          id: row.id,
          index: row.status
        }
      })
    }
    ,
    /** 删除按钮操作 */
    handleDelete(row) {
      const ids = row.id || this.ids;
      this.$modal.confirm('是否确认删除编号为"' + ids + '"的数据项？').then(function () {
        return delExam(ids);
      }).then(() => {
        this.getList();
        this.$modal.msgSuccess("删除成功");
      }).catch(() => {
      });
    }
    ,
    /** 导出按钮操作 */
    handleExport() {
      this.download('system/exam/export', {
        ...this.queryParams
      }, `考试管理${Date.now()}.xlsx`)
    }
  }
};
</script>
