<template>
  <div class="wait-task-detail task-detail">
    <div class="task-title">
      <h2>
        <span>考试名称： {{ task.examName }} </span>
        <span>科目名称：{{ task.courseName }}</span>
      </h2>
      <div class="task-title-infos">
        <el-checkbox v-model="pTypeEnable" @change="pTypeEnableChange"
          >启用{{ paperTypeFieldContent }}卷</el-checkbox
        >
      </div>
    </div>
    <div class="task-body">
      <table class="table">
        <tr>
          <th>试卷类型</th>
          <th>试卷文件</th>
          <th>答题卡</th>
        </tr>
        <tr v-for="(attachment, index) in curPaperAttachments" :key="index">
          <td>{{ attachment.name }}卷</td>
          <td class="td-link">
            <span @click="toUpload(attachment)" title="点击上传试卷">
              <i
                :class="[
                  'icon',
                  attachment.attachmentId ? 'icon-files-act' : 'icon-files'
                ]"
              ></i
              >{{
                attachment.attachmentId
                  ? attachment.filename
                  : "点击上传试卷文件"
              }}
            </span>
          </td>
          <td
            class="td-link"
            :rowspan="pTypeEnable ? curPaperAttachments.length : 1"
            v-if="index === 0"
          >
            <span @click="toCreateCard"
              ><i class="icon icon-plus-act"></i>{{ cardTodoName }}</span
            >
          </td>
        </tr>
      </table>

      <div class="task-action">
        <el-button type="primary" style="width:105px;" @click="toSubmit"
          >确认提交</el-button
        >
        <el-button style="width:88px;" @click="toSave">暂存</el-button>
        <el-button @click="goback" style="width:88px;">取消</el-button>
      </div>
    </div>

    <!-- upload-paper-dialog -->
    <upload-paper-dialog
      :paper-attachment="curAttachment"
      @confirm="uploadConfirm"
      ref="UploadPaperDialog"
    ></upload-paper-dialog>
    <!-- card-option-dialog -->
    <card-option-dialog
      :data="task"
      ref="CardOptionDialog"
      @confirm="cardConfirm"
    ></card-option-dialog>
  </div>
</template>

<script>
import { waitTaskDetail, saveWaitTask, submitWaitTask } from "../api";
import UploadPaperDialog from "../components/UploadPaperDialog";
import CardOptionDialog from "../components/CardOptionDialog";

export default {
  name: "wait-task-detail",
  components: {
    UploadPaperDialog,
    CardOptionDialog
  },
  data() {
    return {
      taskId: this.$route.params.taskId,
      PAPER_TYPE_FIELDS: ["A", "B"],
      task: {
        id: "",
        taskId: "",
        enablePaperType: "A",
        paperAttachmentId: "",
        cardId: "",
        cardSource: "",
        refCardId: ""
      },
      pTypeEnable: false,
      paperAttachments: [],
      curPaperAttachments: [],
      curAttachment: {}
    };
  },
  computed: {
    paperTypeFieldContent() {
      return this.PAPER_TYPE_FIELDS.join("/");
    },
    cardTodoName() {
      let name = "创建答题卡";
      if (this.task.cardId) {
        if (this.task.cardSource === 0) {
          name = "选择题卡";
        } else if (this.task.cardSource === 1) {
          name = "编辑题卡";
        } else {
          // 已经审核的题卡可以自行编辑，未审核的题卡只能查看
          name = this.task.auditingStatus ? "编辑题卡" : "查看题卡";
        }
      }
      return name;
    }
  },
  mounted() {
    this.getData();
  },
  methods: {
    async getData() {
      const data = await waitTaskDetail(this.taskId);
      const nameCode = data.courseNameCode.split(/\(|\)/);
      this.task = Object.assign(this.task, data, {
        courseName: nameCode[0],
        courseCode: nameCode[1]
      });
      this.pTypeEnable =
        this.task.enablePaperType &&
        this.task.enablePaperType.split(",").length > 1;
      this.parsePaperAttachment();
      this.pTypeEnableChange(this.pTypeEnable);
      this.task.enablePaperType = this.getEnablePaperType();
    },
    parsePaperAttachment() {
      const paperAttachment =
        this.task.paperAttachmentId && JSON.parse(this.task.paperAttachmentId);
      const papers = paperAttachment && paperAttachment.paper;
      let paperDict = {};
      if (papers) {
        papers.map(paper => {
          paperDict[paper.name] = paper;
        });
      }
      this.paperAttachments = this.PAPER_TYPE_FIELDS.map(paperType => {
        const paperInfo = paperDict[paperType];
        let paper = {
          attachmentId: "",
          name: paperType
        };
        return paperInfo ? Object.assign({}, paper, paperInfo) : paper;
      });
    },
    pTypeEnableChange(val) {
      this.curPaperAttachments = val
        ? this.paperAttachments
        : [this.paperAttachments[0]];
    },
    toUpload(attachment) {
      this.curAttachment = { ...attachment };
      this.$refs.UploadPaperDialog.open();
    },
    uploadConfirm(attachment) {
      this.curAttachment = Object.assign(this.curAttachment, attachment);
      const index = this.paperAttachments.findIndex(
        item => item.name === attachment.name
      );
      this.paperAttachments.splice(index, 1, { ...this.curAttachment });
      this.pTypeEnableChange(this.pTypeEnable);
    },
    toCreateCard() {
      if (this.task.cardId) {
        if (this.task.cardSource === 0) {
          this.$refs.CardOptionDialog.open();
        } else if (this.task.cardSource === 1) {
          this.$router.push({
            name: "CardDesign",
            params: {
              cardId: this.task.cardId
            }
          });
        } else {
          if (this.task.auditingStatus) {
            this.$router.push({
              name: "CardDesign",
              params: {
                cardId: this.task.cardId
              }
            });
          } else {
            window.open(`/#/card/preview/${this.task.cardId}/view`);
          }
        }
        return;
      }
      this.$refs.CardOptionDialog.open();
    },
    cardConfirm(options) {
      this.task = Object.assign(this.task, options);
    },
    getEnablePaperType() {
      return this.curPaperAttachments.map(item => item.name).join(",");
    },
    getTaskData() {
      let datas = { ...this.task };
      datas.taskId = this.taskId;
      datas.paperAttachmentId = JSON.stringify({
        paper: this.curPaperAttachments
      });
      datas.enablePaperType = this.getEnablePaperType();
      return { tcPExamTaskDetail: datas };
    },
    checkDataValid() {
      const attachmentValid = !this.curPaperAttachments.some(
        item => !item.attachmentId
      );
      if (!attachmentValid) {
        this.$message.error("请完成试卷文件上传！");
        return;
      }

      if (!this.task.cardId) {
        this.$message.error("请选择题卡创建方式！");
        return;
      }
      return true;
    },
    toSubmit() {
      this.$confirm(
        "任务确定提交后，则不可更改试卷及答题卡内容，确定提交该任务？",
        "提示",
        {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning"
        }
      ).then(async () => {
        if (!this.checkDataValid()) return;
        await submitWaitTask(this.getTaskData());
        this.$message.success("提交成功！");
        this.goback();
      });
    },
    async toSave() {
      await saveWaitTask(this.getTaskData());
      this.$message.success("保存成功！");
      this.goback();
    }
  }
};
</script>
