<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="全部"
            @change="courseChange"
            @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.paperName"
            placeholder="试卷标题"
          ></el-input>
        </el-form-item>
        <!-- <el-form-item label="录入人">
          <el-input
            v-model="formSearch.creationBy"
            placeholder="录入人"
          ></el-input>
        </el-form-item> -->
        <el-form-item label="修改人">
          <el-input
            v-model="formSearch.updateBy"
            placeholder="修改人"
          ></el-input>
        </el-form-item>
        <el-form-item>
          <el-button type="danger" @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="primary"
            plain
            icon="icon icon-export"
            :disabled="noBatchSelected"
            @click="openBatchExportPaperDialog"
            >下载成卷</el-button
          >
        </div>
        <el-button
          type="primary"
          icon="icon icon-plus-white"
          @click="toBuildPaper"
          >综合组卷</el-button
        >
      </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.courseName }}</span>
          </template>
        </el-table-column>
        <el-table-column label="业务课代码" width="100">
          <template slot-scope="scope">
            <span>{{ scope.row.courseCode }}</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="153"
          sortable
          prop="creationTime"
        >
        </el-table-column>
        <el-table-column label="修改人" width="150" prop="updateUser">
        </el-table-column>
        <el-table-column
          label="修改时间"
          width="153"
          sortable
          prop="updateTime"
        >
        </el-table-column>
        <el-table-column label="操作" width="220" fixed="right">
          <template slot-scope="scope">
            <div class="operate_left">
              <el-dropdown>
                <el-button size="mini" type="primary" plain>编辑</el-button>
                <el-dropdown-menu slot="dropdown" class="action-dropdown">
                  <el-dropdown-item
                    v-for="paper in scope.row.papers"
                    :key="paper.paperId"
                  >
                    <el-button
                      size="mini"
                      type="primary"
                      plain
                      @click="toEditPaper(paper)"
                      >{{ paper.paperName }}</el-button
                    >
                  </el-dropdown-item>
                </el-dropdown-menu>
              </el-dropdown>
              <el-button
                size="mini"
                type="primary"
                plain
                @click="toViewPaper(scope.row)"
                >预览</el-button
              >
              <el-button
                size="mini"
                type="primary"
                plain
                @click="openExportDialog(scope.row)"
                >下载</el-button
              >
            </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="700px"
      :modal="false"
      append-to-body
      custom-class="side-dialog"
    >
      <el-form :model="exportModel" label-position="right" label-width="100px">
        <el-form-item v-if="exportModel.courseName" label="业务课名称">
          {{ exportModel.courseName }}
        </el-form-item>
        <el-form-item v-if="exportModel.courseCode" label="业务课代码">
          {{ exportModel.courseCode }}
        </el-form-item>
        <el-form-item label="导出内容">
          <el-radio-group
            v-model="exportModel.exportContent"
            @change="getTemplates('')"
          >
            <el-radio label="PAPER">试卷</el-radio>
            <el-radio label="ANSWER">答案</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="showSeqMode" 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>
      <div slot="footer">
        <el-button type="primary" @click="exportPaperInfo">开始导出</el-button>
      </div>
    </el-dialog>
  </section>
</template>

<script>
import { mapState } from "vuex";
import {
  courseQueryApi,
  synthesizePaperPageListApi,
  synthesizePaperDeleteApi,
  synthesizePaperDownloadApi,
} from "../api";
import { downloadByApi } from "@/plugins/download";
import { QUESTION_API } from "@/constants/constants";

export default {
  data() {
    return {
      templateList: [],
      courseLoading: false,
      formSearch: {
        courseId: "",
        courseName: "",
        creationBy: "",
        updateBy: "",
        paperName: "",
      },
      tableData: [],
      currentPage: 1,
      pageSize: 10,
      total: 0,
      loading: false,
      courseList: [],
      selectedPaperIds: [],
      exportDialog: false,
      exportModel: {
        id: "",
        courseCode: "",
        courseName: "",
        templateId: "",
        exportContent: "",
        seqMode: "MODE1",
      },
    };
  },
  computed: {
    courseInfoSelect() {
      var courseList = [];
      for (let course of this.courseList) {
        var courseInfo = course.name + "(" + course.code + ")";
        var courseId = course.id;
        var courseName = courseName;
        courseList.push({
          courseId: courseId,
          courseInfo: courseInfo,
          courseName: courseName,
        });
      }
      return courseList;
    },
    noBatchSelected() {
      return this.selectedPaperIds.length === 0;
    },
    showSeqMode() {
      return (
        this.exportModel.exportContent == "PAPER" ||
        this.exportModel.exportContent == "ANSWER"
      );
    },
    ...mapState({ user: (state) => state.user }),
  },
  created() {
    this.initData();
  },
  methods: {
    getTemplates(name) {
      this.exportModel.templateId = "";
      var url = QUESTION_API + "/exportTemplate/page/1/20";
      let type;
      if (this.exportModel.exportContent == "PAPER") {
        type = "SYNTHESIZE_PAPER_EXPORT";
      } else if (this.exportModel.exportContent == "ANSWER") {
        type = "SYNTHESIZE_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;
      });
    },
    async getCourses(query) {
      this.courseLoading = true;
      query = query && query.trim();
      const res = await courseQueryApi(query, "true");
      this.courseList = res.data || [];
      this.courseLoading = false;
    },
    courseChange() {
      const course = this.courseList.find(
        (item) => item.id === this.formSearch.courseId
      );
      if (course) {
        this.formSearch.courseName = course.name;
      }
    },
    resetForm() {
      this.formSearch = {
        courseId: "",
        courseName: "",
        creationBy: "",
        updateBy: "",
        name: "",
      };
    },
    //查询
    searchFrom() {
      this.currentPage = 1;
      this.searchGenPaper();
    },
    async searchGenPaper() {
      this.loading = true;
      const datas = {
        ...this.formSearch,
        pageNumber: this.currentPage,
        pageSize: this.pageSize,
      };
      const res = await synthesizePaperPageListApi(datas).catch(() => {});
      this.loading = false;

      if (!res) return;
      this.tableData = res.data.content;
      this.total = res.data.totalElements;
    },
    handleCurrentChange(val) {
      this.currentPage = val;
      this.searchGenPaper();
    },
    handleSizeChange(val) {
      this.pageSize = val;
      this.currentPage = 1;
      this.searchGenPaper();
    },
    selectChange(row) {
      this.selectedPaperIds = row.map((item) => item.id);
    },
    toViewPaper(row) {
      var key = this.user.key;
      var token = this.user.token;
      window.open(
        QUESTION_API +
          "/synthesize/paper/preview?synthesizePaperId=" +
          row.id +
          "&$key=" +
          key +
          "&$token=" +
          token
      );
    },
    toEditPaper(paper) {
      this.cacheSearchInfo();
      this.$router.push({
        path: "/edit_paper/" + paper.paperId + "/synthesis_paper_storage",
      });
    },
    openExportDialog(row) {
      this.exportModel.id = row.id;
      this.exportModel.courseCode = row.courseCode;
      this.exportModel.courseName = row.courseName;
      this.exportModel.exportContent = "";
      this.exportModel.templateId = "";

      this.exportDialog = true;
    },
    toBuildPaper() {
      this.cacheSearchInfo();
      this.$router.push({ name: "SynthesisPaper" });
    },
    // batch action
    async batchDeleteGenPaper() {
      if (!this.selectedPaperIds.length) {
        this.$notify({
          message: "请勾选删除的数据",
          type: "warning",
        });
        return;
      }

      const confirm = await this.$confirm("确认删除试卷吗?", "提示", {
        type: "warning",
      }).catch(() => {});
      if (confirm !== "confirm") return;

      const res = await synthesizePaperDeleteApi(this.selectedPaperIds).catch(
        (error) => {
          this.$notify({
            message: error.response.data.desc,
            type: "error",
          });
        }
      );

      if (!res) return;
      this.$notify({
        message: "删除成功",
        type: "success",
      });

      this.searchGenPaper();
      this.selectedPaperIds = [];
    },
    openBatchExportPaperDialog() {
      if (!this.selectedPaperIds.length) {
        this.$notify({
          message: "请勾选数据",
          type: "warning",
        });
        return;
      }

      this.exportModel = {
        id: "",
        courseCode: "",
        courseName: "",
        templateId: "",
        exportContent: "",
        seqMode: "MODE1",
      };
      this.exportDialog = true;
    },
    //导出试卷，答案，机考数据包
    async exportPaperInfo() {
      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;
      }

      let synthesizePaperIds =
        this.selectedPaperIds.join() || this.exportModel.id;
      const exportContent = this.exportModel.exportContent;
      this.exportDialog = false;

      const res = await downloadByApi(() => {
        return synthesizePaperDownloadApi({
          exportContent,
          synthesizePaperIds,
          seqMode: this.exportModel.seqMode,
          templateId: this.exportModel.templateId,
        });
      }).catch((e) => {
        this.$message.error(e || "下载失败，请重新尝试！");
      });
      this.downloading = false;

      if (!res) return;
      this.$message.success("下载成功！");
    },
    // init
    initData() {
      const cacheInfo = window.sessionStorage.getItem("synthesis-paper");
      if (cacheInfo) {
        const { currentPage, pageSize, formSearch } = JSON.parse(cacheInfo);
        this.formSearch = { ...formSearch };
        this.currentPage = currentPage;
        this.pageSize = pageSize;
        this.handleCurrentChange(this.currentPage);
        window.sessionStorage.removeItem("synthesis-paper");
      } else {
        this.handleCurrentChange(1);
      }

      this.getCourses(this.formSearch.courseName);
    },
    cacheSearchInfo() {
      window.sessionStorage.setItem(
        "synthesis-paper",
        JSON.stringify({
          formSearch: this.formSearch,
          currentPage: this.currentPage,
          pageSize: this.pageSize,
        })
      );
    },
  },
};
</script>
