<template>
    <div class="px-5 py-2">
        <n-thing>
            <template #avatar>
                <n-avatar class="!block" round :size="40" :src="avatar"> </n-avatar>
            </template>
            <template #header-extra>
                <div class="text-xs text-[#797A8A]">{{ info.userName }}</div>
            </template>
            <template #description>
                <div class="text-sm">{{ info.content }}</div>
                <div class="flex mt-1 items-center">
                    <span class="text-xs text-[#797A8A]">{{ timeStr }}</span>
                    <span class="flex-1"></span>
                    <!-- <img src="@/assets/icon_pingjia.png" class="w-[24px]" alt="" /> -->
                    <like-btn class="ml-[10px]" @like="like" :liked="info.isLiked">{{
                        info.commentLikeCount
                    }}</like-btn>
                </div>
            </template>
        </n-thing>
    </div>
</template>

<script setup lang="ts">
import { NThing, NAvatar } from 'naive-ui'
import { LikeBtn } from '@/components/common'
import avatar from '@/assets/common-avatar.png'
import { fetchLikeComment } from '@/api'
import { useUserStore } from '@/store'
import { formatDistanceToNowStrict, isToday, format } from 'date-fns'
import { computed } from 'vue'
import zhCN from 'date-fns/locale/zh-CN'

const props = defineProps({
    info: {
        type: Object,
        default: () => {
            return {}
        }
    }
})
const emit = defineEmits(['update:info'])

const timeStr = computed(() => {
    if (props.info.createdAt) {
        if (isToday(new Date(props.info.createdAt))) {
            return formatDistanceToNowStrict(new Date(props.info.createdAt), { addSuffix: true, locale: zhCN })
        } else {
            return format(new Date(props.info.createdAt), 'MM-dd HH:mm')
        }
    }
    return ''
})

const userStore = useUserStore()
function like() {
    fetchLikeComment(userStore.userInfo.id, props.info.id).then(res => {
        if (props.info.isLiked) {
            emit('update:info', {
                ...props.info,
                isLiked: false,
                commentLikeCount: props.info.commentLikeCount - 1
            })
        } else {
            emit('update:info', {
                ...props.info,
                isLiked: true,
                commentLikeCount: props.info.commentLikeCount + 1
            })
        }
    })
}
</script>
