import { ACTIVITY_TYPE, STATUS } from '../../consts';
import { getPlayerFirstGiftData } from './firstGiftService';
import { getPlayerSignInData, } from './signInService';
import { getPlayerGrowthFundData, } from './growthFundService';
import { getPlayerLimitPackageData, } from './limitPackageService';
import { getPlayerYuanbaoShopData, } from './yuanbaoService';
import { getPlayerMonthlyTicketData, } from './monthlyTicketService';
import { getPlayerRechargeMoneyData, } from './rechargeMoneyService';
import { getPlayerThirtyDaysData, playerThirtyDaysActivityDays, } from './thirtyDaysService';
import { getPlayerVipRechargeMoneyData, } from './vipRechargeMoneyService';
import { getPlayerActivityData, } from './selfServiceShopActivityService';
import { ActivitySelfServiceGoodsModel } from '../../db/ActivitySelfServiceGoods';
import { RoleModel } from '../../db/Role';
import moment = require('moment');
import { getPlayerTreasureHuntData, getTreasureHuntData } from './treasureHuntService';
import { getPlayerPopUpShopData } from './popUpShopService';
import { getPlayerSevenDaysData } from './sevenDaysService';
import { getPlayerDailyMealData } from './dailyMealService';
import { getPlayerDailyCoinData } from './dailyCoinService';
import { getPlayerDailyRMBGiftsData } from './dailyRMBGiftsService';
import { getPlayerDailyGKData } from './dailyGKService';
import { getPlayerRefreshShopData } from './refreshShopService';
import { getPlayerRefreshTaskData } from './refreshTaskService';
import { getPlayerMonopolyData } from './monopolyService';
import { getPlayerNewHeroGiftsData } from './newHeroGiftsService';
import { getPlayerNewHeroGKData } from './newHeroGKService';
import { getPlayerNewHeroGachaData } from './newHeroGachaService';
import { pinus } from 'pinus';
import { ActivityModel, ActivityModelType } from '../../db/Activity';
import { getRandSingleEelm } from '../../pubUtils/util';
import { SignInData } from '../../domain/activityField/signInField';
import { ActivityGroupModel } from '../../db/ActivityGroup';
import { ActivityGroupTypeModel } from '../../db/ActivityGroupType';

/**
   * 获取活动数据
   *
   * @param {number} serverId 区Id
   * @param {number} activityId 活动Id
   * @param {string} roleId 角色Id
   *
   */
export async function getActivity(serverId: number, roleId: string, activityId: number, activityType: number) {
    let activityData = null;
    switch (activityType) {
        case ACTIVITY_TYPE.SIGN_IN://签到 4
        case ACTIVITY_TYPE.SIGN_IN_VIP://高级签到 5
        case ACTIVITY_TYPE.NEW_PLAYER_SIGN_IN://新手签到 25
            {
                activityData = await getPlayerSignInData(activityId, serverId, roleId);
                break;
            }
        case ACTIVITY_TYPE.GROWTH_FUND_MAIN://成长基金 6
        case ACTIVITY_TYPE.GROWTH_FUND_MAIN_VIP://高阶成长基金 7
        case ACTIVITY_TYPE.GROWTH_FUND_TOWER://镇念塔成长基金 8
        case ACTIVITY_TYPE.GROWTH_FUND_TOWER_VIP://高阶镇念塔成长基金 9
        case ACTIVITY_TYPE.GROWTH_FUND_MAIN_ELITE://精英成长基金 10
        case ACTIVITY_TYPE.GROWTH_FUND_MAIN_ELITE_VIP://高阶精英成长基金 11
            {
                activityData = await getPlayerGrowthFundData(activityId, serverId, roleId);
                break;
            }
        case ACTIVITY_TYPE.THIRTY_DAYS://30天目标活动 12
            {
                let data = await getPlayerThirtyDaysData(activityId, serverId, roleId);
                let todayIndex = await playerThirtyDaysActivityDays(roleId);
                activityData = { playerData: data, todayIndex }
                break;
            }
        case ACTIVITY_TYPE.SELF_SERVICE_SHOP://自选商店 糜家商队 13
            {
                let data = await getPlayerActivityData(activityId, serverId, roleId);
                let playerGoods = await ActivitySelfServiceGoodsModel.findData(activityId, roleId, data.roundIndex, true);
                activityData = { playerData: data, playerGoods: playerGoods ? playerGoods : [] }
                break;
            }
        case ACTIVITY_TYPE.FIRST_GIFT://首冲礼包活动 14
            {
                activityData = await getPlayerFirstGiftData(activityId, serverId, roleId);
                break;
            }
        case ACTIVITY_TYPE.NEW_PLAYER_LIMIT_PACKAGE://新手限定RMB购买礼包 15
            {
                let { createTime } = await RoleModel.findByRoleId(roleId);
                let createDate = moment(createTime * 1000).toDate();
                let endTime = moment(createDate).startOf('d').add(7, 'd').add(5, 'h').toDate();
                if (new Date() <= endTime) {
                    activityData = await getPlayerLimitPackageData(activityId, serverId, roleId);
                }
                break;
            }
        case ACTIVITY_TYPE.LIMIT_PACKAGE_SHOP_DAILY://每日限购礼包，RMB购买礼包 16
        case ACTIVITY_TYPE.LIMIT_PACKAGE_SHOP_WEEKLY://每周限购礼包，RMB购买礼包 17
            {
                activityData = await getPlayerLimitPackageData(activityId, serverId, roleId);
                break;
            }
        case ACTIVITY_TYPE.YUAN_BAO_SHOP://元宝商店 18
            {
                activityData = await getPlayerYuanbaoShopData(activityId, serverId, roleId);
                break;
            }
        case ACTIVITY_TYPE.MONTHLY_TICKET_1://月卡1 19
        case ACTIVITY_TYPE.MONTHLY_TICKET_2://月卡2 20
            {
                activityData = await getPlayerMonthlyTicketData(activityId, serverId, roleId);
                break;
            }
        case ACTIVITY_TYPE.RECHARGE_MONEY://累计充值RMB活动 21
            {
                activityData = await getPlayerRechargeMoneyData(activityId, serverId, roleId);
                break;
            }
        case ACTIVITY_TYPE.DAILY_RMB_GIFTS://每日特惠RMB购买，一次性购买7天礼包 22
            {
                activityData = await getPlayerDailyRMBGiftsData(activityId, serverId, roleId);
                break;
            }
        case ACTIVITY_TYPE.TREASURE_HUNT://寻宝骑兵活动 23
            {
                let { huntActivityId, huntBeginTime, huntEndTime, huntRoundIndex } = await getTreasureHuntData(serverId, roleId);
                activityData = await getPlayerTreasureHuntData(activityId, serverId, roleId, huntRoundIndex, huntBeginTime, huntEndTime);
                break;
            }
        case ACTIVITY_TYPE.POP_UP_SHOP://弹出商店 24
            {
                activityData = await getPlayerPopUpShopData(activityId, serverId, roleId);
                break;
            }
        case ACTIVITY_TYPE.VIP_RECHARGE_MONEY://vip累计充值活动 26
            {
                activityData = await getPlayerVipRechargeMoneyData(activityId, serverId, roleId);
                break;
            }
        case ACTIVITY_TYPE.SEVEN_DAY://七天乐活动 27
        case ACTIVITY_TYPE.FOURTEEN_DAY://十四天乐活动 28
        case ACTIVITY_TYPE.COMMON_SEVEN_DAY://通用七天乐活动 29
            {
                activityData = await getPlayerSevenDaysData(activityId, serverId, roleId);
                break;
            }
        case ACTIVITY_TYPE.DAILY_MEAL://每日领取免费午饭、晚饭活动 30
            {
                activityData = await getPlayerDailyMealData(activityId, serverId, roleId);
                break;
            }
        case ACTIVITY_TYPE.DAILY_COIN://每日兑换铜币活动 31
            {
                activityData = await getPlayerDailyCoinData(activityId, serverId, roleId);
                break;
            }
        case ACTIVITY_TYPE.DAILY_GK://每日关卡（每日开启一关） 32
            {
                activityData = await getPlayerDailyGKData(activityId, serverId, roleId);
                break;
            }
        case ACTIVITY_TYPE.REFRESH_SHOP://通用的刷新商店（分页，可刷新，限制购买次数，支持rmb与资源兑换） 33
            {
                activityData = await getPlayerRefreshShopData(activityId, serverId, roleId);
                break;
            }
        case ACTIVITY_TYPE.REFRESH_TASK://通用的刷新任务（分页，可刷新，限制领取次数） 34
            {
                activityData = await getPlayerRefreshTaskData(activityId, serverId, roleId);
                break;
            }
        case ACTIVITY_TYPE.MONOPOLY://大富翁游戏 35
            {
                activityData = await getPlayerMonopolyData(activityId, serverId, roleId);
                break;
            }
        case ACTIVITY_TYPE.COMMON_SIGN_IN://通用签到 36
            {
                activityData = await getPlayerSignInData(activityId, serverId, roleId);
                break;
            }
        case ACTIVITY_TYPE.NEW_HERO_GIFTS://新将好礼(很多红包，用积分兑换一遍结束) 37
            {
                activityData = await getPlayerNewHeroGiftsData(activityId, serverId, roleId);
                break;
            }
        case ACTIVITY_TYPE.NEW_HERO_GK://新将演绎 (配置N个武将，每个武将有X个关卡；活动期间，*天(时间自定义)开启每个武将对应的一个关卡，只有第一次通关会获得奖励)
            {
                activityData = await getPlayerNewHeroGKData(activityId, serverId, roleId);
                break;
            }
        case ACTIVITY_TYPE.NEW_HERO_GACHA://新将擢迁（新武将抽取）
            {
                activityData = await getPlayerNewHeroGachaData(activityId, serverId, roleId);
                break;
            }
        default: {
            console.log('未知活动类型.........', activityType)
            break;
        }
    }
    return activityData;
}

export async function getActivityById(activityId: number) {
    let serverType = pinus.app.getServerType();
    if(serverType == 'activity') {
        return _getActivityById(activityId);
    } else {
        let servers = pinus.app.getServersByType('activity');
        let server = getRandSingleEelm(servers);
        return <ActivityModelType>await pinus.app.rpc.activity.activityRemote.getActivityById.toServer(server.id, activityId);
    }
}

export async function getActivitiesByType(serverId: number, type: number) {
    let serverType = pinus.app.getServerType();
    if(serverType == 'activity') {
        return _getActivitiesByType(serverId, type);
    } else {
        let servers = pinus.app.getServersByType('activity');
        let server = getRandSingleEelm(servers);
        return <ActivityModelType[]>await pinus.app.rpc.activity.activityRemote.getActivitiesByType.toServer(server.id, serverId, type);
    }
}

export async function getActivities() {
    let serverType = pinus.app.getServerType();
    if(serverType == 'activity') {
        return _getActivities();
    } else {
        let servers = pinus.app.getServersByType('activity');
        let server = getRandSingleEelm(servers);
        return <ActivityModelType[]>await pinus.app.rpc.activity.activityRemote.getActivities.toServer(server.id);
    }
}

export function _getActivityById(activityId: number) {
    return <ActivityModelType>pinus.app.get('activities')?.get(activityId);
}

export function _getActivitiesByType(serverId: number, type: number) {
    let activityByType = pinus.app.get('activityByType')?.get(serverId)?.get(type)||[];
    let activities: Map<number, ActivityModelType> = pinus.app.get('activities');
    let result: ActivityModelType[] = [];
    for(let activityId of activityByType) {
        let activity = activities.get(activityId);
        if(activity && activity.beginTime <= new Date()) {
            result.push(activity);
        }
    }
    return result;
}

export function _getActivities() {
    let activities = pinus.app.get('activities');
    let result: ActivityModelType[] = [];
    for(let [_, activity] of activities) {
        result.push(activity);
    }
    return result;
}


export async function checkActivityEditable(activities: ActivityModelType[]) {
    let now = new Date();

    if(pinus.app.get('env') == 'production') {
        for(let activity of activities) {
            if(!activity || (activity.beginTime < now && activity.endTime > now)) {
    
                if(activity.type == ACTIVITY_TYPE.SIGN_IN || activity.type == ACTIVITY_TYPE.SIGN_IN_VIP) {
                    // 签到活动的不显示期内也可以编辑
                    let signInObj = new SignInData(activity, 0);
                    if(signInObj.beginTime < now.getTime() && signInObj.endTime > now.getTime() ) {
                        return false;
                    }
                } else {
                    return false;
                }
            }
        }
    }
    return true;
}

export async function checkActivityGroupType(groupId: number, activities: ActivityModelType[]) {

    let activityGroup = await ActivityGroupModel.findGroupData(groupId);
    if(!activityGroup) return false;
    if(activityGroup.type != 0) {
        let activityGroupType = await ActivityGroupTypeModel.findByGroupType(activityGroup.type);
        if(!activityGroupType) return false;
        let dic = activityGroupType.activityTypes;
        for(let { type } of activities) {
            let index = dic.findIndex(cur => cur.activityType == type);
            if(index == -1) {
                return false;
            } else {
                dic.splice(index, 1);
            }
        }
    }

    return true
}
