<template>
  <a-modal
    :confirmLoading="confirmLoading"
    :visible="visible"
    :width="1200"
    @cancel="onCancel"
    @ok="onOk"
    title="授权菜单"
  >
    <yo-authority-view
      :auto-load="false"
      :default-selected-keys="selectedKeys"
      :load-data="loadData"
      @select="onSelect"
      ref="authority-view"
    />
  </a-modal>
</template>

<script>
import YoAuthorityView from '@/components/yoAuthorityView';

export default {
  components: {
    YoAuthorityView,
  },

  data() {
    return {
      visible: false,

      record: {},
      selectedKeys: [],

      confirmLoading: false,
    };
  },

  methods: {
    /**
     * 必要的方法
     * 从外部调用打开本窗口
     */
    onOpen(record) {
      this.visible = true;
      this.record = record;

      this.$nextTick(async () => {
        const view = this.$refs['authority-view'];
        view.loading = true;
        view.data = [];
        this.selectedKeys = await this.onLoadRoleOwnMenu();
        view.onReloadData();
      });
    },

    loadData() {
      return this.$api.SysMenuTreeForGrant().then((res) => {
        return res.data;
      });
    },

    /**
     * 此角色已有菜单权限
     */
    onLoadRoleOwnMenu() {
      return this.$api.sysRoleOwnMenu({ id: this.record.id }).then(({ data }) => {
        return data;
      });
    },

    onSelect(a1, a2) {
      this.selectedKeys = a2;
    },

    onOk() {
      this.confirmLoading = true;

      this.$api
        .sysRoleGrantMenu({
          id: this.record.id,
          grantMenuIdList: this.selectedKeys,
        })
        .then(({ success }) => {
          if (success) {
            this.$message.success('授权成功');
            this.$emit('ok');
            this.onCancel();
          }
        })
        .finally((res) => {
          this.confirmLoading = false;
        });
    },

    onCancel() {
      this.visible = false;
    },
  },
};
</script>
