import {ApiCall} from "tsrpc";
import {ReqOpen, ResOpen} from "../../../shared/protocols/event/zhoumolibao/PtlOpen";
import {PayFun} from "../../../public/pay";
import {HuoDongFun} from "../../../public/huodongfun";
import {PublicShared} from "../../../shared/public/public";


export default async function (call: ApiCall<ReqOpen, ResOpen>) {
    let data = await G.mongodb.cEvent('zhoumolibao').findOne({uid: call.uid, type: 'zhoumolibao'})

    let _hd = (await HuoDongFun.gethdList(call, 9))[0]

    let payIds = _hd?.data?.gift?.filter(i => i.payId)?.map(i => i.payId)

    call.succ({
        record: data?.record || {},
        buyLog: await PayFun.getPayLogs(call.uid, payIds)
    })
}

export async function getConf(call, args?: { id?: string; payId?: string }) {
    let _hd = (await HuoDongFun.gethdList(call, 9))[0]
    if (!_hd) return []
    if (args?.id) return _hd?.data?.gift?.find(i => i.id == args.id)
    if (args?.payId) return _hd?.data?.gift?.find(i => i.payId == args.payId)
    return _hd?.data?.gift
}

export async function checkResetBuyLog(call) {
    let zeroTime = PublicShared.getToDayZeroTime()

    let data = await G.mongodb.cEvent('zhoumolibao').findOne({uid: call.uid, type: 'zhoumolibao'})
    if (!data?.refreshTime || data?.refreshTime < zeroTime) {
        G.mongodb.cEvent(`zhoumolibao`).updateOne(
            {uid: call.uid, type: `zhoumolibao`},
            {$set: {record: {}, refreshTime: G.time}},
            {upsert: true}
        )
    }

    let gifts = await getConf(call)

    let payIds = gifts.filter(i => i.payId)?.map(i => i.payId)
    let payLogs = await PayFun.getPayLogs(call.uid, payIds)
    let payLogLength = R.flatten(R.values(payLogs)).filter(i => i.time < zeroTime).length
    if (payLogLength) {
        PayFun.delPayLog(call.uid, ...payIds.map(i => ({payId: i, val: []})))
    }
}