import { ApiCall } from "tsrpc";
import { FightFun } from '../../public/fight';
import { PlayerFun } from '../../public/player';
import { ReqFind, ResFind } from "../../shared/protocols/conglinshoulie/PtlFind";
import { PublicShared } from '../../shared/public/public';
import { addStar, clslDb } from './ApiOpen';
import { EmailFun } from "../../public/email";

export default async function (call: ApiCall<ReqFind, ResFind>) {
    let weekZeroTime = PublicShared.getToWeekMondayZeroTime();

    // 未到开启时间
    if (G.time < weekZeroTime + G.gc.clsl_com.fightTime[0] || G.time > weekZeroTime + G.gc.clsl_com.fightTime[1]) {
        return call.errorCode(-1)
    };

    // 获取自己的数据
    let db = await clslDb().findOne({ uid: call.uid, type: 'clsl' });

    let curStar = db?.allStar || 0;
    let useNum = db?.useFightNum || 0;
    let buyNum = db?.buyFightNum || 0;
    let danPrize = db?.danPrize || [];
    let curMaxStar = db?.curMaxStar || 0;

    // 战斗次数不足
    if (useNum >= buyNum + G.gc.clsl_com.fightNum) {
        return call.errorCode(-2);
    }

    // 自己战斗数据
    let my = await call.conn.getDefaultFightData();

    // 获取一个对手
    let other = (await G.clientCross.callApi('clsl/FindEnemy', { uid: call.uid, myStasr: curStar })).res;

    let result = FightFun.fight([my, other.info]);

    let starConf = G.gc.clsl_dan[curStar] || Object.values(G.gc.clsl_dan).slice(-1)[0];

    let updata = { $inc: { useFightNum: 1 } };

    // 更新战斗胜利的次数
    if (result.winSide == 0) {
        updata.$inc["fightWinNum"] = 1;

        // 首次达到某个段位
        if (curStar + 1 > curMaxStar) {
            curMaxStar += 1;
            updata.$inc["curMaxStar"] = 1;
        }
    }

    // 段位奖励邮件
    let title = G.gc.clsl_com.email_dan.title;
    let content = G.gc.clsl_com.email_dan.content;
    G.gc.clsl_com.danPrize.forEach(conf => {
        // 段位未达到 或者 奖励已经发放
        if (conf.star > curMaxStar || danPrize.includes(conf.star)) {
            return
        }

        // 发放邮件
        EmailFun.addEmail({
            uid: call.uid,
            type: 'system',
            title: title,
            content: content,
            prize: conf.prize,
            contentInsertArr:[conf.title]
        })

        danPrize.push(conf.star);
        updata["$set"] = { danPrize: danPrize };
    })

    // 输了掉星 或者 赢了加星 同时更新排行数据
    addStar(call, result.winSide == 0 ? 1 : -starConf.failCut, my, updata);
    
    result.initData[0].star = curStar;
    result.initData[1].star = other.allStar;

    // 发送战斗奖励
    await PlayerFun.sendPrize(call, starConf.fightPrize);

    // 记录战斗日志
    G.clientCross?.callApi('clsl/Log', { uid: call.uid, result: result });
    G.clientCross?.callApi('clsl/Log', { uid: other.info.player.uid, result: result });

    call.succ({ enemy: other, result: result });
}