<!-- components/UserFormatter.vue -->
<template>
  <view>
    <!-- 显示格式化后的用户名 -->
    <text v-if="userName">{{ userName }}</text>
    <text v-else>加载中...</text>
  </view>
</template>

<script>
import {getUser} from '@/api/system/user.js'
export default {
  name: 'UserFormatter',
  props: {
    userId: {
      required: true
    },
    userMap: {
      type: Object,
      default: () => ({})
    }
  },
  data() {
    return {
      userName: ''
    };
  },
  watch: {
    // 监听 userId 变化
    userId: {
      immediate: true,
      handler: 'fetchUserName'
    },
    // 监听 userMap 变化
    userMap: {
      immediate: true,
      handler: 'fetchUserName'
    }
  },
  methods: {
    // 获取用户名
    async fetchUserName() {
      if (this.userMap[this.userId]) {
        // 如果 userMap 中有缓存，直接使用
        this.userName = this.userMap[this.userId];
      } else {
        // 否则从接口获取
        try {
					if(!this.userId) return
          const res = await getUser(this.userId);
					const userInfo = res.data;
          this.userName = userInfo.nickName;
          // 更新 userMap
          this.$emit('update:userMap', {
            ...this.userMap,
            [this.userId]: userInfo.userId
          });
        } catch (error) {
          console.error('获取用户信息失败:', error);
          this.userName = '未知用户';
        }
      }
    }
  }
};
</script>

<style scoped>
/* 可根据需要添加样式 */
</style>