bindbox-mini/composables/useRecords.js

66 lines
1.7 KiB
JavaScript

/**
* 购买记录管理 Composable
*/
import { ref } from 'vue'
import { getIssueDrawLogs } from '@/api/appUser'
/**
* 购买记录管理
*/
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 : [])
// 聚合同一奖品的记录
const aggregate = {}
list.forEach(it => {
const key = it.reward_id || it.id
if (!aggregate[key]) {
aggregate[key] = {
id: key,
title: it.reward_name || it.title || it.name || '-',
image: it.reward_image || it.image || '',
count: 0
}
}
aggregate[key].count += 1
})
const total = list.length || 1
winRecords.value = Object.values(aggregate).map(it => ({
...it,
percent: ((it.count / total) * 100).toFixed(1)
}))
} catch (e) {
console.error('fetchWinRecords error', e)
winRecords.value = []
} finally {
loading.value = false
}
}
function clearRecords() {
winRecords.value = []
}
return {
winRecords,
loading,
fetchWinRecords,
clearRecords
}
}