import { ApiCall } from "tsrpc";
import { PlayerFun } from '../../public/player';
import { TaskFun } from "../../public/task";
import { ReqAllFinsh, ResAllFinsh } from "../../shared/protocols/task/PtlAllFinsh";
import { prizeType } from "../../shared/protocols/type";
import { HongDianChange } from "../hongdian/fun";

export default async function (call: ApiCall<ReqAllFinsh, ResAllFinsh>) {
    let _type = call.req.type;
    let _tasks = await TaskFun.getUserTaksList(call.uid, { type: _type, finish: 0 })

    let newTask: {}[] = []
    let _finishTaks: number[] = []
    let _prize: prizeType[] = []
    for (let index = 0; index < _tasks.length; index++) {
        const _task = _tasks[index];
        let _taskCon = await TaskFun.getTaskConByType(_task["type"], _task["taskid"])
        if (!_taskCon || Object.keys(_taskCon).length == 0) {
            // 策划改了任务 找不到 自动删除任务
            await G.mongodb.collection("task").deleteMany({ uid: call.uid, taskid: _task["taskid"] });
            continue
        }
        // 任务未完成
        if (_task["nval"] < _taskCon["pval"]) continue
        _finishTaks.push(_task["taskid"])
        Object.assign(_prize, _taskCon["prize"])

        // 检测后续任务生成
        let _tmp = {}
        if (_taskCon["followtask"]) {
            _tmp = await TaskFun.setTaskInfo(call, _taskCon["followtask"], _task as any)
            if (_tmp["_id"]) delete _tmp["_id"]
            newTask.push(_tmp)
        }
    }

    // 无奖励可领取
    if (_prize.length == 0) {
        return call.error('', { code: -1, message: globalThis.lng.task_finsh_5 })
    }

    // 设置数据
    await TaskFun.setTask(call.uid, { type: _type, taskid: { $in: _finishTaks } }, { finish: 1 })
    let prize = await PlayerFun.sendPrize(call, _prize)
    // 是否是每日任务奖励最终宝箱
    if (_type == 4 && 25 in _finishTaks){
        // 监听任务
        G.emit("Class_task_155", 'Class_task_155', call, 1, 0);
    }


    let data = {
        finishtask: _finishTaks,
        prize: prize,
        newtask: newTask
    }
    HongDianChange.sendChangeKey(call.uid, ['taskhd', 'huodonghd'])
    call.succ(data);
}