<template>
  <el-dialog
    class="modify-school"
    :visible.sync="modalIsShow"
    :title="title"
    top="10vh"
    width="600px"
    :close-on-click-modal="false"
    :close-on-press-escape="false"
    append-to-body
    @opened="visibleChange"
  >
    <el-form
      ref="modalFormComp"
      :model="modalForm"
      :rules="rules"
      :key="modalForm.id"
      label-width="100px"
    >
      <el-form-item prop="code" label="学校代码：">
        {{ modalForm.code }}
      </el-form-item>
      <el-form-item prop="name" label="学校名称：">
        <!-- <el-input
          v-model.trim="modalForm.name"
          placeholder="请输入名称"
          clearable
        ></el-input> -->
        {{ modalForm.name }}
      </el-form-item>
      <el-form-item prop="initPassword" label="用户初始密码：">
        <el-input
          v-model.trim="modalForm.initPassword"
          placeholder="请输入密码"
          clearable
        ></el-input>
      </el-form-item>
      <el-form-item prop="logo" label="学校logo：">
        <UploadFetchFile
          ref="UploadFetchFile"
          input-width="340px"
          :disabled="isSubmit"
          :format="['png', 'jpg']"
          @file-change="logoChange"
          @valid-change="validChange"
        />
        <div class="mt-1">
          <p class="tips-info">logo会展示在登录页及内页；</p>
          <p class="tips-info">
            文件必须是 jpg 或 png 格式的图片，不超过 2M 尺寸：160*40px。
          </p>
        </div>
        <div class="logo-image" v-if="imgSrc">
          <img class="logo-view" :src="imgSrc" alt="logo" />
        </div>
      </el-form-item>
    </el-form>
    <div slot="footer">
      <el-button type="danger" @click="cancel" plain>取消</el-button>
      <el-button type="primary" :disabled="isSubmit" @click="submit"
        >确认</el-button
      >
    </div>
  </el-dialog>
</template>

<script>
import { updateSchool } from "../api";
import UploadFetchFile from "../../../components/UploadFetchFile.vue";
import { password } from "@/plugins/formRules";

const initModalForm = {
  id: "",
  name: "",
  code: "",
  logo: "",
  logoMd5: "",
  initPassword: "",
};

export default {
  name: "modify-school",
  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 },
      imgSrc: "",
      logoValidInfo: {},
      rules: {
        name: [
          {
            required: true,
            message: "请输入学校名称",
            trigger: "change",
          },
        ],
        code: [
          {
            required: true,
            message: "请输入学校代码",
            trigger: "change",
          },
        ],
        logo: [
          {
            validator: (rule, value, callback) => {
              if (!this.logoValidInfo.success && this.logoValidInfo.message) {
                return callback(new Error(this.logoValidInfo.message));
              }

              callback();
            },
          },
        ],
        initPassword: password,
      },
    };
  },
  methods: {
    initData(val) {
      if (val.id) {
        this.modalForm = this.$objAssign(initModalForm, val);
        this.imgSrc = val.logo || "";
        this.modalForm.logo = "";
        this.modalForm.logoMd5 = "";
      } else {
        this.imgSrc = "";
        this.modalForm = { ...initModalForm };
      }
      this.$refs.modalFormComp.clearValidate();
      this.$nextTick(() => {
        this.$refs.UploadFetchFile.setAttachmentName("");
      });
    },
    visibleChange() {
      this.initData(this.instance);
    },
    cancel() {
      this.modalIsShow = false;
    },
    open() {
      this.modalIsShow = true;
    },
    logoChange({ file, md5 }) {
      let uRl = window.URL || window.webkitURL;
      this.imgSrc = uRl.createObjectURL(file);
      this.modalForm.logo = file;
      this.modalForm.logoMd5 = md5;
    },
    validChange(res) {
      this.logoValidInfo = res;
      this.$refs.modalFormComp.validateField("logo", () => {});
    },
    async submit() {
      const valid = await this.$refs.modalFormComp.validate();
      if (!valid) return;

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

      if (!data) return;

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