import {ApiCall} from "tsrpc";
import {PlayerFun} from '../../public/player';
import {XstaskFun} from '../../public/xstask';
import {ReqGet, ResGet} from "../../shared/protocols/xstask/PtlGet";
import {HongDianChange} from "../hongdian/fun";
import {PublicShared} from '../../shared/public/public';
import {TeQuanFun} from "../../public/tequan";

export default async function (call: ApiCall<ReqGet, ResGet>) {

    let task = await XstaskFun.getTask(call.uid, call.req._id);
    let taskInfo = await XstaskFun.getInfo(call.uid);
    let taskConf = G.gc.xstask[task?.taskId];

    if (!task) return call.error(globalThis.lng.xstask_1);
    if (task.receiveData == undefined) return call.error(globalThis.lng.xstask_2);
    if (task.receiveData.rec) return call.error(globalThis.lng.xstask_13); // 奖励已领取
    if (task.receiveData.time + taskConf.time > G.time) {
        let second = task.receiveData.time + taskConf.time - G.time;
        let needConf = G.gc.xstaskcom.jiasu.filter(v => second >= v.time[0] && second <= v.time[1])[0];
        if (needConf) {
            await PlayerFun.checkNeedIsMeet(call, needConf.need);
            await PlayerFun.cutNeed(call, needConf.need);
        }
    }

    let change: Parameters<typeof XstaskFun.changeInfo>[1] = {$inc: {}};
    change.$inc[`finishNum.${taskConf.colour}`] = 1;
    // 比对派遣时间，如果小于当日0点，则更新新任务，否则该变领取状态为true
    if (task.receiveData.time < PublicShared.getToDayZeroTime()) {
        // 更新任务
        let newTask = XstaskFun.randomTasks(taskInfo?.lv, 1)
        XstaskFun.updateTask(call.uid, call.req._id, newTask[0].taskId)
    } else {
        // 更新领取状态
        XstaskFun.finishTask(call.uid, call.req._id)
    }
    // XstaskFun.delTask(call.uid, call.req._id);
    let send_prize = [];
    XstaskFun.changeInfo(call.uid, change);
    if (!await TeQuanFun.getXsTaskNum(call)) {
        send_prize = taskConf.prize;
    } else {
        for (let i = 0; i < 3; i++) {
            send_prize = send_prize.concat(taskConf.prize)
        }
    }
    await PlayerFun.sendPrize(call, send_prize);
    HongDianChange.sendChangeKey(call.uid, ['xstaskhd', 'huodonghd']);

    call.succ({
        taskList: await XstaskFun.getAllTask(call.uid),
        prize: send_prize
    });
}