import { pinus } from "pinus";
import { GVGConfigModel, GVGConfigType } from "../../db/GVGConfig";
import { getTimeFun, getZeroPoint, getZeroPointOfTime, nowSeconds, WEEK_TO_SECOND } from "../../pubUtils/timeUtil";
import { getAllServerCreateTime, getServerCreateTime } from "../redisService";
import { GVG_PERIOD, GVG_SERVER_TYPE, SHOP_REFRESH_TYPE } from "../../consts";
import { GVGLeagueModel, GVGLeagueType } from "../../db/GVGLeague";
import { GVGLeaguePrepareModel } from "../../db/GVGLeaguePrepare";
import { GVGServerGroupModel } from "../../db/GVGServerGroup";
import { gameData } from "../../pubUtils/data";
import { getRandSingleEelm } from "../../pubUtils/util";
import { GVG } from "../../pubUtils/dicParam";
import { ServerlistModel } from "../../db/Serverlist";
import { GuildModel, GuildType } from "../../db/Guild";

// 定时器相关
export async function createNewGVGConfig() {
    let { teamTime, prepareTime, battleTime, scheduleTime } = getPeriodTime();
    const config = await GVGConfigModel.createNewConfig(teamTime, prepareTime, battleTime, scheduleTime);
    try {
        await pinus.app.rpc.guild.guildRemote.setGVGConfig.broadcast(config);
        await pinus.app.rpc.guild.guildRemote.setGVGServerGroup.broadcast();
        await pinus.app.rpc.chat.chatRemote.setGVGServerGroup.broadcast();
        await pinus.app.rpc.connector.connectorRemote.setGVGServerGroup.broadcast();
    } catch(e) {
        console.log('remote未初始完');
    }
    // TODO 每周自动解散一些联军
    return config;
}

// 获取各个周期的时间，大约每周日5点的时候刷的
export function getPeriodTime() {
    let now = new Date();
    let curDay = now.getDay(); // 今天星期几

    let teamConfig = gameData.gvgPeriod.get(GVG_PERIOD.TEAM);
    let prepareConfig = gameData.gvgPeriod.get(GVG_PERIOD.PREPARE);
    let battleConfig = gameData.gvgPeriod.get(GVG_PERIOD.BATTLE);

    // 如果现在是周日，那么就是本周期的组队开始时间，如果是其他日子（启动初始化），就是下周期的组队开始时间
    let _teamTime = <number>getTimeFun().getTimeWithWeek(teamConfig.startDay, teamConfig.startHour, teamConfig.startMinute, teamConfig.startSecond); 
    let _prepareTime = <number>getTimeFun().getTimeWithWeek(prepareConfig.startDay, prepareConfig.startHour, prepareConfig.startMinute, prepareConfig.startSecond);
    let _battleTime = <number>getTimeFun().getTimeWithWeek(battleConfig.startDay, battleConfig.startHour, battleConfig.startMinute, battleConfig.startSecond);
    console.log('_teamTime: ', _teamTime);

    let teamTime = curDay == 0? _teamTime: _teamTime - 7 * 86400;
    let prepareTime = curDay == 0? _prepareTime + 7 * 86400: _prepareTime;
    let battleTime = curDay == 0? _battleTime + 7 * 86400: _battleTime;
    let scheduleTime = teamTime + 7 * 86400;

    return { teamTime, prepareTime, battleTime, scheduleTime }
}

export async function getGVGConfigFromRemote() {
    let guildServers = pinus.app.getServersByType('guild');
    let server = getRandSingleEelm(guildServers);
    return await pinus.app.rpc.guild.guildRemote.getGVGConfig.toServer(server.id);
}

export async function setGVGConfig(config?: GVGConfigType) {
    if(!config) {
        config = await GVGConfigModel.findConfig();
    }
    console.log('##### setGVGConfig', config)
    pinus.app.set('gvgConfigId', config.configId);
    pinus.app.set('gvgTeamTime', config.teamTime);
    pinus.app.set('gvgPrepareTime', config.prepareTime);
    pinus.app.set('gvgBattleTime', config.battleTime);
    pinus.app.set('gvgScheduleTime', config.scheduleTime);
}

/**
 * 获取当前的赛期id
 * @returns 
 */
export function getGVGConfig() {
    let configId = pinus.app.get('gvgConfigId');
    let teamTime = pinus.app.get('gvgTeamTime');
    let prepareTime = pinus.app.get('gvgPrepareTime');
    let battleTime = pinus.app.get('gvgBattleTime');
    let scheduleTime = pinus.app.get('gvgScheduleTime');
    return { configId, teamTime, prepareTime, battleTime, scheduleTime }
}

function getServerTypeByTime(openTime: number) {
    let today = nowSeconds();
    if(today - openTime < WEEK_TO_SECOND) return GVG_SERVER_TYPE.NO;
    let toWeek = getCurrentTeamTime(today);
    let openWeek = getCurrentTeamTime(openTime);
    let n = Math.floor((toWeek - openWeek) / WEEK_TO_SECOND);
    return n <= GVG.GVG_CROSS_SERVICE_STARTTIME? GVG_SERVER_TYPE.SINGLE: GVG_SERVER_TYPE.MULTI;
}

function getCurrentTeamTime(time: number) {
    let teamConfig = gameData.gvgPeriod.get(GVG_PERIOD.TEAM);
    // 本周日
    let _teamTime = <number>getTimeFun(time).getTimeWithWeek(teamConfig.startDay, teamConfig.startHour, teamConfig.startMinute, teamConfig.startSecond); 
    return _teamTime > time? _teamTime - WEEK_TO_SECOND: _teamTime;
}

export async function getGVGServerType(serverId: number) {
    console.log('#### serverId', serverId)
    let openTime = await getServerCreateTime(serverId);
    return getServerTypeByTime(openTime)
}

export function getGVGPeriodData() {
    let { configId, teamTime, prepareTime, battleTime, scheduleTime } = getGVGConfig();
    console.log('#### getGVGPeriodData', configId, teamTime, prepareTime, battleTime, scheduleTime)
    let period = getCurPeriod();
    let countdownTime = teamTime;
    switch(period) {
        case GVG_PERIOD.TEAM: {
            countdownTime = prepareTime; break;
        }
        case GVG_PERIOD.PREPARE: {
            countdownTime = battleTime; break;
        }
        case GVG_PERIOD.BATTLE: {
            countdownTime = scheduleTime; break;
        }
    }
    return { configId, period, countdownTime };
}

export function getCurPeriod() {
    let { teamTime, prepareTime, battleTime } = getGVGConfig();
    let now = nowSeconds();
    if(now >= teamTime && now < prepareTime) {
        return GVG_PERIOD.TEAM;
    } else if (now >= prepareTime && now < battleTime) {
        return GVG_PERIOD.PREPARE;
    } else {
        return GVG_PERIOD.BATTLE;
    }
}

export async function initLeaguePrepare() {
    const config = await GVGConfigModel.findConfig();
    if(!config) return;
    const leagues = await GVGLeagueModel.findAllLeague();
    for(let { leagueCode, memberCnt } of leagues) {
        await GVGLeaguePrepareModel.initData(config.configId, leagueCode, memberCnt);
    }
}

export async function setGVGServerGroup() {
    const servers = await ServerlistModel.findByEnv(pinus.app.get('env'));
    const serverGroups = await GVGServerGroupModel.findByTime(nowSeconds());
    pinus.app.set('gvgServerGroup', servers.map(obj => {
        let server = serverGroups.find(cur => cur.serverId == obj.serverId);
        return { serverId: obj.id, groupId: server? server.groupId: obj.groupId }
    }));
}

// 查询本小区所在的战区
// gvgServerGroup: id-小区唯一id serverId-小区在大区下的id
export async function getGroupIdOfServer(id: number) {
    let arr: { serverId: number; groupId: number }[] = pinus.app.get('gvgServerGroup')||[];
    let obj = arr.find(cur => cur.serverId == id);
    return obj?.groupId||0;
}

// 查询当前和本小区同一个战区的其他小区
export async function getServersOfSameGroup(type: GVG_SERVER_TYPE, id: number) {
    if(type == GVG_SERVER_TYPE.SINGLE) return [id];
    
    let groupId = await getGroupIdOfServer(id);
    console.log('###### getServersOfSameGroup', type, groupId, id);
    return await getServersByGroupId(groupId);
}

export async function getServersByGroupId(groupId: number) {
    let arr: { serverId: number; groupId: number }[] = pinus.app.get('gvgServerGroup')||[];
    let serverCreateTimes = await getAllServerCreateTime();

    return arr.filter(obj => {
        let openTime = parseInt(serverCreateTimes[obj.serverId]);
        return obj.groupId == groupId && getServerTypeByTime(openTime) == GVG_SERVER_TYPE.MULTI;
    }).map(obj => obj.serverId);
}

export async function getGVGInfoInGuild(guild: GuildType) {
    let hasLeague = !!guild.leagueCode;
    let serverId = guild.serverId;
    let { configId, period, countdownTime } = getGVGPeriodData();
    let type = await getGVGServerType(serverId);
    return {
        hasLeague,
        configId, period, countdownTime,
        type
    }
}

export async function calLeagueCe(league: GVGLeagueType) {
    const guildCodes = league?.guildCodes||[];
    const guilds = await GuildModel.findByCodes(guildCodes);
    return guilds.reduce((pre, guild) => pre + guild.guildCe, 0);
}
