import { ApiCall } from "tsrpc";
import { FightFun } from "../../public/fight";
import { KuangDongfun } from "../../public/kuangdong";
import { KuangDongKaiCailog } from "../../shared/protocols/kuangdong/PtlOpen";
import { ReqZhanLing, ResZhanLing } from "../../shared/protocols/kuangdong/PtlZhanLing";
import { PlayerShared } from "../../shared/public/player";
import { HongDianChange } from "../hongdian/fun";
import { getGud } from "../../public/gud";


export default async function (call: ApiCall<ReqZhanLing, ResZhanLing>) {
    let hdid = call.req.hdid;
    let _con = await KuangDongfun.getCon(hdid);

    // 参数错误
    if (!_con) {
        return call.error('', { code: -1, message: globalThis.lng.kudangdong_1 });
    }
    let _kdInfo
    if (_con.public_map == 1){
        _kdInfo = await KuangDongfun.getKaiCaiInfo(hdid);
    }else {
        _kdInfo = await KuangDongfun.getKaiCaiInfo(hdid, call.uid);
    }

    // 重复占领
    if (_kdInfo && _kdInfo.uid == call.uid) {
        return call.error('', { code: -2, message: globalThis.lng.kudangdong_4 });
    }

    // 新手保护期
    let _wudiTime = G.gc.com.TerritoryFight_InvincibleTime.value;
    if (_kdInfo && _kdInfo.ctime >= G.time - _wudiTime * 60) {
        return call.error('', { code: -3, message: globalThis.lng.kudangdong_5 });
    }

    let _chongfu = await G.mongodb.collection('kuangdong').findOne({ uid: call.uid, kdtype: _con.type });
    if (_chongfu) {
        // 此区域不可重复获取
        return call.error('', { code: -6, message: globalThis.lng.kudangdong_11 });
    }

    // 此街道不可抢夺
    if (_kdInfo && !_con.public_map) {
        return call.error('', { code: -4, message: globalThis.lng.kudangdong_3 });
    }

    // 2023.8.29 策划新加 所有矿所有区域，总次数限制（目前各区域一次，总3次）
    let _allAreaDayNum = G.gc.com.dpzd_quyu_num.value
    let _mykdList = await G.mongodb.collection('kuangdong').find({ uid: call.uid }).toArray()
    let _tqNum = Object.keys(call.conn.gud.shoucangping).indexOf("4") != -1 ? 1 : 0
    if (_mykdList.length >= _allAreaDayNum + _tqNum) {
        return call.error('', { code: -4, message: globalThis.lng.kudangdong_12 });
    }

    // 次数信息
    let _mydata = await KuangDongfun.getNumInfo(call);
    // 配置可挑战次数
    let _fightNumCon = G.gc.com.TerritoryFight_ChallengesNum.value;
    // 购买次数
    let _buyNum = _mydata.buynum?.[_con.type] || 0;
    // 已挑战次数
    let _fightNum = _mydata.eara?.[_con.type] || 0;

    let changeData: ResZhanLing = {
        mydata: _mydata
    };
    let _isQdSuccess = 1;
    let isFight = false;
    let GHdata = await call.conn.gonghui;
    
    if (_kdInfo && _kdInfo.uid != call.uid) {
        // 挑战次数不足   打架才扣次数
        if (_fightNumCon + _buyNum + (PlayerShared.getMingDaoBuff(call.conn.gud, 'dpzd_zl') || 0) <= _fightNum) {
            return call.error('', { code: -5, message: globalThis.lng.kudangdong_6 });
        }
        _mydata.eara[_con.type] = 1 + (_mydata.eara?.[_con.type] || 0);
        let update = {
            $set: {
                eara: _mydata.eara,
                time: _mydata.time
            }
        };
        await G.mongodb.collection('playerInfo', 'kuangdong').updateOne({ uid: call.uid, type: 'kuangdong' }, update, { upsert: true });

        // 有人占领 抢夺
        let _toFightData = await FightFun.getPlayerFightData(_kdInfo.uid);
        //let _gud = await G.mongodb.collection('user').findOne({ uid: _kdInfo.uid });
        let _gud = await getGud(_kdInfo.uid)

        isFight = true;
        
        if (Object.keys(_toFightData.roles).length < 1) {
            // 该玩家没有上阵干部，默认被抢夺 进行收益结算
            await KuangDongfun.getKuangDongPrize(hdid, _kdInfo, { msgtype: 2, toname: _gud.name, touid: _gud.name });

            // GHdata?.addExp(5, call.uid);
        } else {
            let result = await FightFun.fight([await call.conn.getDefaultFightData(), _toFightData]);
            if (result.winSide == 0) {
                // 胜利
                await KuangDongfun.getKuangDongPrize(hdid, _kdInfo, { msgtype: 2, toname: call.conn.gud.name, touid: call.conn.gud.uid });

                // GHdata?.addExp(5, call.uid);
            } else {
                // 失败
                // 增加抢夺失败日志
                _isQdSuccess = 0;
                let _log: KuangDongKaiCailog = {
                    uid: _kdInfo.uid,
                    hdid: hdid,
                    name: _gud.name,
                    toname: call.conn.gud.name,
                    touid: call.conn.gud.uid,
                    ctime: G.time,
                    msgtype: 3,
                    longtime: G.time - _kdInfo.ctime,
                };
                await KuangDongfun.newKuangDongLog(_log);
            }
            // 增加战斗返回数据
            changeData.result = result;
        }
    }

    if (_isQdSuccess != 0) {
        let kdInfo = await KuangDongfun.miningZhanLing(call, hdid);
        kdInfo.userinfo = await KuangDongfun.getUserInfo(kdInfo.uid);
        changeData.kdInfo = kdInfo;
    }

    // if (_isQdSuccess != 0 && !isFight) {
    //     GHdata?.addExp(10, call.uid);
    // }

    HongDianChange.sendChangeKey(call.uid, ['kuangdonghd', 'taskhd', 'huodonghd']);

    changeData.mydata = _mydata;
    call.succ(changeData);
}