import {ApiCall} from "tsrpc";
import {PlayerFun} from '../../../public/player';
import {ReqRepair, ResRepair} from "../../../shared/protocols/gongyu/mingdao/PtlRepair";
import {prizeType} from '../../../shared/protocols/type';
import {PublicShared} from '../../../shared/public/public';
import {RankKfjs} from "../../../public/rank/rank_kfjs";

export default async function (call: ApiCall<ReqRepair, ResRepair>) {
    let id = call.req.id;
    if (!G.gc.mingdao[id]) return call.errorCode(-1);

    let conf = G.gc.mingdao[id];
    if (call.conn.gud.shoucangping[id] >= conf.level) return call.errorCode(-2);

    let need: prizeType[] = [];
    let itemNeed = {...conf.need, n: conf.need.n * call.req.num};
    let itemNum = await PlayerFun.getAtnNum(call, itemNeed);

    if (itemNum < itemNeed.n) {
        if (itemNum > 0) {
            need.push({...itemNeed, n: itemNum});
        }
        need.push({...G.gc.mingdao_com.changeNeed, n: G.gc.mingdao_com.changeNeed.n * itemNeed.n - itemNum});
    } else {
        need.push(itemNeed);
    }
    await PlayerFun.checkNeedIsMeet(call, need);
    await PlayerFun.cutNeed(call, need);

    let multiple = new Array(call.req.num).fill(1).map(v => PublicShared.randomDropAny(G.gc.mingdao_com.crit).multiple);
    let addExp = multiple.map(v => v * G.gc.mingdao_com.addExp).reduce((a, b) => a + b);// G.gc.mingdao_com.addExp * multiple * call.req.num;
    let curExp = (await G.mongodb.collection('mingdao').findOne({uid: call.uid}))?.list?.[id]?.pre || 0;
    let newExp = 0;

    if (curExp + addExp >= conf.needExp) {
        newExp = curExp + addExp - conf.needExp;
        let send = Object.assign({}, call.conn.gud.shoucangping);
        send[id] += 1;
        await PlayerFun.addAttr(call, {shoucangping: send});

        if (send[id] >= conf.level && G.gc.mingdao[~~id + 1]) {
            G.server.sendMsgByUid(call.uid, 'msg_s2c/HongDianChange', ['mingdao']);
        }
    } else {
        newExp = curExp + addExp;
    }

    G.mongodb.collection('mingdao').updateOne(
        {uid: call.uid},
        {$set: G.mongodb.createTreeObj({key: `list.${id}.pre`, val: newExp})},
        {upsert: true}
    );

    call.succ({
        multiple: multiple,
        pre: newExp
    });

    let cutItem = R.find(R.whereEq({a: "attr", t: "rmbmoney"}))(need)
    if (cutItem) {
        cutItem = {a: "item", t: "21", n: cutItem.n / 5}
    } else {
        cutItem = R.find(R.whereEq({a: "item", t: "21"}))(need)
    }
    let rankKfjs = RankKfjs(6)
    rankKfjs.setDataAndCheck({
        player: call.conn.gud,
        valArr: [await rankKfjs.getRankScore(call.uid) + cutItem.n]
    });

}