/**
 * 购买记录管理 Composable
 */
import { ref } from 'vue'
import { getIssueDrawLogs } from '@/api/appUser'
import { levelToAlpha } from '@/utils/activity'

/**
 * 购买记录管理
 */
export function useRecords() {
    const winRecords = ref([])
    const loading = ref(false)

    /**
     * 获取购买记录
     * @param {string} activityId - 活动ID
     * @param {string} issueId - 期ID
     */
    async function fetchWinRecords(activityId, issueId) {
        if (!activityId || !issueId) return

        loading.value = true
        try {
            const res = await getIssueDrawLogs(activityId, issueId)
            const list = (res && res.list) || (Array.isArray(res) ? res : [])

            // 直接使用原始记录列表，不进行聚合
            // 映射字段以符合 RecordsList 组件的展示需求
            winRecords.value = list.map(it => ({
                id: it.id,
                title: it.reward_name || it.title || it.name || '-', // 奖品名称
                image: it.reward_image || it.image || '', // 奖品图片
                count: 1, // 单个记录数量为1

                // 用户信息
                user_id: it.user_id,
                user_name: it.user_name || '匿名用户',
                avatar: it.avatar,

                // 时间信息
                created_at: it.created_at,

                // 其他元数据
                is_winner: it.is_winner,
                level: it.level,
                level_name: getLevelName(it.level)
            }))
        } catch (e) {
            console.error('fetchWinRecords error', e)
            winRecords.value = []
        } finally {
            loading.value = false
        }
    }

    function getLevelName(level) {
        if (!level) return ''
        const alpha = levelToAlpha(level)
        return alpha + '赏'
    }

    function clearRecords() {
        winRecords.value = []
    }

    return {
        winRecords,
        loading,
        fetchWinRecords,
        clearRecords
    }
}
