<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">
      <privilege-set
        v-if="menus && menus.length"
        ref="PrivilegeSet"
        :menus="menus"
      ></privilege-set>
    </div>
  </div>
</template>

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

export default {
  name: "school-menu-manage",
  components: { PrivilegeSet },
  data() {
    return {
      schoolId: "",
      menus: [],
      loading: false,
      fetching: false,
      defaultProps: {
        label: "name"
      }
    };
  },
  mounted() {
    this.getPrivileges();
  },
  methods: {
    async getPrivileges() {
      const needHideModules = ["common", "customer"];
      const data = await schoolMenuTree();
      const menus = data || [];

      this.menus = menus
        .filter(item => !needHideModules.includes(item.url))
        .map(item => {
          item.parentId = null;
          return item;
        });

      this.$nextTick(() => {
        this.$refs.PrivilegeSet.buildTableData([]);
      });
    },
    async search() {
      if (!this.schoolId) return;
      this.fetching = true;
      const data = await schoolSelectedMenuTree(this.schoolId).catch(() => {});
      this.fetching = false;

      const privilegeIds = data || [];
      this.$refs.PrivilegeSet.buildTableData(privilegeIds);
    },
    async save() {
      if (!this.schoolId) {
        this.$message.error("学校必须选择！");
        return;
      }
      if (this.loading) return;

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

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