<template>
  <div class="course-document-detail">
    <el-dialog
      class="page-dialog"
      :visible.sync="modalIsShow"
      :close-on-click-modal="false"
      :close-on-press-escape="false"
      top="20px"
      append-to-body
      width="750px"
      @opened="getList"
    >
      <div slot="title">
        文档详情
        <span class="color-gray ml-2"
          >{{ course.courseName }}（{{ course.courseCode }}）</span
        >
      </div>
      <div class="box-justify mb-2">
        <div>
          <el-button
            type="primary"
            :loading="bloading"
            icon="el-icon-download"
            @click="toBatchDownload"
            >批量下载</el-button
          >
        </div>
        <div>
          <el-button
            v-if="checkPrivilege('button', 'add')"
            type="primary"
            icon="el-icon-circle-plus-outline"
            @click="toAdd"
            >新建文档</el-button
          >
        </div>
      </div>
      <div class="part-box part-box-pad">
        <el-table :data="dataList">
          <el-table-column
            type="index"
            label="序号"
            width="70"
          ></el-table-column>
          <el-table-column prop="name" label="材料名称"></el-table-column>
          <el-table-column
            prop="fileCount"
            label="数量"
            width="80"
          ></el-table-column>
          <el-table-column
            class-name="action-column"
            label="操作"
            width="120px"
            align="right"
            fixed="right"
          >
            <template slot-scope="scope">
              <upload-button
                v-if="checkUpload(scope.row)"
                btn-content="上传"
                btn-type="text"
                btn-class="btn-primary"
                :upload-url="uploadUrl"
                :upload-data="{ id: scope.row.id }"
                :format="format"
                style="margin: 0"
                @valid-error="validError"
                @upload-success="uploadSuccess"
              >
              </upload-button>
              <el-button
                v-if="checkView(scope.row)"
                class="btn-primary"
                type="text"
                @click="toView(scope.row)"
                >查看</el-button
              >
              <el-button
                v-if="checkDelete(scope.row)"
                class="btn-danger"
                type="text"
                @click="toDelete(scope.row)"
                >删除</el-button
              >
              <el-button
                v-if="checkDownload(scope.row)"
                class="btn-primary"
                type="text"
                :disabled="downloading"
                @click="toDownload(scope.row)"
                >下载</el-button
              >
              <el-button
                v-if="checkDownloadUrl(scope.row)"
                class="btn-primary"
                type="text"
                @click="toDownloadUrl(scope.row)"
                >下载</el-button
              >
            </template>
          </el-table-column>
        </el-table>
      </div>

      <div class="tips-markedness">
        <p v-if="toolUrl">
          学生答卷原图和轨迹图请先下载工具后登录账号再进行下载
          <a class="btn-link ml-2" :href="toolUrl" download>点击下载工具</a>
        </p>
      </div>

      <div slot="footer"></div>
    </el-dialog>

    <!-- AddDocumentDialog -->
    <add-document-dialog
      ref="AddDocumentDialog"
      :course="course"
      @modified="getList"
    ></add-document-dialog>
    <!-- ScoreReportPreview -->
    <score-report-preview
      ref="ScoreReportPreview"
      :instance="reportParams"
    ></score-report-preview>
    <!-- PaperApproveTable -->
    <paper-approve-table
      :instance="course"
      ref="PaperApproveTable"
    ></paper-approve-table>
    <!-- paper view -->
    <el-dialog
      class="paper-view-dialog"
      :visible.sync="paperViewDialogVisible"
      title="请选择卷型"
      top="10vh"
      width="300px"
      :close-on-click-modal="false"
      :close-on-press-escape="false"
      append-to-body
    >
      <div class="text-center">
        <el-button
          v-for="item in papers"
          :key="item.name"
          type="primary"
          size="large"
          @click="toViewUrl(item.url)"
          >{{ item.name }}</el-button
        >
      </div>
      <div slot="footer"></div>
    </el-dialog>
  </div>
</template>

<script>
import { downloadByApi } from "@/plugins/download";
import { toolInfo } from "@/modules/admin/api";
import {
  documentListPage,
  documentDownload,
  documentDelete,
  documentBatchDownload,
} from "../api";
import AddDocumentDialog from "./AddDocumentDialog.vue";
import UploadButton from "@/components/UploadButton.vue";
import ScoreReportPreview from "@/modules/mark/components/ScoreReportPreview.vue";
import PaperApproveTable from "@/modules/exam/components/PaperApproveTable.vue";

/*
SYLLABUS("课程教学大纲", 1),
PROCESS_SCORE("过程考核成绩", 2),
PAPER("试卷样卷", 3),
ANSWER("试卷评阅标准", 4),
PAPER_REPORT("试卷分析报告", 5),
APPROVE_RECORD("试卷审批记录", 6),
SCORE("学生期末考试成绩单", 7),
SCORE_REPORT("学生期末考试成绩分析", 8),
SHEET("学生答卷原图", 9),
TRACK("学生答卷轨迹图", 10),
SIGN("期末考试签到表", 11),
CHECK_IN("期考考试考场记录单", 12),
CUSTOM("自定义", 13),
*/

export default {
  name: "course-document-detail",
  components: {
    AddDocumentDialog,
    UploadButton,
    ScoreReportPreview,
    PaperApproveTable,
  },
  props: {
    course: {
      type: Object,
      default() {
        return {};
      },
    },
  },
  data() {
    return {
      modalIsShow: false,
      dataList: [],
      curRow: {},
      downloading: false,
      uploadUrl: "/api/admin/mark/archive/document/import",
      reportParams: {},
      curExamTask: {},
      format: ["docx", "doc", "xlsx", "xls", "pdf", "jpg", "png", "zip"],
      toolUrl: "",
      bloading: false,
      // paper view
      paperViewDialogVisible: false,
      papers: [],
    };
  },
  mounted() {
    this.getToolInfo();
  },
  methods: {
    async getToolInfo() {
      const res = await toolInfo();
      const info = res || {};
      this.toolUrl = info.url || "";
    },
    cancel() {
      this.modalIsShow = false;
    },
    open() {
      this.modalIsShow = true;
    },
    checkView(row) {
      return ["PAPER", "ANSWER", "APPROVE_RECORD", "SCORE_REPORT"].includes(
        row.type
      );
    },
    checkDelete(row) {
      return ["CUSTOM"].includes(row.type);
    },
    checkUpload(row) {
      return ["SYLLABUS", "PROCESS_SCORE", "PAPER_REPORT", "CHECK_IN"].includes(
        row.type
      );
    },
    checkDownload(row) {
      return ["SCORE", "SHEET", "TRACK", "SIGN"].includes(row.type);
    },
    checkDownloadUrl(row) {
      return [
        "SYLLABUS",
        "PROCESS_SCORE",
        "PAPER_REPORT",
        "CHECK_IN",
        "CUSTOM",
      ].includes(row.type);
    },
    async getList() {
      const datas = {
        examId: this.course.examId,
        paperNumber: this.course.paperNumber,
      };
      const res = await documentListPage(datas);
      this.dataList = res || [];
    },
    toView(row) {
      // 试卷样卷
      if (row.type === "PAPER") {
        const filePath = row.filePath ? JSON.parse(row.filePath) : [];
        if (!filePath.length) {
          this.$message.error("当前无文档可查看");
          return;
        }

        if (filePath.length === 1) {
          window.open(filePath[0]);
          return;
        }

        this.papers = [
          { name: "A", url: filePath[0] },
          { name: "B", url: filePath[1] },
        ];
        this.paperViewDialogVisible = true;
        return;
      }
      // 试卷审批记录
      if (row.type === "APPROVE_RECORD") {
        this.$refs.PaperApproveTable.open();
        return;
      }
      // 学生期末考试成绩分析
      if (row.type === "SCORE_REPORT") {
        this.reportParams = {
          ...this.course,
          filter: {},
        };
        this.$refs.ScoreReportPreview.open();
        return;
      }

      this.toViewUrl(row.filePath);
    },
    toViewUrl(url) {
      if (!url) {
        this.$message.error("当前无文档可查看");
        return;
      }

      window.open(url);
    },
    toDownloadUrl(row) {
      if (!row.filePath) {
        this.$message.error("当前无文档可下载");
        return;
      }

      window.open(row.filePath);
    },
    async toDownload(row) {
      if (this.downloading) return;
      this.downloading = true;

      const res = await downloadByApi(() => {
        return documentDownload(row.id);
      }).catch((e) => {
        this.$message.error(e || "下载失败，请重新尝试！");
      });
      this.downloading = false;

      if (!res) return;
      this.$message.success("下载成功！");
    },
    toAdd() {
      this.$refs.AddDocumentDialog.open();
    },
    toDelete(row) {
      this.$confirm(`确定要删除文档【${row.name}】吗?`, "提示", {
        type: "warning",
      })
        .then(async () => {
          await documentDelete(row.id);
          this.$message.success("删除成功！");
          this.getList();
        })
        .catch(() => {});
    },
    async toBatchDownload() {
      if (this.bloading) return;
      this.bloading = true;

      const res = await downloadByApi(() => {
        return documentBatchDownload({
          examId: this.course.examId,
          paperNumber: this.course.paperNumber,
        });
      }).catch((e) => {
        this.$message.error(e || "下载失败，请重新尝试！");
      });
      this.bloading = false;

      if (!res) return;
      this.$message.success("下载成功！");
    },
    // upload
    validError(errorData) {
      this.$message.error(errorData.message);
    },
    uploadSuccess(data) {
      this.$message.success(data.data || "文档上传成功！");
      this.getList();
    },
  },
};
</script>
