<template>
  <div class="school-menu-manage">
    <div class="part-box part-box-filter part-box-flex">
      <el-form ref="FilterForm" label-position="left" inline>
        <el-form-item label="学校：">
          <school-select
            v-model="schoolId"
            placeholder="请选择学校"
            :clearable="false"
            style="width:100%;"
            @change="search"
          ></school-select>
        </el-form-item>
      </el-form>
      <div class="part-box-action">
        <el-button
          type="primary"
          :disabled="fetching"
          :loading="loading"
          @click="save"
          >保存</el-button
        >
      </div>
    </div>

    <div class="part-box part-box-pad">
      <el-tree
        :data="menus"
        show-checkbox
        default-expand-all
        node-key="id"
        ref="MenuTree"
        :props="defaultProps"
        check-on-click-node
        :expand-on-click-node="false"
      >
      </el-tree>
    </div>
  </div>
</template>

<script>
import {
  schoolMenuTree,
  schoolSelectedMenuTree,
  updateSchoolMenu
} from "../api";

export default {
  name: "school-menu-manage",
  data() {
    return {
      schoolId: "",
      menus: [],
      loading: false,
      fetching: false,
      defaultProps: {
        label: "name"
      }
    };
  },
  mounted() {
    this.getPrivileges();
  },
  methods: {
    async getPrivileges() {
      const data = await schoolMenuTree();
      this.menus = data || [];
    },
    async search() {
      if (!this.schoolId) return;
      this.fetching = true;
      const data = await schoolSelectedMenuTree(this.schoolId).catch(() => {});
      this.fetching = false;

      const privilegeIds = data || [];
      this.$refs.MenuTree.setCheckedKeys(privilegeIds);
    },
    async save() {
      const privilegeIds = this.$refs.MenuTree.getCheckedKeys();

      if (!this.schoolId || !privilegeIds.length) {
        this.$message.error("学校和权限都必须选择！");
        return;
      }
      if (this.loading) return;

      this.loading = true;
      const res = await updateSchoolMenu({
        schoolId: this.schoolId,
        privilegeIds: privilegeIds
      });
      this.loading = false;
      if (!res) return;

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