<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="subjectWarehouseClassId">
        <el-select v-model="queryParams.subjectWarehouseClassId" placeholder="请选择模拟考试" clearable>
          <el-option v-for="dict in subjectWarehouseClassList" :key="dict.subjectWarehouseClassId" :label="dict.name"
            :value="dict.subjectWarehouseClassId" />
        </el-select>
      </el-form-item>
      <el-form-item label="考试" prop="examId">
        <el-select v-model="queryParams.examId" placeholder="请选择考试" clearable>
          <el-option v-for="dict in examList" :key="dict.examId" :label="dict.name" :value="dict.examId" />
        </el-select>
      </el-form-item>
      <el-form-item label="等级" prop="level">
        <el-select v-model="queryParams.level" placeholder="请选择等级" clearable>
          <el-option v-for="dict in dict.type.tb_subject_level" :key="dict.value" :label="dict.label"
            :value="dict.value" />
        </el-select>
      </el-form-item>
      <el-form-item label="题目" prop="question">
        <el-input v-model="queryParams.question" placeholder="请输入题目" clearable @keyup.enter.native="handleQuery" />
      </el-form-item>
      <el-form-item label="题目类型" prop="subjectType">
        <el-select v-model="queryParams.subjectType" placeholder="请选择题目类型" clearable>
          <el-option v-for="dict in dict.type.tb_subject_type" :key="dict.value" :label="dict.label"
            :value="dict.value" />
        </el-select>
      </el-form-item>
      <el-form-item label="状态" prop="status">
        <el-select v-model="queryParams.status" placeholder="请选择状态" clearable>
          <el-option v-for="dict in dict.type.tb_status" :key="dict.value" :label="dict.label" :value="dict.value" />
        </el-select>
      </el-form-item>
      <el-form-item label="创建时间">
        <el-date-picker v-model="daterangeCreateTime" style="width: 240px"
                        value-format="yyyy-MM-dd HH:mm:ss" type="daterange"
                        :default-time="['00:00:00', '23:59:59']"
                        range-separator="-" start-placeholder="开始日期" end-placeholder="结束日期" />
      </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"
          v-hasPermi="['hezhi:examSubject:add']">新增</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="['hezhi:examSubject: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="['hezhi:examSubject: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="['hezhi:examSubject:export']">导出</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="info" icon="el-icon-upload2" size="mini" @click="handleImport">导入</el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="examSubjectList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="考试题目编号" align="center" prop="examSubjectId" width="100px">
        <template slot-scope="scope">
          <tooltip :contentName="scope.row.examSubjectId" />
        </template>
      </el-table-column>
      <!--      <el-table-column label="分类ID" align="center" prop="classId" />-->
      <!--      <el-table-column label="分类名" align="center" prop="className" />-->
      <!--      <el-table-column label="专业ID" align="center" prop="majorId" />-->
      <!--      <el-table-column label="题库" align="center" prop="subjectWarehouseClassName" width="180px" />-->
      <!--      <el-table-column label="专业" align="center" prop="majorName" />-->
      <el-table-column label="类型" align="center" prop="examType" width="120px">
        <template slot-scope="scope">
          <span v-if="scope.row.examType ? scope.row.examType.includes('0') : false">考试</span>
          <span v-if="scope.row.examType ? scope.row.examType.includes(['0', '1']) : false">、</span>
          <span v-if="scope.row.examType ? scope.row.examType.includes('1') : false">模拟考试</span>
        </template>
      </el-table-column>
      <el-table-column label="等级" align="center" prop="level" width="100px">
        <template slot-scope="scope">
          <dict-tag :options="dict.type.tb_subject_level" :value="scope.row.level" />
        </template>
      </el-table-column>
      <el-table-column label="题目" align="center" prop="question" width="120px">
        <template slot-scope="scope">
          <tooltip :contentName="scope.row.question" />
        </template>
      </el-table-column>
      <!--      <el-table-column label="文件" align="center" prop="fileUrl" width="100">-->
      <!--        <template slot-scope="scope">-->
      <!--          <image-preview :src="scope.row.fileUrl" :width="50" :height="50"/>-->
      <!--        </template>-->
      <!--      </el-table-column>-->
      <!--      <el-table-column label="文件类型" align="center" prop="fileType" />-->
      <el-table-column label="题目类型" align="center" prop="subjectType" width="100px">
        <template slot-scope="scope">
          <dict-tag :options="dict.type.tb_subject_type" :value="scope.row.subjectType" />
        </template>
      </el-table-column>
      <!--      <el-table-column label="是否精选" align="center" prop="isSelected" />-->
      <!--      <el-table-column label="答案ID集合" align="center" prop="answerIds" />-->
      <el-table-column label="答案" align="center" prop="answer" :show-overflow-tooltip="true" width="100px" />
      <!--      <el-table-column label="试题详解" align="center" prop="subjectExplain" />-->
      <el-table-column label="分数" align="center" prop="score" width="100px" />
      <!--      <el-table-column label="等级" align="center" prop="level" />-->
      <!--      <el-table-column label="类型" align="center" prop="type" />-->
      <!--      <el-table-column label="审核状态" align="center" prop="examineStatus">-->
      <!--        <template slot-scope="scope">-->
      <!--          <dict-tag :options="dict.type.tb_examine_status" :value="scope.row.examineStatus"/>-->
      <!--        </template>-->
      <!--      </el-table-column>-->
      <!--      <el-table-column label="审核反馈" align="center" prop="examineFeedback" />-->
      <!--      <el-table-column label="排序" align="center" prop="sort" />-->
      <!--      <el-table-column label="备注" align="center" prop="remarks" />-->
      <el-table-column label="状态" align="center" prop="status">
        <template slot-scope="scope">
          <dict-tag :options="dict.type.tb_status" :value="scope.row.status" />
        </template>
      </el-table-column>
      <el-table-column label="创建时间" align="center" prop="createTime" width="150" show-overflow-tooltip />
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width" fixed="right">
        <template slot-scope="scope">
          <el-button size="mini" type="text" icon="el-icon-edit" @click="handleUpdate(scope.row)"
            v-hasPermi="['hezhi:examSubject:edit']">修改</el-button>
          <el-button size="mini" type="text" icon="el-icon-delete" @click="handleDelete(scope.row)"
            v-hasPermi="['hezhi:examSubject:remove']">删除</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="800px" append-to-body destroy-on-close>
      <el-form ref="form" :model="form" :rules="rules" label-width="100px">
        <el-form-item label="类型" prop="examType">
          <el-checkbox-group v-model="form.examType">
            <el-checkbox v-for="(item, index) in examTypeOptions" :key="index" :label="item.value">{{ item.label
            }}</el-checkbox>
          </el-checkbox-group>
        </el-form-item>
        <el-form-item label="模拟考试" prop="subjectWarehouseClassId" v-if="form.examType.indexOf('1') != -1">
          <el-select v-model="form.subjectWarehouseClassId" placeholder="请选择模拟考试" clearable>
            <el-option v-for="dict in subjectWarehouseClassList" :key="dict.subjectWarehouseClassId" :label="dict.name"
              :value="dict.subjectWarehouseClassId" />
          </el-select>
        </el-form-item>
        <el-form-item label="考试" prop="examId" v-if="form.examType.indexOf('0') != -1">
          <el-select v-model="form.examId" placeholder="请选择考试" clearable>
            <el-option v-for="dict in examList" :key="dict.examId" :label="dict.name" :value="dict.examId" />
          </el-select>
        </el-form-item>
        <el-form-item label="等级" prop="level">
          <el-select v-model="form.level" placeholder="请选择等级">
            <el-option v-for="dict in dict.type.tb_subject_level" :key="dict.value" :label="dict.label"
              :value="parseInt(dict.value)"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="题目" prop="question">
          <el-input v-model="form.question" placeholder="请输入题目" />
        </el-form-item>
        <el-form-item label="是否有图片">
          <el-radio-group v-model="form.fileType">
            <el-radio :label="0">否</el-radio>
            <el-radio :label="1">是</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="图片" prop="fileUrl" v-if="this.form.fileType === 1">
          <image-upload v-model="form.fileUrl" />
        </el-form-item>
        <el-form-item label="题目类型" prop="subjectType">
          <el-select v-model="form.subjectType" placeholder="请选择题目类型" @change="setScoreChange">
            <el-option v-for="dict in dict.type.tb_subject_type" :key="dict.value" :label="dict.label"
              :value="parseInt(dict.value)"></el-option>
          </el-select>
        </el-form-item>

        <el-form-item label="选项" v-if="this.form.subjectType !== 3">
          <subject-answer :exam-subject-answer-list="examSubjectAnswerList"
            @getExamSubjectAnswerList="setExamSubjectAnswerList" :subject-type="this.form.subjectType" />
        </el-form-item>

        <!--        <el-form-item label="答案ID集合" prop="answerIds">-->
        <!--          <el-input v-model="form.answerIds" placeholder="请输入答案ID集合" />-->
        <!--        </el-form-item>-->
        <!--        <el-form-item label="答案" prop="answer">-->
        <!--          <el-input v-model="form.answer" placeholder="请输入答案" />-->
        <!--        </el-form-item>-->
        <el-form-item label="试题详解" prop="subjectExplain">
          <el-input v-model="form.subjectExplain" type="textarea" placeholder="请输入内容" />
        </el-form-item>
        <el-form-item label="分数" prop="score">
          <el-input v-model="form.score" type="number" placeholder="请输入分数" />
        </el-form-item>
        <div style="color: red;margin-left: 92px;
    margin-top: -20px;">注：该分数为参考分数，实际分数以【考试-设置考试信息】为准</div>
        <el-form-item label="判断题答案" v-if="this.form.subjectType === 3">
          <el-radio-group v-model="form.answer">
            <el-radio label="正确">正确</el-radio>
            <el-radio label="错误">错误</el-radio>
          </el-radio-group>
        </el-form-item>
        <!--        <el-form-item label="等级" prop="level">-->
        <!--          <el-input v-model="form.level" placeholder="请输入等级" />-->
        <!--        </el-form-item>-->
        <el-form-item label="状态" prop="status">
          <el-radio-group v-model="form.status">
            <el-radio v-for="dict in dict.type.tb_status" :key="dict.value" :label="parseInt(dict.value)">{{ dict.label
            }}</el-radio>
          </el-radio-group>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>

    <!-- 用户导入对话框 -->
    <el-dialog :title="upload.title" :visible.sync="upload.open" width="750px">
      <el-form ref="form" :model="upload" label-width="100px">
        <el-form-item label="" prop="">
          <el-button type="primary" @click="importTemplate">下载模板</el-button>
        </el-form-item>
        <el-form-item label="上传文件">
          <el-upload ref="upload" :limit="1" accept=".xlsx" :headers="upload.headers"
            :action="upload.url + '?dateTime=' + upload.dateTime" :disabled="upload.isUploading"
            :on-progress="handleFileUploadProgress" :on-success="handleFileSuccess" :auto-upload="false" drag>
            <i class="el-icon-upload"></i>
            <div class="el-upload__text">
              将文件拖到此处，或
              <em>点击上传</em>
            </div>
            <div class="el-upload__tip" style="color:red" slot="tip">提示：仅允许导入“xls”或“xlsx”格式文件！</div>
          </el-upload>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitFileForm">确 定</el-button>
        <el-button @click="upload.open = false">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { listExamSubject, getExamSubject, delExamSubject, addExamSubject, updateExamSubject } from "@/api/hezhi/examSubject";
import subjectAnswer from "@/views/hezhi/examSubject/subjectAnswer";
import { getTbMajorClassTreeList } from "@/api/hezhi/majorClass";
import { listTeacher } from "@/api/hezhi/teacher";
import { getAllExamList } from "@/api/hezhi/exam";
import { getAllSubjectWarehouseCalssList } from "@/api/hezhi/subjectWarehouseClass";
import { selectDictLabel } from "../../../utils/ruoyi";
import { getToken } from "@/utils/auth";

export default {
  name: "ExamSubject",
  dicts: ['tb_examine_status', 'tb_subject_type', 'tb_status', 'tb_subject_level'],
  components: {
    subjectAnswer,
  },
  data() {
    return {
      // 用户导入参数
      upload: {
        // 是否显示弹出层（用户导入）
        open: false,
        // 弹出层标题（用户导入）
        title: "",
        // 是否禁用上传
        isUploading: false,
        // 是否更新已经存在的用户数据
        dateTime: null,
        // 设置上传的请求头部
        headers: { Authorization: "Bearer " + getToken() },
        // 上传的地址
        url: process.env.VUE_APP_BASE_API + "/hezhi/examSubject/importData"
      },

      majorClassTreeConfig: {
        checkStrictly: true,
        emitPath: false
      },
      // 选项列表
      examSubjectAnswerList: [],
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 考试题目表格数据
      examSubjectList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 删除标记时间范围
      daterangeCreateTime: [],
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        subjectWarehouseClassId: null,
        classId: null,
        className: null,
        majorId: null,
        majorName: null,
        question: null,
        fileType: null,
        subjectType: null,
        isSelected: null,
        answerIds: null,
        answer: null,
        subjectExplain: null,
        score: null,
        level: null,
        type: null,
        examineStatus: null,
        examineFeedback: null,
        sort: null,
        remarks: null,
        status: null,
        createTime: null,
        deleteTime: null,
        deleteBy: null,
      },
      // 表单参数
      form: {
        examType: [],
      },
      // 表单校验
      rules: {
        // subjectWarehouseClassId: [
        //   { required: true, message: "请选择题库", trigger: "change" }
        // ],
        examType: [
          { required: true, message: "类型不能为空", trigger: "change" }
        ],
        examId: [
          { required: true, message: "考试不能为空", trigger: "change" }
        ],
        subjectWarehouseClassId: [
          { required: true, message: "模拟考试不能为空", trigger: "change" }
        ],
        level: [
          { required: true, message: "等级不能为空", trigger: "change" }
        ],
        question: [
          { required: true, message: "题目不能为空", trigger: "blur" }
        ],
        score: [
          { required: true, message: "分数不能为空", trigger: "blur" }
        ],
      },
      examTypeOptions: [
        {
          label: '模拟考试',
          value: '1'
        },
        {
          label: '考试',
          value: '0'
        },
      ],
      subjectWarehouseClassList: [],
      examList: [],
    };
  },
  created() {
    this.getList();
    getAllSubjectWarehouseCalssList().then(response => {
      console.log(response)
      this.subjectWarehouseClassList = response.data;
    });
    getAllExamList().then(res => {
      this.examList = res.data
    })
  },
  methods: {
    selectDictLabel,
    /** 选择题目类型触发 */
    setScoreChange() {
      // 题目类型（1-单选，2-多选，3-判断，4-论述）
      const subjectType = this.form.subjectType
      if (subjectType === 1) {
        this.form.score = 2;
      }
      if (subjectType === 2) {
        this.form.score = 4;
      }
      if (subjectType === 3) {
        this.form.score = 1;
      }
      if (subjectType === 4) {
        this.form.score = 10;
      }
    },

    // 选项列表
    setExamSubjectAnswerList(examSubjectAnswerList) {
      this.examSubjectAnswerList = examSubjectAnswerList
    },

    /** 查询考试题目列表 */
    getList() {
      this.loading = true;
      if (this.queryParams.majorId != null) {
        let majorIds = this.queryParams.majorId

        if (majorIds.length !== undefined) {
          this.queryParams.majorId = majorIds[majorIds.length - 1]
        }
      }
      this.queryParams.params = {};
      if (null != this.daterangeCreateTime && '' != this.daterangeCreateTime) {
        this.queryParams.params["beginCreateTime"] = this.daterangeCreateTime[0];
        this.queryParams.params["endCreateTime"] = this.daterangeCreateTime[1];
      }
      listExamSubject(this.queryParams).then(response => {
        this.examSubjectList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        examSubjectId: null,
        examType: [],
        examId: null,
        subjectWarehouseClassId: null,
        classId: null,
        className: null,
        majorId: null,
        majorName: null,
        question: null,
        fileUrl: null,
        fileType: 0,
        subjectType: 1,
        isSelected: null,
        answerIds: null,
        answer: '正确',
        subjectExplain: null,
        score: 2,
        level: null,
        type: null,
        examineStatus: 1,
        examineFeedback: null,
        sort: null,
        remarks: null,
        status: 0,
        publicationTime: null,
        publisher: null,
        createTime: null,
        createBy: null,
        updateTime: null,
        updateBy: null,
        deleteTime: null,
        deleteBy: null,
        delFlag: null
      };
      this.examSubjectAnswerList = [];
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.daterangeCreateTime = [];
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.examSubjectId)
      this.single = selection.length !== 1
      this.multiple = !selection.length
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
      this.title = "添加考试题目";
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      const examSubjectId = row.examSubjectId || this.ids
      getExamSubject(examSubjectId).then(response => {
        this.form = response.data;

        if (this.form.examType) {
          this.form.examType = this.form.examType.split(',');
        } else {
          this.form.examType = [];
        }

        if (this.form.examSubjectAnswerList) {
          this.examSubjectAnswerList = this.form.examSubjectAnswerList
        }

        this.open = true;
        this.title = "修改考试题目";
      });
    },
    /** 提交按钮 */
    submitForm() {
      if (this.form.majorId != null) {
        let majorIds = this.form.majorId
        this.form.majorId = majorIds[majorIds.length - 1]
      }
      this.form.examSubjectAnswerList = this.examSubjectAnswerList
      this.$refs["form"].validate(valid => {
        if (valid) {
          if (this.form.examType && this.form.examType instanceof Array) {
            this.form.examType = this.form.examType.join(',');
          } else {
            this.form.examType = '';
          }
          if (this.form.examSubjectId != null) {
            updateExamSubject(this.form).then(response => {
              this.$modal.msgSuccess("修改成功");
              this.open = false;
              this.examSubjectAnswerList = []
              this.getList();
            }).catch(error => {
              // 错误处理：恢复examType为数组
              if (this.form.examType) {
                this.form.examType = this.form.examType.split(',');
              } else {
                this.form.examType = [];
              }
            });;
          } else {
            addExamSubject(this.form).then(response => {
              this.$modal.msgSuccess("新增成功");
              this.open = false;
              this.examSubjectAnswerList = []
              this.getList();
            }).catch(error => {
              // 错误处理：恢复examType为数组
              if (this.form.examType) {
                this.form.examType = this.form.examType.split(',');
              } else {
                this.form.examType = [];
              }
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const examSubjectIds = row.examSubjectId || this.ids;
      this.$modal.confirm('是否确认删除考试题目编号为"' + examSubjectIds + '"的数据项？').then(function () {
        return delExamSubject(examSubjectIds);
      }).then(() => {
        this.getList();
        this.$modal.msgSuccess("删除成功");
      }).catch(() => { });
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download('hezhi/examSubject/export', {
        ...this.queryParams
      }, `考试题目导出.xlsx`)
    },
    /** 导入按钮操作 */
    handleImport() {
      this.upload.title = "考试题目导入";
      this.upload.dateTime = null;
      this.upload.open = true;
    },
    /** 下载模板操作 */
    importTemplate() {
      this.download('/hezhi/examSubject/importTemplate', {}, `考试题目导入模板.xlsx`)
    },
    // 文件上传中处理
    handleFileUploadProgress(event, file, fileList) {
      this.upload.isUploading = true;
    },
    // 文件上传成功处理
    handleFileSuccess(response, file, fileList) {
      this.upload.open = false;
      this.upload.isUploading = false;
      this.$refs.upload.clearFiles();
      this.$alert(response.msg, "导入结果", { dangerouslyUseHTMLString: true });
      this.getList();
    },
    // 提交上传文件
    submitFileForm() {
      this.$refs.upload.submit();
    }
  }
};
</script>
