<template>
    <app-block class="app-article">
        <h4 class="app-article__title">{{ title }}</h4>
        <section class="app-article__section" v-for="(group, index) in newsList" :key="index">
            <dl class="news-list">
                <dt class="news-list__date">
                    <time class="news-list__time">{{ group.time }}</time>
                </dt>
                <dd class="news-list__item" v-for="(item, index) in group.list" :key="index">
                    <div class="news-item">
                        <div class="news-item__content">
                            <div class="news-item__title">{{ item.title }}</div>
                            <div class="news-item__meta">
                                <span class="news-item__time">{{ formatDate(item.publishdate, 'HH:mm') }}</span>
                                <span class="news-item__author" v-if="item.author">{{ item.author }}</span>
                            </div>
                        </div>
                        <div class="news-item__image" v-if="item.coverimage">
                            <Image class="news-item__img" fit="cover" :src="item.coverimage" :width="68" :height="60" :radius="4" />
                        </div>
                    </div>
                </dd>
            </dl>
        </section>
    </app-block>
</template>

<script lang="ts" setup>
import { computed } from 'vue'
import { Image } from 'vant'
import { formatDate } from '@/filters'
import { useRequest } from '@/hooks/request'
import { queryNewTitles } from '@/services/api/news'

defineProps({
    title: {
        type: String,
        default: '新闻资讯'
    }
})

const { dataList } = useRequest(queryNewTitles, {
    defaultParams: {
        pagesize: 20
    }
})

const newsList = computed(() => {
    const list = dataList.value.reduce<{ time: string; list: Model.NewTitlesRsp[] }[]>((res, item) => {
        const date = item.publishdate.split('T')[0]
        const group = res.find(group => group.time === date)

        if (group) {
            group.list.push(item)
        } else {
            res.push({
                time: date,
                list: [item]
            })
        }

        return res
    }, [])

    return list.sort((a, b) => b.time.localeCompare(a.time))
})
</script>

<style lang="less">
@import "./index.less";
</style>