import { ActivityRechargeMoneyModel, ActivityRechargeMoneyModelType } from '../../db/ActivityRechargeMoney';
import { RechargeMoneyData } from '../../domain/activityField/rechargeMoneyField';
import moment = require('moment');
import { RoleModel } from '../../db/Role';
import { getActivitiesByType, getActivityById, pushActivities, pushActivityInter } from './activityService';
import { ACTIVITY_TYPE } from '../../consts';
import { getRoleCreateTime, getRoleOnlineInfo, getServerCreateTime } from '../redisService';
import { getZeroPointD, getZeroPointOfTime } from '../../pubUtils/timeUtil';

/**
   * 玩家活动数据
   *
   * @param {number} serverId 区Id
   * @param {number} activityId 活动Id
   * @param {string} roleId 角色Id
   *
   */
export async function getPlayerRechargeMoneyData(activityId: number, serverId: number, roleId: string) {
    let activityData = await getActivityById(activityId);
    let createTime = await getRoleCreateTime(roleId);
    let serverTime = await getServerCreateTime(serverId);
    let playerData = new RechargeMoneyData(activityData, createTime, serverTime);
    let beginTime = new Date(getZeroPointOfTime(playerData.beginTime));
    let endTime = new Date(getZeroPointD().getTime() + 24 * 60 * 60 * 1000);
    let playerRecord: ActivityRechargeMoneyModelType[] = await ActivityRechargeMoneyModel.findDataByTime(serverId, roleId, beginTime, endTime);

    playerData.setPlayerRecords(playerRecord);
    return playerData;
}

export async function getPlayerRechargeMoneyDataShow(activityId: number, serverId: number, roleId: string) {
    let playerData = await getPlayerRechargeMoneyData(activityId, serverId, roleId);
    if(playerData && playerData.canShow && playerData.canShow()) {
        return playerData.getShowResult();
    }
    return null
}

/**
   * 统计充值金额
   *
   * @param {number} serverId 区Id
   * @param {string} roleId 角色Id
   * @param {string} RMB 金额
   *
   */
export async function addRechargeMoney(roleId: string, serverId: number, RMB: number) {
    let beginTime = getZeroPointD();
    let endTime = new Date(getZeroPointD().getTime() + 24 * 60 * 60 * 1000);
    let result = await ActivityRechargeMoneyModel.addRMB(serverId, roleId, RMB, beginTime, endTime);
    if(result.RMB == RMB) { // 获得木签的时候推送给在线玩家
        let onlineUser = await getRoleOnlineInfo(roleId);
        if(!!onlineUser.sid) {
            let result: pushActivityInter[] = [];
            let activities = await getActivitiesByType(serverId, ACTIVITY_TYPE.RECHARGE_MONEY);
            for(let { activityId, type: activityType } of activities) {
                let playerData = await getPlayerRechargeMoneyData(activityId, serverId, roleId);
                result.push({ activityId, activityType, param: { ticketCnt: playerData.ticketCnt } });
            }

            await pushActivities(result, roleId, onlineUser.sid);
        }
    }
}

