import { ApiCall } from "tsrpc";
import { HeroFun } from '../../public/hero';
import { XstaskFun } from '../../public/xstask';
import { ReqOnekeyReceive, ResOnekeyReceive } from "../../shared/protocols/xstask/PtlOnekeyReceive";
import { HeroShared } from '../../shared/public/hero';
import { HongDianChange } from "../hongdian/fun";

export default async function (call: ApiCall<ReqOnekeyReceive, ResOnekeyReceive>) {

    let args = call.req;
    let _ids = args.map(a => a._id);
    let heroIds = args.map(a => a.heroIds).reduce((a, b) => a.concat(b));

    if (args.length < 1 || _ids.isDuplication() || heroIds.isDuplication()) return call.error(globalThis.lng.kbzz_1);

    let event = await G.mongodb.cEvent('xstask').findOne({uid: call.uid, type: 'xstask'});
    if (event?.receiveNum >= 8) return call.error(globalThis.lng.xstask_11);

    //所有的任务
    let taskList = await XstaskFun.getAllTask(call.uid);
    //所有的任务id
    let allTaskIds = taskList.map(task => task._id);
    //已派遣的任务id
    let receiveIds = taskList.filter(task => task.receiveData != undefined).map(task => task._id);
    //已派遣的英雄id
    let receiveHeroIds = receiveIds.length > 0 ? taskList.filter(task => task.receiveData != undefined).map(task => task.receiveData.heros).reduce((a, b) => a.concat(b)) : [];

    if (allTaskIds.intersection(_ids).length != _ids.length) return call.error(globalThis.lng.xstask_1);
    if (receiveIds.intersection(_ids).length > 0) return call.error(globalThis.lng.xstask_4);
    if (receiveHeroIds.intersection(heroIds).length > 0) return call.error(globalThis.lng.xstask_5);

    let heroList = (await HeroFun.getHeros(call, heroIds)).filter(hero => hero != null);
    if (heroList.length != heroIds.length) return call.error(globalThis.lng.xstask_6);

    let change: ResOnekeyReceive = {};
    for (let receive of args) {
        let task = taskList.find(task => task._id == receive._id);
        let taskConf = G.gc.xstask[task.taskId];

        if (receive.heroIds.length > taskConf.needNum) return call.error(globalThis.lng.xstask_7);

        let heros = heroList.filter(hero => receive.heroIds.includes(hero._id));
        let star = heros.map(h => G.gc.hero[h.heroId].star).reduce((a, b) => a + b);
        if (star < taskConf.needStar) return call.error(globalThis.lng.xstask_8);

        change[receive._id] = { time: G.time, heros: receive.heroIds };
        XstaskFun.receiveNum(call.uid)
    }

    Object.entries(change).forEach(([k, v]) => {
        XstaskFun.receiveTask(call.uid, k, v);
    });
    HongDianChange.sendChangeKey(call.uid, ['xstaskhd', 'huodonghd']);

    call.succ(change);
}