import { ApiCall } from "tsrpc";
import { EmailFun } from "../../public/email";
import { FightFun } from "../../public/fight";
import { Rank } from "../../public/rank/rank";
import { WangZheRongYaofun } from "../../public/wzry";
import { ReqDldFight, ResDldFight } from "../../shared/protocols/wzry/PtlDldFight";
import { PublicShared } from "../../shared/public/public";
import { HongDianChange } from "../hongdian/fun";

const maxScore = 269; // 积分上限
const lockPrefix = 'lock:DldFight:';

export default async function (call: ApiCall<ReqDldFight, ResDldFight>) {
    const lockKey = lockPrefix + call.uid;
    const gotLock = await G.ioredis.setnx(lockKey, 1);
    if (!gotLock) {
        return call.errorCode(-101); // -101 并发请求, 告知客户端稍后再试 request_too_fast
    }
    await G.ioredis.expire(lockKey, 1); // 设置 ttl 避免死锁
    let status = await WangZheRongYaofun.getWangZheStatus();
    if (status.status != 3) {
        // 未到大乱斗时间
        return call.error('', { code: -1/* , message: globalThis.lng.wzry_5 */ });
    }

    let _mydata = await WangZheRongYaofun.getMyData(call);
    if (!_mydata.isbm) {
        // 未报名
        return call.error('', { code: -2/* , message: globalThis.lng.wzry_7 */ });
    }

    if (_mydata.dldinfo.dldpknum >= G.gc.wangzherongyao.wangzhe.dlpknum) {
        // 挑战次数不足
        return call.error('', { code: -3/* , message: globalThis.lng.wzry_7 */ });
    }

    // 我的大乱斗战斗数据
    let _myFight = await WangZheRongYaofun.getMyFight(call);
    if (!_myFight || !_mydata.info) {
        return call.error('', { code: -4/* , message: globalThis.lng.wzry_16 */ });
    }
    _myFight.data = await call.conn.getDefaultFightData();
    let [my, npc] = JSON.parse(JSON.stringify([_myFight.data, _mydata.info]));
    const result = FightFun.fight([my, npc]);

    let dldfight = _mydata.dldinfo?.dldfight || [];
    dldfight.push(result.winSide);
    _mydata.dldinfo.dldfight = dldfight;
    _mydata.dldinfo.dldpknum += 1;

    let _jifen = _myFight.jifen;
    _myFight.jifen = _myFight.jifen + await WangZheRongYaofun.getMyScore(dldfight);
    // 添加积分上限 (策划要求)
    if (_myFight.jifen > maxScore) {
        _myFight.jifen = maxScore;
    }

    // 设置数据
    let _r = await WangZheRongYaofun.setWzryDldFight(call, _myFight);
    let _enemy = (await G.clientCross.callApi('wzry/DldRefre', { uid: _mydata.uid })).res.info;
    G.mongodb.cPlayerInfo("wzry").updateOne({ uid: call.uid, type: 'wzry' }, { $set: { info: _enemy, dldinfo: _mydata.dldinfo } });
    _mydata.info = _enemy;


    let _con = await WangZheRongYaofun.getCon();
    for (let index = 0; index < _con.wangzhe.jiangli.dld.length; index++) {
        const element = _con.wangzhe.jiangli.dld[index];
        if (_jifen < element.jifen && _myFight.jifen >= element.jifen) {
            let prize = element.p;//G.gc.wangzherongyao.wangzhe.bmprize;
            prize.length > 0 && EmailFun.addEmail({
                uid: call.uid,
                type: 'system',
                title: G.gc.wangzherongyao.wangzhe.email.dldjifen.title,
                content: G.gc.wangzherongyao.wangzhe.email.dldjifen.content,
                prize: PublicShared.mergePrize(prize),
                contentInsertArr: [element.jifen]
            });
        }
    }

    _mydata.rank = _r.rank;
    _mydata.jifen = _myFight.jifen;

    HongDianChange.sendChangeKey(call.uid, ['wzryhd']);
    await G.ioredis.del(lockKey);
    call.succ({
        mydata: _mydata,
        result: result,
        wzfight: _myFight
    });
}