<template>
  <el-dialog
    class="modify-template"
    :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="top"
      :rules="rules"
      :model="modalForm"
    >
      <el-form-item prop="name" label="模板名称：">
        <el-input
          v-model.trim="modalForm.name"
          placeholder="建议不超过30个字，规则名称不允许重复"
          style="width: 100%"
          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="classify" label="分类：">
        <el-select v-model="modalForm.classify" placeholder="请选择" clearable>
          <el-option
            v-for="(val, key) in categories"
            :key="key"
            :value="key"
            :label="val"
          ></el-option>
        </el-select>
      </el-form-item>
      <el-form-item
        v-if="modalForm.classify === 'SIGN'"
        label="显示字段："
        prop="fields"
      >
        <el-checkbox
          v-for="field in signDatas.basic"
          :key="field.code"
          v-model="field.enable"
          :disabled="field.disabled"
          >{{ field.name }}</el-checkbox
        >
        <el-divider></el-divider>
        <el-checkbox
          v-for="field in signDatas.table"
          :key="field.code"
          v-model="field.enable"
          :disabled="field.disabled"
          >{{ field.name }}</el-checkbox
        >
      </el-form-item>
      <el-form-item
        v-else-if="modalForm.classify === 'PACKAGE'"
        label="显示字段："
        prop="fields"
      >
        <el-checkbox
          v-for="field in packageDatas"
          :key="field.code"
          v-model="field.enable"
          :disabled="field.disabled"
          >{{ field.name }}</el-checkbox
        >
      </el-form-item>
      <el-form-item
        v-else-if="modalForm.classify === 'CHECK_IN'"
        prop="attachmentId"
        label="上传模板文件："
      >
        <upload-file-view
          :upload-data="uploadData"
          :upload-url="uploadUrl"
          :format="format"
          @valid-error="validError"
          @upload-success="uploadSuccess"
          ref="UploadFileView"
        ></upload-file-view>
      </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 { templateDetail, updateTemplate } from "../api";
import { attachmentDetail } from "../../login/api";
import UploadFileView from "@/components/UploadFileView";
import { PACKAGE_DATA, SIGN_DATA } from "@/constants/printTemplateData";

const initModalForm = {
  id: null,
  name: "",
  type: "",
  remark: "",
  classify: "",
  attachmentId: ""
};

export default {
  name: "modify-print-template",
  components: { UploadFileView },
  props: {
    instance: {
      type: Object,
      default() {
        return {};
      }
    }
  },
  computed: {
    isEdit() {
      return !!this.instance.id;
    },
    title() {
      return (this.isEdit ? "编辑" : "新增") + "模板";
    }
  },
  data() {
    const fieldsValidator = (rule, value, callback) => {
      if (this.modalForm.classify === "PACKAGE") {
        if (!this.packageDatas.some(item => item.enable)) {
          return callback(new Error("请选择显示字段"));
        }
        return callback();
      } else {
        if (
          !this.signDatas.basic.some(item => item.enable) ||
          !this.signDatas.table.some(item => item.enable)
        ) {
          return callback(new Error("请选择显示字段"));
        }
        return callback();
      }
    };
    return {
      modalIsShow: false,
      isSubmit: false,
      modalForm: {},
      attachment: {},
      format: ["ftl", "html", "pdf"],
      categories: {
        SIGN: "签到表",
        PACKAGE: "卷袋贴",
        CHECK_IN: "考试情况登记表"
      },
      rules: {
        name: [
          {
            required: true,
            message: "题卡规则名称不能超过30个字",
            max: 30,
            trigger: "change"
          }
        ],
        classify: [
          {
            required: true,
            message: "请选择分类",
            trigger: "change"
          }
        ],
        attachmentId: [
          {
            required: true,
            message: "请上传模板文件",
            trigger: "change"
          }
        ],
        fields: [
          {
            required: true,
            validator: fieldsValidator,
            trigger: "change"
          }
        ]
      },
      packageDatas: [...PACKAGE_DATA],
      signDatas: { ...SIGN_DATA },
      // upload
      uploadUrl: "/api/admin/common/file/upload",
      uploadData: {
        type: "UPLOAD"
      }
    };
  },
  methods: {
    async initData(val) {
      if (val.id) {
        const data = await templateDetail(val.id);
        this.modalForm = this.$objAssign(initModalForm, data);

        const unAttachmentTemps = ["SIGN", "PACKAGE"];
        if (unAttachmentTemps.includes(this.modalForm.classify)) {
          this.initFieldData(data);
        } else {
          this.getAttachment();
        }
      } else {
        this.modalForm = this.$objAssign(initModalForm, val);
        this.packageDatas = [...PACKAGE_DATA];
        this.signDatas = { ...SIGN_DATA };
        // this.$nextTick(() => {
        //   this.$refs.UploadFileView.setAttachmentName("");
        // });
      }
    },
    initFieldData(data) {
      const displayRange = data.displayRange
        ? JSON.parse(data.displayRange)
        : null;
      if (!displayRange) {
        this.packageDatas = [...PACKAGE_DATA];
        this.signDatas = { ...SIGN_DATA };
        return;
      }

      if (data.classify === "PACKAGE") {
        this.packageDatas = displayRange;
      } else {
        this.signDatas = displayRange;
      }
    },
    async getAttachment() {
      if (!this.instance.attachmentId) return;
      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.isSubmit) return;
      this.isSubmit = true;
      let datas = {
        ...this.modalForm
      };
      if (this.modalForm.classify === "PACKAGE") {
        datas.displayRange = this.packageDatas;
      } else if (this.modalForm.classify === "SIGN") {
        datas.displayRange = this.signDatas;
      }
      const data = await updateTemplate(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>
