<template>
  <div>
    <section class="content">
      <div class="box box-info">
        <div class="box-header with-border">
          <h3 class="box-title">考试试卷管理</h3>
        </div>
        <div class="box-body">
          <el-form
            :inline="true"
            :model="formSearch"
            label-position="right"
            label-width="110px"
          >
            <el-form-item label="课程名称" class="pull-left">
              <el-select
                v-model="formSearch.courseNo"
                :remote-method="getCourses"
                :loading="courseLoading"
                remote
                filterable
                clearable
                placeholder="全部"
              >
                <el-option
                  v-for="item in courseInfoSelect"
                  :label="item.courseInfo"
                  :value="item.courseNo"
                  :key="item.courseNo"
                >
                </el-option>
              </el-select>
            </el-form-item>
            <el-form-item label="试卷名称" class="pull-left">
              <el-input
                v-model="formSearch.name"
                placeholder="试卷名称"
              ></el-input>
            </el-form-item>
            <el-form-item label="层次" class="pull-left">
              <el-select v-model="formSearch.level">
                <el-option label="请选择" value=""> </el-option>
                <el-option
                  v-for="item in levelList"
                  :label="item.label"
                  :value="item.value"
                  :key="item.value"
                >
                </el-option>
              </el-select>
            </el-form-item>
            <el-form-item class="pull-right">
              <el-button
                size="small"
                type="primary"
                icon="search"
                @click="searchGenPaper"
                >查询</el-button
              >
              <el-button
                size="small"
                type="primary"
                icon="plus"
                @click="genPaperDetail"
                >组卷</el-button
              >
              <el-button
                size="small"
                type="danger"
                icon="delete"
                @click="batchDeleteGenPaper"
                >批量删除
              </el-button>
              <el-button
                size="small"
                type="primary"
                icon="upload2"
                @click="openBatchExportPaperDialog"
              >
                批量导出
              </el-button>
            </el-form-item>
          </el-form>
          <el-table
            v-loading="loading"
            element-loading-text="拼命加载中"
            :data="tableData"
            border
            style="width: 100%"
            @selection-change="selectChange"
          >
            <el-table-column type="selection" width="55"></el-table-column>
            <el-table-column label="课程名称" width="150">
              <template slot-scope="scope">
                <div>
                  <span>{{ scope.row.course.name }}</span>
                </div>
              </template>
            </el-table-column>
            <el-table-column label="课程代码" width="120">
              <template slot-scope="scope">
                <div>
                  <span>{{ scope.row.course.code }}</span>
                </div>
              </template>
            </el-table-column>
            <el-table-column label="试卷名称" width="150">
              <template slot-scope="scope">
                <div>
                  <span>{{ scope.row.name }}</span>
                </div>
              </template>
            </el-table-column>
            <el-table-column label="试卷总分" width="100">
              <template slot-scope="scope">
                <div>
                  <span>{{ scope.row.totalScore }}</span>
                </div>
              </template>
            </el-table-column>
            <el-table-column label="试卷难度" width="100">
              <template slot-scope="scope">
                <div>
                  <span>{{ scope.row.difficultyDegree }}</span>
                </div>
              </template>
            </el-table-column>
            <el-table-column label="大题数量" width="100">
              <template slot-scope="scope">
                <div>
                  <span>{{ scope.row.paperDetailCount }}</span>
                </div>
              </template>
            </el-table-column>
            <el-table-column label="录入员" width="100">
              <template slot-scope="scope">
                <div>
                  <span>{{ scope.row.creator }}</span>
                </div>
              </template>
            </el-table-column>
            <el-table-column label="创建时间" width="120">
              <template slot-scope="scope">
                <div>
                  <span>{{ scope.row.createTime }}</span>
                </div>
              </template>
            </el-table-column>
            <el-table-column label="最后修改人" width="120">
              <template slot-scope="scope">
                <div>
                  <span>{{ scope.row.lastModifyName }}</span>
                </div>
              </template>
            </el-table-column>
            <el-table-column label="操作" width="330">
              <template slot-scope="scope">
                <div>
                  <el-button
                    @click="openExportDialog(scope.row);"
                    type="success"
                    size="mini"
                    >导出</el-button
                  >
                  <el-button
                    @click="editGenPaper(scope.row);"
                    type="info"
                    size="mini"
                    >编辑</el-button
                  >
                  <el-button
                    @click="deleteGenPaper(scope.row);"
                    type="danger"
                    size="mini"
                    >删除</el-button
                  >
                  <el-button
                    @click="previewPDF2(scope.row);"
                    type="warning"
                    size="mini"
                    >预览PDF</el-button
                  >
                  <el-button
                    @click="openPrint(scope.row);"
                    type="warning"
                    size="mini"
                    >传至印刷</el-button
                  >
                </div>
              </template>
            </el-table-column>
          </el-table>
          <div class="page pull-right">
            <el-pagination
              @current-change="handleCurrentChange"
              :current-page="currentPage"
              :page-size="pageSize"
              layout="total, prev, pager, next, jumper"
              :total="total"
            >
            </el-pagination>
          </div>
        </div>
      </div>
      <el-dialog title="导出" :visible.sync="exportDialog">
        <el-form :model="exportModel" label-position="right" label-width="80px">
          <el-row v-if="isShow">
            <el-col :md="12">
              <el-form-item label="课程名称">
                {{ exportModel.courseName }}
              </el-form-item>
            </el-col>
          </el-row>
          <el-row v-if="isShow">
            <el-col :md="12">
              <el-form-item label="课程代码">
                {{ exportModel.courseCode }}
              </el-form-item>
            </el-col>
          </el-row>
          <el-row>
            <el-col :md="24">
              <el-form-item label="导出内容">
                <el-checkbox-group v-model="exportModel.exportContentList">
                  <el-checkbox label="PAPER">试卷</el-checkbox>
                  <el-checkbox label="ANSWER">答案</el-checkbox>
                  <el-checkbox label="COMPUTERTEST_PACKAGE"
                    >机考数据包</el-checkbox
                  >
                  <el-checkbox
                    v-if="isShowPrintExamPackage"
                    label="PRINT_EXAM_PACKAGE"
                    >分布式印刷数据包
                  </el-checkbox>
                  <el-input
                    v-if="isShowPrintExamPackagePassword"
                    v-model="printExamPackagePassword"
                    placeholder="加密密码 (可选)"
                    type="password"
                    style="width: 150px"
                  ></el-input>
                </el-checkbox-group>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row>
            <el-col :md="24" class="text-center">
              <el-button type="primary" @click="exportPaperInfo"
                >开始导出</el-button
              >
            </el-col>
          </el-row>
        </el-form>
      </el-dialog>

      <el-dialog title="传送印刷平台" v-model="dialogModel">
        <el-form>
          <el-row>
            <el-form-item label="学校名称" label-width="120px">
              <el-input v-model="this.Org.name" :disabled="true"></el-input>
            </el-form-item>
          </el-row>
          <el-row>
            <el-form-item label="考试名称" label-width="120px">
              <el-select
                v-model="examId"
                filterable
                clearable
                :remote-method="getExams"
                remote
                placeholder="请选择"
              >
                <el-option
                  v-for="item in examList"
                  :label="item.name"
                  :value="item.id"
                  :key="item.id"
                ></el-option>
              </el-select>
            </el-form-item>
          </el-row>
        </el-form>
        <div slot="footer" class="dialog-footer">
          <el-button @click="cancel">取 消</el-button>
          <el-button type="primary" @click="sendPrint">确 定</el-button>
        </div>
      </el-dialog>
    </section>
  </div>
</template>

<script>
import {
  CORE_API,
  EXAM_WORK_API,
  LEVEL_TYPE,
  Q_API
} from "../constants/constants";
import { mapState } from "vuex";
export default {
  data() {
    return {
      isClear: 0,
      courseLoading: false,
      formSearch: {
        courseNo: "",
        courseName: "",
        level: "",
        name: ""
      },
      tableData: [],
      currentPage: 1,
      pageSize: 10,
      total: 0,
      loading: false,
      courseList: [],
      levelList: LEVEL_TYPE,
      dialogVisible: false,
      selectedPaperIds: [],
      fileList: [],
      uploadAction: "",
      formUpload: {
        paperName: ""
      },
      uploadData: {},
      fileLoading: false,
      exportDialog: false,
      exportModel: {
        id: "",
        courseCode: "",
        courseName: "",
        exportContentList: []
      },
      isShow: true,
      examList: [],
      Org: {},
      dialogModel: false,
      examId: "",
      rowId: "",
      isShowPrintExamPackage: false,
      isShowPrintExamPackagePassword: false,
      printExamPackagePassword: ""
    };
  },
  methods: {
    searchGenPaper() {
      this.loading = true;
      var url = Q_API + "/genPaper/" + this.currentPage + "/" + this.pageSize;
      this.$http.get(url, { params: this.formSearch }).then(response => {
        this.tableData = response.data.content;
        this.total = response.data.totalElements;
      });
      this.loading = false;
    },
    genPaperDetail() {
      var courseNo = this.formSearch.courseNo;
      this.getCourseName(courseNo);
      var courseName = this.formSearch.courseName;
      var level = this.formSearch.level;
      if (!courseNo) {
        this.$notify({
          message: "请选择课程",
          type: "error"
        });
      } else {
        sessionStorage.setItem("gen_paper_courseNo", this.formSearch.courseNo);
        sessionStorage.setItem("gen_paper_name", this.formSearch.name);
        sessionStorage.setItem(
          "gen_paper_specialtyNo",
          this.formSearch.specialtyNo
        );
        sessionStorage.setItem("gen_paper_currentPage", this.currentPage);
        sessionStorage.setItem("gen_paper_courseName", courseName);
        this.$router.push({
          path: "/questions/gen_paper_detail/" + courseNo + "/" + level
        });
      }
    },
    handleCurrentChange(val) {
      this.currentPage = val;
      this.searchGenPaper();
    },
    getCourseName(courseNo) {
      for (let course of this.courseList) {
        if (course.code == courseNo) {
          this.formSearch.courseName = course.name;
          this.formSearch.level = course.level;
          console.log(course.level);
        }
      }
    },
    exportGenPaper(row) {
      window.open(
        Q_API + "/paper/export/" + row.id + "/" + this.user.rootOrgName
      );
    },
    editGenPaper(row) {
      sessionStorage.setItem("gen_paper_courseNo", this.formSearch.courseNo);
      sessionStorage.setItem("gen_paper_name", this.formSearch.name);
      sessionStorage.setItem(
        "gen_paper_specialtyNo",
        this.formSearch.specialtyNo
      );
      sessionStorage.setItem("gen_paper_currentPage", this.currentPage);
      this.$router.push({ path: "/edit_paper/" + row.id + "/gen_paper" });
    },
    deleteGenPaper(row) {
      this.$confirm("确认删除试卷吗?", "提示", {
        type: "warning"
      }).then(() => {
        this.loading = true;
        this.$http.delete(Q_API + "/paper/" + row.id).then(
          () => {
            this.$notify({
              message: "删除成功",
              type: "success"
            });
            this.searchGenPaper();
          },
          response => {
            this.$notify({
              message: response.data.msg,
              type: "error"
            });
            this.loading = false;
          }
        );
      });
    },
    selectChange(row) {
      this.selectedPaperIds = [];
      row.forEach(element => {
        this.selectedPaperIds.push(element.id);
      });
    },
    batchDeleteGenPaper() {
      var paperIds = this.paperIds;
      console.log("试卷id：", paperIds);
      if (this.selectedPaperIds.length != 0) {
        this.$confirm("确认删除试卷吗?", "提示", {
          type: "warning"
        }).then(() => {
          this.loading = true;
          this.$http.delete(Q_API + "/paper/" + paperIds).then(
            () => {
              this.$notify({
                message: "删除成功",
                type: "success"
              });
              this.searchGenPaper();
              this.selectedPaperIds = [];
            },
            response => {
              this.$notify({
                message: response.data.msg,
                type: "error"
              });
              this.loading = false;
            }
          );
        });
      } else {
        this.$notify({
          message: "请勾选删除的数据",
          type: "warning"
        });
      }
    },
    //查询所有课程
    getCourses(query) {
      query = query.trim();
      if (query) {
        if (!(query.indexOf("(") > -1 && query.indexOf(")") > -1)) {
          this.courseLoading = true;
          this.$http
            .get(CORE_API + "/course/query?name=" + query + "&enable=true")
            .then(response => {
              this.courseList = response.data;
              this.courseLoading = false;
            });
        }
      } else {
        this.courseList = [];
      }
    },
    //打开导出弹框
    openExportDialog(row) {
      this.isShow = true;
      this.isShow = true;
      this.exportDialog = true;
      this.exportModel.id = row.id;
      this.exportModel.courseCode = row.course.code;
      this.exportModel.courseName = row.course.name;
      this.exportModel.exportContentList = [];
      /* 分布式印刷数据包设置 */
      this.isShowPrintExamPackage = true;
      this.isShowPrintExamPackagePassword = false;
      this.printExamPackagePassword = "";
    },
    //打开批量弹出框
    openBatchExportPaperDialog() {
      if (this.selectedPaperIds.length != 0) {
        this.exportDialog = true;
        this.isShow = false;
        this.isShow = false;
        this.exportModel.exportContentList = [];
      } else {
        this.$notify({
          message: "请勾选导出的数据",
          type: "warning"
        });
      }
      /* 分布式印刷数据包设置 */
      this.isShowPrintExamPackage = false;
      this.isShowPrintExamPackagePassword = false;
      this.printExamPackagePassword = "";
    },
    //导出试卷，答案，机考数据包
    exportPaperInfo() {
      if (this.exportModel.exportContentList.length == 0) {
        this.$notify({
          message: "请选择导出内容",
          type: "error"
        });
        return false;
      }
      if (this.printExamPackagePassword.length > 0) {
        var reg = /^[0-9A-Za-z]{6,12}$/;
        if (!reg.test(this.printExamPackagePassword)) {
          this.$notify({
            message: "加密密码请输入6至12位的数字或字母！",
            type: "error"
          });
          return false;
        }
      }
      var key = this.user.key;
      var token = this.user.token;
      if (this.isShow) {
        console.log("单个导出");
        window.location.href =
          Q_API +
          "/paper/export/" +
          this.exportModel.id +
          "/" +
          this.exportModel.exportContentList +
          "/" +
          this.user.rootOrgName +
          "/" +
          this.user.displayName +
          "/onLine" +
          "?psw=" +
          this.printExamPackagePassword +
          "&$key=" +
          key +
          "&$token=" +
          token;
        this.exportDialog = false;
      } else {
        console.log("批量导出");
        var paperIds = this.paperIds;
        console.log(paperIds);
        window.location.href =
          Q_API +
          "/paper/batch_export/" +
          paperIds +
          "/" +
          this.exportModel.exportContentList +
          "/" +
          this.user.rootOrgName +
          "/" +
          this.user.displayName +
          "/onLine" +
          "?$key=" +
          key +
          "&$token=" +
          token;
        this.exportDialog = false;
        console.log(paperIds);
      }
    },
    removeItem() {
      sessionStorage.removeItem("gen_paper_courseNo");
      sessionStorage.removeItem("gen_paper_name");
      sessionStorage.removeItem("gen_paper_specialtyNo");
      sessionStorage.removeItem("gen_paper_currentPage");
    },
    previewPDF2(row) {
      window.open(Q_API + "/paper/pdf/" + row.id);
    },
    openPrint(row) {
      this.dialogModel = true;
      this.examId = "";
      this.rowId = row.id;
      console.log("this.examList:", this.examList);
    },
    cancel() {
      this.dialogModel = false;
    },
    //传至印刷模块
    sendPrint() {
      var orgId = "";
      for (let exam of this.examList) {
        if ((exam.id = this.examId)) {
          orgId = exam.rootOrgId;
        }
      }
      if (orgId != "") {
        this.$http.get(
          Q_API + "/sendPrint/" + this.rowId + "/" + this.examId + "/" + orgId
        );
        this.$notify({
          message: "已推送",
          type: "success"
        });
        this.dialogModel = false;
      }
    },
    //查询考试
    getExams(query) {
      query = query.trim();
      this.$http
        .get(
          EXAM_WORK_API + "/exam/queryByNameLike?name=" + query + "&enable=true"
        )
        .then(response => {
          this.examList = response.data;
        });
    },
    searchExamList() {
      //查询所有考试
      this.$http
        .get(EXAM_WORK_API + "/exam/queryByNameLike?name=&enable=true")
        .then(response => {
          var list = response.data;
          for (var i = 0; i < list.length; i++) {
            if (list[i].examType == "TRADITION") {
              this.examList.push(list[i]);
            }
          }
        });
    },
    //根据orgId查询学校名称
    searchOrgName() {
      this.$http
        .get(CORE_API + "/org/rootOrg/" + this.user.rootOrgId)
        .then(response => {
          this.Org = response.data;
        });
    }
  },
  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 courseNo = course.code;
        var courseName = course.name;
        courseList.push({
          courseNo: courseNo,
          courseInfo: courseInfo,
          courseName: courseName
        });
      }
      return courseList;
    },
    ...mapState({ user: state => state.user })
  },
  created() {
    this.isClear = this.$route.params.isClear;
    if (this.isClear == 0 || !this.isClear) {
      this.removeItem();
    } else {
      this.formSearch.courseNo =
        sessionStorage.getItem("gen_paper_courseNo") == "null"
          ? ""
          : sessionStorage.getItem("gen_paper_courseNo");
      this.formSearch.specialtyNo =
        sessionStorage.getItem("gen_paper_specialtyNo") == "null"
          ? ""
          : sessionStorage.getItem("gen_paper_specialtyNo");
      this.formSearch.name =
        sessionStorage.getItem("gen_paper_name") == "null"
          ? ""
          : sessionStorage.getItem("gen_paper_name");
      this.currentPage =
        sessionStorage.getItem("gen_paper_currentPage") == null
          ? 1
          : parseInt(sessionStorage.getItem("gen_paper_currentPage"));
    }
    this.searchGenPaper();
    this.searchExamList();
    this.searchOrgName();
  }
};
</script>
