/**
 * 每日本相关
 */

import { resResult, shouldRefresh, calculateNum } from '../pubUtils/util';
import { STATUS } from '../consts/statusCode';
import { RoleModel, RoleType } from '../db/Role';
import { DUNGEON_CONST, GOLD_COST_RATIO } from '../consts';

/**
 * 获取秘境本数据
 * @param role 
 */
export async function getDungeonData(role: RoleType) {
    let { dungeonCnt = 0, dungeonBuyCnt = 0, dungeonRefTime, dungeonHeroes=[] } = role;
    let curTime = new Date();
    if(shouldRefresh(dungeonRefTime, curTime)) {
        dungeonCnt = 0; dungeonBuyCnt = 0;
    }

    let nextCostGold = calculateNum(GOLD_COST_RATIO.DUNGRON_BUY_NUM, {num: dungeonBuyCnt + 1 }, 50);
    return {
        nextCostGold,
        dungeonHeroes,
        battleCount: DUNGEON_CONST.MAX_CNT + dungeonBuyCnt - dungeonCnt, 
        buyCount: DUNGEON_CONST.MAX_BUY_CNT - dungeonBuyCnt 
    }
}

// 检查秘境本次数checkBattle使用
export async function checkDungeonNum(roleId: string, inc: number) {
    let { dungeonCnt = 0, dungeonBuyCnt = 0, dungeonRefTime } = await RoleModel.findByRoleId(roleId);
    let curTime = new Date();
    let needRefresh = shouldRefresh(dungeonRefTime, curTime);
    if(needRefresh) {
        dungeonCnt = 0; dungeonBuyCnt = 0;
    }
    if(dungeonCnt + inc > DUNGEON_CONST.MAX_CNT + dungeonBuyCnt) {
        return {status: -1, resResult: resResult(STATUS.DUNGEON_TIMES_LACK)}
    }
    await RoleModel.increaseDungeonCnt(roleId, needRefresh, 0, curTime);

    return { status: 0, data: { 
        battleCount: DUNGEON_CONST.MAX_CNT + dungeonBuyCnt - dungeonCnt, 
        buyCount: DUNGEON_CONST.MAX_BUY_CNT - dungeonBuyCnt 
    }};
}

/**
 * 检查秘境本次数并添加，warEnd和warSweep使用
 * @param roleId 
 * @param inc 增加的次数
 * @param isRef 在计算之前是否检查每日的刷新
 */

export async function checkDungeonAndIncrease(roleId: string, inc: number, isRef: boolean) {

    let { dungeonCnt = 0, dungeonBuyCnt = 0, dungeonRefTime } = await RoleModel.findByRoleId(roleId);
    let curTime = new Date();

    let needRefresh = isRef && shouldRefresh(dungeonRefTime, curTime);
    if(needRefresh) {
        dungeonCnt = 0; dungeonBuyCnt = 0;
    }
    
    if(dungeonCnt + inc > DUNGEON_CONST.MAX_CNT + dungeonBuyCnt ) {
        return { status: -1, resResult: resResult(STATUS.DUNGEON_TIMES_LACK) }
    }
    // console.log('needRefresh', needRefresh);
    await RoleModel.increaseDungeonCnt(roleId, needRefresh, inc, curTime);
    return {status: 1, data: {
        battleCount: DUNGEON_CONST.MAX_CNT + dungeonBuyCnt - dungeonCnt - inc, 
        buyCount: DUNGEON_CONST.MAX_BUY_CNT - dungeonBuyCnt 
    }};
}