import { time } from "console";
import { ApiCall } from "tsrpc";
import { KuangDongfun } from "../../public/kuangdong";
import { PlayerFun } from "../../public/player";
import { ReqAddPkNum, ResAddPkNum } from "../../shared/protocols/kuangdong/PtlAddPkNum";
import { HongDianChange } from "../hongdian/fun";

export default async function (call: ApiCall<ReqAddPkNum, ResAddPkNum>) {
    let _area = call.req.area
    let _num = call.req?.num || 1
    // 我的次数信息
    let _myData = await KuangDongfun.getNumInfo(call)
    // 可增加的次数配置
    let _addNumCon = G.gc.com.TerritoryFight_PurchaseNum.value
    // 已购买次数
    let _buyNum = _myData.buynum?.[_area] || 0
    if (_buyNum + _num > _addNumCon) {
        return call.error('', { code: -1, message: globalThis.lng.kudangdong_9 })
    }

    // @ts-ignore
    let need: atn[] = G.gc.com.TerritoryFight_PurchasePrice.value
    // let need: atn[] = [{ a: 'attr', t: 'rmbmoney', n: 50 }]
    need[0].n *= _num
    let meet = await PlayerFun.checkNeedByArgs(call, need[0]);
    need = [meet.atn];
    need && await PlayerFun.cutNeed(call, need);

    // 增加次数
    const newNum = _num + (_myData.buynum?.[_area.toString()] || 0)
    _myData.buynum[_area.toString()] = newNum
    let update = {
        $set: {
            buynum: _myData.buynum,
            time: _myData.time
        }
    }
    await G.mongodb.collection('playerInfo', 'kuangdong').updateOne({ uid: call.uid, type: 'kuangdong' }, update, { upsert: true })

    HongDianChange.sendChangeKey(call.uid, ['kuangdonghd'])

    call.succ({
        mydata: _myData
    });
}