<template>
  <div class="school-set-role">
    <el-form
      ref="modalFormComp"
      :model="modalForm"
      :rules="rules"
      label-width="140px"
    >
      <el-form-item prop="roleIds" label="系统角色管理：">
        <el-checkbox-group v-model="modalForm.roleIds">
          <el-checkbox
            v-for="item in roleList"
            :key="item.id"
            :label="item.id"
            :disabled="item.disabled"
            >{{ item.name }}</el-checkbox
          >
        </el-checkbox-group>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" :loading="loading" @click="confirm"
          >保存</el-button
        >
      </el-form-item>
    </el-form>
  </div>
</template>

<script>
import {
  sysCustomRoleList,
  schoolSetRoleInfo,
  schoolSetRoleUpdate,
} from "../../api";

export default {
  name: "school-set-role",
  props: {
    school: {
      type: Object,
      default() {
        return {};
      },
    },
  },
  data() {
    return {
      loading: false,
      defaultSelectedRole: ["SCHOOL_ADMIN", "SCHOOL_TEACHER", "ASSISTANT"],
      // SCHOOL_ADMIN("学校管理员"),SCHOOL_TEACHER("学校老师"), ASSISTANT("学院秘书");
      modalForm: {
        roleIds: [],
      },
      roleList: [],
      rules: {
        roleIds: [
          {
            required: true,
            validator: (rule, value, callback) => {
              if (!value || !value.length) {
                return callback(new Error(`请选择系统角色管理`));
              }

              callback();
            },
            trigger: "change",
          },
        ],
      },
    };
  },
  mounted() {
    this.initData();
  },
  methods: {
    async initData() {
      const roleData = await sysCustomRoleList();
      const res = roleData || [];
      this.roleList = res.map((item) => {
        item.disabled = this.defaultSelectedRole.includes(item.type);
        return item;
      });
      const data = await schoolSetRoleInfo(this.school.id);
      this.modalForm.roleIds = data.roleIdList;
      this.roleList
        .filter((item) => this.defaultSelectedRole.includes(item.type))
        .forEach((item) => {
          if (this.modalForm.roleIds.includes(item.id)) return;
          this.modalForm.roleIds.push(item.id);
        });
    },
    async confirm() {
      const valid = await this.$refs.modalFormComp.validate();
      if (!valid) return;

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

      let datas = {
        roleIds: this.modalForm.roleIds,
        schoolId: this.school.id,
      };
      const res = await schoolSetRoleUpdate(datas).catch(() => {});
      this.loading = false;

      if (!res) return;

      this.$message.success("修改成功！");
    },
  },
};
</script>
