import { ACTIVITY_TYPE, PUSH_ROUTE, STATUS } from '../../consts';
import { getPlayerFirstGiftDataShow } from './firstGiftService';
import { getPlayerSignInData, } from './signInService';
import { getPlayerGrowthFundData, } from './growthFundService';
import { getPlayerLimitPackageData, } from './limitPackageService';
import { getPlayerYuanbaoShopData, } from './yuanbaoService';
import { getPlayerMonthlyTicketData, } from './monthlyTicketService';
import { getPlayerRechargeMoneyDataShow, } from './rechargeMoneyService';
import { getPlayerThirtyDaysData } from './thirtyDaysService';
import { getPlayerVipRechargeMoneyData, } from './vipRechargeMoneyService';
import { getPlayerActivityData, } from './selfServiceShopActivityService';
import { ActivitySelfServiceGoodsModel } from '../../db/ActivitySelfServiceGoods';
import { getPlayerTreasureHuntDataShow } from './treasureHuntService';
import { getPopUpShopDataShow } 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, newHeroGiftPoint, getPlayerNewHeroGKData, getPlayerNewHeroGachaData } from './newHeroService';
import { BackendSession, pinus } from 'pinus';
import { ActivityModel, ActivityModelType } from '../../db/Activity';
import { getRandSingleEelm, resResult } from '../../pubUtils/util';
import { SignInData } from '../../domain/activityField/signInField';
import { ActivityInRemote, transActivityInRemoteToModelType } from '../../domain/activityField/activityField';
import { getPlayerLuckyTurntableDataShow } from './luckyTurntableService';
import { getTimeLimitRankDataShow } from './timeLimitRankService';
import { ActivityTaskPointModel } from '../../db/ActivityTaskPoint';
import { getRoleOnlineInfo } from '../redisService';
import { addTaskPassPoint, getTaskPassDataShow } from './taskPassService';
import { getGuildPayDataShow } from './guildPayService';
import { PopUpShopItemShow } from '../../domain/activityField/popUpShopField';
import { sendMessageToGuildWithSuc, sendMessageToUserWithSuc } from '../pushService';
import { UserOrderModelType } from '../../db/UserOrder';
import { isArray } from 'underscore';
import { getGuideGachaData } from './gachaService';
import { getPopNoticeData } from './popNoticeService';
import { _getActivities, _getActivitiesByServerId, _getActivitiesByType, _getActivityById } from './activityRemoteService';
import { getGroupShopDataShow } from './groupShopService';
import { getBindPhoneDataShow } from './bindPhoneService';

/**
   * 获取活动数据
   *
   * @param {number} serverId 区Id
   * @param {number} activityId 活动Id
   * @param {string} roleId 角色Id
   *
   */
export async function getActivity(serverId: number, roleId: string, uid: number, guildCode: string, activityId: number, activityType: number) {
    try {
    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
        case ACTIVITY_TYPE.COMMON_SIGN_IN://通用签到 36
            {
                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
            {
                activityData = await getPlayerThirtyDaysData(activityId, serverId, roleId);
                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);
                if(data.canShow()) {
                    activityData = { playerData: data, playerGoods: playerGoods ? playerGoods : [] }
                }
                break;
            }
        case ACTIVITY_TYPE.FIRST_GIFT://首冲礼包活动 14
            {
                activityData = await getPlayerFirstGiftDataShow(activityId, serverId, roleId);
                break;
            }
        case ACTIVITY_TYPE.NEW_PLAYER_LIMIT_PACKAGE://新手限定RMB购买礼包 15
            {
                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 getPlayerRechargeMoneyDataShow(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
            {
                activityData = await getPlayerTreasureHuntDataShow(activityId, serverId, roleId);
                break;
            }
        case ACTIVITY_TYPE.POP_UP_SHOP://弹出商店 24
            {
                activityData = await getPopUpShopDataShow(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.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;
            }
        case ACTIVITY_TYPE.LUCKY_TURNTABLE://幸运转盘
            {
                activityData = await getPlayerLuckyTurntableDataShow(activityId, serverId, roleId);
                break;
            }
        case ACTIVITY_TYPE.TIME_LIMIT_RANK: // 限时排行
            {
                activityData = await getTimeLimitRankDataShow(activityId, serverId);
                break;
            }
        case ACTIVITY_TYPE.TASK_PASS: // 战令、朝花夕拾
            {
                activityData = await getTaskPassDataShow(activityId, serverId, roleId);
                break;
            }
        case ACTIVITY_TYPE.GUILD_PAY:
            {
                activityData = await getGuildPayDataShow(serverId, activityId, roleId, guildCode);
                break
            }
        case ACTIVITY_TYPE.GUIDE_GACHA:
            {
                activityData = await getGuideGachaData(serverId, activityId, roleId);
                break
            }
        case ACTIVITY_TYPE.SHOP:
            break
        case ACTIVITY_TYPE.POP_NOTICE:
            {
                activityData = await getPopNoticeData(serverId, activityId, roleId);
                break
            }
        case ACTIVITY_TYPE.GROUP_SHOP:
            {
                activityData = await getGroupShopDataShow(activityId, roleId);
                break
            }
        case ACTIVITY_TYPE.BIND_PHONE:
            {
                activityData = await getBindPhoneDataShow(activityId, roleId, serverId, uid);
                break
            }
        default: {
            console.log('未知活动类型.........', activityType)
            break;
        }
    }
    if(activityData && activityData.canShow && !activityData.canShow()) {
        return null
    }
    return activityData;
    } catch(e) {
        console.log('activity error', activityId, activityType);
        return null;
    }
}

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

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

export async function getActivitiesByTypes(serverId: number, types: number[]) {
    let result: ActivityModelType[] = [];
    for(let type of types) {
        let activities = await getActivitiesByType(serverId, type);
        if(activities && isArray(activities)) result.push(...activities);
    }
    return result;
}

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 <ActivityInRemote[]>await pinus.app.rpc.activity.activityRemote.getActivities.toServer(server.id);
    }
}

export async function getActivityByServerId(serverId: number) {
    let activities: ActivityInRemote[] = [];
    let serverType = pinus.app.getServerType();
    if(serverType == 'activity') {
        activities = _getActivitiesByServerId(serverId);
    } else {
        let servers = pinus.app.getServersByType('activity');
        let server = getRandSingleEelm(servers);
        activities = await pinus.app.rpc.activity.activityRemote.getActivitiesByServerId.toServer(server.id, serverId);
    }
    return activities.map(transActivityInRemoteToModelType);
}

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

    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, 0);
                if(signInObj.beginTime < now.getTime() && signInObj.endTime > now.getTime() ) {
                    return false;
                }
            } else {
                return false;
            }
        }
    }
        
    return true;
}

/**
 * 达成任务可活动活动积分
 * @param type 任务类型，主线、每日、成就
 * @param id 
 * @param point 
 * @param session 
 */
export async function addActvityTaskPoint(type: number, id: number, session: BackendSession) {
    let serverId: number = session.get('serverId');
    let roleId: string = session.get('roleId');
    let sid: string = session.get('sid');
    let activityTaskPoint = await ActivityTaskPointModel.findData(type, id);
    let result: pushActivityInter[] = [];
    for (let { activityId, activityType, point } of activityTaskPoint) {
        if(activityType == ACTIVITY_TYPE.NEW_HERO_GIFTS) { // 新武将活动
            let totalPoint = await newHeroGiftPoint(serverId, activityId, roleId, point);
            result.push({ activityId, activityType, param: { totalPoint } });
        } else if (activityType == ACTIVITY_TYPE.TASK_PASS) {
            let totalPoint = await addTaskPassPoint(serverId, activityId, roleId, point);
            result.push({ activityId, activityType, param: { totalPoint } });
        } else {
            break;
        }
    }
    await pushActivities(result, roleId, sid);
}


interface pushActivityParamInter {
    ticketCnt?: number;     // 木签活动的签数(type21)
    totalPoint?: number;     // 新将好礼（type37）和战令（type42）更新后的积分
    payMemberCnt?: number;    // 军团充值活动，你的军团充值的人数
    payMember?: string;       // 军团充值活动，充值人员名字，添加到payRecord里面
    payRecord?: string[];     // 军团全部充值人名字
    popUpShopItems?: PopUpShopItemShow[]; // 弹出礼包
}

export interface pushActivityInter {
    activityId: number,
    activityType: number,
    param: pushActivityParamInter;
}

export async function pushSingleActivity(activityId: number, activityType: number, param: pushActivityParamInter, roleId: string, sid?: string) {
    await pushActivities([{ activityId, activityType, param }], roleId, sid);
}

export async function pushActivities(arr: pushActivityInter[], roleId: string, sid?: string) {
    if(!sid) {
        let onlineUser = await getRoleOnlineInfo(roleId);
        sid = onlineUser.sid;
    }
    if(!!sid && arr.length > 0) {
        sendMessageToUserWithSuc(roleId, PUSH_ROUTE.ACTIVITY_UPDATE, { activities: arr }, sid);
    }
    return arr
}

export async function pushActivitiesToGuild(arr: pushActivityInter[], guildCode: string) {
    if(arr.length > 0) await sendMessageToGuildWithSuc(guildCode, PUSH_ROUTE.ACTIVITY_UPDATE, { activities: arr })
}

export async function getActivitiesWithOrder(orderInfo: UserOrderModelType) {
    let activities: ActivityModelType[] = [];
    let curActivity = await getActivityById(orderInfo.activityId);
    if(curActivity) activities.push(curActivity);

    let activitiesWithSum = await getActivitiesByTypes(orderInfo.serverId, [ACTIVITY_TYPE.FIRST_GIFT, ACTIVITY_TYPE.RECHARGE_MONEY, ACTIVITY_TYPE.VIP_RECHARGE_MONEY, ACTIVITY_TYPE.GUILD_PAY]);
    if(activitiesWithSum && isArray(activitiesWithSum)) activities.push(...activitiesWithSum);

    if(orderInfo.paramStr) { //大富翁商店结算
        try {
            let paramObj = JSON.parse(orderInfo.paramStr);
            let paramActivity = paramObj.activityId && await getActivityById(paramObj.activityId);
            if(paramActivity) activities.push(paramActivity);
        } catch(e) {
            console.error(e);
        }
    }
    return activities;
}

export function shouldReplace(activityType: ACTIVITY_TYPE) {
    switch(activityType) {
        case ACTIVITY_TYPE.TASK_PASS:
        // case ACTIVITY_TYPE.SIGN_IN:
        // case ACTIVITY_TYPE.SIGN_IN_VIP:        
        // 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
            return true;
        default:
            return false;
    }
}