<template>
  <div class="info-exam-task">
    <div class="part-box part-box-pad part-box-border part-box-gray">
      <el-form
        ref="examTaskComp"
        :model="examTask"
        :rules="rules"
        label-width="120px"
      >
        <el-row>
          <el-col :span="12">
            <el-form-item prop="teachingRoomId" label="教研室：">
              <teaching-room-select
                v-model="examTask.teachingRoomId"
                @change="teachingRoomChange"
              ></teaching-room-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item prop="courseCode" label="课程（代码）：">
              <el-select
                v-model="examTask.courseCode"
                placeholder="请选择"
                filterable
                @change="courseChange"
              >
                <el-option
                  v-for="item in courses"
                  :key="item.code"
                  :value="item.code"
                  :label="`${item.name}（${item.code}）`"
                >
                </el-option>
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item prop="cardRuleId" label="题卡规则：">
              <el-input v-model.trim="cardRuleName" readonly></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="试卷编号：">
              <el-input
                v-model.trim="examTask.paperNumber"
                placeholder="请输入试卷编号"
                :maxlength="50"
                clearable
              ></el-input>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="拟卷教师：">
              <el-input
                v-model.trim="examTask.teacherName"
                placeholder="请输入拟卷教师"
                :maxlength="50"
                clearable
              ></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="试卷名称：">
              <el-input
                v-model.trim="examTask.paperName"
                placeholder="请输入试卷名称"
                :maxlength="100"
                clearable
              ></el-input>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
    </div>

    <div class="apply-content task-detail">
      <div class="task-body">
        <div class="mb-2 text-right">
          <el-button
            type="info"
            icon="el-icon-circle-plus-outline"
            @click="addAtachment"
            >增加卷型</el-button
          >
        </div>
        <table class="table mb-2">
          <tr>
            <th>试卷类型</th>
            <th>试卷文件</th>
            <th>答题卡创建方式</th>
            <th>答题卡</th>
            <th>操作</th>
          </tr>
          <tr v-for="(attachment, index) in paperAttachments" :key="index">
            <td>{{ attachment.name }}卷</td>
            <td>
              <el-button
                type="text"
                class="btn-primary"
                @click="toUpload(attachment)"
              >
                <i
                  :class="[
                    'icon',
                    attachment.attachmentId ? 'icon-files-act' : 'icon-files'
                  ]"
                ></i
                >{{
                  attachment.attachmentId
                    ? attachment.filename
                    : "点击上传试卷文件"
                }}
              </el-button>
            </td>
            <td :rowspan="paperAttachments.length" v-if="index === 0">
              {{ createCardTypeName }}
            </td>
            <td :rowspan="paperAttachments.length" v-if="index === 0">
              <el-select v-model="examTaskDetail.cardId" placeholder="请选择">
                <el-option
                  v-for="item in cards"
                  :key="item.id"
                  :value="item.id"
                  :label="item.title"
                >
                </el-option>
              </el-select>
            </td>
            <td>
              <el-button
                class="btn-danger"
                type="text"
                @click="deleteAttachment(index)"
                >删除</el-button
              >
            </td>
          </tr>
          <tr v-if="!paperAttachments.length">
            <td colspan="5">
              <p class="tips-info text-center">暂无数据</p>
            </td>
          </tr>
        </table>

        <p class="tips-info tips-dark mb-2">
          提示：多卷型试卷由于会绑定一个答题卡模板，因此试卷结构必须相同。多卷型试卷之间客观题要求试题内容相同，可允许大题内的小题题序不同。
        </p>

        <el-form>
          <el-form-item label="单次抽卷卷型数量：" label-width="150">
            <el-input-number
              v-model="examTaskDetail.drawCount"
              :min="1"
              :max="maxFetchCount"
              :step="1"
              step-strictly
              :controls="false"
            ></el-input-number>
          </el-form-item>
        </el-form>

        <h4 class="mb-2">备注说明：</h4>
        <el-input
          class="mb-2"
          v-model="examTaskDetail.remark"
          type="textarea"
          resize="none"
          :rows="2"
          :maxlength="100"
          clearable
          show-word-limit
          placeholder="建议不超过100个字"
        ></el-input>

        <h4 class="mb-2">上传入库审核表（最多4张）</h4>
        <div class="image-list">
          <div
            class="image-item"
            v-for="(img, index) in paperConfirmAttachments"
            :key="index"
          >
            <img
              :src="img.url"
              :alt="img.filename"
              title="点击查看大图"
              @click="toPreview(index)"
            />
            <div class="image-delete">
              <i
                class="el-icon-delete-solid"
                @click="deletePaperConfirmAttachment(index)"
              ></i>
            </div>
          </div>
          <div
            v-if="paperConfirmAttachments.length < 4"
            class="image-item image-add"
            title="上传入库审核表"
            @click="toUploadPaperConfirm"
          >
            <i class="el-icon-plus"></i>
          </div>
        </div>
      </div>
    </div>

    <!-- upload-paper-dialog -->
    <upload-paper-dialog
      :paper-attachment="curAttachment"
      :upload-type="curUploadType"
      @confirm="uploadConfirm"
      ref="UploadPaperDialog"
    ></upload-paper-dialog>
    <!-- image-preview -->
    <simple-image-preview
      :cur-image="curImage"
      @on-prev="toPrevImage"
      @on-next="toNextImage"
      ref="SimpleImagePreview"
    ></simple-image-preview>
  </div>
</template>

<script>
import UploadPaperDialog from "../UploadPaperDialog";
import SimpleImagePreview from "@/components/SimpleImagePreview";
import { CARD_SOURCE_TYPE } from "@/constants/enumerate";
import { cardForSelectList } from "../../api";
import { courseQuery } from "../../../base/api";

export default {
  name: "info-exam-task",
  components: { UploadPaperDialog, SimpleImagePreview },
  props: {
    datas: {
      type: Object,
      default() {
        return {};
      }
    }
  },
  data() {
    return {
      task: {},
      rules: {
        teachingRoomId: [
          {
            required: true,
            message: "请选择教研室",
            trigger: "change"
          }
        ],
        courseCode: [
          {
            required: true,
            message: "请选择课程",
            trigger: "change"
          }
        ],
        cardRuleId: [
          {
            required: true,
            message: "请选择题卡规则",
            trigger: "change"
          }
        ]
      },
      examTask: {},
      cards: [],
      courses: [],
      cardRuleName: "全部通卡",
      // exam-task-detail
      examTaskDetail: { makeMethod: "" },
      paperConfirmAttachmentId: { attachmentId: "", filename: "", url: "" },
      paperAttachments: [],
      paperConfirmAttachments: [],
      curAttachment: {},
      curUploadType: "paper",
      attachmentLimitCount: 26,
      abc: "abcdefghijklmnopqrstuvwxyz".toUpperCase(),
      // image-preview
      curImage: {},
      curImageIndex: 0
    };
  },
  computed: {
    createCardTypeName() {
      return CARD_SOURCE_TYPE[this.examTaskDetail.makeMethod] || "";
    },
    maxFetchCount() {
      return this.paperAttachments.length < 1
        ? 1
        : this.paperAttachments.length;
    }
  },
  mounted() {
    this.initData();
  },
  methods: {
    initData() {
      console.log(this.datas.examTask);
      this.examTask = { ...this.datas.examTask };
      this.examTaskDetail = { ...this.datas.examTaskDetail };
      this.paperAttachments = this.examTaskDetail.paperAttachmentIds
        ? JSON.parse(this.examTaskDetail.paperAttachmentIds)
        : [];

      if (!this.paperAttachments.length) {
        this.addAtachment();
      }

      this.paperConfirmAttachments = this.examTaskDetail
        .paperConfirmAttachmentIds
        ? JSON.parse(this.examTaskDetail.paperConfirmAttachmentIds)
        : [];

      this.getCourses();
      this.getCardList();

      this.$emit("on-ready");
    },
    async getCardList() {
      if (!this.examTask.courseCode) return;
      const data = await cardForSelectList({
        courseCode: this.examTask.courseCode,
        paperType: this.paperAttachments.map(item => item.name).join(","),
        cardRuleId: this.examTask.cardRuleId
      });
      this.cards = data || [];
    },
    async getCourses() {
      if (!this.examTask.teachingRoomId) return;
      const res = await courseQuery({
        teachingRoomId: this.examTask.teachingRoomId
      });
      this.courses = res || [];
    },
    async checkData() {
      const valid = await this.$refs.examTaskComp.validate().catch(() => {});
      if (!valid) {
        this.$emit("on-ready");
        return;
      }

      const attachmentValid = !this.paperAttachments.some(
        item => !item.attachmentId
      );
      // 设置了入库强制包含试卷时，校验试卷是否上传。
      if (this.examTaskDetail.includePaper && !attachmentValid) {
        this.$message.error("请完成试卷文件上传！");
        this.$emit("on-ready");
        return;
      }
      // if (!this.paperConfirmAttachments.length) {
      //   this.$message.error("请上传入库审核表！");
      //   return;
      // }

      if (!this.examTaskDetail.cardId) {
        this.$message.error("请选择题卡！");
        this.$emit("on-ready");
        return;
      }

      this.updateData();
      this.$emit("next-step");
    },
    getData() {
      return {
        examTask: this.examTask,
        examTaskDetail: this.getTaskDetailData()
      };
    },
    updateData() {
      this.$emit("data-change", this.getData());
    },
    // exam-task-detail edit
    addAtachment() {
      if (this.paperAttachments.length >= this.attachmentLimitCount) return;

      const newAttachment = {
        name: this.abc[this.paperAttachments.length],
        attachmentId: "",
        filename: "",
        pages: 0
      };
      this.paperAttachments.push(newAttachment);
    },
    deleteAttachment(index) {
      if (this.paperAttachments.length <= 1) {
        this.$message.error("试卷类型数量不得少于1");
        return;
      }
      this.paperAttachments.splice(index, 1);
      this.paperAttachments.forEach((item, itemIndex) => {
        item.name = this.abc[itemIndex];
      });
      if (
        this.examTaskDetail.drawCount &&
        this.examTaskDetail.drawCount > this.paperAttachments.length
      ) {
        this.examTaskDetail.drawCount = this.paperAttachments.length;
      }
    },
    toUpload(attachment) {
      this.curUploadType = "paper";
      this.curAttachment = {
        ...attachment
      };
      this.$refs.UploadPaperDialog.open();
    },
    toUploadPaperConfirm() {
      if (this.paperConfirmAttachments.length >= 4) return;
      this.curUploadType = "paperConfirm";
      this.curAttachment = {
        ...this.paperConfirmAttachmentId
      };
      this.$refs.UploadPaperDialog.open();
    },
    uploadConfirm(attachment, uploadType) {
      if (uploadType === "paper") {
        const index = this.paperAttachments.findIndex(
          item => item.name === attachment.name
        );
        this.paperAttachments.splice(index, 1, { ...attachment });
      } else {
        this.paperConfirmAttachments.push(attachment);
      }
    },
    deletePaperConfirmAttachment(index) {
      this.paperConfirmAttachments.splice(index, 1);
    },
    toViewCard() {
      window.open(
        this.getRouterPath({
          name: "CardPreview",
          params: {
            cardId: this.examTaskDetail.cardId,
            viewType: "view"
          }
        })
      );
    },
    cardConfirm(data) {
      this.examTaskDetail = this.$objAssign(this.examTaskDetail, data);
    },
    teachingRoomChange() {
      this.examTask.courseCode = "";
      this.examTask.courseName = "";
      this.courses = [];
      this.examTaskDetail.cardId = "";
      this.cards = [];
      this.getCourses();
    },
    courseChange(val) {
      if (val) {
        const course = this.courses.find(item => item.code === val);
        this.examTask.courseName = course.name;
      } else {
        this.examTask.courseName = "";
      }

      this.examTaskDetail.cardId = "";
      this.cards = [];
      this.getCardList();
    },
    getTaskDetailData() {
      let data = { ...this.examTaskDetail };
      data.paperType = this.paperAttachments.map(item => item.name).join(",");
      data.paperAttachmentIds = JSON.stringify(this.paperAttachments, (k, v) =>
        k === "url" ? undefined : v
      );
      data.paperConfirmAttachmentIds = JSON.stringify(
        this.paperConfirmAttachments
      );
      return data;
    },
    // image-preview
    toPreview(index) {
      this.curImageIndex = index;
      this.selectImage(index);
      this.$refs.SimpleImagePreview.open();
    },
    selectImage(index) {
      this.curImage = this.paperConfirmAttachments[index];
    },
    toPrevImage() {
      if (this.curImageIndex === 0) {
        this.curImageIndex = this.paperConfirmAttachments.length - 1;
      } else {
        this.curImageIndex--;
      }

      this.selectImage(this.curImageIndex);
    },
    toNextImage() {
      if (this.curImageIndex === this.paperConfirmAttachments.length - 1) {
        this.curImageIndex = 0;
      } else {
        this.curImageIndex++;
      }

      this.selectImage(this.curImageIndex);
    }
  }
};
</script>
