import {ApiCall} from "tsrpc";
import {HeroFun} from '../../public/hero';
import {XstaskFun} from '../../public/xstask';
import {ReqReceive, ResReceive} from "../../shared/protocols/xstask/PtlReceive";
import {HongDianChange} from "../hongdian/fun";

export default async function (call: ApiCall<ReqReceive, ResReceive>) {
    if (call.req.heroIds.length < 1) return call.error(globalThis.lng.xstask_9);
    if (call.req.heroIds.isDuplication()) return call.error(globalThis.lng.xstask_10);

    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 task = await XstaskFun.getTask(call.uid, call.req._id);
    let taskConf = G.gc.xstask[task?.taskId];
    if (!task) return call.error(globalThis.lng.xstask_1);
    if (call.req.heroIds.length > taskConf.needNum) return call.error(globalThis.lng.xstask_7);
    if (task.receiveData) return call.error(globalThis.lng.xstask_4);

    let recevieHeroIds = await XstaskFun.getAllReceiveHero(call.uid);
    if (recevieHeroIds.intersection(call.req.heroIds).length > 0) return call.error(globalThis.lng.xstask_5);

    let heros = await HeroFun.getHeros(call, call.req.heroIds);
    if (heros.filter(h => h != null).length < call.req.heroIds.length) return call.error(globalThis.lng.xstask_6);

    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);

    let change = {
        time: G.time,
        heros: call.req.heroIds
    };

    XstaskFun.receiveNum(call.uid)
    XstaskFun.receiveTask(call.uid, call.req._id, change);
    HongDianChange.sendChangeKey(call.uid, ['xstaskhd', 'huodonghd']);

    call.succ(change);
}