<template>
  <div class="school-set-menu">
    <privilege-set
      v-if="menus && menus.length"
      ref="PrivilegeSet"
      :menus="menus"
    ></privilege-set>

    <el-button type="primary" :loading="loading" @click="confirm"
      >保存</el-button
    >
  </div>
</template>

<script>
import {
  sysCustomMenuList,
  schoolSetMenuInfo,
  schoolSetMenuUpdate
} from "../../api";
import PrivilegeSet from "../../../base/components/PrivilegeSet";

export default {
  name: "school-set-menu",
  components: { PrivilegeSet },
  props: {
    school: {
      type: Object,
      default() {
        return {};
      }
    }
  },
  data() {
    return {
      menus: [],
      privilegeIds: [],
      dataPermissionInfo: [],
      loading: false
    };
  },
  mounted() {
    this.initData();
  },
  methods: {
    async initData() {
      await this.getPrivileges();
      await this.getSchoolMenuInfo();
      this.$nextTick(() => {
        this.$refs.PrivilegeSet.buildTableData(
          this.privilegeIds,
          this.dataPermissionInfo
        );
      });
    },
    async getPrivileges() {
      const needHideModules = ["common", "customer"];
      const data = await sysCustomMenuList();
      const menus = data.customPrivilegeList || [];

      this.menus = menus
        .filter(item => !needHideModules.includes(item.url))
        .map(item => {
          item.parentId = null;
          return item;
        });
    },
    async getSchoolMenuInfo() {
      const data = await schoolSetMenuInfo(this.school.id);
      this.privilegeIds = data.privilegeIdList || [];
      this.dataPermissionInfo = data.dataPermissionInfo || [];
    },
    async confirm() {
      if (this.loading) return;
      this.loading = true;
      const {
        privilegeIds,
        dataPermissionInfo
      } = this.$refs.PrivilegeSet.getSelectedPrivileges();
      const res = await schoolSetMenuUpdate({
        schoolId: this.school.id,
        privilegeIds,
        dataPermissionInfo
      }).catch(() => {});
      this.loading = false;
      if (!res) return;

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