import {ApiCall} from "tsrpc";
import {playerInfoType} from '../../module/collection_palyerInfo';
import {TeQuanFun} from '../../public/tequan';
import {XstaskFun} from '../../public/xstask';
import {ReqOpen, ResOpen} from "../../shared/protocols/xstask/PtlOpen";
import {PublicShared} from '../../shared/public/public';

export default async function (call: ApiCall<ReqOpen, ResOpen>) {
    let needAddTask: number;
    let changeInfo: Partial<playerInfoType['xstask']>;
    let taskInfo = await XstaskFun.getInfo(call.uid);
    let taskList = await XstaskFun.getAllTask(call.uid);

    if (!taskInfo) {
        changeInfo = {
            lv: 1,
            finishNum: {},
            lastRefreshTime: G.time,
            useFreeRefreshNum: 0
        };
        needAddTask = G.gc.xstaskcom.lv[changeInfo.lv].maxTaskNum;
        XstaskFun.changeInfo(call.uid, {$set: {...changeInfo}});
    } else if (PublicShared.getToDayZeroTime() > taskInfo.lastRefreshTime) {
        changeInfo = {
            lastRefreshTime: G.time,
            useFreeRefreshNum: 0
        };
        Object.assign(taskInfo, changeInfo);

        let delTask = taskList.filter(task => task.receiveData == undefined || task.receiveData.rec == true);
        let retainTask = taskList.filter(task => task.receiveData != undefined && !task.receiveData.rec);

        needAddTask = G.gc.xstaskcom.lv[taskInfo.lv].maxTaskNum - retainTask.length;

        XstaskFun.changeInfo(call.uid, {$set: {...changeInfo}});
        XstaskFun.delTasks(call.uid, delTask.map(task => task._id));
        XstaskFun.receiveNum(call.uid, true)
    }

    // needAddTask += await TeQuanFun.getXsTaskNum(call);
    needAddTask && await XstaskFun.addTasks(call.uid, XstaskFun.randomTasks(taskInfo?.lv || changeInfo.lv, needAddTask));

    let {_id, uid, type, ...info} = taskInfo || changeInfo as typeof taskInfo;
    call.succ({
        ...info,
        taskList: await XstaskFun.getAllTask(call.uid),
    });
}