<template>
  <el-dialog
    class="modify-course-target-template"
    :visible.sync="modalIsShow"
    :title="title"
    top="10vh"
    width="600px"
    :close-on-click-modal="false"
    :close-on-press-escape="false"
    append-to-body
    @open="visibleChange"
  >
    <el-form
      ref="modalFormComp"
      :model="modalForm"
      :rules="rules"
      :key="modalForm.id"
      label-width="100px"
    >
      <el-form-item prop="name" label="模板名称：">
        <el-input
          v-model.trim="modalForm.name"
          placeholder="请输入模板名称"
          clearable
        ></el-input>
      </el-form-item>
      <el-form-item prop="uploadData" label="模板文件：">
        <upload-fetch-file
          input-width="320px"
          :format="format"
          @valid-change="validChange"
          @file-change="fileChange"
          ref="UploadFetchFile"
        ></upload-fetch-file>
        <p class="tips-info">
          上传的文件只支持{{ format.join(",") }}，大小不超过2M
        </p>
      </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 { updateCourseTargetTemplate } from "../api";
import UploadFetchFile from "@/components/UploadFetchFile";

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

export default {
  name: "modify-course-target-template",
  components: { UploadFetchFile },
  props: {
    instance: {
      type: Object,
      default() {
        return {};
      },
    },
  },
  computed: {
    isEdit() {
      return !!this.instance.id;
    },
    title() {
      return (this.isEdit ? "编辑" : "新增") + "课程目标模板";
    },
  },
  data() {
    return {
      modalIsShow: false,
      isSubmit: false,
      modalForm: { ...initModalForm },
      rules: {
        name: [
          {
            required: true,
            message: "请输入模板名称",
            trigger: "change",
          },
          {
            message: "模板名称不能超过100个字符",
            max: 100,
            trigger: "change",
          },
        ],
        uploadData: [
          {
            required: true,
            validator: (rule, value, callback) => {
              if (this.uploadData) {
                callback();
              } else {
                return callback(new Error(`请选择合适的文件`));
              }
            },
            trigger: "change",
          },
        ],
      },
      // upload
      format: ["doc", "docx"],
      maxSize: 2 * 1024 * 1024,
      uploadData: null,
    };
  },
  methods: {
    initData(val) {
      if (val.id) {
        this.modalForm = this.$objAssign(initModalForm, val);
      } else {
        this.modalForm = { ...initModalForm };
      }
      this.uploadData = null;
    },
    visibleChange() {
      this.initData(this.instance);
    },
    cancel() {
      this.modalIsShow = false;
    },
    open() {
      this.modalIsShow = true;
    },
    validChange(result) {
      if (!result.success) {
        this.uploadData = null;
        this.$notify.error({ title: "错误提示", message: result.message });
        this.$refs.modalFormComp.validateField("uploadData");
      }
    },
    fileChange(data) {
      this.uploadData = data;
      this.$refs.modalFormComp.validateField("uploadData");
    },
    async submit() {
      const valid = await this.$refs.modalFormComp.validate().catch(() => {});
      if (!valid) return;

      if (this.isSubmit) return;
      this.isSubmit = true;

      const formData = new FormData();
      Object.entries(this.modalForm).forEach(([k, v]) => {
        formData.append(k, v);
      });
      formData.append("file", this.uploadData.file);

      const data = await updateCourseTargetTemplate(formData, {
        md5: this.uploadData.md5,
      }).catch(() => {});
      this.isSubmit = false;
      if (!data) return;

      this.$message.success(this.title + "成功！");
      this.$emit("modified");
      this.cancel();
    },
  },
};
</script>
