<template>
  <section class="content">
    <!-- 正文信息 -->
    <div class="part-box">
      <h2 class="part-box-title">题库列表</h2>

      <el-form class="part-filter-form" :inline="true" :model="formSearch">
        <el-form-item label="课程名称">
          <el-select
            v-model="formSearch.courseId"
            filterable
            :remote-method="getCourses"
            remote
            clearable
            placeholder="请输入"
            @clear="getCourses('')"
          >
            <el-option
              v-for="item in courseInfoSelect"
              :key="item.courseId"
              :label="item.courseInfo"
              :value="item.courseId"
            >
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="试卷名称">
          <el-input v-model="formSearch.name" placeholder="试卷名称"></el-input>
        </el-form-item>
        <el-form-item label="层次">
          <el-select v-model="formSearch.level" clearable placeholder="请选择">
            <el-option
              v-for="item in levelList"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            >
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="录入人">
          <el-input
            v-model="formSearch.creator"
            placeholder="录入人"
          ></el-input>
        </el-form-item>
        <el-form-item label="修改人">
          <el-input
            v-model="formSearch.lastModifyName"
            placeholder="修改人"
          ></el-input>
        </el-form-item>
        <el-form-item>
          <el-button type="danger" @click="searchFrom">查询</el-button>
        </el-form-item>
      </el-form>
      <div class="part-box-action">
        <div>
          <el-button
            type="primary"
            plain
            icon="icon icon-star"
            :disabled="noBatchSelected"
            @click="useBasePaper"
            >使用原卷</el-button
          >
          <el-button
            type="danger"
            plain
            icon="icon icon-delete"
            :disabled="noBatchSelected"
            @click="batchDeletePaper"
            >删除原卷</el-button
          >
        </div>
        <div>
          <el-button
            type="primary"
            plain
            icon="icon icon-import"
            @click="impPaper"
            >导入</el-button
          >
          <el-dropdown>
            <el-button type="primary" plain>
              更多 <i class="el-icon-more el-icon--right"></i>
            </el-button>
            <el-dropdown-menu slot="dropdown" class="action-dropdown">
              <el-dropdown-item>
                <el-button type="primary" plain @click="expQuesType"
                  >试题分布</el-button
                >
              </el-dropdown-item>
              <el-dropdown-item>
                <el-button type="primary" plain @click="openQuesPro"
                  >试卷属性</el-button
                >
              </el-dropdown-item>
              <el-dropdown-item>
                <el-button type="primary" plain @click="openQuesProC"
                  >课程属性</el-button
                >
              </el-dropdown-item>
            </el-dropdown-menu>
          </el-dropdown>
        </div>
      </div>
    </div>

    <div class="part-box">
      <el-table
        v-loading="loading"
        element-loading-text="拼命加载中"
        :data="tableData"
        @selection-change="selectChange"
      >
        <el-table-column
          type="selection"
          width="50"
          align="center"
        ></el-table-column>
        <el-table-column label="课程名称" width="180">
          <template slot-scope="scope">
            <span>{{ scope.row.course.name }}</span>
          </template>
        </el-table-column>
        <el-table-column label="课程代码" width="80">
          <template slot-scope="scope">
            <span>{{ scope.row.course.code }}</span>
          </template>
        </el-table-column>
        <el-table-column label="试卷名称" width="180">
          <template slot-scope="scope">
            <span>{{ scope.row.name }}</span>
          </template>
        </el-table-column>
        <el-table-column
          label="试卷总分"
          width="103"
          sortable
          prop="totalScore"
        >
        </el-table-column>
        <el-table-column
          label="大题数量"
          width="103"
          sortable
          prop="paperDetailCount"
        >
        </el-table-column>
        <el-table-column label="标准差" width="103" sortable prop="std">
        </el-table-column>
        <el-table-column label="难度" width="103" sortable prop="difficulty">
        </el-table-column>
        <el-table-column label="差异系数" width="103" sortable prop="cv">
        </el-table-column>
        <el-table-column label="信度" width="103" sortable prop="reliability">
        </el-table-column>
        <el-table-column
          label="综合曝光率"
          width="153"
          sortable
          prop="exposureRate"
        >
        </el-table-column>
        <el-table-column label="录入员" width="150">
          <template slot-scope="scope">
            <span>{{ scope.row.creator }}</span>
          </template>
        </el-table-column>
        <el-table-column
          label="创建时间"
          width="153"
          sortable
          prop="creationTime"
        >
        </el-table-column>
        <el-table-column label="修改人" width="150">
          <template slot-scope="scope">
            <span>{{ scope.row.lastModifyName }}</span>
          </template>
        </el-table-column>
        <el-table-column
          label="修改时间"
          width="153"
          sortable
          prop="updateTime"
        >
        </el-table-column>
        <el-table-column
          label="最终审核时间"
          width="153"
          sortable
          prop="lastAuditTime"
        >
        </el-table-column>
        <el-table-column label="操作" width="180" fixed="right">
          <template slot-scope="scope">
            <div class="operate_left">
              <el-button
                size="mini"
                type="primary"
                plain
                @click="editImportPaper(scope.row)"
                >编辑</el-button
              >
              <el-dropdown>
                <el-button type="primary" size="mini" plain>
                  更多 <i class="el-icon-more el-icon--right"></i>
                </el-button>
                <el-dropdown-menu slot="dropdown" class="action-dropdown">
                  <el-dropdown-item>
                    <el-button
                      size="mini"
                      type="primary"
                      plain
                      @click="copyImportPaper(scope.row)"
                      >复制</el-button
                    >
                  </el-dropdown-item>
                  <el-dropdown-item>
                    <el-button
                      size="mini"
                      type="primary"
                      plain
                      @click="exportOriginalPaper(scope.row)"
                      >下载</el-button
                    >
                  </el-dropdown-item>
                  <el-dropdown-item>
                    <el-button
                      size="mini"
                      type="primary"
                      plain
                      @click="exportPaperAnswer(scope.row)"
                      >导出答案</el-button
                    >
                  </el-dropdown-item>
                  <el-dropdown-item>
                    <el-button
                      size="mini"
                      type="danger"
                      plain
                      @click="deleteImportPaper(scope.row)"
                      >删除</el-button
                    >
                  </el-dropdown-item>
                  <el-dropdown-item>
                    <el-button
                      size="mini"
                      type="primary"
                      plain
                      @click="auditInfo(scope.row)"
                      >审核记录</el-button
                    >
                  </el-dropdown-item>
                </el-dropdown-menu>
              </el-dropdown>
            </div>
          </template>
        </el-table-column>
      </el-table>
      <div class="part-page">
        <el-pagination
          :current-page="currentPage"
          :page-size="pageSize"
          :page-sizes="[10, 20, 50, 100, 200, 300]"
          layout="total, sizes, prev, pager, next, jumper"
          :total="total"
          @current-change="handleCurrentChange"
          @size-change="handleSizeChange"
        >
        </el-pagination>
      </div>
    </div>
    <!-- 克隆试卷 -->
    <el-dialog
      v-loading.body="cloneLoading"
      title="克隆试卷"
      :visible.sync="copyPaperDialog"
      width="520px"
      :modal="false"
      append-to-body
      custom-class="side-dialog"
    >
      <el-form
        ref="copyPaperForm"
        :model="copyPaperForm"
        :rules="rules"
        label-position="right"
        label-width="120px"
        inline-message
        class="form-tight"
      >
        <el-form-item label="试卷名称" prop="paperName">
          <el-input
            v-model="copyPaperForm.paperName"
            class="dialog-input-width"
            placeholder="请输试卷名称"
          ></el-input>
        </el-form-item>
        <el-form-item label="课程名称" prop="courseId">
          <el-select
            v-model="copyPaperForm.courseId"
            class="dialog-input-width"
            :remote-method="getCourses"
            remote
            filterable
            clearable
            placeholder="全部"
            @clear="getCourses('')"
          >
            <el-option
              v-for="item in courseInfoSelect"
              :key="item.courseId"
              :label="item.courseInfo"
              :value="item.courseId"
            >
            </el-option>
          </el-select>
        </el-form-item>
      </el-form>
      <div slot="footer">
        <el-button type="primary" @click="submitCopy('copyPaperForm')"
          >保存</el-button
        >
        <el-button type="danger" plain @click="resetForm2('copyPaperForm')"
          >重置</el-button
        >
        <el-button type="danger" plain @click="back2('copyPaperForm')"
          >返回</el-button
        >
      </div>
    </el-dialog>
    <!-- 属性修改 -->
    <el-dialog
      title="属性修改"
      :visible.sync="quesPropertyDialog"
      width="500px"
      :modal="false"
      append-to-body
      custom-class="side-dialog"
    >
      <el-form :loading="quesLoading" label-position="right" label-width="80px">
        <el-form-item label="难  度">
          <el-select v-model="difficulty">
            <el-option
              v-for="item in difficultyList"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="公开度">
          <el-select v-model="publicity">
            <el-option
              v-for="item in publicityList"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            ></el-option>
          </el-select>
        </el-form-item>
      </el-form>
      <div slot="footer">
        <el-button
          v-loading.fullscreen.lock="quesLoading"
          type="primary"
          @click="submitUpdate()"
          >保存</el-button
        >
        <el-button type="danger" plain @click="resetForm">重置</el-button>
        <el-button type="danger" plain @click="closePropertyDialog"
          >返 回</el-button
        >
      </div>
    </el-dialog>
    <!-- 审核记录 -->
    <el-dialog
      title="审核记录"
      width="700"
      :visible.sync="auditInfoDialog"
      :modal="false"
      append-to-body
      custom-class="side-dialog"
    >
      <AuditInfo
        v-if="auditInfoDialog"
        :paper-id="auditInfoPaperId"
      ></AuditInfo>
    </el-dialog>
  </section>
</template>

<script>
import { QUESTION_API } from "@/constants/constants";
import { LEVEL_TYPE, PUBLICITY_LIST } from "../constants/constants";
import { mapState } from "vuex";
import AuditInfo from "./AuditInfo.vue";

export default {
  components: { AuditInfo },
  data() {
    return {
      auditInfoPaperId: null,
      auditInfoDialog: false,
      courseLoading: false,
      quesLoading: false,
      formSearch: {
        courseId: "",
        courseName: "",
        creator: "",
        lastModifyName: "",
        level: "",
        name: "",
      },
      tableData: [],
      levelList: LEVEL_TYPE,
      currentPage: 1,
      pageSize: 10,
      isClear: 0,
      total: 0,
      loading: false,
      courseList: [],
      options: [],
      selectedPaperIds: [],
      cloneLoading: false,
      copyPaperDialog: false,
      copyPaperForm: {
        paperName: "",
        courseId: null,
      },
      copyPaperId: "",
      quesPropertyDialog: false,
      difficultyDegree: 0.1,
      difficulty: "易",
      publicity: true,
      updateType: "",
      difficultyList: [
        { label: "难", value: "难" },
        { label: "中", value: "中" },
        { label: "易", value: "易" },
      ],
      publicityList: PUBLICITY_LIST,
      rules: {
        paperName: [
          { required: true, message: "请输试卷名称", trigger: "blur" },
        ],
        courseId: [
          { required: true, message: "请选择课程名称", trigger: "change" },
        ],
      },
    };
  },
  computed: {
    paperIds() {
      var paperIds = "";
      for (let paperId of this.selectedPaperIds) {
        if (!paperIds) {
          paperIds += paperId;
        } else {
          paperIds += "," + paperId;
        }
      }
      return paperIds;
    },
    courseInfoSelect() {
      var courseList = [];
      for (let course of this.courseList) {
        var courseInfo = course.name + "(" + course.code + ")";
        var courseId = course.id;
        courseList.push({ courseId: courseId, courseInfo: courseInfo });
      }
      return courseList;
    },
    noBatchSelected() {
      return this.selectedPaperIds.length === 0;
    },
    ...mapState({ user: (state) => state.user }),
  },
  watch: {
    $route: "initVue",
  },
  created() {
    this.initVue();
  },
  methods: {
    auditInfo(row) {
      this.auditInfoPaperId = row.id;
      this.auditInfoDialog = true;
    },
    searchFrom() {
      this.currentPage = 1;
      this.searchImportPaper();
    },
    searchImportPaper() {
      var pageNo = Number(this.currentPage);
      this.currentPage = 1;
      this.loading = true;
      var url = QUESTION_API + "/importPaper/" + pageNo + "/" + this.pageSize;
      this.$http.get(url, { params: this.formSearch }).then((response) => {
        this.tableData = response.data.content;
        this.total = response.data.totalElements;
        this.currentPage = pageNo;
        this.loading = false;
      });
    },
    handleCurrentChange(val) {
      this.currentPage = val;
      this.searchImportPaper();
    },
    handleSizeChange(val) {
      this.pageSize = val;
      this.currentPage = 1;
      this.searchImportPaper();
    },
    getCourseName(courseId) {
      for (let course of this.courseList) {
        if (course.code == courseId) {
          this.formSearch.courseName = course.name;
        }
      }
    },
    editImportPaper(row) {
      //缓存查询对象
      this.getCourseName(this.formSearch.courseId);
      sessionStorage.setItem("import_paper", JSON.stringify(this.formSearch));
      sessionStorage.setItem("import_paper_currentPage", this.currentPage);
      sessionStorage.setItem("question_back", "false");
      this.$router.push({
        path: "/edit_paper/" + row.id + "/import_paper",
      });
    },
    deleteImportPaper(row) {
      this.$confirm("确认删除试卷吗?", "提示", {
        type: "warning",
      }).then(() => {
        this.loading = true;
        this.$http.delete(QUESTION_API + "/paper/" + row.id).then(
          () => {
            this.$notify({
              message: "删除成功",
              type: "success",
            });
            this.searchImportPaper();
          },
          (error) => {
            this.$notify({
              message: error.response.data.desc,
              type: "error",
            });
            this.loading = false;
          }
        );
      });
    },
    selectChange(row) {
      this.selectedPaperIds = [];
      row.forEach((element) => {
        this.selectedPaperIds.push(element.id);
      });
    },
    batchDeletePaper() {
      var paperIds = this.paperIds;
      this.$confirm("确认删除试卷吗?", "提示", {
        type: "warning",
      }).then(() => {
        this.loading = true;
        this.$http.delete(QUESTION_API + "/paper/" + paperIds).then(
          () => {
            this.$notify({
              message: "删除成功",
              type: "success",
            });
            this.searchImportPaper();
            this.selectedPaperIds = [];
          },
          (error) => {
            this.$notify({
              message: error.response.data.desc,
              type: "error",
            });
            this.loading = false;
          }
        );
      });
    },
    //导入试卷
    impPaper() {
      this.$router.push({
        path: "/questions/import_paper_info",
      });
    },
    //查询所有课程
    getCourses(query) {
      this.courseLoading = true;
      this.$http
        .get(QUESTION_API + "/course/query?name=" + query + "&enable=true")
        .then((response) => {
          this.courseList = response.data;
          this.courseLoading = false;
        });
    },
    useBasePaper() {
      this.loading = true;
      this.$http
        .put(QUESTION_API + "/useBasePaper/" + this.selectedPaperIds)
        .then(
          (response) => {
            console.log("come in response:", response);
            if (!response.data.desc) {
              this.$notify({
                message: "操作成功",
                type: "success",
              });
            } else {
              this.$notify({
                message: response.data.desc,
                type: "error",
              });
            }
            this.loading = false;
          },
          (error) => {
            var message = error.response.data.desc;
            this.$notify({
              message: message,
              type: "error",
            });
            this.loading = false;
          }
        );
    },
    //克隆试卷
    copyImportPaper(row) {
      this.copyPaperForm.paperName = "";
      this.copyPaperForm.courseId = "";
      this.copyPaperId = row.id;
      this.copyPaperDialog = true;
    },
    //保存
    submitCopy(formData) {
      this.$refs[formData].validate((valid) => {
        if (valid) {
          this.cloneLoading = true;
          this.$http
            .post(
              QUESTION_API +
                "/clonePaper/" +
                this.copyPaperId +
                "?paperName=" +
                encodeURIComponent(this.copyPaperForm.paperName) +
                "&courseId=" +
                encodeURIComponent(this.copyPaperForm.courseId)
            )
            .then(() => {
              this.$notify({
                message: "复制成功",
                type: "success",
              });
              this.cloneLoading = false;
              this.copyPaperDialog = false;
              this.searchImportPaper();
            })
            .catch((error) => {
              this.$notify({
                type: "error",
                message: error.response.data.desc,
              });
              this.cloneLoading = false;
            });
        } else {
          return false;
        }
      });
    },
    removeItem() {
      sessionStorage.removeItem("import_paper");
      sessionStorage.removeItem("import_paper_currentPage");
    },
    expQuesType() {
      if (!this.formSearch.courseId) {
        this.$notify({
          title: "警告",
          message: "请输入课程",
          type: "warning",
        });
        return;
      }
      var key = this.user.key;
      var token = this.user.token;
      window.location.href =
        QUESTION_API +
        "/paper/export/course/question/" +
        this.formSearch.courseId +
        "?$key=" +
        key +
        "&$token=" +
        token;
    },
    exportOriginalPaper(row) {
      var key = this.user.key;
      var token = this.user.token;
      //window.location.href = QUESTION_API+"/originalPaper/export/"+row.id+"/"+ this.user.displayName;
      window.open(
        QUESTION_API +
          "/originalPaper/export/" +
          row.id +
          "?$key=" +
          key +
          "&$token=" +
          token
      );
    },
    exportPaperAnswer(row) {
      var key = this.user.key;
      var token = this.user.token;
      window.open(
        QUESTION_API +
          "/paper/answer/export/" +
          row.id +
          "?$key=" +
          key +
          "&$token=" +
          token
      );
    },
    openInit() {
      this.difficultyDegree = 0.1;
      this.difficulty = "易";
      this.publicity = true;
      this.quesPropertyDialog = true;
    },
    //重置
    resetForm() {
      this.difficultyDegree = 0.1;
      this.difficulty = "易";
      this.publicity = true;
    },
    resetForm2(formData) {
      this.copyPaperForm.paperName = "";
      this.copyPaperForm.courseId = "";
      this.$refs[formData].clearValidate();
    },
    back2(formData) {
      this.resetForm2(formData);
      this.copyPaperDialog = false;
    },
    //试卷修改属性 openQuesPro
    openQuesPro() {
      if (!this.selectedPaperIds || this.selectedPaperIds.length < 1) {
        this.$notify({
          title: "警告",
          message: "请选择试卷",
          type: "warning",
        });
        return;
      }
      this.updateType = "paper";
      this.openInit();
    },
    //课程修改属性 openQuesProC
    openQuesProC() {
      if (!this.formSearch.courseId) {
        this.$notify({
          title: "警告",
          message: "请输入课程",
          type: "warning",
        });
        return;
      }
      this.updateType = "course";
      this.openInit();
    },
    closePropertyDialog() {
      this.quesPropertyDialog = false;
    },
    submitUpdate() {
      console.log("aaa");
      if (this.updateType == "paper") {
        console.log("paper");
        this.updateQuesPropertyByPaper();
      }
      if (this.updateType == "course") {
        console.log("course");
        this.updateQuesPropertyByCourse();
      }
    },
    updateQuesPropertyByPaper() {
      var params = "?ids=" + this.selectedPaperIds;
      params = params + "&difficulty=" + this.difficulty;
      params = params + "&publicity=" + this.publicity;
      this.quesLoading = true;
      this.$http
        .put(QUESTION_API + "/question/updatePro/paperIds" + params)
        .then(() => {
          this.$notify({
            message: "更新成功",
            type: "success",
          });
          this.searchImportPaper();
          this.quesLoading = false;
          this.closePropertyDialog();
        })
        .catch(() => {
          this.$notify({
            type: "error",
            message: "更新失败",
          });
          this.quesLoading = false;
          this.closePropertyDialog();
        });
    },
    updateQuesPropertyByCourse() {
      this.quesLoading = true;
      var orgId = this.user.rootOrgId;
      this.$http
        .put(
          QUESTION_API +
            "/question/updatePro/courseCode/" +
            this.formSearch.courseId +
            "/" +
            this.difficulty +
            "/" +
            this.publicity +
            "/" +
            orgId
        )
        .then(() => {
          this.$notify({
            message: "更新成功",
            type: "success",
          });
          this.quesLoading = false;
          this.closePropertyDialog();
        })
        .catch(() => {
          this.$notify({
            type: "error",
            message: "更新失败",
          });
          this.quesLoading = false;
          this.closePropertyDialog();
        });
    },
    initVue() {
      this.isClear = this.$route.params.isClear;
      if (this.isClear == 0 || !this.isClear) {
        this.removeItem();
        this.formSearch = {
          courseId: "",
          level: "",
          name: "",
        };
        this.currentPage = 1;
      } else {
        this.formSearch = JSON.parse(sessionStorage.getItem("import_paper"));
        this.currentPage =
          sessionStorage.getItem("import_paper_currentPage") == null
            ? 1
            : parseInt(sessionStorage.getItem("import_paper_currentPage"));
      }
      this.getCourses(this.formSearch.courseName || "");
      this.handleCurrentChange(this.currentPage);
    },
  },
};
</script>
