import {ApiCall} from "tsrpc";
import {PlayerFun} from '../../public/player';
import {TaskFun} from "../../public/task";
import {ReqFinsh, ResFinsh} from "../../shared/protocols/task/PtlFinsh";
import {HongDianChange} from "../hongdian/fun";
import {taskType} from "../../shared/protocols/task/type";

export default async function (call: ApiCall<ReqFinsh, ResFinsh>) {
    let taskid = call.req.taskid;
    let _tasks = await TaskFun.getUserTaksList(call.uid, {taskid: taskid})
    let _task
    // 无此id任务
    if (_tasks.length == 0) {
        return call.error('', {code: -1, message: globalThis.lng.task_finsh_1})
    } else {
        _task = _tasks[0]
    }

    // 任务配置错误
    let _con = await TaskFun.getTaskConByType(_task["type"], taskid)
    if (!_con || Object.keys(_con).length == 0) {
        // 策划改了任务 找不到 自动删除任务
        await G.mongodb.collection("task").deleteMany({uid: call.uid, taskid: _task["taskid"]});
        HongDianChange.sendChangeKey(call.uid, ['taskhd', 'huodonghd'])
        return call.error('', {code: -2, message: globalThis.lng.task_finsh_2})
    }

    // 任务已完成
    if (_task["finish"]) {
        return call.error('', {code: -3, message: globalThis.lng.task_finsh_3})
    }

    // 任务未完成
    if (_task["nval"] < _con["pval"]) {
        return call.error('', {code: -4, message: globalThis.lng.task_finsh_4})
    }

    // 检测生成后续任务
    let _follow = _con["followtask"]
    let newTask = {}
    if (_follow) {
        // 检测生成新任务
        newTask = await TaskFun.setTaskInfo(call, _follow, _task)
    }
    // 设置数据
    await TaskFun.setTask(call.uid, {taskid: taskid}, {finish: 1})
    // 是否是每日任务奖励最终宝箱
    if (_task["type"] == 4 && 25 == taskid){
        // 监听任务
        G.emit("Class_task_155", 'Class_task_155', call, 1, 0);
    }

    let _prize = await PlayerFun.sendPrize(call, _con["prize"])
    _task["finish"] = 1

    let data = {
        task: _task,
        prize: _prize,
        newtask: newTask
    }

    HongDianChange.sendChangeKey(call.uid, ['taskhd', 'huodonghd'])
    call.succ(data);
}