<template>
  <div class="card-option-dialog">
    <el-dialog
      class="card-option-dialog"
      :visible.sync="modalIsShow"
      title="选择制卡方式"
      top="10vh"
      width="600px"
      :close-on-click-modal="false"
      :close-on-press-escape="false"
      append-to-body
      @open="visibleChange"
    >
      <div class="card-option-body">
        <p>请您选择创建题卡方式：</p>
        <p>1.自助创建：使用题卡工具自助设计题卡，操作简单，即刻生成；</p>
        <p>
          2.申请客服制卡：由客服后台统一处理，处理完毕后您可查看或微调。
        </p>
        <div class="card-type">
          <el-radio-group v-model="modalForm.makeMethod">
            <el-radio
              v-for="item in cardSourceTypes"
              :key="item.type"
              :label="item.type"
              :disabled="item.disabled"
              >{{ item.name }}</el-radio
            >
          </el-radio-group>
        </div>
        <!-- card-select -->
        <div class="card-select" v-if="modalForm.makeMethod === 'SELECT'">
          <el-form
            ref="ModalForm"
            :model="modalForm"
            :rules="rules"
            label-width="90px"
          >
            <el-form-item prop="cardId" label="已选题卡：">
              <el-select
                v-model="modalForm.cardId"
                style="width: 300px;"
                placeholder="请选择"
                clearable
                filterable
              >
                <el-option
                  v-for="item in cards"
                  :key="item.id"
                  :value="item.id"
                  :label="item.title"
                >
                </el-option>
              </el-select>
              <span class="card-view" @click="toPreview">预览</span>
            </el-form-item>
          </el-form>
        </div>
        <!-- apply-customer -->
        <div class="card-apply" v-if="modalForm.makeMethod === 'CUST'">
          <el-form
            ref="ApplyModalForm"
            :model="applyModalForm"
            :rules="applyRules"
            label-width="90px"
          >
            <el-form-item prop="title" label="题卡标题：">
              <el-input
                style="width:300px"
                v-model.trim="applyModalForm.title"
                placeholder="请输入题卡标题"
              ></el-input>
            </el-form-item>
            <el-form-item prop="custAttachmentId" label="上传文件：">
              <upload-file-view
                input-width="300px"
                :upload-url="uploadUrl"
                :upload-data="uploadData"
                :format="format"
                @valid-error="validError"
                @upload-success="uploadSuccess"
                ref="UploadFileView"
              ></upload-file-view>
              <p class="tips-info">
                上传的文件只支持{{ format.join(",") }}，大小不超过20M
              </p>
            </el-form-item>
          </el-form>
        </div>
      </div>
      <div slot="footer">
        <el-button type="primary" :disabled="isSubmit" @click="confirm"
          >确定</el-button
        >
        <el-button @click="cancel">返回</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { cardForSelectList } from "../api";
import { applyCustomerCard } from "../../customer/api";
import { CARD_SOURCE_TYPE, COMMON_CARD_RULE_ID } from "@/constants/enumerate";
import UploadFileView from "@/components/UploadFileView";

const initModalForm = {
  examId: "",
  examTaskId: "",
  paperType: "",
  courseCode: "",
  courseName: "",
  cardRuleId: "",
  cardId: "",
  makeMethod: "",
  // 考务规则
  customCard: false
};

export default {
  name: "card-option-dialog-view",
  props: {
    data: {
      type: Object,
      default() {
        return {};
      }
    }
  },
  components: { UploadFileView },
  data() {
    return {
      modalIsShow: false,
      isSubmit: false,
      modalForm: { ...initModalForm },
      rules: {
        cardId: [
          {
            required: true,
            message: "请选择已选题卡",
            trigger: "change"
          }
        ]
      },
      onlySelect: false,
      cards: [],
      cardSourceTypes: [],
      CARD_SOURCE_TYPE,
      // apply-customer
      applyModalForm: {
        title: "",
        custAttachmentId: ""
      },
      applyRules: {
        title: [
          {
            required: true,
            message: "请输入文件标题",
            trigger: "change"
          },
          {
            message: "文件标题不能超过100个字",
            max: 100,
            trigger: "change"
          }
        ],
        custAttachmentId: [
          {
            required: true,
            message: "请上传样卷或试卷结构文件",
            trigger: "change"
          }
        ]
      },
      // upload
      format: ["pdf"],
      maxSize: 20 * 1024 * 1024,
      uploadUrl: "/api/admin/common/file/upload",
      uploadData: {
        type: "PAPER"
      }
    };
  },
  methods: {
    visibleChange() {
      this.getCardSourceTypes();
      this.modalForm = this.$objAssign(initModalForm, this.data);
      this.modalForm.makeMethod =
        this.data.makeMethod || this.cardSourceTypes[0].type;

      this.getCardList();
    },
    getCardSourceTypes() {
      let cardSourceTypes = [];
      Object.keys(CARD_SOURCE_TYPE).forEach(key => {
        // 自助创建 =>
        // 若题卡规则为专卡，命题人可即时创建专卡；
        // 若题卡规则为全部通卡，则不显示该制卡方式；
        // 申请客服制卡 =>
        // 若题卡规则为专卡，命题人可即时创建专卡；
        // 若题卡规则为全部通卡，则不显示该制卡方式；
        if (this.data.cardRuleId === COMMON_CARD_RULE_ID && key !== "SELECT")
          return;

        // 考务规则中未开启客服制卡时，不显示客服制卡选项
        if (!this.data.customCard && key === "CUST") return;

        cardSourceTypes.push({
          type: key,
          name: CARD_SOURCE_TYPE[key]
        });
      });
      this.cardSourceTypes = cardSourceTypes;
    },
    async getCardList() {
      // 选择已有题卡 =>
      // 若题卡规则为专卡，选择已有题卡时，下拉列表将显示适用的专卡和通卡；
      // 若题卡规则为“全部通卡”，则下拉列表中只显示适用的通卡模板；
      const data = await cardForSelectList({
        courseCode: this.modalForm.courseCode,
        paperType: this.modalForm.paperType,
        cardRuleId: this.modalForm.cardRuleId,
        examId: this.modalForm.examId
      });
      this.cards = data || [];
    },
    cancel() {
      this.modalIsShow = false;
    },
    open() {
      this.modalIsShow = true;
    },
    validError(errorData) {
      this.$message.error(errorData.message);
    },
    uploadSuccess(data) {
      this.$message.success("上传成功！");
      this.applyModalForm.custAttachmentId = data.id;
      this.$refs.ApplyModalForm.validateField("custAttachmentId");
    },
    async confirm() {
      // 客服制卡
      if (this.modalForm.makeMethod === "CUST") {
        const valid = await this.$refs.ApplyModalForm.validate().catch(
          () => {}
        );
        if (!valid) return;

        if (this.isSubmit) return;
        this.isSubmit = true;
        // 创建题卡
        const result = await applyCustomerCard({
          status: "STAGE",
          examTaskId: this.modalForm.examTaskId,
          courseCode: this.modalForm.courseCode,
          courseName: this.modalForm.courseName,
          makeMethod: "CUST",
          type: "CUSTOM",
          ...this.applyModalForm
        }).catch(() => {});
        this.isSubmit = false;
        if (!result) return;
        this.$message.success("申请成功！");
        this.$emit("confirm", {
          cardId: result,
          makeMethod: this.modalForm.makeMethod
        });
        this.cancel();
        return;
      }

      // 自主创建
      if (this.modalForm.makeMethod === "SELF") {
        this.$emit("confirm", {
          examTaskId: this.modalForm.examTaskId,
          courseCode: this.modalForm.courseCode,
          courseName: this.modalForm.courseName,
          schoolName: this.$ls.get("schoolName"),
          makeMethod: this.modalForm.makeMethod,
          cardRuleId: this.modalForm.cardRuleId,
          paperType: this.modalForm.paperType,
          type: "CUSTOM",
          createMethod: "STANDARD"
        });
        this.cancel();
        return;
      }

      // 选择已有题卡
      if (this.modalForm.makeMethod === "SELECT") {
        if (!this.modalForm.cardId) {
          this.$message.error("请选择已有的题卡！");
          return;
        }

        this.$emit("confirm", {
          cardId: this.modalForm.cardId,
          makeMethod: this.modalForm.makeMethod
        });
        this.cancel();
      }
    },
    toPreview() {
      if (!this.modalForm.cardId) {
        this.$message.error("请先选择题卡！");
        return;
      }
      window.open(
        this.getRouterPath({
          name: "CardPreview",
          params: {
            cardId: this.modalForm.cardId,
            viewType: "view"
          }
        })
      );
    }
  }
};
</script>

<style scoped>
.card-option-body {
  color: #878787;
}
.card-type {
  margin: 32px 0;
}
.card-select {
  margin-bottom: 10px;
}
.card-view {
  display: inline-block;
  margin-left: 10px;
  color: rgba(35, 196, 185, 1);
  cursor: pointer;
}
.card-view:hover {
  color: rgba(28, 208, 161, 1);
}
</style>
