/**
 * 每日本相关
 */

import DailyRecord, { DailyRecordModel } from '../db/DailyRecord';
import { resResult } from '../pubUtils/util';
import { STATUS } from '../consts/statusCode';
import { RoleModel, RoleType } from '../db/Role';
import { gameData } from '../pubUtils/data';
import { DicWar } from '../pubUtils/dictionary/DicWar';
import { WarStar } from '../domain/dbGeneral';
import * as dicParam from '../pubUtils/dicParam';
import { calculateWarStar } from './normalBattleService';
import { getVipDailyCnt } from './activity/monthlyTicketService';

/**
 * 获取全部每日关卡列表
 * @param role 
 */
export async function getDailyBattleList(role: RoleType) {
    let { roleId, warStar } = role;
    let dicDaily = gameData.daily;

    let result = new Array();
    for(let {dailyType: type, timesPerDay, timesCanBuy, name } of dicDaily) {
        let refreshResult = await DailyRecordModel.refreshRecord(roleId, type);
        let wars: {battleId: number, cost: number, star: number, status: number}[] = new Array();
        let dicDailyWar = gameData.dailyWarByType.get(type);
        for(let dic of dicDailyWar) {
            let war = getDailyWarStatus(dic, warStar);
            wars.push(war);
        }
        let checkDailyResult = await getDailyNum(refreshResult, role);
        result.push({
            type, name, ...checkDailyResult,
            wars
        });
    }
    return result;
}

function getDailyWarStatus(dicDailyWar: DicWar, warStar: WarStar[]) {
    let {war_id, cost, previousGk } = dicDailyWar;
    let status = 0, star = 0;
    let curBattle = warStar.find(cur => cur.id == war_id);
    if(curBattle) {
        status = 2;
        star = curBattle.star;
    } else {
        if (previousGk) {
            let preBattleRecord = warStar.find(cur => cur.id == previousGk);
            if(preBattleRecord) {
                status = 1;
            } else {
                status = 0;
            }
        } else {
            status = 1;
        }
    }
    return {
        battleId: war_id, cost, star, status
    }
}

// 检查每日本次数checkBattle使用
export async function checkDaily(roleId: string, battleId: number, inc: number) {
    let dailyWar = gameData.war.get(battleId);
    if(!dailyWar) return { status: -1, resResult: resResult(STATUS.DAILY_WAR_NOT_FOUND) };
    let type = dailyWar.dailyType;

    let curDaily = gameData.daily.find(cur => cur.dailyType == type);
    if(!curDaily) return { status: -1, resResult: resResult(STATUS.DAILY_TYPE_NOT_FOUND) };
    let dailyRecord = await DailyRecordModel.refreshRecord(roleId, type);
    let checkDailyResult = await getDailyNum(dailyRecord);
    let { count = 0 } = checkDailyResult;
    if(count < inc) {
        return { status: -1, resResult: resResult(STATUS.DAILY_TIMES_LACK) }
    }
    return {status: 1, data: {type, ...checkDailyResult }};
}

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

export async function checkDailyAndIncrease(roleId: string, warStar: WarStar[], battleId: number, inc: number, isRef: boolean, stars = [], role?: RoleType) {
    let { newWarStars } = calculateWarStar(warStar, battleId, stars);

    let dailyWar = gameData.war.get(battleId);
    if(!dailyWar) return { status: -1, resResult: resResult(STATUS.DAILY_WAR_NOT_FOUND) };
    let type = dailyWar.dailyType;
    let war = getDailyWarStatus(dailyWar, newWarStars);

    let dailyRecord: any;
    if(isRef) { 
        dailyRecord = await DailyRecordModel.refreshRecord(roleId, type);
    } else { // 如果是手动挑战，由于在进入时已经检查过了，所以即使结算时过去了一天也还是累计在上一天
        dailyRecord = await DailyRecordModel.getDailyRecordById(roleId, type);
    }

    let { count } = await getDailyNum(dailyRecord, role);
    if(count < inc) {
        return { status: -1, resResult: resResult(STATUS.DAILY_TIMES_LACK) }
    }
    let result = await DailyRecordModel.increseDailyCount(roleId, type, inc);
    let checkDailyResult = await getDailyNum(result);
    return {status: 1, data: {type, ...checkDailyResult, war}};
}

export async function getDailyNum(dailyRecord: DailyRecord, role?: RoleType) {
    let {roleId, type, count = 0, buyCount = 0} = dailyRecord;
    const curDaily = gameData.daily.find(cur => cur.dailyType == type);
    let {timesPerDay, timesCanBuy} = curDaily;

    if(!role) {
        role = await RoleModel.findByRoleId(roleId, 'vipStartTime');
    }
    timesPerDay = getVipDailyCnt(timesPerDay, role);
    // console.log('###### getDailyNum', timesPerDay, count, buyCount, timesCanBuy)
    return {count: timesPerDay - count + buyCount, buyCount: timesCanBuy - buyCount}
}

/**
 * 每日购买次数的花费
 * @param num 如果没有买过次数，那么这里算第一次，传1
 * @returns 
 */
export function getDailyBuyCountCost(num: number) {
    let cost = ( num - 1 ) * dicParam.DAILY_CONST.DAILY_CONST_UP + dicParam.DAILY_CONST.DAILY_CONST_BASE;
    if(cost > dicParam.DAILY_CONST.DAILY_CONST_TOP) {
        cost = dicParam.DAILY_CONST.DAILY_CONST_TOP;
    }
    return cost;
}