import { Application, BackendSession, pinus } from 'pinus';
import { resResult, genCode, getRandSingleEelm } from '../../../pubUtils/util';
import { STATUS, TASK_TYPE } from '../../../consts';
import { BossInstanceModel } from '../../../db/BossInstance';
import { BattleRecordModel } from '../../../db/BattleRecord';
import { nowSeconds, getZeroPoint } from '../../../pubUtils/timeUtil';
import { getBossInstanceInfo, bossResult, checkBossBattleMemberExists, pushBossHpMessage, getBossInstanceWhenEnd, addBossInstance } 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 { GUILD_OPERATE } from '../../../consts';
import { checkAuth, addActive } from '../../../services/guildService';
import { GuildModel } from '../../../db/Guild';
import { getBossByLv } from '../../../pubUtils/data';
import { lockData } from '../../../services/redLockService';
import { pushGuildBossSucMsg, getGuildChannelSid } from '../../../services/chatService';
import { checkTask } from '../../../services/taskService';

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

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

    async debugAddBattleTimes(msg: {}, session: BackendSession) {
        const roleId: string = session.get('roleId');
        let userGuild = await UserGuildModel.getMyGuild(roleId, 'guildCode');
        if (!userGuild) 
            return resResult(STATUS.WRONG_PARMS); 
        const { guildCode: code } = userGuild;
        let { ranks } = await BossInstanceModel.findBossInstance(code);
        for (let i = 0;i < ranks.length; i++) {
            let rank = ranks[i];
            if (rank.roleId == roleId) {
                rank.time = 0;
                break;
            }
        }
        let { ranks : resRanks } = await BossInstanceModel.updateBossInstance(code, {ranks});
        return resResult(STATUS.SUCCESS, { ranks: resRanks });
    }

    // 获得boss关卡
    async getBossInstance(msg: {}, session: BackendSession) {
        const roleId: string = session.get('roleId');
        let userGuild = await UserGuildModel.getMyGuild(roleId, 'guildCode');
        if (!userGuild) 
            return resResult(STATUS.WRONG_PARMS); 
        const { guildCode: code } = userGuild;
        let bossInstance = await BossInstanceModel.findBossInstance(code);
        if (!bossInstance) {
            return resResult(STATUS.SUCCESS, {status: GUILD_BOSS_STATUS.WAIT_OPEN});//等待团长开启
        }
        let result = await getBossInstanceInfo(bossInstance, roleId);
        return resResult(STATUS.SUCCESS, result);
    }
    
    //开启演武场
    async openBossInstance(msg: {}, session: BackendSession) {
        const roleId: string = session.get('roleId');
        const sid: string = session.get('sid');

        const serverId: number = parseInt(session.get('serverId'));
        let userGuild = await UserGuildModel.getMyGuild(roleId, 'auth guildCode');
        if (!userGuild) 
            return resResult(STATUS.WRONG_PARMS); 
        const { guildCode: code } = userGuild;
        const checkMyResult = await checkAuth(GUILD_OPERATE.OPEN_BOSS, roleId, null, userGuild);
        if(!checkMyResult) return resResult(STATUS.GUILD_AUTH_NOT_ENOUGH);
        let res:any = await lockData(serverId, DATA_NAME.BOSS_SCRIPT, code);//加锁
        if (!!res.err) 
            return resResult(STATUS.REDLOCK_ERR); 
        let bossInstance = await BossInstanceModel.findBossInstance(code);
        if (!!bossInstance && ( bossInstance.bossHp > 0 || bossInstance.startTime >= getZeroPoint() )) {
            res.releaseCallback();
            return resResult(STATUS.GUILD_SCRIPT_IS_OPENED_TODAY);
        }
        const guild = await GuildModel.findByCode(code, serverId, 'lv structure');
        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 { bossHp, warId } = getRandSingleEelm(bossBase.wars);
        let resGuild = await GuildModel.costFund(code, bossBase.opencost);
        if (!resGuild) {
            res.releaseCallback();
            return resResult(STATUS.GUILD_FUND_NOT_ENOUGH);
        }
        await BossInstanceModel.openBossInstance(code, bossHp, warId, bossBase.bossLevel);
        res.releaseCallback();
        let result = {warId, ranks: [], myRank: {}, bossHp, status: 3, bossLv: bossBase.bossLevel, isBattled: false};

        let chatSid = await getGuildChannelSid(code);
        pinus.app.rpc.chat.guildRemote.pushBossOpen.toServer(chatSid, code, warId, bossHp, result.status);

        return resResult(STATUS.SUCCESS, result);
    }

    async battleBoss(msg: {}, session: BackendSession) {
        const roleId: string = session.get('roleId');
        const roleName: string = session.get('roleName');
        let userGuild = await UserGuildModel.getMyGuild(roleId, 'guildCode job');
        if (!userGuild) 
            return resResult(STATUS.WRONG_PARMS); 
        const { guildCode: code } = userGuild;
        let bossInstance = await BossInstanceModel.findBossInstance(code);
        if (!bossInstance) 
            return resResult(STATUS.GUILD_SCRIPT_NOT_OPENED);
        if (bossInstance.bossHp <= 0) 
            return resResult(STATUS.GUILD_SCRIPT_IS_COMPLETE);
        let myRank = findWhere(bossInstance.ranks, {roleId});
        if (!!myRank && myRank.time > getZeroPoint()) 
            return resResult(STATUS.GUILD_SCRIPT_IS_BATTLED);
        let { warId, ranks } = bossInstance;
        const battleCode = genCode(8); // 关卡唯一值
        await BattleRecordModel.updateBattleRecordByCode(battleCode, {
            $set: {
                roleId, roleName, battleId: warId,
                status: 0,
                record: { heroes:[],recordNum: bossInstance.num, bossHp: bossInstance.bossHp},
            }
        }, true);
        const serverId:number = parseInt(session.get('serverId'));
        await addBossInstance(code, serverId, roleId);
        if (!findWhere(ranks, {roleId})) {
            await BossInstanceModel.pushRanks(code, {roleId, score: 0, time: nowSeconds(), job: userGuild.job});
        } else {
            await BossInstanceModel.updateRank(code, roleId);
        }
        return resResult(STATUS.SUCCESS, { battleCode });
    }

    async action (msg: { damage: number, battleCode: string }, session: BackendSession ) {
        const { battleCode, damage } = msg;
        const roleId: string = session.get('roleId');
        const roleName: string = session.get('roleName');
        const serverId: number = parseInt(session.get('serverId'));
        let userGuild = await UserGuildModel.getMyGuild(roleId, 'guildCode');
        if (!userGuild) 
            return resResult(STATUS.WRONG_PARMS); 
        const { guildCode: code } = userGuild;
        let flag = await checkBossBattleMemberExists(code, serverId, roleId, battleCode);
        if (!flag) {
            return resResult(STATUS.REDLOCK_ERR); 
        }
        //记录伤害
        let bossInstance = await BossInstanceModel.updateBossHp(code, damage, roleId);
        if (!bossInstance|| bossInstance.bossHp == 0) {//进入结算
            let flag = await bossResult(code, serverId, DATA_NAME.BOSS_SCRIPT, roleId, damage);
            if (!flag) {
                return resResult(STATUS.WRONG_PARMS);
            }
            pushGuildBossSucMsg(roleId, roleName, code, bossInstance);
            return resResult(STATUS.SUCCESS, { bossHp: 0 });
        } else {
            pushBossHpMessage(code, serverId, bossInstance.bossHp);
            return resResult(STATUS.SUCCESS, { bossHp: bossInstance.bossHp });
        }
    }

    async battleBossEnd(msg: { battleCode: string }, session: BackendSession) {
        const { battleCode } = msg;
        const roleId = session.get('roleId');
        const sid = session.get('sid');
        const funcs: number[] = session.get('funcs');
        const serverId: number = parseInt(session.get('serverId'));
        let userGuild = await UserGuildModel.getMyGuild(roleId, 'guildCode');
        if (!userGuild) 
            return resResult(STATUS.WRONG_PARMS); 
        const { guildCode: code } = userGuild;
        const battleRecord = await BattleRecordModel.getBattleRecordByCode(battleCode, true);
        if (!battleRecord || battleRecord.status != 0 || roleId != battleRecord.roleId) {
            return resResult(STATUS.WRONG_PARMS);
        } 
        await BattleRecordModel.updateBattleRecordByCode(battleCode, {
            $set: { status: 1 }//战斗结束统一设置成1
        }, true);
        let bossInstance = await BossInstanceModel.findBossInstance(code);
        let result = await getBossInstanceWhenEnd(bossInstance, roleId, battleRecord.record.recordNum);
        await addActive(roleId, serverId, GUILD_POINT_WAYS.BOSS_WAR);//获得活跃值
        // 任务
        await checkTask(roleId, sid, funcs, TASK_TYPE.GUILD_BOSS, 1, true, {});
        return resResult(STATUS.SUCCESS, result);
    }
    
}