<template>
  <el-dialog
    class="modify-user"
    :visible.sync="modalIsShow"
    :title="title"
    top="10vh"
    width="600px"
    :close-on-click-modal="false"
    :close-on-press-escape="false"
    append-to-body
    @open="visibleChange"
  >
    <div class="part-box part-box-pad part-box-border">
      <el-form
        ref="modalFormComp"
        :model="modalForm"
        :rules="rules"
        label-width="100px"
      >
        <el-form-item prop="loginName" label="用户名：">
          <el-input
            style="width:100%;"
            v-model.trim="modalForm.loginName"
            placeholder="请输入用户名"
            :disabled="isEdit"
          ></el-input>
        </el-form-item>
        <el-form-item prop="realName" label="姓名：">
          <el-input
            style="width:100%;"
            v-model.trim="modalForm.realName"
            placeholder="请输入姓名"
            clearable
          ></el-input>
        </el-form-item>
        <el-form-item prop="mobileNumber" label="手机号：">
          <el-input
            style="width:100%;"
            v-model.trim="modalForm.mobileNumber"
            placeholder="请输入手机号"
            clearable
          ></el-input>
        </el-form-item>
        <el-form-item prop="roleIds" label="角色：">
          <el-select
            style="width:100%;"
            v-model="modalForm.roleIds"
            placeholder="请选择角色"
            multiple
            @change="rolesChange"
          >
            <el-option
              v-for="item in roles"
              :key="item.id"
              :value="item.id"
              :label="item.name"
            >
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item
          prop="courseIds"
          label="课程："
          v-if="IS_QUESTION_TEACHER"
        >
          <el-select
            style="width:100%;"
            v-model="modalForm.courseIds"
            placeholder="请选择课程"
            multiple
            filterable
          >
            <el-option
              v-for="item in courses"
              :key="item.id"
              :value="item.id"
              :label="item.name"
            >
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item prop="orgId" label="所属学院：">
          <select-orgs
            ref="SelectOrgs"
            v-model="modalForm.orgId"
            :multiple="false"
            @change="orgChange"
          ></select-orgs>
        </el-form-item>
      </el-form>
    </div>
    <div slot="footer">
      <el-button type="primary" :disabled="isSubmit" @click="submit"
        >确认</el-button
      >
      <el-button type="danger" @click="cancel" plain>取消</el-button>
    </div>
  </el-dialog>
</template>

<script>
import { updateUser, courseQuery } from "../api";
import { logout } from "../../login/api";
import { phone } from "@/plugins/formRules";
import SelectOrgs from "./SelectOrgs";
import { SYS_ADMIN_NAME } from "@/constants/enumerate";

const initModalForm = {
  id: "",
  loginName: "",
  realName: "",
  mobileNumber: "",
  roleIds: [],
  courseIds: [],
  orgId: []
};

export default {
  name: "modify-user",
  components: { SelectOrgs },
  props: {
    instance: {
      type: Object,
      default() {
        return {};
      }
    },
    roles: {
      type: Array,
      default() {
        return [];
      }
    }
  },
  computed: {
    isEdit() {
      return !!this.instance.id;
    },
    title() {
      return (this.isEdit ? "编辑" : "新增") + "用户";
    },
    IS_QUESTION_TEACHER() {
      return this.roleTypes.includes("QUESTION_TEACHER");
    }
  },
  data() {
    const roleIdsValidator = (rule, value, callback) => {
      if (!value || !value.length) {
        callback(new Error("请选择角色"));
      } else {
        callback();
      }
    };
    const courseIdsValidator = (rule, value, callback) => {
      if (!value || !value.length) {
        callback(new Error("请选择课程"));
      } else {
        callback();
      }
    };
    const orgIdValidator = (rule, value, callback) => {
      if (this.IS_SUPER_ADMIN) return callback();

      if (!value || !value.length) {
        callback(new Error("请选择所属学院"));
      } else {
        callback();
      }
    };

    const IS_SUPER_ADMIN =
      this.$ls.get("user", { loginName: "" }).loginName === SYS_ADMIN_NAME;

    return {
      modalIsShow: false,
      isSubmit: false,
      modalForm: {},
      rules: {
        mobileNumber: phone,
        loginName: [
          {
            required: true,
            message: "请输入用户名",
            trigger: "change"
          },
          {
            max: 50,
            message: "用户名不能超过50",
            trigger: "change"
          }
        ],
        realName: [
          {
            required: true,
            message: "请输入姓名",
            trigger: "change"
          },
          {
            max: 50,
            message: "姓名不能超过50",
            trigger: "change"
          }
        ],
        roleIds: [
          {
            required: true,
            validator: roleIdsValidator,
            trigger: "change"
          }
        ],
        courseIds: [
          {
            required: true,
            validator: courseIdsValidator,
            trigger: "change"
          }
        ],
        orgId: [
          {
            required: !IS_SUPER_ADMIN,
            validator: orgIdValidator,
            trigger: "change"
          }
        ]
      },
      user: {},
      courses: [],
      roleTypes: [],
      IS_SUPER_ADMIN
    };
  },
  created() {
    this.getCourseList();
  },
  methods: {
    initData(val) {
      if (val.id) {
        this.modalForm = this.$objAssign(initModalForm, val);
        this.modalForm.roleIds = val.roles.map(item => item.id);
        this.modalForm.courseIds = val.courses.map(item => item.id);
        this.modalForm.orgId = [val.orgId];
        this.roleTypes = val.roles.map(role => role.type);
      } else {
        this.modalForm = { ...initModalForm };
      }
    },
    visibleChange() {
      this.initData(this.instance);
    },
    cancel() {
      this.modalIsShow = false;
    },
    open() {
      this.modalIsShow = true;
    },
    async getCourseList() {
      const data = await courseQuery("");
      this.courses = data;
    },
    rolesChange(roleIds) {
      this.roleTypes = this.roles
        .filter(role => roleIds.includes(role.id))
        .map(role => role.type);
    },
    orgChange() {
      this.$nextTick(() => {
        this.$refs.modalFormComp.validateField("orgId");
      });
    },
    async submit() {
      const valid = await this.$refs.modalFormComp.validate().catch(() => {});
      if (!valid) return;

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

      const datas = { ...this.modalForm };
      if (!this.IS_QUESTION_TEACHER) delete datas.courseIds;
      datas.orgId = datas.orgId.join();
      const data = await updateUser(datas).catch(() => {});
      this.isSubmit = false;
      if (!data) return;

      this.$message.success("修改成功！");
      this.cancel();

      if (!this.isEdit) {
        this.$emit("modified");
        return;
      }

      // 自己把自己的角色改了之后要重新登录，重新获取权限
      const oldRoleIds = this.instance.roles
        .map(item => item.id)
        .sort((a, b) => a - b)
        .join();
      const newRoleIds = datas.roleIds.sort((a, b) => a - b).join();
      if (
        oldRoleIds !== newRoleIds &&
        this.$ls.get("user").id === this.instance.id
      ) {
        await logout();
        this.$ls.clear();
        this.$router.push({ name: "Login" });
        this.$message.info("您的权限已经变更，请重新登录系统！");
      } else {
        this.$emit("modified");
      }
    }
  }
};
</script>
