<template>
  <el-dialog
    class="switch-school-dialog"
    :visible.sync="modalIsShow"
    title="切换学校"
    top="10vh"
    width="440px"
    :close-on-click-modal="false"
    :close-on-press-escape="false"
    append-to-body
    @open="visibleChange"
  >
    <el-form
      ref="modalFormComp"
      :model="modalForm"
      :rules="rules"
      label-width="70px"
    >
      <el-form-item prop="schoolId" label="学校：">
        <el-select
          v-model="modalForm.schoolId"
          class="width-full"
          placeholder="请选择学校"
          filterable
        >
          <el-option
            v-for="item in schoolInfo"
            :key="item.id"
            :value="item.id"
            :label="item.name"
          >
          </el-option>
        </el-select>
      </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 { login } from "../api";

export default {
  name: "switch-school-dialog",
  data() {
    return {
      modalIsShow: false,
      isSubmit: false,
      schoolInfo: [],
      loginName: "",
      modalForm: { schoolId: "" },
      rules: {
        schoolId: [
          {
            required: true,
            message: "请选择学校",
            trigger: "change",
          },
        ],
      },
    };
  },
  methods: {
    visibleChange() {
      const user = this.$ls.get("user", {
        schoolInfo: [],
        loginName: "",
      });
      this.schoolInfo = user.schoolInfo;
      this.loginName = user.loginName;
      this.modalForm.schoolId = this.$ls.get("schoolId");
    },
    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;
      const curSchool = this.schoolInfo.find(
        (item) => item.id === this.modalForm.schoolId
      );

      const datas = {
        schoolCode: curSchool.code,
        type: "ACCOUNT",
        loginName: this.loginName,
        password: curSchool.password,
      };
      const data = await login(datas).catch(() => {});
      this.isSubmit = false;
      if (!data) return;

      if (data.orgInfo)
        this.$ls.set("orgId", data.orgInfo.id, this.GLOBAL.authTimeout);
      this.$ls.set("schoolId", curSchool.id, this.GLOBAL.authTimeout);
      this.$ls.set("schoolName", curSchool.name);
      this.$ls.set("user", data, this.GLOBAL.authTimeout);
      this.$ls.set("token", data.accessToken, this.GLOBAL.authTimeout);
      this.cancel();

      window.location.href = this.getRouterPath({
        name: "Home",
      });
      window.location.reload();
    },
  },
};
</script>
