import {ApiCall} from "tsrpc";
import {Wjjl} from "../../module/collection_wjjl";
import {TaskFun} from "../../public/task";
import {ReqOpen, ResOpen} from "../../shared/protocols/task/PtlOpen";
import {ActionLog} from "../../public/actionLog/actionLog";
import {PublicShared} from "../../shared/public/public";

export default async function (call: ApiCall<ReqOpen, ResOpen>) {
    let _types = call.req.type
    let ischk = 0
    if (_types.indexOf(1) != -1) ischk = 1
    // 所有未完成的任务
    let _taskInfo: {} = await TaskFun.getFinishByTtype(call, _types, {finish: 0}, ischk = ischk);
    // 任务 129 为自减任务
    let _rank = await Wjjl.getVal(call.uid, "jjc_rank")
    // 检查数据是否未初始化
    let reInit = Object.keys(_taskInfo).filter(key => (!_taskInfo[key] || _taskInfo[key].length == 0) && ~~key < 5)
    for (let key of reInit) {
        // 初始化
        _taskInfo[key] = await TaskFun.reInitTask(call, key)
    }
    let data = {
        taskinfo: _taskInfo,
        jjcrank: _rank
    }
    call.succ(data);

    checkTaskIsFinished(call, _taskInfo[2]?.[0])
}

/**
 * todo 目前任务计数有问题
 * 此特殊处理仅针对主线任务134类型，宝箱使用后任务未完成情况的修补，补全任务计数
 * @param call
 * @param _task
 */
async function checkTaskIsFinished(call, _task) {
    if (!_task || _task.stype != 134 || _task.type != 2) return
    if (_task.pval == _task.nval) return

    let _taskList: {} = await TaskFun.getFinishByTtype(call, [2], {
        stype: 134,
        retime: {$gte: PublicShared.getToDayZeroTime()}
    });

    let dayCount633 = R.sum(_taskList[2].map(i => i.nval >= 10 ? i.nval : 0))
    let dayCount33 = R.sum(_taskList[2].map(i => i.nval < 10 ? i.nval : 0))

    let dayLog = await ActionLog.getDayLog(call.uid, ['use_item_33', 'use_item_633'])

    let _val = 0
    if (_task.pval < 10 && dayLog?.use_item_33 > dayCount33) {
        _val = dayLog.use_item_33 - dayCount33 + _task.nval
    }

    if (_task.pval >= 10 && dayLog?.use_item_633 > dayCount633) {
        _val = dayLog.use_item_633 - dayCount633 + _task.nval
    }

    if (_val == 0) return

    // 任务值上限检测
    let _resVal = _val > _task.pval ? _task.pval : _val;
    // 设置任务
    await TaskFun.setTask(call.uid, {taskid: _task["taskid"]}, {nval: _resVal});

    if (_resVal == _task.pval) {
        G.server.sendMsgByUid(call.uid, 'msg_s2c/TaskChange', {..._task, nval: _resVal})
    }

}