<template>
    <view class="im-avatar" :class="[
        `im-avatar--${size}`,
        {
            'im-avatar--square': shape === 'square',
            'im-avatar--rounded': shape === 'rounded',
            'im-avatar--circle': shape === 'circle',
            'im-avatar--with-border': border,
            'im-avatar--clickable': clickable
        }
    ]" :style="[customStyle, avatarStyle]" @click="handleClick" @longpress="handleLongPress">
        <!-- 图片头像 -->
        <image v-if="url" :class="['im-avatar__image',
            {
                'im-avatar__image--square': shape === 'square',
                'im-avatar__image--rounded': shape === 'rounded',
                'im-avatar__image--circle': shape === 'circle',
                'im-avatar__image--with-border': border,
            }
        ]" :src="url" :mode="imageMode" :show-menu-by-longpress="showMenuByLongpress" @error="handleImageError" />

        <!-- 文字头像（无图片时显示） -->
        <text v-else-if="title" class="im-avatar__text" :style="textStyle">
            {{ displayText }}
        </text>

        <!-- 默认图标（无图片和文字时显示） -->
        <im-icon v-else-if="icon" :name="icon" class="im-avatar__icon" :color="iconColor" :size="iconSize" />

        <!-- 在线状态指示器 -->
        <view v-if="showStatus && status" class="im-avatar__status" :class="`im-avatar__status--${status}`" />

        <!-- 加载状态 -->
        <im-loading v-if="loading" :custom-style="loadingStyle" :size="32" text="" :mask="true" />
    </view>
</template>

<script setup lang="ts">
import { computed } from 'vue'
import ImIcon from '../im-icon/im-icon.vue'
import type { AvatarProps, AvatarEmits } from '../../types/components/avatar'

// 默认Props
const props = withDefaults(defineProps<AvatarProps>(), {
    size: 'medium',
    shape: 'circle',
    border: false,
    borderColor: '#dcdfe6',
    bgColor: '#409eff',
    textColor: '#ffffff',
    fontSize: undefined,
    fontWeight: 500,
    icon: '👤',
    iconColor: '#909399',
    iconSize: undefined,
    status: 'offline',
    showStatus: false,
    clickable: false,
    loading: false,
    showMenuByLongpress: false,
    imageMode: 'aspectFill',
    customStyle: () => ({})
})

// 定义事件
const emit = defineEmits<AvatarEmits>()

// 计算属性
const displayText = computed(() => {
    if (!props.title) return ''
    // 取最后一个字符或前两个字符
    if (props.title.length <= 2) {
        return props.title
    }
    // 中文取最后两个字符，英文取首字母
    const isChinese = /[\u4e00-\u9fa5]/.test(props.title)
    if (isChinese) {
        return props.title.slice(-2)
    } else {
        const words = props.title.split(' ').filter(word => word.length > 0)
        if (words.length >= 2) {
            return words[0][0] + words[1][0]
        } else {
            return props.title.slice(0, 2)
        }
    }
})

const avatarStyle = computed(() => {
    const style: Record<string, string> = {}

    if (props.bgColor && !props.url) {
        style.backgroundColor = props.bgColor
    }

    if (props.border) {
        style.border = `2rpx solid ${props.borderColor}`
    }

    return style
})

const textStyle = computed(() => {
    const style: Record<string, string> = {
        color: props.textColor,
        fontWeight: String(props.fontWeight)
    }

    // 根据尺寸设置字体大小
    if (props.fontSize) {
        style.fontSize = `${props.fontSize}rpx`
    }

    return style
})

const loadingStyle = computed(() => {
    let borderRadius = '8rpx'

    switch (props.shape) {
        case 'circle':
            borderRadius = '50%'
            break
        case 'square':
            borderRadius = '8rpx'
            break
        case 'rounded':
            borderRadius = '20%'
            break
    }

    return { borderRadius }
})

// 事件处理
const handleClick = () => {
    if (props.clickable && !props.loading) {
        emit('click', props.id)
    }
}

const handleLongPress = () => {
    if (props.clickable && !props.loading) {
        emit('longpress', props.id)
    }
}

const handleImageError = (error: any) => {
    emit('error', error)
}
</script>

<style lang="scss" scoped>
@import '../../styles/variables.scss';

.im-avatar {
    position: relative;
    display: inline-flex;
    align-items: center;
    justify-content: center;
    box-sizing: border-box;
    vertical-align: middle;
    transition: all 0.3s ease;
    user-select: none;
    background-color: #ffffff;

    // 形状
    &--circle {
        border-radius: 50%;
    }

    &--square {
        border-radius: 8rpx;
    }

    &--rounded {
        border-radius: 20%;
    }

    &--with-border {
        box-shadow: 0 6rpx 12rpx rgba(0, 0, 0, 0.3);
    }

    &--clickable {
        cursor: pointer;

        &:active {
            opacity: 0.8;
            transform: scale(0.95);
        }
    }

    // 尺寸
    &--mini {
        width: 64rpx;
        height: 64rpx;
        font-size: 24rpx;

        .im-avatar__text {
            font-size: 24rpx;
        }

        .im-avatar__icon {
            font-size: 32rpx;
        }
    }

    &--small {
        width: 80rpx;
        height: 80rpx;
        font-size: 28rpx;

        .im-avatar__text {
            font-size: 28rpx;
        }

        .im-avatar__icon {
            font-size: 40rpx;
        }
    }

    &--medium {
        width: 100rpx;
        height: 100rpx;
        font-size: 32rpx;

        .im-avatar__text {
            font-size: 32rpx;
        }

        .im-avatar__icon {
            font-size: 48rpx;
        }
    }

    &--large {
        width: 120rpx;
        height: 120rpx;
        font-size: 36rpx;

        .im-avatar__text {
            font-size: 36rpx;
        }

        .im-avatar__icon {
            font-size: 56rpx;
        }
    }

    &--xlarge {
        width: 160rpx;
        height: 160rpx;
        font-size: 48rpx;

        .im-avatar__text {
            font-size: 48rpx;
        }

        .im-avatar__icon {
            font-size: 72rpx;
        }
    }

    &--xxlarge {
        width: 200rpx;
        height: 200rpx;
        font-size: 60rpx;

        .im-avatar__text {
            font-size: 60rpx;
        }

        .im-avatar__icon {
            font-size: 88rpx;
        }
    }

    // 子元素
    &__image {
        width: 100%;
        height: 100%;
        object-fit: cover;

        // 形状
        &--circle {
            border-radius: 50%;
        }

        &--square {
            border-radius: 8rpx;
        }

        &--rounded {
            border-radius: 20%;
        }

        &--with-border {
            box-shadow: 0 2rpx 8rpx rgba(0, 0, 0, 0.3);
        }
    }

    &__text {
        font-weight: 500;
        line-height: 1;
        text-transform: uppercase;
    }

    // &__icon {
    //     line-height: 1;
    // }

    // 状态指示器
    &__status {
        position: absolute;
        right: 0;
        bottom: 0;
        width: 20rpx;
        height: 20rpx;
        border: 2rpx solid white;
        border-radius: 50%;

        &--online {
            background-color: #07c160;
        }

        &--offline {
            background-color: #c8c9cc;
        }

        &--busy {
            background-color: #ff976a;
        }

        &--away {
            background-color: #ffd700;
        }

        // 根据尺寸调整位置和大小
        .im-avatar--mini &,
        .im-avatar--small & {
            width: 16rpx;
            height: 16rpx;
            right: -2rpx;
            bottom: -2rpx;
        }

        .im-avatar--large &,
        .im-avatar--xlarge &,
        .im-avatar--xxlarge & {
            width: 24rpx;
            height: 24rpx;
            right: 4rpx;
            bottom: 4rpx;
        }
    }

    // 加载状态
    &__loading {

        // 形状
        &--circle {
            border-radius: 50%;
        }

        &--square {
            border-radius: 8rpx;
        }

        &--rounded {
            border-radius: 20%;
        }
    }
}

// 暗黑模式适配
@media (prefers-color-scheme: dark) {
    .im-avatar {
        &--with-border {
            border-color: #5c5c5c;
        }

        &__status {
            border-color: #2c2c2c;
        }

        &__badge {

            &--dot,
            &--number {
                border-color: #2c2c2c;
            }
        }
    }
}
</style>