<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>
  </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,
    };
  },
  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 === "APPROVE_RECORD") {
        this.$refs.PaperApproveTable.open();
        return;
      }
      // 学生期末考试成绩分析
      if (row.type === "SCORE_REPORT") {
        this.reportParams = {
          ...this.course,
          filter: {},
        };
        this.$refs.ScoreReportPreview.open();
        return;
      }

      this.toDownloadUrl(row);
    },
    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>
