import { ApiCall } from "tsrpc";
import { ReqLiBao, ResLiBao } from "../../../shared/protocols/event/christmas/PtlLiBao";
import {Christmasfun} from "./fun";
import {PlayerFun} from "../../../public/player";
import {HongDianChange} from "../../hongdian/fun";

export default async function (call: ApiCall<ReqLiBao, ResLiBao>) {
    let initCon = await Christmasfun.getCon(call)
    let lbid = call.req.lbid;
    let _con = initCon[call.req.hdid].data.libao[call.req.lbid];
    if (!_con) {
        // 礼包id 不存在
        return call.error('', { code: -1, message: globalThis.lng.yangchengmubiao_2 })
    }
    if (_con.payid) {
        // 判断是否能购买
        return call.error('', { code: -2, message: globalThis.lng.yangchengmubiao_2 })
    }
    let _mydata = await Christmasfun.getMyData(call, call.req.hdid)
    let _buyNum = _mydata.libao[lbid] || 0
    if (_buyNum >= _con.buynum) {
        // 判断是否能购买
        return call.error('', { code: -3, message: globalThis.lng.yangchengmubiao_2 })
    }
    let _select = _mydata.select[lbid] || {}
    if (Object.keys(_select).length < _con.dlz.length) {
        // 判断是否选择奖励了
        return call.error('', { code: -3, message: globalThis.lng.yangchengmubiao_2 })
    }
    let _prize: atn[] = _con.basep

    for (let key in _select) {
       _prize.push(_con.dlz[parseInt(key)][_select[key]])
    }

    let _setData = {}
    _mydata.libao[lbid] = _buyNum + 1
    _setData["libao"] = _mydata.libao
    await Christmasfun.setMyData(call.uid, call.req.hdid, { $set: _setData })

    await PlayerFun.sendPrize(call, _prize);
    let changedata = { mydata: _mydata, prize: _prize}
    // 推送红点
    HongDianChange.sendChangeKey(call.uid, ['huodonghd']);
    call.succ(changedata);
}