import { BossInstanceType, BossInstanceModel } from '../db/BossInstance';
import { getZeroPoint } from '../pubUtils/timeUtil';
import { lockData } from '../services/redLockService';
import { findIndex } from 'underscore';
import { MailType } from '../db/Mail';
import { sismemberAsync, smembersAsync, saddAsync, delAsync, getRoleOnlineInfo } from '../services/redisService';
import { pinus } from 'pinus';
import { STATUS } from '../consts/statusCode';
import { deepCopy, resResult } from '../pubUtils/util';
import { BattleRecordModel } from '../db/BattleRecord';
import { getArmyBossRank, gameData } from '../pubUtils/data';
import { sendMailByContent } from '../services/mailService';
import { pushMail } from '../pubUtils/interface';
import { MAIL_TYPE, AUCTION_SOURCE } from '../consts';
import { GUILD_BOSS_STATUS } from '../consts/constModules/guildConst';
import { genAuction } from './auctionService';
/**
 * 获得boss界面
 * @param bossInstance 
 * @param roleId 
 */
export async function getBossInstanceInfo(bossInstance: BossInstanceType, roleId:string) {
    let { warId, ranks,  bossHp, bossLv, winWarId, winTime, roleIdRecords, guildCode, startTime, winBossLv } = bossInstance;
    ranks.sort(function(a, b) {
        return b.score - a.score + a.time - b.time;
    });
    let result:any = {};
    if (!!winWarId && winTime > getZeroPoint() && roleIdRecords.indexOf(roleId) == -1) {
        //今日通关过，且首次点开boss界面，提示某某boss已通关
        result = { showParam: { winWarId, winBossLv } };
        await BossInstanceModel.recordRoleIdWhenCheck(guildCode, roleId);
    }
    if ( bossHp <= 0 ) { 
        result = { warId };
        if (startTime < getZeroPoint()) {
            //今日未开启过boss，等待开启
            result.status = GUILD_BOSS_STATUS.WAIT_OPEN;
            return result;
        } else {
            //今日已开启，且boss通关
            result.status = GUILD_BOSS_STATUS.OPENED;
            return result;
        }
    }
    let isBattled = false;
    let myRank = {};
    let lastRanks = ranks.map(({roleId: battleRoleId, score, time}, index) => {
        if (roleId == battleRoleId) {
            myRank = { roleId, score, rankLv: index + 1 };
            if (time >= getZeroPoint())
                isBattled = true;
        }
        return {roleId, score, rankLv: index + 1};
    });
    return { warId, ranks: lastRanks, myRank, bossHp, status: GUILD_BOSS_STATUS.OPEN, isBattled, bossLv };
}
/**
 * 战斗结束返回
 * @param bossInstance 
 * @param roleId 
 * @param battleNum 
 */
export async function getBossInstanceWhenEnd(bossInstance: BossInstanceType, roleId:string, battleNum:number) {
    let { warId, ranks, bossHp, winWarId, guildCode, recordRanks, winNum, bossLv, winBossLv } = bossInstance;
    let pushRanks;
    let result:any = {};
    if (battleNum == winNum) { //检查当前战斗回调是否是上一次战斗的回调，若是返回上次排名的结果
        pushRanks = deepCopy(recordRanks);
        result = {warId: winWarId, bossHp: 0, bossLv: winBossLv, status:  GUILD_BOSS_STATUS.OPEN};
        await BossInstanceModel.recordRoleIdWhenCheck(guildCode, roleId);
    } else { 
        pushRanks = deepCopy(ranks);
        result = {warId, bossHp, bossLv, status:  GUILD_BOSS_STATUS.OPEN};
    }
    pushRanks.sort(function(a, b) {
        return b.score - a.score + a.time - b.time;
    });
    let isBattled = false;
    let myRank = {};
    pushRanks.forEach(({roleId: battleRoleId, score, time}, index) => {
        if (roleId == battleRoleId) {
            myRank = {roleId, score, rankLv: index + 1};
            if (time >= getZeroPoint())
                isBattled = true;
        }
        return {roleId, score, rankLv: index + 1};
    });
    result.myRank = myRank;
    result.ranks = pushRanks;
    result.isBattled = isBattled;
    return result;
}

/**
 * 结算战斗
 * @param code 
 * @param serverId 
 * @param dataName 
 * @param damage 
 * @param roleId 
 */
export async function bossResult(code: string, serverId: number, dataName: string, roleId: string, damage: number) {
    let res:any = await lockData(serverId, dataName, code);//加锁
    if (!!res.err) 
        return true;
    let {winSettled, ranks, num, warId, bossHp, bossLv, code: bossCode } = await BossInstanceModel.findBossInstance(code);//锁定关卡信息
    if (winSettled) {
        res.releaseCallback();//解锁
        await BossInstanceModel.recordRoleIdWhenCheck(code, roleId);
        return true;
    } 
    let index = findIndex(ranks, {roleId});
    if (index == -1) {
        res.releaseCallback();//解锁
        return false;
    }
    ranks[index].score += bossHp; 
    if (bossHp > damage) {//检查造成的伤害是否会让boss死亡
        res.releaseCallback();//解锁
        return true;
    }
    let { recordRanks } = await BossInstanceModel.updateBossInstance(code, { bossHp: 0, winSettled: true, ranks,  recordRanks: ranks, winNum: num, winWarId: warId, winBossLv: bossLv, roleIdRecords:[roleId]}, );
    await pushBossHpMessage(code, serverId, 0, true);
    res.releaseCallback();//数据修改解锁
    recordRanks.sort(function(a, b) {
        return b.score - a.score + a.time - b.time;
    });
    //下发邮件奖励
    let mails = new Array<MailType>();
    let pushMessage = new Array<pushMail>();
    recordRanks.forEach(async function({ roleId }, index){
        let rankLv = index + 1;
        let goods = getArmyBossRankReward(rankLv);
        if (!goods || !goods.length)
            return;
        await sendMailByContent(MAIL_TYPE.GUILD_BOSS_REWARD, roleId, {
            params: [JSON.stringify(rankLv)], goods
        })
    });
    // 加入拍卖行
    let dicBossBase = gameData.bossBaseByBossLv.get(bossLv);
    if(dicBossBase) {
        await genAuction(code, AUCTION_SOURCE.BOSS, bossCode, serverId, dicBossBase.reward);
    }

    return true;
}
/**
 * 获得排名区间奖励
 * @param rankLv 
 */
export function getArmyBossRankReward(rankLv: number) {
    let armybossRankReward = getArmyBossRank();
    for (let item of armybossRankReward) {
        if (item.rankMin <= rankLv && (rankLv <= item.rankMax || item.rankMax == -1)) {
            return item.reward;
        }
    }
}
 /**
  * 将玩家加入到正在挑战boss队列中
  * @param code 
  * @param serverId 
  * @param roleId 
  */
export async function addBossInstance(code: string, serverId:number, roleId: string) {
    let hisOnlineInfo = await getRoleOnlineInfo(roleId);
    if(hisOnlineInfo.isOnline) {
        let key = 'serverId_' + serverId + 'guildCode_' + code;
        let value = roleId+ '|' + hisOnlineInfo.sid;
        await saddAsync(key, [value]);
    }
}

/**
 * 给当前正在挑战的玩家下发血量同步信息
 * @param code 
 * @param serverId 
 * @param bossHp 
 * @param isDelKey 
 */
export async function pushBossHpMessage(code: string, serverId:number, bossHp:number, isDelKey?: boolean ) {
    let key = 'serverId_' + serverId + 'guildCode_' + code;
    let members = await smembersAsync(key);
    let uids = members.map(member=>{
        let arr = member.split('|');
        let uid = arr[0];
        let sid = arr[1];
        return {uid, sid};
    });
    pinus.app.channelService.pushMessageByUids('onBossHpUpdate', resResult(STATUS.SUCCESS, {bossHp}), uids);
    if (isDelKey) {
        delAsync(key);
    }
}
/**
 * 检查该玩家当前是否正在挑战boss的队列中
 * @param code 
 * @param serverId 
 * @param roleId 
 * @param battleCode 
 */
export async function checkBossBattleMemberExists(code: string, serverId:number, roleId: string, battleCode:string ) {
    let hisOnlineInfo = await getRoleOnlineInfo(roleId);
    let key = 'serverId_' + serverId + 'guildCode_' + code ;
    let value = roleId+ '|' + hisOnlineInfo.sid;
    let flag = await sismemberAsync(key, value);
    if (!flag) {
        const battleRecord = await BattleRecordModel.getBattleRecordByCode(battleCode, true);
        if(!battleRecord || battleRecord.status != 0 || roleId != battleRecord.roleId) {
            return false;
        } 
        await addBossInstance(code, serverId, roleId);
        flag = true;
    }
    return flag;
}
/**
 * 成员退出，删除boss关排行信息
 * @param guildCode 
 * @param roleId 
 */
export async function removeBossRank(guildCode: string, roleId: string) {
    await BossInstanceModel.removeBossRank(guildCode, roleId);  
}
