<template>
  <el-dialog
    class="modify-school"
    :visible.sync="modalIsShow"
    :title="title"
    top="10vh"
    width="640px"
    :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="130px"
    >
      <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>
        <el-checkbox v-model="modalForm.defaultSchool"
          >是否默认学校
        </el-checkbox>
      </el-form-item>
      <el-form-item>
        <el-checkbox v-model="modalForm.hasPaperNumber"
          >学校是否有固定试卷编号
        </el-checkbox>
      </el-form-item>
      <el-form-item prop="logo" label="学校logo：">
        <UploadFetchFile
          ref="LogoUploadFetchFile"
          input-width="300px"
          :disabled="isSubmit"
          :format="['png', 'jpg']"
          @file-change="logoChange"
          @valid-change="logoValidChange"
        />
        <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="logoSrc">
          <img class="logo-view" :src="logoSrc" alt="logo" />
        </div>
      </el-form-item>
      <el-form-item prop="backgroundImage" label="登录背景：">
        <UploadFetchFile
          ref="BgUploadFetchFile"
          input-width="300px"
          :disabled="isSubmit"
          :format="['png', 'jpg']"
          @file-change="bgChange"
          @valid-change="bgValidChange"
        />
        <div class="mt-1">
          <p class="tips-info">背景会展示在登录页；</p>
          <p class="tips-info">文件必须是jpg或png格式的图片，不超过2M。</p>
        </div>
        <div class="logo-image" v-if="bgSrc">
          <img class="bg-view" :src="bgSrc" alt="logo" />
        </div>
      </el-form-item>
      <el-form-item prop="examTaskInstr" label="命题任务提示语：">
        <el-input
          v-model.trim="modalForm.examTaskInstr"
          placeholder="请输入"
          clearable
        ></el-input>
      </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: "",
  backgroundImage: "",
  backgroundImageMd5: "",
  initPassword: "",
  examTaskInstr: "",
  defaultSchool: false,
  hasPaperNumber: false,
};

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 },
      logoSrc: "",
      logoValidInfo: {},
      bgSrc: "",
      bgValidInfo: {},
      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();
            },
          },
        ],
        backgroundImage: [
          {
            validator: (rule, value, callback) => {
              if (!this.bgValidInfo.success && this.bgValidInfo.message) {
                return callback(new Error(this.bgValidInfo.message));
              }

              callback();
            },
          },
        ],
        initPassword: password,
        examTaskInstr: [
          {
            required: false,
            max: 100,
            message: "内容不超过100字符",
            trigger: "change",
          },
        ],
      },
    };
  },
  methods: {
    initData(val) {
      if (val.id) {
        this.modalForm = this.$objAssign(initModalForm, val);
        this.logoSrc = val.logo || "";
        this.modalForm.logo = "";
        this.modalForm.logoMd5 = "";
        this.bgSrc = val.backgroundImage || "";
        this.modalForm.backgroundImage = "";
        this.modalForm.backgroundImageMd5 = "";
      } else {
        this.logoSrc = "";
        this.bgSrc = "";
        this.modalForm = { ...initModalForm };
      }
      this.$refs.modalFormComp.clearValidate();
      this.$nextTick(() => {
        this.$refs.LogoUploadFetchFile.setAttachmentName("");
        this.$refs.BgUploadFetchFile.setAttachmentName("");
      });
    },
    visibleChange() {
      this.initData(this.instance);
    },
    cancel() {
      this.modalIsShow = false;
    },
    open() {
      this.modalIsShow = true;
    },
    logoChange({ file, md5 }) {
      let uRl = window.URL || window.webkitURL;
      this.logoSrc = uRl.createObjectURL(file);
      this.modalForm.logo = file;
      this.modalForm.logoMd5 = md5;
    },
    logoValidChange(res) {
      this.logoValidInfo = res;
      this.$refs.modalFormComp.validateField("logo", () => {});
    },
    bgChange({ file, md5 }) {
      let uRl = window.URL || window.webkitURL;
      this.bgSrc = uRl.createObjectURL(file);
      this.modalForm.backgroundImage = file;
      this.modalForm.backgroundImageMd5 = md5;
    },
    bgValidChange(res) {
      this.bgValidInfo = res;
      this.$refs.modalFormComp.validateField("backgroundImage", () => {});
    },
    async submit() {
      const valid = await this.$refs.modalFormComp.validate();
      if (!valid) return;

      if (this.isSubmit) return;
      this.isSubmit = true;
      const datas = { ...this.modalForm };
      if (!datas.examTaskInstr) datas.examTaskInstr = "";
      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>
