<template>
  <section class="content gen-paper">
    <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="primary" @click="searchFrom">查询</el-button>
          <el-button type="danger" plain @click="resetForm">重置</el-button>
        </el-form-item>
      </el-form>
      <!-- <div class="part-box-action">
        <div>
          <el-button
            type="danger"
            plain
            icon="icon icon-delete"
            :disabled="noBatchSelected"
            @click="batchDeleteGenPaper"
            >删除成卷
          </el-button>
          <el-button
            type="danger"
            plain
            icon="icon icon-delete"
            :disabled="noBatchSelected"
            @click="recoveryPapers"
            >回收
          </el-button>
          <el-button
            type="primary"
            plain
            icon="icon icon-export"
            :disabled="noBatchSelected"
            @click="openBatchExportPaperDialog"
            >下载成卷</el-button
          >
          <el-button
            type="danger"
            plain
            icon="el-icon-delete"
            @click="toRecycle"
            >回收站</el-button
          >
        </div>
        <div>
          <el-button
            type="primary"
            icon="icon icon-plus-white"
            @click="genPaperDetail"
            >组卷</el-button
          >
        </div>
      </div> -->
    </div>
    <div class="part-box">
      <div class="icon-btn-group">
        <svg-btn name="zujuan" @click="genPaperDetail">组卷</svg-btn>
        <svg-btn
          name="daoru"
          :disabled="noBatchSelected"
          @click="openBatchExportPaperDialog"
          >下载</svg-btn
        >
        <svg-btn
          name="shanchu"
          :disabled="noBatchSelected"
          @click="batchDeleteGenPaper"
          >删除</svg-btn
        >
      </div>
      <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="difficulty"
        >
        </el-table-column>
        <el-table-column
          label="大题数量"
          width="103"
          sortable
          prop="paperDetailCount"
        >
        </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="120">
          <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="180" fixed="right">
          <template slot-scope="scope">
            <div class="operate_left">
              <el-button
                size="medium"
                type="text"
                class="normal"
                @click="editGenPaper(scope.row)"
                >编辑</el-button
              >
              <el-button
                size="medium"
                type="text"
                class="normal"
                @click="openExportDialog(scope.row)"
                >下载</el-button
              >
              <el-button
                size="medium"
                type="text"
                class="normal"
                @click="previewPDF2(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="danger"
                      plain
                      @click="recoveryPaper(scope.row)"
                    >
                      回收
                    </el-button>
                  </el-dropdown-item>
                  <el-dropdown-item>
                    <el-button
                      size="mini"
                      type="primary"
                      plain
                      @click="openExportDialog(scope.row)"
                      >下载</el-button
                    >
                  </el-dropdown-item>
                  <el-dropdown-item>
                    <el-button
                      size="mini"
                      type="primary"
                      plain
                      @click="previewPDF2(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
      title="导出"
      :visible.sync="exportDialog"
      width="600px"
      :modal="true"
      append-to-body
      custom-class="side-dialog"
    >
      <el-form :model="exportModel" label-position="right" label-width="80px">
        <el-form-item v-if="isShow" label="课程名称">
          {{ exportModel.courseName }}
        </el-form-item>
        <el-form-item v-if="isShow" label="课程代码">
          {{ exportModel.courseCode }}
        </el-form-item>
        <el-form-item label="导出内容">
          <el-radio-group
            v-model="exportModel.exportContent"
            @change="exportContentChange"
          >
            <el-radio v-if="exportModel.id" label="PAPER">试卷</el-radio>
            <el-radio v-if="exportModel.id" label="ANSWER">答案</el-radio>
            <el-radio label="THEMIS_PACKAGE">数据包</el-radio>
            <el-radio label="CARD_PACKAGE">题卡数据</el-radio>
            <el-radio label="CARD_PDF">题卡PDF</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item v-if="showSeqMode()" label="小题序号">
          <el-radio-group v-model="exportModel.seqMode" class="input">
            <!-- <el-radio label="MODE1">单题型连续</el-radio>
            <el-radio label="MODE2">客观题整体连续</el-radio> -->
            <el-radio label="MODE3">按大题独立</el-radio>
            <el-radio label="MODE5">整卷连续</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item
          v-if="exportModel.exportContent === 'PAPER'"
          label="试卷模板"
        >
          <el-select
            v-model="curPaperTemp"
            placeholder="请选择试卷模板"
            value-key="id"
            @change="paperTempChange"
          >
            <el-option
              v-for="item in paperTempList"
              :key="item.id"
              :label="item.name"
              :value="item"
            >
            </el-option>
          </el-select>
        </el-form-item>
        <!-- <el-form-item
          v-if="exportModel.exportContent === 'ANSWER'"
          label="答案模板"
        >
          <el-select
            v-model="exportModel.templateId"
            filterable
            :remote-method="getTemplates"
            remote
            clearable
            placeholder="请选择答案模板"
            @clear="getTemplates('')"
          >
            <el-option
              v-for="item in templateList"
              :key="item.id"
              :label="item.fileName"
              :value="item.id"
            >
            </el-option>
          </el-select>
        </el-form-item> -->
        <el-form-item
          v-if="exportModel.exportContent === 'ANSWER'"
          label="页数模式"
        >
          <el-radio-group v-model="pageCountMode" style="width: 160px">
            <el-radio-button label="SIMPLE">单页</el-radio-button>
            <el-radio-button label="DOUBLE">双页</el-radio-button>
          </el-radio-group>
        </el-form-item>
      </el-form>
      <paper-build-config
        v-if="exportModel.exportContent === 'PAPER'"
        ref="PaperBuildConfig"
        :config-sources="configSources"
        :show-confirm-btn="false"
      ></paper-build-config>
      <div slot="footer">
        <el-button
          type="primary"
          :loading="downloading"
          @click="exportPaperInfo"
          >开始导出</el-button
        >
      </div>
    </el-dialog>

    <!-- 试卷属性 -->
    <el-dialog
      title="属性修改"
      :visible.sync="quesPropertyDialog"
      width="500px"
      :modal="true"
      append-to-body
      custom-class="side-dialog"
    >
      <el-form :loading="quesLoading" :inline="true" label-width="100px">
        <el-form-item>
          <span slot="label">
            <el-checkbox
              v-model="difficultyDegreeDis"
              style="margin-right: 30px"
            ></el-checkbox>
            <span>难度</span>
          </span>
          <el-select
            v-model="difficulty"
            class="dialog_input_width"
            :disabled="!difficultyDegreeDis"
          >
            <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>
          <span slot="label">
            <el-checkbox
              v-model="publicityDis"
              style="margin-right: 16px"
            ></el-checkbox>
            <span>公开度</span>
          </span>
          <el-select
            v-model="publicity"
            class="dialog_input_width"
            :disabled="!publicityDis"
          >
            <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="updateQuesPropertyByPaper()"
          >保存</el-button
        >
        <el-button type="danger" plain @click="resetQuesProForm"
          >重置</el-button
        >
        <el-button type="danger" plain @click="closePropertyDialog"
          >返 回</el-button
        >
      </div>
    </el-dialog>

    <!-- paper-view-frame -->
    <div v-if="paperPreviewUrl" class="design-preview-frame">
      <iframe
        :src="paperPreviewUrl"
        frameborder="0"
        width="1000"
        height="800"
      ></iframe>
    </div>

    <div v-if="answerPreviewUrl" class="design-preview-frame">
      <iframe
        :src="answerPreviewUrl"
        frameborder="0"
        width="1000"
        height="800"
      ></iframe>
    </div>
  </section>
</template>

<script>
import PaperBuildConfig from "../../paper-export/components/PaperBuildConfig.vue";
import { QUESTION_API } from "@/constants/constants";
import { LEVEL_TYPE, PUBLICITY_LIST } from "../constants/constants";
import { mapState } from "vuex";
import { downloadByApi } from "@/plugins/download";
import {
  paperTemplateListApi,
  paperPdfDownloadApi,
  answerPdfDownloadApi,
} from "../../paper-export/api";
import { deepCopy } from "@/plugins/utils";

export default {
  components: {
    PaperBuildConfig,
  },
  data() {
    return {
      templateList: [],
      publicityDis: false,
      difficultyDegreeDis: false,
      quesLoading: false,
      quesPropertyDialog: false,
      difficultyDegree: 0.1,
      difficulty: "易",
      publicity: true,
      difficultyList: [
        { label: "难", value: "难" },
        { label: "中", value: "中" },
        { label: "易", value: "易" },
      ],
      publicityList: PUBLICITY_LIST,
      isClear: 0,
      courseLoading: false,
      formSearch: {
        courseId: "",
        courseName: "",
        creator: "",
        lastModifyName: "",
        // 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: "",
        templateId: "",
        exportContent: "",
        seqMode: "MODE3",
      },
      pageCountMode: "SIMPLE",
      isShow: true,
      examList: [],
      dialogModel: false,
      rowIds: [],
      isShowPrintExamPackage: false,
      isShowPrintExamPackagePassword: false,
      printExamPackagePassword: "",
      printFrom: {
        examId: "",
      },
      rules: {
        examId: [{ required: true, message: "请输入名称", trigger: "change" }],
      },
      // pdf download
      paperPreviewUrl: "",
      answerPreviewUrl: "",
      downloading: false,
      curPaperTemp: null,
      paperTempList: [],
      configSources: [],
      configModalForm: {},
    };
  },
  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;
        var courseName = course.name;
        courseList.push({
          courseId: courseId,
          courseInfo: courseInfo,
          courseName: courseName,
        });
      }
      return courseList;
    },
    noBatchSelected() {
      return this.selectedPaperIds.length === 0;
    },
    ...mapState({ user: (state) => state.user }),
  },
  watch: {
    $route: "initVue",
  },
  created() {
    this.initVue();
    this.registWindowSubmit();
  },
  beforeDestroy() {
    delete window.submitPaperTemp;
  },
  methods: {
    exportContentChange(val) {
      if (val === "PAPER") {
        this.getPaperTempList();
        return;
      }
      if (val === "ANSWER") {
        this.getTemplates("");
        return;
      }
    },
    getTemplates(name) {
      this.exportModel.templateId = "";
      var url = QUESTION_API + "/exportTemplate/page/1/20";
      let type;
      if (this.exportModel.exportContent == "PAPER") {
        type = "PAPER_EXPORT";
      } else if (this.exportModel.exportContent == "ANSWER") {
        type = "ANSWER_EXPORT";
      } else {
        return;
      }
      let params = {
        rootOrgId: this.user.rootOrgId,
        fileName: name,
        enable: true,
        type: type,
      };
      this.$httpWithMsg.get(url, { params: params }).then((response) => {
        this.templateList = response.data.content;
      });
    },
    recoveryPaper(row) {
      this.$confirm("确认回收试卷吗?", "提示", {
        type: "warning",
      }).then(() => {
        this.loading = true;
        this.$http.put(QUESTION_API + "/paper_storage/recovery/" + row.id).then(
          () => {
            this.$notify({
              message: "操作成功",
              type: "success",
            });
            this.searchGenPaper();
          },
          (response) => {
            this.$notify({
              message: response.response.data.desc,
              type: "error",
            });
            this.loading = false;
          }
        );
      });
    },
    recoveryPapers() {
      var paperIds = this.paperIds;
      if (this.selectedPaperIds.length != 0) {
        this.$confirm("确认回收试卷吗?", "提示", {
          type: "warning",
        }).then(() => {
          this.loading = true;
          this.$http
            .put(QUESTION_API + "/paper_storage/recovery/" + paperIds)
            .then(
              () => {
                this.$notify({
                  message: "操作成功",
                  type: "success",
                });
                this.selectedPaperIds = [];
                this.searchGenPaper();
              },
              (response) => {
                this.$notify({
                  message: response.response.data.desc,
                  type: "error",
                });
                this.loading = false;
              }
            );
        });
      } else {
        this.$notify({
          message: "请勾选回收的试卷",
          type: "warning",
        });
      }
    },
    showSeqMode() {
      let element = this.exportModel.exportContent;
      if (element == "PAPER" || element == "ANSWER") {
        return true;
      }
      return false;
    },
    updateQuesPropertyByPaper() {
      if (!this.difficultyDegreeDis && !this.publicityDis) {
        this.$notify({
          title: "警告",
          message: "请勾选难度或公开度",
          type: "warning",
        });
        return;
      }
      var params = "?ids=" + this.selectedPaperIds;
      if (this.difficultyDegreeDis) {
        params = params + "&difficulty=" + this.difficulty;
      }
      if (this.publicityDis) {
        params = params + "&publicity=" + this.publicity;
      }
      this.quesLoading = true;
      this.$httpWithMsg
        .put(QUESTION_API + "/question/updatePro/paperIds" + params)
        .then(() => {
          this.$notify({
            message: "更新成功",
            type: "success",
          });
          this.searchGenPaper();
          this.quesLoading = false;
          this.closePropertyDialog();
        })
        .catch(() => {
          this.quesLoading = false;
        });
    },
    openQuesPro() {
      if (!this.selectedPaperIds || this.selectedPaperIds.length < 1) {
        this.$notify({
          title: "警告",
          message: "请选择试卷",
          type: "warning",
        });
        return;
      }
      this.difficultyDegree = 0.1;
      this.difficulty = "易";
      this.publicity = true;
      this.quesPropertyDialog = true;
    },
    closePropertyDialog() {
      this.quesPropertyDialog = false;
    },
    resetQuesProForm() {
      this.difficultyDegree = 0.1;
      this.difficulty = "易";
      this.publicity = true;
    },
    resetForm() {
      this.formSearch = {
        courseId: "",
        courseName: "",
        // level: "",
        name: "",
      };
    },
    //查询
    searchFrom() {
      this.currentPage = 1;
      this.searchGenPaper();
    },
    searchGenPaper() {
      var pageNo = this.currentPage;
      this.currentPage = 1;
      this.loading = true;
      var url = QUESTION_API + "/genPaper/" + pageNo + "/" + this.pageSize;
      this.$http.get(url, { params: this.formSearch }).then((response) => {
        this.tableData = response.data.content;
        this.total = response.data.totalElements;
        this.currentPage = Number(pageNo);
      });
      this.loading = false;
    },
    genPaperDetail() {
      var courseId = this.formSearch.courseId;
      if (!courseId) {
        this.$notify({
          title: "警告",
          message: "请选择课程",
          type: "warning",
        });
      } else {
        let genPaperData = { ...this.formSearch };
        var course = this.getCourseObj(this.formSearch.courseId);
        if (course) {
          genPaperData.courseName = course.name;
          genPaperData.courseCode = course.code;
        }
        sessionStorage.setItem("gen_paper", JSON.stringify(genPaperData));
        sessionStorage.setItem("gen_paper_currentPage", this.currentPage);
        this.$router.push({
          name: "gen_paper_detail",
          params: { courseId: courseId },
        });
      }
    },
    handleCurrentChange(val) {
      this.currentPage = val;
      this.searchGenPaper();
    },
    handleSizeChange(val) {
      this.pageSize = val;
      this.currentPage = 1;
      this.searchGenPaper();
    },
    getCourseObj(courseId) {
      for (let course of this.courseList) {
        if (course.id == courseId) {
          return course;
        }
      }
      return "";
    },
    editGenPaper(row) {
      var course = this.getCourseObj(this.formSearch.courseId);
      if (course) {
        this.formSearch.courseName = course.name;
      }
      sessionStorage.setItem("gen_paper", JSON.stringify(this.formSearch));
      sessionStorage.setItem("gen_paper_currentPage", this.currentPage);
      sessionStorage.setItem("question_back", "false");
      this.$router.push({
        path: "/edit_paper/" + row.id + "/gen_paper",
      });
    },
    deleteGenPaper(row) {
      this.$confirm("确认删除试卷吗?", "提示", {
        type: "warning",
      }).then(() => {
        this.loading = true;
        this.$http.delete(QUESTION_API + "/paper/" + row.id).then(
          () => {
            this.$notify({
              message: "删除成功",
              type: "success",
            });
            this.searchGenPaper();
          },
          (response) => {
            this.$notify({
              message: response.response.data.desc,
              type: "error",
            });
            this.loading = false;
          }
        );
      });
    },
    selectChange(row) {
      this.selectedPaperIds = [];
      row.forEach((element) => {
        this.selectedPaperIds.push(element.id);
      });
    },
    batchDeleteGenPaper() {
      var paperIds = this.paperIds;
      if (this.selectedPaperIds.length != 0) {
        this.$confirm("确认删除试卷吗?", "提示", {
          type: "warning",
        }).then(() => {
          this.loading = true;
          this.$http.delete(QUESTION_API + "/paper/" + paperIds).then(
            () => {
              this.$notify({
                message: "删除成功",
                type: "success",
              });
              this.searchGenPaper();
              this.selectedPaperIds = [];
            },
            (response) => {
              this.$notify({
                message: response.response.data.desc,
                type: "error",
              });
              this.loading = false;
            }
          );
        });
      } else {
        this.$notify({
          message: "请勾选删除的数据",
          type: "warning",
        });
      }
    },
    //查询所有课程
    getCourses(query) {
      if (query) {
        query = query.trim();
      }
      this.courseLoading = true;
      this.$http
        .get(QUESTION_API + "/course/query?name=" + query + "&enable=true")
        .then((response) => {
          this.courseList = response.data;
          this.courseLoading = false;
        });
    },
    //打开导出弹框
    openExportDialog(row) {
      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.exportContent = "";
      this.exportModel.templateId = "";
      /* 分布式印刷数据包设置 */
      this.isShowPrintExamPackage = true;
      this.isShowPrintExamPackagePassword = false;
      this.printExamPackagePassword = "";
    },
    //打开批量弹出框
    openBatchExportPaperDialog() {
      if (this.selectedPaperIds.length != 0) {
        this.exportDialog = true;
        this.isShow = false;
        this.exportModel.exportContent = "";
        this.exportModel.templateId = "";
        // 多于两个试卷时候，将无法导出试卷。todo
        if (this.selectedPaperIds.length === 1) {
          this.exportModel.id = this.selectedPaperIds[0];
        } else {
          this.exportModel.id = "";
        }
      } else {
        this.$notify({
          message: "请勾选导出的数据",
          type: "warning",
        });
      }
      /* 分布式印刷数据包设置 */
      this.isShowPrintExamPackage = false;
      this.isShowPrintExamPackagePassword = false;
      this.printExamPackagePassword = "";
    },
    //导出试卷，答案，机考数据包
    async exportPaperInfo() {
      // 下载pdf
      if (this.exportModel.exportContent === "PAPER") {
        if (!this.curPaperTemp) {
          this.$notify({
            message: "请选择试卷模板",
            type: "error",
          });
          return;
        }
        this.toDownloadPaperPdf();
        return;
      }
      if (this.exportModel.exportContent === "ANSWER") {
        // if (!this.exportModel.templateId) {
        //   this.$notify({
        //     message: "请选择答案模板",
        //     type: "error",
        //   });
        //   return;
        // }
        this.toDownloadAnswerPdf();
        return;
      }

      if (
        !this.exportModel.exportContent ||
        this.exportModel.exportContent == ""
      ) {
        this.$notify({
          message: "请选择导出内容",
          type: "error",
        });
        return false;
      }
      let element = this.exportModel.exportContent;
      if (
        (element == "PAPER" || element == "ANSWER") &&
        !this.exportModel.templateId
      ) {
        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;
        }
      }

      if (this.downloading) return;
      this.downloading = true;
      const params = {
        psw: this.printExamPackagePassword,
        seqMode: this.exportModel.seqMode,
        templateId: this.exportModel.templateId,
      };
      let url = "";
      if (this.isShow) {
        url = `${QUESTION_API}/paper/export/${this.exportModel.id}/${this.exportModel.exportContent}/onLine`;
      } else {
        url = `${QUESTION_API}/paper/batch_export/${this.paperIds}/${this.exportModel.exportContent}/onLine`;
      }
      const res = await downloadByApi(() => {
        return this.$httpWithMsg.get(url, {
          params,
          responseType: "blob",
        });
      }).catch((e) => {
        this.$message.error(e || "下载失败，请重新尝试！");
      });

      this.exportDialog = false;
      this.downloading = false;

      if (!res) return;
      this.$message.success("下载成功！");
    },
    removeItem() {
      sessionStorage.removeItem("gen_paper");
      sessionStorage.removeItem("gen_paper_currentPage");
    },
    previewPDF2(row) {
      window.open(
        this.getRouterPath({
          name: "PaperTemplateBuild",
          params: {
            paperId: row.id,
          },
        })
      );
    },
    toRecycle() {
      this.$router.push({
        name: "PaperRecycle",
      });
    },
    initVue() {
      this.isClear = this.$route.params.isClear;
      if (this.isClear == 0 || !this.isClear) {
        this.removeItem();
        this.formSearch = {
          courseId: "",
          courseName: "",
          // level: "",
          name: "",
        };
        this.currentPage = 1;
      } else {
        this.formSearch = JSON.parse(sessionStorage.getItem("gen_paper"));
        this.currentPage =
          sessionStorage.getItem("gen_paper_currentPage") == null
            ? 1
            : parseInt(sessionStorage.getItem("gen_paper_currentPage"));
      }
      this.getCourses(this.formSearch.courseName);
      this.searchGenPaper();
    },
    // download paper pdf
    async getPaperTempList() {
      if (this.paperTempList.length) return;
      const res = await paperTemplateListApi("PAPER_EXPORT");
      this.paperTempList = res.data;
    },
    paperTempChange(paperTemp) {
      // console.log(paperTemp);
      let paperTempJson = paperTemp.content
        ? JSON.parse(paperTemp.content)
        : { pages: [], pageConfig: {} };
      this.getConfigSources(paperTempJson.pages);
    },
    getConfigSources(pages) {
      let sources = [],
        fieldAble = {};
      pages.forEach((page) => {
        page.columns.forEach((column) => {
          column.elements.forEach((element) => {
            if (element.type !== "PAPER_PROPS") return;
            if (!sources.length) {
              sources = deepCopy(element.props);
            }
            element.props.forEach((prop) => {
              fieldAble[prop.field] = fieldAble[prop.field] || prop.enable;
            });
          });
        });
      });

      sources.forEach((item) => {
        item.enable = fieldAble[item.field];
      });
      this.configSources = sources;
    },
    async toDownloadPaperPdf() {
      const valid = await this.$refs.PaperBuildConfig.checkData().catch(
        () => {}
      );
      if (!valid) return;

      if (this.downloading) return;
      this.downloading = true;

      const configModalForm = this.$refs.PaperBuildConfig.getData();
      window.paperSet = {
        paperTemp: this.curPaperTemp,
        seqMode: this.exportModel.seqMode,
        configModalForm,
      };
      console.log("window.paperSet", window.paperSet);
      const { href } = this.$router.resolve({
        name: "PaperTemplateBuild",
        params: {
          paperId: this.exportModel.id,
          viewType: "frame",
        },
        query: {
          t: Date.now(),
        },
      });

      // console.log(href);
      this.paperPreviewUrl = href;
    },
    toDownloadAnswerPdf() {
      if (this.downloading) return;
      this.downloading = true;
      window.answerSet = {
        // answerTemplateId: this.exportModel.templateId,
        pageCountMode: this.pageCountMode,
        seqMode: this.exportModel.seqMode,
      };
      const { href } = this.$router.resolve({
        name: "AnswerTemplateBuild",
        params: {
          paperId: this.exportModel.id,
          viewType: "frame",
        },
        query: {
          t: Date.now(),
        },
      });
      this.answerPreviewUrl = href;
    },
    registWindowSubmit() {
      window.submitPaperTemp = async ({
        success,
        errorMsg,
        htmlCont,
        templateId,
      }) => {
        if (!success) {
          this.downloading = false;
          if (templateId) {
            delete window.paperSet;
            this.paperPreviewUrl = "";
          } else {
            delete window.answerSet;
            this.answerPreviewUrl = "";
          }

          this.$message.error(errorMsg);
          this.exportDialog = false;
          return;
        }
        // this.paperPreviewUrl = "";
        if (templateId) {
          const res = await downloadByApi(() => {
            return paperPdfDownloadApi({
              content: htmlCont,
              templateId,
              paperId: this.exportModel.id,
            });
          }).catch((e) => {
            this.$message.error(e || "下载失败，请重新尝试！");
          });
          this.exportDialog = false;
          this.downloading = false;

          if (!res) return;
          this.$message.success("下载成功！");
          delete window.paperSet;
        } else {
          const res = await downloadByApi(() => {
            return answerPdfDownloadApi({
              content: htmlCont,
              size: "A4",
              paperId: this.exportModel.id,
            });
          }).catch((e) => {
            this.$message.error(e || "下载失败，请重新尝试！");
          });
          this.exportDialog = false;
          this.downloading = false;

          if (!res) return;
          this.$message.success("下载成功！");
          delete window.answerSet;
        }
      };
    },
  },
};
</script>
