<template>
  <h-icon
    v-if="ifIcon"
    :key="userInfo[avaterField]"
    class="avatar"
    :style="avatarStyle"
    :name="userInfo[avaterField].split(';')[0]"
    :color="userInfo[avaterField].split(';')[1]"
  ></h-icon>
  <img
    v-else-if="userInfo[avaterField] && !hasError"
    :src="avatarUrl"
    class="avatar"
    :style="avatarStyle"
    :onerror="handleError"
  />
  <img v-else class="avatar" :style="avatarStyle" src="@/assets/touxiang.png" alt="avatar" />
</template>

<script lang="ts">
import { defineComponent, ref, reactive, watch } from 'vue';
import { localStorage } from '@/utils/local-storage';

export default defineComponent({
  name: 'senderAvatar',
  props: {
    userInfo: {},
    avaterField: {
      type: String,
      default: 'userAvatar',
    },
    size: {
      type: Number,
      default: 24,
    },
  },

  // setup({ userInfo, avaterField, size }) {
  setup(props) {
    const ifIcon = ref(false);
    const avatarUrl = ref('');
    const avatarStyle = reactive({
      width: undefined,
      height: undefined,
    });

    const init = () => {
      const { userInfo, avaterField, size } = props;
      if (avatarUrl.value === userInfo[avaterField] && avatarUrl.value) return;
      ifIcon.value = false;
      if (userInfo[avaterField]) {
        if (userInfo[avaterField].indexOf('hoteam') > -1) {
          ifIcon.value = true;
          avatarUrl.value = userInfo[avaterField];
        } else {
          // 之前用户头像使用链接
          if (/^(http:|https:)/ig.test(userInfo[avaterField])) {
            avatarUrl.value = userInfo[avaterField];
          } 
          // 最新的方式用户头像使用id
          else {
            let access_token = localStorage.get('access_token');
            avatarUrl.value = `${window.location.origin}/api/file/applicationFile/download/?eid=${userInfo[avaterField]}&token=${access_token}`;
          }
        }
      }

      avatarStyle.width = `${size}px`;
      avatarStyle.height = `${size}px`;
    };

    watch(
      () => props.userInfo,
      () => {
        init();
      },
      {
        immediate: true,
      },
    );

    const hasError = ref(false);
    const handleError = (e: any) => {
      let img = e.srcElement || e.target;
      img.onerror = null;
      hasError.value = true;
    };

    return {
      ifIcon,
      avatarUrl,
      avatarStyle,
      hasError,
      handleError,
    };
  },
});
</script>

<style lang="less" scoped>
.avatar {
  // width: 24px;
  // height: 24px;
  border-radius: 50%;
  margin-right: 8px;
}
</style>
