import { ApiCall } from "tsrpc";
import { PlayerFun } from '../../public/player';
import { TeQuanFun } from '../../public/tequan';
import { XstaskFun } from '../../public/xstask';
import { ReqRefresh, ResRefresh } from "../../shared/protocols/xstask/PtlRefresh";
import { HongDianChange } from "../hongdian/fun";

export default async function (call: ApiCall<ReqRefresh, ResRefresh>) {
    let info = await XstaskFun.getInfo(call.uid);
    let taskList = await XstaskFun.getAllTask(call.uid);
    let delNum = (G.gc.xstaskcom.lv[info.lv].maxTaskNum + await TeQuanFun.getXsTaskNum(call)) - taskList.filter(task => task.receiveData != undefined && !task.receiveData.rec).length;

    if (delNum < 1) return call.error(globalThis.lng.xstask_11);

    let event = await G.mongodb.cEvent('xstask').findOne({uid: call.uid, type: 'xstask'});
    if (event?.receiveNum >= 8) return call.error(globalThis.lng.xstask_11);

    let change: ResRefresh = {};
    let needDel = taskList.filter(task => task.receiveData == undefined || task.receiveData.rec == true);

    if (info.useFreeRefreshNum >= G.gc.xstaskcom.freeRefreshNum) {
        let meet = await PlayerFun.checkNeedByArgs(call, ...G.gc.xstaskcom.refreshNeed);
        await PlayerFun.cutNeed(call, [meet.atn]);
    } else {
        change.useFreeRefreshNum = info.useFreeRefreshNum + 1;
        XstaskFun.changeInfo(call.uid, { $inc: { useFreeRefreshNum: 1 } });
    }

    XstaskFun.delTasks(call.uid, needDel.map(v => v._id));
    await XstaskFun.addTasks(call.uid, XstaskFun.randomTasks(info.lv, delNum));
    change.taskList = await XstaskFun.getAllTask(call.uid);
    HongDianChange.sendChangeKey(call.uid, ['xstaskhd', 'huodonghd'])
    call.succ(change);
}