import { ACTIVITY_TYPE, DAILY_MEAL_TYPE } from '../../consts';
import { ActivityModel, ActivityModelType } from '../../db/Activity';
import { ActivityDailyCoinModel, ActivityDailyCoinModelType } from '../../db/ActivityDailyCoin';
import { ActivityGroupModel } from '../../db/ActivityGroup';
import { RoleModel } from '../../db/Role';
import { ServerlistModel } from '../../db/Serverlist';
import { DailyCoinData } from '../../domain/activityField/dailyCoinField';


/**
   * 获取活动数据
   *
   * @param {number} serverId 区Id
   * @param {number} activityId 活动Id
   * @param {string} roleId 角色Id
   *
   */
export async function dailyCoinActivity(serverId: number, roleId: string) {
    let { activityGroupId } = await ServerlistModel.findByServerId(serverId);
    let activityDataArray: ActivityModelType[] = await ActivityModel.findOpenActivityByType(activityGroupId, ACTIVITY_TYPE.DAILY_COIN, new Date());
    if (activityDataArray.length === 0) {
        return null;
    }
    let activityData: ActivityModelType = activityDataArray[0];
    let { createTime } = await RoleModel.findByRoleId(roleId);
    let playerData = new DailyCoinData(activityData, createTime);

    let playerRecord: ActivityDailyCoinModelType = await ActivityDailyCoinModel.findData(serverId, activityData.activityId, roleId, playerData.beginTime);
    playerData.setPlayerRecords(playerRecord);
    return playerData;
}


/**
   * 玩家玩家活动数据
   *
   * @param {number} serverId 区Id
   * @param {number} activityId 活动Id
   * @param {string} roleId 角色Id
   *
   */
export async function getPlayerDailyCoinData(activityId: number, serverId: number, roleId: string) {
    let activityData: ActivityModelType = await ActivityModel.findActivity(activityId);
    let { createTime } = await RoleModel.findByRoleId(roleId);
    let playerData = new DailyCoinData(activityData, createTime);

    let playerRecord: ActivityDailyCoinModelType = await ActivityDailyCoinModel.findData(serverId, activityData.activityId, roleId, playerData.beginTime);
    playerData.setPlayerRecords(playerRecord);
    return playerData;
}

export function mergeData(data: any[]) {
    let newDate = [];
    for (let item of data) {
        let index = newDate.findIndex(obj => { return obj.id === item.id });
        if (index != -1) {
            newDate[index].count += item.count;
        } else {
            newDate = newDate.concat(item);
        }
    }
    return newDate;
}
