import { Application, BackendSession, pinus, HandlerService, } from 'pinus';
import { resResult, genCode, getRandSingleEelm } from '../../../pubUtils/util';
import { AUCTION_SOURCE, DEBUG_MAGIC_WORD, ITEM_CHANGE_REASON, MAIL_TYPE, PUSH_ROUTE, STATUS, TASK_TYPE, WAR_TYPE } from '../../../consts';
import { BossInstanceModel } from '../../../db/BossInstance';
import { BattleRecordModel } from '../../../db/BattleRecord';
import { nowSeconds, getZeroPoint, getSeconds } from '../../../pubUtils/timeUtil';
import { getBossInstanceInfo, checkBossBattleMemberExists, pushBossHpMessage, addBossInstance, refreshUserGuildOfBoss, refreshGuildOfBoss, getBossHp, getBossInstanceInfoByData, pushBossStatus, zoomOutDamage, zoomInDamage } from '../../../services/guildBossService';
import { findWhere } from 'underscore'
import { GUILD_STRUCTURE, GUILD_BOSS_STATUS, GUILD_POINT_WAYS } from '../../../consts/constModules/guildConst';
import { DATA_NAME } from '../../../consts/dataName';
import { UserGuildModel } from '../../../db/UserGuild';
import { addActive } from '../../../services/guildService';
import { GuildModel } from '../../../db/Guild';
import { gameData, getBossByLv } from '../../../pubUtils/data';
import { lockData } from '../../../services/redLockService';
import { pushGuildBossSucMsg, getGuildChannelSid } from '../../../services/chatService';
import { checkTask } from '../../../services/task/taskService';
import { guildInter } from '../../../pubUtils/interface';
import { addItems, getGoldObject, handleCost } from '../../../services/role/rewardService';
import * as dicParam from '../../../pubUtils/dicParam';
import { RoleModel } from '../../../db/Role';
import { sendMailToGuildByContent } from '../../../services/mailService';
import { genAuction, getAuctionRewardByPoolId } from '../../../services/auctionService';
import { sendMessageToGuildWithSuc } from '../../../services/pushService';

export default function (app: Application) {
    new HandlerService(app, {});
    return new GuildHandler(app);
}

export class GuildHandler {
    constructor(private app: Application) {
    }

    // 获得boss关卡
    async getBossInstance(msg: guildInter & {}, session: BackendSession) {
        let { myUserGuild: userGuild } = msg;
        let result = await getBossInstanceInfo(userGuild);
        return resResult(STATUS.SUCCESS, result);
    }

    //开启演武场
    async openBossInstance(msg: guildInter & {}, session: BackendSession) {

        const serverId: number = parseInt(session.get('serverId'));
        const { myUserGuild: userGuild } = msg;
        
        const { guildCode: code } = userGuild;
        let res: any = await lockData(serverId, DATA_NAME.BOSS_SCRIPT, code);//加锁
        if (!!res.err)
            return resResult(STATUS.REDLOCK_ERR);
        const guild = await GuildModel.findByCode(code, serverId, 'code lv structure refOpenBossTime openBossCnt');
        if (!guild) {
            res.releaseCallback();
            return resResult(STATUS.GUILD_NOT_FOUND);
        }
        const { structure } = guild;
        const curStructure = structure.find(cur => cur.id == GUILD_STRUCTURE.BOSS);
        if (!curStructure) {
            res.releaseCallback();
            return resResult(STATUS.GUILD_STRUCTURE_NOT_FOUND);
        }
        let bossBase = getBossByLv(curStructure.lv);
        let dicBossBaseWar = getRandSingleEelm(bossBase.wars);
        // let bossHp = Math.ceil(medianCe * bossBase.ratio);
        let { ratio, bossHp } = await getBossHp(serverId, code, dicBossBaseWar, bossBase.bossLevel);

        let resGuild = await GuildModel.costFund(code, bossBase.opencost);
        if (!resGuild) {
            res.releaseCallback();
            return resResult(STATUS.GUILD_FUND_NOT_ENOUGH);
        }
        let bossInstance = await BossInstanceModel.findBossInstance(code);
        if (!!bossInstance && bossInstance.status == GUILD_BOSS_STATUS.OPEN) {
            res.releaseCallback();
            return resResult(STATUS.GUILD_SCRIPT_IS_OPENED_TODAY);
        }
        // 每天开启一次
        let { leaderOpenCnt } = await refreshGuildOfBoss(guild);
        if(leaderOpenCnt >= dicParam.GUILD_BOSS.GUILD_BOSS_OPEN_COUNT) {
            res.releaseCallback();
            return resResult(STATUS.GUILD_SCRIPT_IS_OPENED_TODAY);
        }
        await refreshGuildOfBoss(guild, 1);

        bossInstance = await BossInstanceModel.openBossInstance(code, bossHp, ratio, dicBossBaseWar.warId, bossBase.bossLevel);
        res.releaseCallback();
        
        let result = await getBossInstanceInfoByData(bossInstance, userGuild, guild);
        await pushBossStatus(code, result);
        return resResult(STATUS.SUCCESS, result);
    }

    async battleBoss(msg: guildInter & {}, session: BackendSession) {
        const roleId: string = session.get('roleId');
        const roleName: string = session.get('roleName');
        const sid: string = session.get('sid');
        const { myUserGuild: userGuild } = msg;
        const { guildCode } = userGuild;
        let bossInstance = await BossInstanceModel.findBossInstance(guildCode);
        if (!bossInstance)
            return resResult(STATUS.GUILD_SCRIPT_NOT_OPENED);
        if (bossInstance.bossHp <= 0)
            return resResult(STATUS.GUILD_SCRIPT_IS_COMPLETE);
        let { myChallengeCnt } = await refreshUserGuildOfBoss(userGuild, 0, 0);
        if(myChallengeCnt >= dicParam.GUILD_BOSS.GUILD_BOSS_CHALLENGE_COUNT) {
            return resResult(STATUS.GUILD_SCRIPT_IS_BATTLED);
        }

        let { code: bossCode, warId, ranks, bossHp, encourageCnt } = bossInstance;
        const battleCode = genCode(8); // 关卡唯一值
        await BattleRecordModel.updateBattleRecordByCode(battleCode, {
            $set: {
                roleId, roleName, battleId: warId, warType: WAR_TYPE.BOSS,
                status: 0,
                record: { heroes: [], bossInstanceCode: bossCode, bossHp: zoomOutDamage(bossHp), encourageCnt },
            }
        }, true);
        const serverId: number = parseInt(session.get('serverId'));
        await addBossInstance(guildCode, serverId, roleId);
        if (!findWhere(ranks, { roleId })) {
            await BossInstanceModel.pushRanks(bossCode, { roleId, score: 0, time: nowSeconds(), job: userGuild.job });
        } else {
            await BossInstanceModel.updateRank(bossCode, roleId);
        }
        let { myChallengeCnt: newMyChallengeCnt } = await refreshUserGuildOfBoss(userGuild, 0, 1);
        // 任务
        await checkTask(serverId, roleId, sid, TASK_TYPE.GUILD_BOSS);
        await addActive(roleId, serverId, GUILD_POINT_WAYS.BOSS_WAR);//获得活跃值
        
        return resResult(STATUS.SUCCESS, { battleCode, bossCode: bossInstance.code, myChallengeCnt: newMyChallengeCnt });
    }

    async getBossInstanceByBattleCode(msg: guildInter & { battleCode: string }, session: BackendSession) {
        const { battleCode, myUserGuild: userGuild } = msg;
        let result = {
            status: 0,
            bossInfo: null
        };
        let battleRecord = await BattleRecordModel.getBattleRecordByCode(battleCode);
        if(battleRecord && battleRecord.record && battleRecord.record.bossInstanceCode) {
            let bossInstance = await BossInstanceModel.findByCode(battleRecord.record.bossInstanceCode);
            if(bossInstance) {
                let info = await getBossInstanceInfoByData(bossInstance, userGuild);
                result.status = bossInstance.status;
                result.bossInfo = info.bossInfo && { ...info.bossInfo, encourageCnt: battleRecord.record.encourageCnt }
            }
        }
        return resResult(STATUS.SUCCESS, result);
    }

    async action(msg: guildInter & { bossCode: string, damage: number, battleCode: string }, session: BackendSession) {
        const { battleCode, damage, myUserGuild: userGuild, bossCode } = msg;
        const roleId: string = session.get('roleId');
        const roleName: string = session.get('roleName');
        const serverId: number = parseInt(session.get('serverId'));
        const { guildCode } = userGuild;
        let flag = await checkBossBattleMemberExists(guildCode, serverId, roleId, battleCode);
        if (!flag) {
            return resResult(STATUS.SUCCESS);
        }

        //记录伤害
        let bossInstance = await BossInstanceModel.updateBossHp(bossCode, zoomInDamage(damage), roleId);
        if(!bossInstance) {  // 如果已经被扣成负的了
            return resResult(STATUS.SUCCESS, { bossHp: 0 });
        }
        await BattleRecordModel.incBossDamage(battleCode, zoomInDamage(damage), bossInstance.bossHp);

        if (bossInstance.bossHp <= 0) {//进入结算

            let res:any = await lockData(serverId, DATA_NAME.BOSS_SCRIPT, guildCode);//加锁
            if (!!res.err) 
                return resResult(STATUS.SUCCESS, { bossHp: 0 });
            bossInstance = await BossInstanceModel.clearBoss(bossCode, bossInstance.bossHp, roleId);
            if (!bossInstance) return resResult(STATUS.SUCCESS, { bossHp: 0 });

            let { warId, bossLv } = bossInstance;//锁定关卡信息
            
            await pushBossHpMessage(guildCode, serverId, 0, true);
            // 击杀奖励&伤害奖励
            let dicBossBase = gameData.bossBaseByBossLv.get(bossLv);
            let dicWar = gameData.war.get(warId);
            await sendMailToGuildByContent(MAIL_TYPE.GUILD_BOSS_REWARD, guildCode, {
                params: [`${dicWar.gk_name}`], goods: dicBossBase.killReward
            });
        
            // 加入拍卖行
            if(dicBossBase) {
                let rewards = getAuctionRewardByPoolId(dicBossBase.rewards);
                await genAuction(guildCode, AUCTION_SOURCE.BOSS, bossCode, serverId, rewards);
            }

            let result = await getBossInstanceInfoByData(bossInstance, userGuild);
            await pushBossStatus(guildCode, result);
            pushGuildBossSucMsg(roleId, roleName, guildCode, bossInstance);

            res.releaseCallback();//解锁
            return resResult(STATUS.SUCCESS, { bossHp: 0 });
        } else {
            pushBossHpMessage(guildCode, serverId, bossInstance.bossHp);
            return resResult(STATUS.SUCCESS, { bossHp: bossInstance.bossHp });
        }
    }

    async battleBossEnd(msg: guildInter & { bossCode: string, battleCode: string }, session: BackendSession) {
        const { battleCode, myUserGuild: userGuild, bossCode } = msg;
        const roleId = session.get('roleId');
        const roleName = session.get('roleName');
        const sid = session.get('sid');

        let bossInstance = await BossInstanceModel.findByCode(bossCode);
        if(!bossInstance) return resResult(STATUS.WRONG_PARMS);

        let battleRecord = await BattleRecordModel.updateBattleRecordByCode(battleCode, {
            $set: { status: 1 }//战斗结束统一设置成1
        }, true);

        let { bossDamage = 0 } = battleRecord.record; // 伤害奖励
        let dicBossBase = gameData.bossBaseByBossLv.get(bossInstance.bossLv);
        let { basicReward, damageRewardTotal } = dicBossBase;
        let damageReward = damageRewardTotal.map(cur => {
            return { id: cur.id, count: Math.ceil(cur.count * bossDamage / bossInstance.bossTotalHp )}
        })
        let reward = [...basicReward, ...damageReward];

        let battleGoods = await addItems(roleId, roleName, sid, reward, ITEM_CHANGE_REASON.BOSS_BATTLE_END);
        
        let result = await getBossInstanceInfoByData(bossInstance, userGuild);

        return resResult(STATUS.SUCCESS, { ...result, battleGoods, createdAt: getSeconds(battleRecord.createdAt) });
    }

    async encourage(msg: guildInter & { count: number }, session: BackendSession) {
        const { count, myUserGuild: userGuild } = msg;
        const roleId: string = session.get('roleId');
        const sid: string = session.get('sid');

        let bossInstance = await BossInstanceModel.findBossInstance(userGuild.guildCode);
        if(!bossInstance) return resResult(STATUS.GUILD_SCRIPT_NOT_OPENED);

        let { myEncourageCnt } = await refreshUserGuildOfBoss(userGuild);
        let freeCount = dicParam.GUILD_BOSS.GUILD_BOSS_ENCOURAGE_FREECOUNT - myEncourageCnt > 0? dicParam.GUILD_BOSS.GUILD_BOSS_ENCOURAGE_FREECOUNT - myEncourageCnt: 0;
        let costGold = (count - freeCount) * dicParam.GUILD_BOSS.GUILD_BOSS_ENCOURAGE_COST;
        if(costGold < 0) costGold = 0;
        let { gold } = await RoleModel.findByRoleId(roleId, 'gold');
        if(gold < costGold) return resResult(STATUS.BATTLE_GOLD_NOT_ENOUGH);

        let { code, bossLv } = bossInstance;
        let dicBossBase = gameData.bossBaseByBossLv.get(bossLv);

        bossInstance = await BossInstanceModel.encourage(code, count, dicBossBase.encourageSum); // 军团次数
        if(!bossInstance) return resResult(STATUS.GUILD_SCRIPT_ENCOURGE_NOT_ENOUGH);

        let consume = getGoldObject(costGold);
        let costResult = await handleCost(roleId, sid, [consume], ITEM_CHANGE_REASON.GUILD_BOSS_ENCOURAGE);
        if(!costResult) return resResult(STATUS.BATTLE_GOLD_NOT_ENOUGH);

        let { myEncourageCnt: myEncourageCntResult } = await refreshUserGuildOfBoss(userGuild, count);

        let result = {
            encourageCnt: bossInstance.encourageCnt,
            encourageMax: dicBossBase.encourageSum,
            myEncourageCnt: myEncourageCntResult
        }
        await sendMessageToGuildWithSuc(userGuild.guildCode, PUSH_ROUTE.GUILD_BOSS_ENCOURAGE, result);
        return resResult(STATUS.SUCCESS, result);

    }

    async debugAddBattleTimes(msg: { magicWord: string }, session: BackendSession) {
        const { magicWord } = msg;
        if (magicWord !== DEBUG_MAGIC_WORD) {
            return resResult(STATUS.TOKEN_ERR);
        }
        const roleId: string = session.get('roleId');
        await UserGuildModel.updateInfo(roleId, { bossChallengeCnt: 0 }, {});

        return resResult(STATUS.SUCCESS);

    }

    async debugAddOpenTimes(msg: { magicWord: string }, session: BackendSession) {
        const { magicWord } = msg;
        if (magicWord !== DEBUG_MAGIC_WORD) {
            return resResult(STATUS.TOKEN_ERR);
        }
        const guildCode: string = session.get('guildCode');
        await GuildModel.updateInfo(guildCode, { openBossCnt: 0 }, {});

        return resResult(STATUS.SUCCESS);

    }
}