<template>
  <el-dialog
    class="modify-card-info"
    :visible.sync="modalIsShow"
    :title="title"
    width="600px"
    :close-on-click-modal="false"
    :close-on-press-escape="false"
    append-to-body
    @open="visibleChange"
  >
    <el-form
      ref="modalFormComp"
      label-width="120px"
      :rules="rules"
      :model="modalForm"
    >
      <el-form-item prop="title" label="题卡名称：">
        <el-input
          v-model.trim="modalForm.title"
          placeholder="建议不超过30个字，题卡名称不允许重复"
          clearable
        ></el-input>
      </el-form-item>
      <el-form-item prop="remark" label="备注：">
        <el-input
          v-model="modalForm.remark"
          type="textarea"
          resize="none"
          :rows="2"
          :maxlength="50"
          clearable
          show-word-limit
          placeholder="建议不超过50个字"
        ></el-input>
      </el-form-item>
      <el-form-item prop="createMethod" label="题卡创建方式：">
        <el-radio-group v-model="modalForm.createMethod" :disabled="isEdit">
          <el-radio-button
            v-for="(val, key) in CARD_CREATE_METHOD_TYPE"
            :key="key"
            :label="key"
            >{{ val }}</el-radio-button
          >
        </el-radio-group>
      </el-form-item>
      <el-form-item v-if="IS_UPLOAD" prop="attachmentId" label="上传模板文件：">
        <upload-file-view
          :upload-data="uploadData"
          :upload-url="uploadUrl"
          :format="format"
          input-width="300px"
          @valid-error="validError"
          @upload-success="uploadSuccess"
          ref="UploadFileView"
        ></upload-file-view>
      </el-form-item>
      <el-form-item v-if="IS_STANDARD" prop="cardRuleId" label="题卡规则：">
        <card-rule-select
          ref="CardRuleSelect"
          v-model.trim="modalForm.cardRuleId"
          placeholder="请选择题卡规则"
          clearable
          class="width-full"
          :disabled="isEdit"
          :show-common-card="false"
        ></card-rule-select>
      </el-form-item>
    </el-form>

    <div slot="footer">
      <el-button type="primary" :disabled="isSubmit" @click="submit"
        >确认</el-button
      >
      <el-button @click="cancel">取消</el-button>
    </div>
  </el-dialog>
</template>

<script>
import { updateCard } from "../api";
import { attachmentDetail } from "../../login/api";
import { CARD_CREATE_METHOD_TYPE } from "../../../constants/enumerate";
import UploadFileView from "@/components/UploadFileView";

const initModalForm = {
  id: null,
  title: "",
  type: "GENERIC",
  createMethod: "UPLOAD",
  remark: "",
  cardRuleId: "",
  attachmentId: "",
  status: "STAGE",
};

export default {
  name: "modify-card-info",
  components: { UploadFileView },
  props: {
    instance: {
      type: Object,
      default() {
        return {};
      },
    },
  },
  computed: {
    isEdit() {
      return !!this.modalForm.id;
    },
    title() {
      return (this.isEdit ? "编辑" : "新增") + "题卡";
    },
    IS_GENGRIC() {
      return this.modalForm.type === "GENERIC";
    },
    IS_UPLOAD() {
      return this.modalForm.createMethod === "UPLOAD";
    },
    IS_STANDARD() {
      return this.modalForm.createMethod === "STANDARD";
    },
    IS_FREE() {
      return this.modalForm.createMethod === "FREE";
    },
  },
  data() {
    return {
      modalIsShow: false,
      isSubmit: false,
      modalForm: {},
      attachment: {},
      format: ["html"],
      CARD_CREATE_METHOD_TYPE,
      rules: {
        title: [
          {
            required: true,
            message: "题卡名称不能超过30个字",
            max: 30,
            trigger: "change",
          },
        ],
        createMethod: [
          {
            required: true,
            message: "请选择题卡创建方式",
            trigger: "change",
          },
        ],
        attachmentId: [
          {
            required: true,
            message: "请上传模板文件",
            trigger: "change",
          },
        ],
        cardRuleId: [
          {
            required: true,
            message: "请选择题卡规则",
            trigger: "change",
          },
        ],
      },
      // upload
      uploadUrl: "/api/admin/common/file/upload",
      uploadData: {
        type: "UPLOAD",
      },
    };
  },
  methods: {
    initData(val) {
      this.modalForm = this.$objAssign(initModalForm, val);
      if (val.id) {
        if (this.modalForm.createMethod !== "UPLOAD") return;
        this.getAttachment();
      } else {
        if (this.modalForm.createMethod !== "UPLOAD") return;
        this.$nextTick(() => {
          this.$refs.UploadFileView.setAttachmentName("");
        });
      }
    },
    async getAttachment() {
      const data = await attachmentDetail(this.instance.attachmentId);
      this.attachment = data;

      this.$nextTick(() => {
        this.$refs.UploadFileView.setAttachmentName(`${data.name}${data.type}`);
      });
    },
    visibleChange() {
      this.initData(this.instance);

      this.$nextTick(() => {
        this.$refs.modalFormComp.clearValidate();
      });
    },
    cancel() {
      this.modalIsShow = false;
    },
    open() {
      this.modalIsShow = true;
    },
    async submit() {
      const valid = await this.$refs.modalFormComp.validate().catch(() => {});
      if (!valid) return;

      if (!this.IS_UPLOAD && !this.isEdit) {
        this.$emit("new-card", this.modalForm);
        this.cancel();
        return;
      }

      if (this.isSubmit) return;
      this.isSubmit = true;
      let datas = {
        ...this.modalForm,
      };
      const data = await updateCard(datas).catch(() => {});
      this.isSubmit = false;
      if (!data) return;

      this.$message.success("保存成功！");
      this.$emit("modified");
      this.cancel();
    },
    validError(errorData) {
      this.$message.error(errorData.message);
    },
    uploadSuccess(data) {
      this.$message.success("上传成功！");

      this.modalForm.attachmentId = data.id;
      this.$refs.modalFormComp.validateField("attachmentId");
    },
  },
};
</script>
