<template>
  <a-modal
    :confirmLoading="confirmLoading"
    :visible="visible"
    @cancel="onCancel"
    @ok="onOk"
    class="yo-modal-form"
    title="授权角色"
  >
    <a-form-model class="yo-form" ref="form">
      <a-spin :spinning="loading">
        <a-icon slot="indicator" spin type="loading" />
        <div class="yo-form-group">
          <a-form-model-item class="yo-form--fluid">
            <a-select mode="multiple" placeholder="请选择角色" v-model="roles">
              <a-select-option
                :key="role.id"
                :value="role.id"
                v-for="role in roleList"
              >{{ role.name }}</a-select-option>
            </a-select>
          </a-form-model-item>
        </div>
      </a-spin>
    </a-form-model>
  </a-modal>
</template>
<script>
export default {
  data() {
    return {
      visible: false,
      confirmLoading: false,

      loading: false,

      id: '',
      roles: [],
      roleList: [],
    };
  },

  methods: {
    /**
     * 必要的方法
     * 从外部调用打开本窗口
     */
    async onOpen(params) {
      this.visible = true;
      this.id = params.record.id;
      this.$nextTick(() => {
        this.onInit();
      });
    },

    /**
     * 必要的方法
     * 点击保存时的操作
     */
    onOk() {
      this.confirmLoading = true;
      this.$api
        /** !!此处必须修改调用的接口方法 */
        .sysUserGrantRole({
          id: this.id,
          grantRoleIdList: this.roles,
        })
        .then(({ success }) => {
          if (success) {
            this.$message.success('授权成功');
            this.onCancel();
            this.$emit('ok');
          }
        })
        .finally(() => {
          this.confirmLoading = false;
        });
    },

    /**
     * 必要的方法
     * 关闭窗口时的操作
     */
    onCancel() {
      this.visible = false;
      setTimeout(() => {
        this.roles = [];
      }, 300);
    },

    async onInit() {
      this.loading = true;
      this.roleList = await this.onLoadRoleList();
      this.roles = await this.onLoadRole();
      this.loading = false;
    },

    onLoadRoleList() {
      return this.$api.getRolePage().then(({ data }) => {
        return data.rows;
      });
    },

    onLoadRole() {
      return this.$api.sysUserOwnRole({ id: this.id }).then(({ data }) => {
        return data;
      });
    },
  },
};
</script>