<template>
  <el-dialog
    class="modify-paper-template-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-position="left"
      :rules="rules"
      :model="modalForm"
      label-width="95px"
    >
      <el-form-item prop="name" label="模板名称：">
        <el-input
          v-model.trim="modalForm.name"
          placeholder="建议不超过30个字"
          clearable
        ></el-input>
      </el-form-item>
      <el-form-item prop="type" label="模板类型：">
        <el-radio-group v-model="modalForm.type" :disabled="isEdit">
          <el-radio-button
            v-for="(val, key) in PAPER_TEMPLATE_TYPE"
            :key="key"
            :label="key"
            >{{ val }}</el-radio-button
          >
        </el-radio-group>
      </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 { PAPER_TEMPLATE_TYPE } from "@/constants/constants";

const initModalForm = {
  id: null,
  name: "",
  type: "PAPER_EXPORT",
};

export default {
  name: "ModifyPaperTemplateInfo",
  props: {
    instance: {
      type: Object,
      default() {
        return {};
      },
    },
  },
  data() {
    return {
      modalIsShow: false,
      isSubmit: false,
      modalForm: {},
      PAPER_TEMPLATE_TYPE,
      rules: {
        name: [
          {
            required: true,
            message: "模板名称不能超过30个字",
            max: 30,
            trigger: "change",
          },
        ],
        type: [
          {
            required: true,
            message: "请选择模板类型",
            trigger: "change",
          },
        ],
      },
    };
  },
  computed: {
    isEdit() {
      return !!this.modalForm.id;
    },
    title() {
      return (this.isEdit ? "编辑" : "新增") + "模板信息";
    },
  },
  methods: {
    initData(val) {
      this.modalForm = this.$objAssign(initModalForm, val);
    },
    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.isEdit) {
        this.$emit("new-temp", this.modalForm);
        this.cancel();
        return;
      }
    },
  },
};
</script>
