<template>
  <a-dropdown :trigger="['click']">
    <a-button type="link" class="ant-dropdown-link" @click.prevent>
      {{ displayRoleName }}
      <down-outlined />
    </a-button>
    <template #overlay>
      <a-menu v-if="userRoleOrTemplateList.length > 0">
        <a-menu-item
          v-for="userRoleOrTemplate in userRoleOrTemplateList"
          :key="userRoleOrTemplate.userRoleTemplateId + '-' + userRoleOrTemplate.userRoleId"
          @click="handleRoleSelect(userRoleOrTemplate)"
        >
          {{ userRoleOrTemplate.roleOrTemplateName }}
        </a-menu-item>
        <a-menu-item @click="handleRoleSelect(null)">
          全部
        </a-menu-item>
      </a-menu>
    </template>
  </a-dropdown>
</template>

<script>
import { DownOutlined } from '@ant-design/icons-vue';
import Common from '../common/Common.js';
import { Notify } from 'pc-component-v3';
import { useRoleStateSingleton } from './RoleState.js';
import { UserStorageResource } from 'pc-component-v3';

export default {
  components: {
    DownOutlined,
  },

  data() {
    return {
      userRoleOrTemplateList: [],
      roleStateInstance: useRoleStateSingleton,
    };
  },

  computed: {
    displayRoleName() {
      return this.roleStateInstance.userRoleOrTemplate?.roleOrTemplateName || '全部';
    },
  },

  mounted() {
    this.init();
  },

  methods: {
    // 入口：先获取已保存的选中项，再加载角色列表，最后通知消费者就绪
    async init() {
      try {
        const savedRole = await this.fetchSavedRole();
        await this.loadRoleList(savedRole);
      } finally {
        // 无论角色列表加载成功或失败，都必须通知消费者初始化已完成
        this.roleStateInstance.markRoleReady();
      }
    },

    // 仅从远端获取已保存的选中角色，不做任何副作用
    async fetchSavedRole() {
      const key = 'UserSelectedRole';
      try {
        const { errorCode, data } = await UserStorageResource.uniqueByKey(key);
        if (errorCode === 0) {
          return data ? JSON.parse(data) : null;
        }
        return null;
      } catch (error) {
        Common.processException(error);
        return null;
      }
    },

    // 加载角色列表后，将已保存的选中项匹配到列表并设置选中状态
    async loadRoleList(savedRole) {
      try {
        const response = await $.ajax({
          url: Common.getApiURL('RoleResourceV3/listUserRoleOrTemplate'),
          type: 'GET',
          contentType: 'application/json',
          beforeSend: request => Common.addTokenToRequest(request),
        });

        if (response.errorCode === 0) {
          this.userRoleOrTemplateList = response.datas;
          this.applySavedRole(savedRole);
        } else {
          Notify.error('错误', response.errorMessage, false);
        }
      } catch (error) {
        Common.processException(error);
      }
    },

    // 在已加载的角色列表中匹配 savedRole，匹配不到或 savedRole 为 null 时显式选择「全部」
    applySavedRole(savedRole) {
      if (!savedRole) {
        this.roleStateInstance.setUserRoleOrTemplate(null);
      } else {
        const matched = this.userRoleOrTemplateList.find(item =>
          `${item.userRoleTemplateId}-${item.userRoleId}` ===
          `${savedRole.userRoleTemplateId}-${savedRole.userRoleId}`,
        );
        this.roleStateInstance.setUserRoleOrTemplate(matched || null);
      }
    },

    handleRoleSelect(userRoleOrTemplate) {
      this.roleStateInstance.setUserRoleOrTemplate(userRoleOrTemplate);
      this.uploadSelectedRole(userRoleOrTemplate);
    },

    async uploadSelectedRole(userRoleOrTemplate) {
      const key = 'UserSelectedRole';
      const userStorageDtos = [{
        key,
        value: userRoleOrTemplate ? JSON.stringify(userRoleOrTemplate) : null,
      }];

      try {
        await UserStorageResource.uploadUserStorage(userStorageDtos);
      } catch (error) {
        Common.processException(error);
      }
    },
  },
};
</script>

<style scoped>
.ant-dropdown-link {
  padding: 0;
  color: rgba(0, 0, 0, 0.85);
  transition: all 0.3s;
}

.ant-dropdown-link:hover {
  color: #1890ff;
}
</style>