<template>
  <div class="avatar" :style="avatarStyle">
    <a-avatar
      v-if="user.avatar"
      :size="size"
      class="icon"
      :src="user.avatar"
      shape="circle"
    />
    <a-avatar
      v-else
      :size="size"
      class="icon"
      shape="circle"
      :style="{ color: '#fff', backgroundColor: '#03a9f4' }"
    >
      {{ shortName }}
    </a-avatar>
    <div v-if="showName && user.name" class="name" :style="nameStyle">
      {{ user.name }}
    </div>
  </div>
</template>

<script>
import { getAction } from '@api/manage'

export default {
  name: 'FlowNodeAvatar',
  props: {
    size: {
      type: Number,
      default: 32
    },
    userId: {
      type: String,
      default: ''
    },
    showName: {
      type: Boolean,
      default: true
    },
    setType: {
      type: Number,
      default: 1
    }
  },
  data() {
    return {
      user: {
        name: '',
        avatar: ''
      }
    };
  },
  computed: {
    shortName() {
      const name = this.user.name || '';
      return name.length > 2 ? name.slice(-2) : name;
    },
    avatarStyle() {
      const padding = this.showName ? 4 : 0;
      const size = this.size + padding * 2;
      return {
        height: `${size}px`,
        borderRadius: `${size / 2}px`,
        padding: `${padding}px`
      };
    },
    nameStyle() {
      return {
        fontSize: `${this.size / 2 + 4}px`
      };
    }
  },
  watch: {
    userId: {
      immediate: true,
      handler() {
        this.loadUserDetail();
      }
    }
  },
  methods: {
    loadUserDetail() {
      getAction('sys/user/ugetUserInfo',{userId:this.userId, setType:this.setType}).then((resp) => {
        if(resp.result) {
          this.user.name = resp.result.name;
          this.user.avatar = resp.result.avatar;
        }else {
          this.user = { name: '', avatar: '' };
        }
      });
    }
  }
};
</script>

<style lang="less" scoped>
.avatar {
  background: #f2f4f5;
  display: flex;
  align-items: center;
  width: fit-content;
  box-sizing: border-box;

  .icon {
    overflow: hidden;
    flex-shrink: 0;
  }

  .name {
    user-select: none;
    font-family: PingFangSC-Regular, PingFang SC;
    color: #34383e;
    margin: 0 4px;
    overflow: hidden;
    white-space: nowrap;
    text-overflow: ellipsis;
    max-width: 100px;
  }
}
</style>
