import { gameData } from './data';
import { DicTask } from './dictionary/DicTask';
import { TASK_TYPE, ABI_STAGE, WAR_TYPE, GUILD_JOB } from '../consts';
import { UserTaskRecModel, UserTaskRecType } from '../db/UserTaskRec'
import { RoleType, RoleModel } from '../db/Role';
import { TaskParam, TaskListReturn } from '../domain/roleField/task';
import { getZeroPoint } from './timeUtil';
import { HeroType } from '../db/Hero';
import { EquipType, EquipModel } from '../db/Equip';
import { ItemInter } from './interface';
import { DailyChallengesData } from '../domain/activityField/dailyChallengesField';
import { splitString } from './util';
import { ActivityModel, ActivityModelType } from '../db/Activity';
import { ACTIVITY_TYPE } from '../consts/constModules/activityConst';
import { ActivityGrowthModel } from '../db/ActivityGrowth';
import { ActivityDailyChallengesModel } from '../db/ActivityDailyChallenges';
import { ThirtyDaysData } from '../domain/activityField/thirtyDaysField';
import { GrowthFundData } from '../domain/activityField/growthFundField';
import { ActivityThirtyDaysModel, ActivityThirtyDaysModelType } from '../db/ActivityThirtyDays';
import { ServerlistModel } from '../db/Serverlist';
import { ActivityGrowthFundModel, ActivityGrowthFundModelType } from '../db/ActivityGrowthFund';
import { ActivityBuyRecordsModel } from '../db/ActivityBuyRecords';
import { PopUpShopData } from '../domain/activityField/popUpShopField';
import { ActivityPopUpShopModel } from '../db/ActivityPopUpShop';
import { ServerTempModel, ServerTempModelType } from '../db/ServerTemp';
import { TreasureHuntData } from '../domain/activityField/treasureHuntField';
import { ActivityTreasureHuntTaskModel, ActivityTreasureHuntTaskModelType } from '../db/ActivityTreasureHuntTask';
import { ActivityPopUpShopRecordModel, ActivityPopUpShopRecordModelType } from '../db/ActivityPopUpShopRecord';
import { SevenDaysData } from '../domain/activityField/sevenDaysField';
import moment = require("moment");
import { GuildModel } from '../db/Guild';
import { RefreshTaskData } from '../domain/activityField/refreshTaskField';
import { ActivityRefreshTaskModel } from '../db/ActivityRefreshTask';



export async function checkTaskWithRoles(serverId: number, taskType: number, roles: RoleType[]) {
    let pushMessage = new Array<TaskListReturn>();
    for (let role of roles) {
        if (role) {
            let singlePush = await checkTaskWithRole(serverId, role.roleId, taskType, role);
            pushMessage.concat(singlePush);
        }
    }
    return pushMessage
}

export async function checkTaskWithRole(serverId: number, roleId: string, taskType: number, role: RoleType) {
    let pushMessage = new Array<TaskListReturn>();

    if (taskType == TASK_TYPE.LOGIN_SUM) {
        let today = getZeroPoint();
        if (today > role.loginTime) {
            pushMessage = await checkTask(roleId, taskType, 1, true, {});
            //成长任务-累计登录游戏天数
            await accomplishTask(serverId, roleId, taskType, 1)
        }
    }
    else if (taskType == TASK_TYPE.LOGIN_SERIES) {
        let today = getZeroPoint();
        if (today > role.loginTime) {
            if (today - role.loginTime > 24 * 60 * 60) {
                pushMessage = await checkTask(roleId, taskType, 1, false, {});
            } else {
                pushMessage = await checkTask(roleId, taskType, 1, true, {});
            }
        }
    }
    else if (taskType == TASK_TYPE.FRIEND_NUM) {
        let { friendCnt } = role;
        pushMessage = await checkTask(roleId, taskType, friendCnt, false, {});
    }

    return pushMessage
}


export async function checkTaskWithHeroes(roleId: string, taskType: number, heroes: HeroType[]) {
    let pushMessage = new Array<TaskListReturn>();
    for (let hero of heroes) {
        let singlePush = await checkTaskWithHero(roleId, taskType, hero, []);
        pushMessage.concat(singlePush);
    }
    return pushMessage
}

export async function checkTaskWithHero(roleId: string, taskType: number, hero: HeroType, args: number[] = []) {
    let pushMessage = new Array<TaskListReturn>();
    if (taskType == TASK_TYPE.HERO_STAR_UP) {
        let dicHero = gameData.hero.get(hero.hid);
        let starUp = hero.star - dicHero.initialStars;
        if (hero.colorStar > 1) starUp += hero.colorStar - 1;
        pushMessage = await checkTask(roleId, taskType, 1, true, { star: starUp })
    }
    else if (taskType == TASK_TYPE.HERO_QUALITY) {
        let dicHero = gameData.hero.get(hero.hid);
        pushMessage = await checkTask(roleId, taskType, 1, true, { quality: dicHero.quality });
    }
    else if (taskType == TASK_TYPE.HERO_QUALITY_STAR_UP) {
        let dicHero = gameData.hero.get(hero.hid);
        pushMessage = await checkTask(roleId, taskType, 1, true, { quality: dicHero.quality, star: hero.star });
    }
    else if (taskType == TASK_TYPE.HERO_LV) {
        pushMessage = await checkTask(roleId, taskType, 1, true, { lv: hero.lv, oldLv: args[0] });
    }
    else if (taskType == TASK_TYPE.HERO_TRAIN) {
        let dicHero = gameData.hero.get(hero.hid);
        let initGrage = gameData.job.get(dicHero.jobid).grade;
        let curGrade = gameData.job.get(hero.job).grade;
        let count = (curGrade - initGrage) * (ABI_STAGE.END - ABI_STAGE.START) + (hero.jobStage - ABI_STAGE.START); // 训练次数
        pushMessage = await checkTask(roleId, taskType, 1, true, { count });
    }
    else if (taskType == TASK_TYPE.HERO_QUALITY_UP) {
        let dicHero = gameData.hero.get(hero.hid);
        if (hero.quality - dicHero.quality == 1) { // 每个武将升品算一次
            pushMessage = await checkTask(roleId, taskType, 1, true, {});
        }
    }
    else if (taskType == TASK_TYPE.HERO_STAGE_UP) {
        let dicHero = gameData.hero.get(hero.hid);
        let initGrage = gameData.job.get(dicHero.jobid).grade;
        let curGrade = gameData.job.get(hero.job).grade;
        let count = curGrade - initGrage; // 进阶次数
        pushMessage = await checkTask(roleId, taskType, 1, true, { count });
    }
    else if (taskType == TASK_TYPE.HERO_FAVOUR_LV) {
        pushMessage = await checkTask(roleId, taskType, 1, true, { favourLv: hero.favourLv })
    }
    else if (taskType == TASK_TYPE.EQUIP_BY_HERO) {
        // arg[0] 1：穿上 -1：脱下
        let { ePlace } = hero;
        let count = ePlace.filter(cur => cur.equip).length;
        pushMessage = await checkTask(roleId, taskType, args[0], true, { count, isPutOn: args[0] });
    }
    else if (taskType == TASK_TYPE.EQUIP_STRENGTHEN) {
        // args: 依次为原先的装备的强化等级
        let { ePlace } = hero;
        let index = 0;
        for (let { lv } of ePlace) {
            let p = await checkTask(roleId, taskType, 1, true, { oldLv: args[index++], lv });
            pushMessage = pushMessage.concat(p);
        }
    }

    return pushMessage
}


export async function checkTaskWithEquip(roleId: string, taskType: number, equip: EquipType, args: number[] = []) {
    let pushMessage = new Array<TaskListReturn>();
    if (taskType == TASK_TYPE.EQUIP_QUALITY) {
        // args[0] 1：装上 -1：脱下
        let dicGood = gameData.goods.get(equip.id);
        pushMessage = await checkTask(roleId, taskType, args[0], true, { quality: dicGood.quality })
    }
    else if (taskType == TASK_TYPE.EQUIP_JEWEL) {
        // args[0] 原来镶嵌了多少宝石
        let { holes } = equip;
        let jewelCount = holes.filter(cur => cur.jewel > 0).length;
        if (jewelCount > 0 && args[0] <= 0) { // 原来没有，镶嵌上了
            pushMessage = await checkTask(roleId, taskType, 1, true, {});
        } else if (jewelCount <= 0 && args[0] > 0) { // 原来镶嵌着，现在没了
            pushMessage = await checkTask(roleId, taskType, -1, true, {});
        }
    }
    else if (taskType == TASK_TYPE.EQUIP_COMPOSE_SUIT) {
        let dicGood = gameData.goods.get(equip.id);
        if (dicGood.suitId) {
            pushMessage = await checkTask(roleId, taskType, 1, true, {});
        }
    }
    else if (taskType == TASK_TYPE.EQUIP_SUIT) {
        let dicGood = gameData.goods.get(equip.id);
        if (dicGood.suitId) {
            let suit = gameData.suit.get(dicGood.suitId);
            let equips = await EquipModel.getEquipsByIds(roleId, suit.tireInfo);
            let everyEquip = new Map<number, number>();
            for (let equip of equips) {
                if (everyEquip.has(equip.id)) {
                    everyEquip.set(equip.id, everyEquip.get(equip.id) + 1);
                } else {
                    everyEquip.set(equip.id, 1);
                }
            }
            let minCount = 0, curCount = 0;
            for (let id of suit.tireInfo) {
                let count = everyEquip.get(id) || 0;
                if (minCount > count) minCount = count;
                if (id == equip.id) curCount = count;
            }
            if (curCount == minCount) {
                pushMessage = await checkTask(roleId, taskType, 1, true, {});
            }
        }
    }
    else if (taskType == TASK_TYPE.EQUIP_JEWEL_SUM) {
        // args[0] 原来镶嵌了多少宝石
        let { holes } = equip;
        let jewelCount = holes.filter(cur => cur.jewel > 0).length;
        pushMessage = await checkTask(roleId, taskType, jewelCount - args[0], true, {});
    }
    return pushMessage
}

export async function checkTaskWithArgs(roleId: string, taskType: number, args: number[]) {
    let pushMessage = new Array<TaskListReturn>();

    if (taskType == TASK_TYPE.ROLE_SCHOOL_PUT_HERO) {
        let [hid, preHid] = args;
        if (hid > 0 && preHid <= 0) { // 放置
            pushMessage = await checkTask(roleId, taskType, 1, true, {});
        } else if (hid <= 0 && preHid > 0) { // 卸下
            pushMessage = await checkTask(roleId, taskType, -1, true, {});
        }
    }
    else if (taskType == TASK_TYPE.EQUIP_JEWEL_STAGE) {
        // args 装上的， 卸下的
        let [putOnJewel, putOffJewel] = args;
        if (putOnJewel > 0) {
            let dicGood = gameData.goods.get(putOnJewel);
            let push = await checkTask(roleId, taskType, 1, true, { stage: dicGood.lvLimited });
            pushMessage.concat(push);
        }
        if (putOffJewel > 0) {
            let dicGood = gameData.goods.get(putOffJewel);
            let push = await checkTask(roleId, taskType, -1, true, { stage: dicGood.lvLimited });
            pushMessage.concat(push);
        }
    }
    else if (taskType == TASK_TYPE.CHAT) {
        // args[0] 聊天type 1-系统 2-世界 3-军团 4-组队 5-私聊
        pushMessage = await checkTask(roleId, taskType, 1, true, { chatType: args[0] })
    }

    return pushMessage
}

export async function checkTaskWithWar(roleId: string, taskType: number, warId: number, heroes: number[], count: number, star: number) {
    let dicWar = gameData.war.get(warId);
    let pushMessage = new Array<TaskListReturn>();
    if (taskType == TASK_TYPE.BATTLE_WITH_HERO) {
        pushMessage = await checkTask(roleId, taskType, count, true, { warId, heroes });
    }
    else if (taskType == TASK_TYPE.BATTLE_MAIN) {
        if (dicWar.warType == WAR_TYPE.NORMAL) {
            pushMessage = await checkTask(roleId, taskType, count, true, { warId });
        }
    }
    else if (taskType == TASK_TYPE.BATTLE_MAIN_SWEEP) {
        if (dicWar.warType == WAR_TYPE.NORMAL) {
            pushMessage = await checkTask(roleId, taskType, count, true, {});
        }
    }
    else if (taskType == TASK_TYPE.BATTLE_DAILY_STAR) {
        if (dicWar.warType == WAR_TYPE.DAILY) {
            pushMessage = await checkTask(roleId, taskType, count, true, { warId, star });
        }
    }
    else if (taskType == TASK_TYPE.BATTLE_DAILY) {
        if (dicWar.warType == WAR_TYPE.DAILY) {
            pushMessage = await checkTask(roleId, taskType, count, true, { dailyType: dicWar.dailyType })
        }
    }
    else if (taskType == TASK_TYPE.BATTLE_DUNGEON) {
        if (dicWar.warType == WAR_TYPE.MYSTERY || dicWar.warType == WAR_TYPE.MYSTERY_ELITE) {
            pushMessage = await checkTask(roleId, taskType, count, true, {});
        }
    }
    else if (taskType == TASK_TYPE.BATTLE_DUNGEON_WAR) {
        if (dicWar.warType == WAR_TYPE.MYSTERY || dicWar.warType == WAR_TYPE.MYSTERY_ELITE) {
            pushMessage = await checkTask(roleId, taskType, count, true, { warId });
        }
    }
    else if (taskType == TASK_TYPE.BATTLE_TOWER) {
        if (dicWar.warType == WAR_TYPE.TOWER) {
            pushMessage = await checkTask(roleId, taskType, count, true, {});
        }
    }
    else if (taskType == TASK_TYPE.BATTLE_VESTIGE) {
        if (dicWar.warType == WAR_TYPE.VESTIGE) {
            pushMessage = await checkTask(roleId, taskType, count, true, {});
        }
    }
    else if (taskType == TASK_TYPE.BATTLE_EXPEDITION) {
        if (dicWar.warType == WAR_TYPE.EXPEDITION) {
            pushMessage = await checkTask(roleId, taskType, count, true, {});
        }
    }
    return pushMessage
}


export async function checkTaskWithGoods(roleId: string, taskType: number, goods: ItemInter[]) {
    let pushMessage = new Array<TaskListReturn>();
    if (taskType == TASK_TYPE.COM_BATTLE_DROP) {
        for (let { id, count } of goods) {
            let push = await checkTask(roleId, taskType, count, true, { gid: id });
            pushMessage.concat(push);
        }
    }
    return pushMessage
}

// 根据taskType判断有哪些任务需要check的
export async function checkTask(roleId: string, taskType: number, count: number, isInc: boolean, param: TaskParam) {
    // console.log('******checkTask', roleId, taskType, count, isInc, param)
    let tasks = gameData.taskType.get(taskType) || [];
    let pushMessage = new Array<TaskListReturn>();
    let groups = new Map<string, { task0: DicTask, tasks: DicTask[] }>();
    for (let dicTask of tasks) {
        if (!groups.has(`${dicTask.type}_${dicTask.group}`)) {
            groups.set(`${dicTask.type}_${dicTask.group}`, { task0: dicTask, tasks: new Array<DicTask>() });
        }
        groups.get(`${dicTask.type}_${dicTask.group}`).tasks.push(dicTask);
    }

    for (let [typeAndGroup, { task0, tasks }] of groups) {
        let arr = typeAndGroup.split('_');
        let type = parseInt(arr[0]);
        let group = parseInt(arr[1]);

        let rec = await checkTaskRec(roleId, type, group, task0, count, isInc, param);
        if (rec) {
            for (let dicTask of tasks) {
                if (checkRecResult(rec, dicTask.id)) {
                    let received = rec.received || [];
                    pushMessage.push({ type: dicTask.type, id: dicTask.id, count: rec.count, received: received.includes(dicTask.id) });
                }
            }
        }
    }
    return pushMessage;
}

// 检查各项任务是否达成，达成了就保存到数据库
export async function checkTaskRec(roleId: string, type: number, group: number, dicTask: DicTask, count: number, isInc: boolean, param: TaskParam) {
    let { taskParam, taskType } = dicTask;

    let isMatch = true; // 条件是否满足
    let checkHistory = false; // 是否检查历史
    switch (taskType) {
        case TASK_TYPE.ROLE_TITLE:
            isMatch = taskParam[0] == param.title;
            checkHistory = true;
            break;
        case TASK_TYPE.HERO_STAR_UP:
            isMatch = taskParam[1] == param.star;
            break;
        case TASK_TYPE.HERO_QUALITY:
        case TASK_TYPE.EQUIP_QUALITY:
            isMatch = taskParam[1] == param.quality;
            break;
        case TASK_TYPE.HERO_QUALITY_STAR_UP:
            isMatch = taskParam[1] == param.quality && taskParam[2] == param.star;
            break;
        case TASK_TYPE.HERO_LV:
            isMatch = param.lv >= taskParam[1] && param.oldLv < taskParam[1];
            break;
        case TASK_TYPE.HERO_TRAIN:
            isMatch = taskParam[1] == param.count;
            break;
        case TASK_TYPE.HERO_FAVOUR_LV:
            isMatch = taskParam[1] == param.favourLv;
            break;
        case TASK_TYPE.HERO_CONNECT:
            isMatch = taskParam[1] == param.connectLv;
            break;
        case TASK_TYPE.EQUIP_BY_HERO:
            isMatch = false;
            if (param.isPutOn && param.count == taskParam[1]) { // 装上之后达到 +1
                isMatch = true;
            } else if (!param.isPutOn && param.count < taskParam[1]) { // 脱下后不能达到 -1
                isMatch = true;
            }
            break;
        case TASK_TYPE.EQUIP_STRENGTHEN:
            isMatch = param.oldLv < taskParam[1] && param.lv >= taskParam[1];
            break;
        case TASK_TYPE.EQUIP_JEWEL_STAGE:
            isMatch = param.stage == taskParam[1];
            break;
        case TASK_TYPE.CHAT:
            isMatch = taskParam[0] == 0 || param.chatType == taskParam[0];
            break;
        case TASK_TYPE.BATTLE_WITH_HERO:
            isMatch = checkIdList(taskParam, 2, param.warId) && checkHero(taskParam, 0, param.heroes);
            break;
        case TASK_TYPE.BATTLE_MAIN:
        case TASK_TYPE.BATTLE_DUNGEON_WAR:
            isMatch = checkIdList(taskParam, 0, param.warId);
            break;
        case TASK_TYPE.BATTLE_EVENT:
            isMatch = taskParam[0] == 0 || param.eventType == taskParam[0];
            break;
        case TASK_TYPE.BATTLE_DAILY_STAR:
            isMatch = (taskParam[0] == 0 || param.star == taskParam[0]) && checkIdList(taskParam, 2, param.warId);
            break;
        case TASK_TYPE.BATTLE_DAILY:
            isMatch = taskParam[0] == 0 || param.dailyType == taskParam[0];
            break;
        case TASK_TYPE.BATTLE_EXPEDITION_BOX:
            isMatch = taskParam[1] == 0 || param.point == taskParam[1];
            break;
        case TASK_TYPE.COM_BATTLE_BLUEPRT:
        case TASK_TYPE.COM_BATTLE_QUALITY:
            isMatch = taskParam[0] == 0 || param.quality == taskParam[0];
            break;
        case TASK_TYPE.COM_BATTLE_DROP:
            isMatch = checkIdList(taskParam, 1, param.gid);
            break;
        case TASK_TYPE.PVP_HERO_SCORE:
            for (let { score } of param.heroScores) {
                if (score >= taskParam[0]) {
                    count++;
                }
            }
            if (count <= 0) isMatch = false;
            break;
        case TASK_TYPE.PVP_RANK:
            isMatch = taskParam[0] <= param.rankLv;
            checkHistory = true;
            break;
        case TASK_TYPE.GUILD_JOB:
            isMatch = taskParam[0] <= param.job && param.job != GUILD_JOB.DAJIANGJUN;
            checkHistory = true;
            break;
        case TASK_TYPE.GUILD_REFINE:
            isMatch = taskParam[0] == 0 || param.quality == taskParam[0];
            break;
    }
    // console.log('****isMatch', isMatch, checkHistory, type, taskType, group, count)
    if (param.isDebug) {
        isMatch = true;
    }

    if (isMatch) {
        if (isInc) {
            let rec = await UserTaskRecModel.incTaskRec(roleId, type, taskType, group, count);
            return rec;
        } else {
            if (checkHistory) {
                let rec = await UserTaskRecModel.checkHistoryAndSetTaskRec(roleId, type, taskType, group, count);
                return rec;
            } else {
                let rec = await UserTaskRecModel.setTaskRec(roleId, type, taskType, group, count);
                return rec;
            }
        }
    }
}

/**
 * 检查id是否在某列表中
 * @param taskParam 条件number[] 填法 如： count&id&... 有多少id就count填几
 * @param index count在第几位，0开始
 * @param id 关卡id
 */
function checkIdList(taskParam: number[], index: number, id: number) {
    let count = taskParam[index];
    if (!count) return false;
    let idList = taskParam.slice(index + 1, index + 1 + count);
    return idList.indexOf(id) != -1;
}

function checkHero(taskParam: number[], index: number, heroes: number[]) {
    let hid = taskParam[index];
    return heroes.indexOf(hid) != -1;
}

function checkRecResult(rec: UserTaskRecType, id: number) {
    if (!rec) return false;
    if (rec.received && rec.received.includes(id)) return false; // 已领取，不再推送

    return rec
}


/**
   * 任务统计
   *
   * @param {number} serverId 区Id
   * @param {string} roleId 角色Id
   * @param {number} taskType 任务类型
   * @param {number} count 任务数据
   * @param {number} parma 参数
   *
   */
export async function accomplishTask(serverId: number, roleId: string, taskType: TASK_TYPE, count: number, parma?: any, activities?: ActivityModelType[]) {
    // console.log('accomplishTask', roleId, taskType, count, JSON.stringify(parma))
    let pushMessage = [];
    let { activityGroupId } = await ServerlistModel.findByServerId(serverId);
    let findActivitiesByTypes = async (types: number[]) => {
        if(activities) {
            let result: ActivityModelType[] = [];
            for(let activity of activities) {
                if(activityGroupId.includes(activity.groupId) && types.includes(activity.type)) {
                    result.push(activity);
                }
            }
            return result;
        } else {
            if(types.length > 1) {
                return ActivityModel.findOpenActivityByTypes(activityGroupId, types, new Date());
            } else {
                return ActivityModel.findOpenActivityByType(activityGroupId, types[0], new Date());
            }
        }
    }
    let { createTime } = await RoleModel.findByRoleId(roleId);
    // //成长活动统计
    // let allActivity: ActivityModelType[] = await ActivityModel.findOpenActivityByType(activityGroupId, ACTIVITY_TYPE.TASK_GROWTH, new Date());
    // for (let activity of allActivity) {
    //     let growthActivity = new GrowthData(activity);
    //     let taskArray = growthActivity.findTaskByType(taskType);
    //     for (let task of taskArray) {
    //         let taskRecord = await ActivityGrowthModel.findDataByCellIndex(serverId, growthActivity.activityId, roleId, task.dayIndex, task.cellIndex, task.taskType)
    //         let recordData = taskRecord && taskRecord.data ? JSON.parse(taskRecord.data) : null;
    //         let { addCount, record } = isComplete(roleId, task.taskType, task.taskParam, count, parma, recordData);
    //         if (addCount) {
    //             if (taskType == TASK_TYPE.ROLE_LV || taskType == TASK_TYPE.ROLE_TITLE || taskType == TASK_TYPE.BATTLE_TOWER_LV) {
    //                 let playerRecord = await ActivityGrowthModel.setTaskCount(serverId, growthActivity.activityId, roleId, task.dayIndex, task.cellIndex, task.taskType, addCount);
    //                 //推送
    //                 task.totalCount = playerRecord.totalCount;
    //                 task.receiveRewardCount = playerRecord.receiveRewardCount ? playerRecord.receiveRewardCount : 0;
    //                 pushMessage = pushMessage.concat(Object.assign(task, { activityId: growthActivity.activityId }));
    //             } else {
    //                 let playerRecord = await ActivityGrowthModel.addTaskCount(serverId, growthActivity.activityId, roleId, task.dayIndex, task.cellIndex, task.taskType, addCount);
    //                 //推送
    //                 task.totalCount = playerRecord.totalCount;
    //                 task.receiveRewardCount = playerRecord.receiveRewardCount ? playerRecord.receiveRewardCount : 0;
    //                 pushMessage = pushMessage.concat(Object.assign(task, { activityId: growthActivity.activityId }));
    //             }
    //         }
    //         if (record) {
    //             await ActivityGrowthModel.addTaskRecord(serverId, growthActivity.activityId, roleId, task.dayIndex, task.cellIndex, task.taskType, JSON.stringify(record));
    //         }
    //     }
    // }

    // //今日挑战统计
    // allActivity = await ActivityModel.findOpenActivityByType(activityGroupId, ACTIVITY_TYPE.TASK_DAILY_CHALLENGES, new Date());
    // for (let activity of allActivity) {
    //     let growthActivity = new DailyChallengesData(activity);
    //     let taskArray = growthActivity.findTaskByType(taskType, growthActivity.today());
    //     for (let task of taskArray) {
    //         let taskRecord = await ActivityDailyChallengesModel.findDataByCellIndex(serverId, growthActivity.activityId, roleId, task.dayIndex, task.cellIndex, task.taskType)
    //         let recordData = taskRecord && taskRecord.data ? JSON.parse(taskRecord.data) : null
    //         let { addCount, record } = isComplete(roleId, task.taskType, task.taskParam, count, parma, recordData);
    //         if (addCount) {
    //             if (taskType == TASK_TYPE.ROLE_LV || taskType == TASK_TYPE.ROLE_TITLE || taskType == TASK_TYPE.BATTLE_TOWER_LV) {
    //                 let playerRecord = await ActivityDailyChallengesModel.setTaskCount(serverId, growthActivity.activityId, roleId, task.dayIndex, task.cellIndex, task.taskType, addCount);
    //                 //推送
    //                 task.totalCount = playerRecord.totalCount;
    //                 task.receiveRewardCount = playerRecord.receiveRewardCount ? playerRecord.receiveRewardCount : 0;
    //                 pushMessage = pushMessage.concat(Object.assign(task, { activityId: growthActivity.activityId }));
    //             } else {
    //                 let playerRecord = await ActivityDailyChallengesModel.addTaskCount(serverId, growthActivity.activityId, roleId, task.dayIndex, task.cellIndex, task.taskType, addCount);
    //                 //推送
    //                 task.totalCount = playerRecord.totalCount;
    //                 task.receiveRewardCount = playerRecord.receiveRewardCount ? playerRecord.receiveRewardCount : 0;
    //                 pushMessage = pushMessage.concat(Object.assign(task, { activityId: growthActivity.activityId }));
    //             }
    //         }
    //         if (record) {
    //             await ActivityGrowthModel.addTaskRecord(serverId, growthActivity.activityId, roleId, task.dayIndex, task.cellIndex, task.taskType, JSON.stringify(record));
    //         }
    //     }
    // }

    // console.log('***** sevenDay before', Date.now());
    //七天乐
    let allActivity: ActivityModelType[] = await findActivitiesByTypes([ACTIVITY_TYPE.SEVEN_DAY]);
    for (let activity of allActivity) {
        let playerData = new SevenDaysData(activity, createTime)
        //成长活动统计
        let growthActivity = playerData.growth;
        let growthTaskArray = growthActivity.findTaskByType(taskType);
        for (let task of growthTaskArray) {
            let taskRecord = await ActivityGrowthModel.findDataByCellIndex(serverId, activity.activityId, roleId, task.dayIndex, task.cellIndex, task.taskType)
            let recordData = taskRecord && taskRecord.data ? JSON.parse(taskRecord.data) : null;
            let { addCount, record } = isComplete(roleId, task.taskType, task.taskParam, count, activity.activityId, parma, recordData);
            if (addCount) {
                if (taskType == TASK_TYPE.ROLE_LV || taskType == TASK_TYPE.ROLE_TITLE || taskType == TASK_TYPE.BATTLE_TOWER_LV) {
                    let playerRecord = await ActivityGrowthModel.setTaskCount(serverId, activity.activityId, roleId, task.dayIndex, task.cellIndex, task.taskType, addCount);
                    //推送
                    task.totalCount = playerRecord.totalCount;
                    task.receiveRewardCount = playerRecord.receiveRewardCount ? playerRecord.receiveRewardCount : 0;
                    pushMessage = pushMessage.concat(Object.assign(task, { activityId: activity.activityId, activityType: "growth" }));
                } else {
                    let playerRecord = await ActivityGrowthModel.addTaskCount(serverId, activity.activityId, roleId, task.dayIndex, task.cellIndex, task.taskType, addCount);
                    //推送
                    task.totalCount = playerRecord.totalCount;
                    task.receiveRewardCount = playerRecord.receiveRewardCount ? playerRecord.receiveRewardCount : 0;
                    pushMessage = pushMessage.concat(Object.assign(task, { activityId: activity.activityId, activityType: "growth" }));
                }
            }
            if (record) {
                await ActivityGrowthModel.addTaskRecord(serverId, activity.activityId, roleId, task.dayIndex, task.cellIndex, task.taskType, JSON.stringify(record));
            }
        }
        //今日挑战统计
        let dailyChallengeActivity = playerData.dailyChallenge;
        let dailyChallengeTaskArray = dailyChallengeActivity.findTaskByType(taskType, playerData.today());
        for (let task of dailyChallengeTaskArray) {
            let taskRecord = await ActivityDailyChallengesModel.findDataByCellIndex(serverId, activity.activityId, roleId, task.dayIndex, task.cellIndex, task.taskType)
            let recordData = taskRecord && taskRecord.data ? JSON.parse(taskRecord.data) : null
            let { addCount, record } = isComplete(roleId, task.taskType, task.taskParam, count, activity.activityId, parma, recordData);
            if (addCount) {
                if (taskType == TASK_TYPE.ROLE_LV || taskType == TASK_TYPE.ROLE_TITLE || taskType == TASK_TYPE.BATTLE_TOWER_LV) {
                    let playerRecord = await ActivityDailyChallengesModel.setTaskCount(serverId, activity.activityId, roleId, task.dayIndex, task.cellIndex, task.taskType, addCount);
                    //推送
                    task.totalCount = playerRecord.totalCount;
                    task.receiveRewardCount = playerRecord.receiveRewardCount ? playerRecord.receiveRewardCount : 0;
                    pushMessage = pushMessage.concat(Object.assign(task, { activityId: activity.activityId, activityType: "daily" }));
                } else {
                    let playerRecord = await ActivityDailyChallengesModel.addTaskCount(serverId, activity.activityId, roleId, task.dayIndex, task.cellIndex, task.taskType, addCount);
                    //推送
                    task.totalCount = playerRecord.totalCount;
                    task.receiveRewardCount = playerRecord.receiveRewardCount ? playerRecord.receiveRewardCount : 0;
                    pushMessage = pushMessage.concat(Object.assign(task, { activityId: activity.activityId, activityType: "daily" }));
                }
            }
            if (record) {
                await ActivityGrowthModel.addTaskRecord(serverId, activity.activityId, roleId, task.dayIndex, task.cellIndex, task.taskType, JSON.stringify(record));
            }
        }
    }
    // console.log('***** sevenDay after', Date.now());

    // console.log('***** DailyChallenge before', Date.now());
    //今日挑战统计
    allActivity = await findActivitiesByTypes([ACTIVITY_TYPE.TASK_DAILY_CHALLENGES]);
    for (let activity of allActivity) {
        let growthActivity = new DailyChallengesData(activity, createTime);
        let taskArray = growthActivity.findTaskByType(taskType, growthActivity.today());
        for (let task of taskArray) {
            let taskRecord = await ActivityDailyChallengesModel.findDataByCellIndex(serverId, growthActivity.activityId, roleId, task.dayIndex, task.cellIndex, task.taskType)
            let recordData = taskRecord && taskRecord.data ? JSON.parse(taskRecord.data) : null
            let { addCount, record } = isComplete(roleId, task.taskType, task.taskParam, count, growthActivity.activityId, parma, recordData);
            if (addCount) {
                if (taskType == TASK_TYPE.ROLE_LV || taskType == TASK_TYPE.ROLE_TITLE || taskType == TASK_TYPE.BATTLE_TOWER_LV) {
                    let playerRecord = await ActivityDailyChallengesModel.setTaskCount(serverId, growthActivity.activityId, roleId, task.dayIndex, task.cellIndex, task.taskType, addCount);
                    //推送
                    task.totalCount = playerRecord.totalCount;
                    task.receiveRewardCount = playerRecord.receiveRewardCount ? playerRecord.receiveRewardCount : 0;
                    pushMessage = pushMessage.concat(Object.assign(task, { activityId: growthActivity.activityId }));
                } else {
                    let playerRecord = await ActivityDailyChallengesModel.addTaskCount(serverId, growthActivity.activityId, roleId, task.dayIndex, task.cellIndex, task.taskType, addCount);
                    //推送
                    task.totalCount = playerRecord.totalCount;
                    task.receiveRewardCount = playerRecord.receiveRewardCount ? playerRecord.receiveRewardCount : 0;
                    pushMessage = pushMessage.concat(Object.assign(task, { activityId: growthActivity.activityId }));
                }
            }
            if (record) {
                await ActivityGrowthModel.addTaskRecord(serverId, growthActivity.activityId, roleId, task.dayIndex, task.cellIndex, task.taskType, JSON.stringify(record));
            }
        }
    }
    // console.log('***** DailyChallenge after', Date.now());

    // console.log('***** RefreshTask before', Date.now());
    //刷新任务统计
    allActivity = await findActivitiesByTypes([ACTIVITY_TYPE.REFRESH_TASK]);
    for (let activity of allActivity) {
        let taskActivity = new RefreshTaskData(activity, createTime);
        let taskArray = taskActivity.findTaskByType(taskType);
        for (let task of taskArray) {
            let taskRecord = await ActivityRefreshTaskModel.findDataById(serverId, taskActivity.activityId, roleId, taskActivity.roundIndex, task.pageIndex, task.id, task.taskType)
            let recordData = taskRecord && taskRecord.data ? JSON.parse(taskRecord.data) : null
            let { addCount, record } = isComplete(roleId, task.taskType, task.taskParam, count, taskActivity.activityId, parma, recordData);
            if (addCount) {
                if (taskType == TASK_TYPE.ROLE_LV || taskType == TASK_TYPE.ROLE_TITLE || taskType == TASK_TYPE.BATTLE_TOWER_LV) {
                    let playerRecord = await ActivityRefreshTaskModel.setTaskCount(serverId, taskActivity.activityId, roleId, taskActivity.roundIndex, task.pageIndex, task.id, task.taskType, addCount);
                    //推送
                    task.totalCount = playerRecord.totalCount;
                    task.receiveRewardCount = playerRecord.receiveRewardCount ? playerRecord.receiveRewardCount : 0;
                    pushMessage = pushMessage.concat(Object.assign(task, { activityId: taskActivity.activityId }));
                } else {
                    let playerRecord = await ActivityRefreshTaskModel.addTaskCount(serverId, taskActivity.activityId, roleId, taskActivity.roundIndex, task.pageIndex, task.id, task.taskType, addCount);
                    //推送
                    task.totalCount = playerRecord.totalCount;
                    task.receiveRewardCount = playerRecord.receiveRewardCount ? playerRecord.receiveRewardCount : 0;
                    pushMessage = pushMessage.concat(Object.assign(task, { activityId: taskActivity.activityId }));
                }
            }
            if (record) {
                await ActivityRefreshTaskModel.addTaskRecord(serverId, taskActivity.activityId, roleId, taskActivity.roundIndex, task.pageIndex, task.id, task.taskType, JSON.stringify(record));
            }
        }
    }
    // console.log('***** RefreshTask after', Date.now());

    // console.log('***** hunt before', Date.now());
    //寻宝骑兵活动任务
    let tempData: ServerTempModelType = await ServerTempModel.findData(serverId);
    if (tempData) {
        // let huntActivityId = tempData.huntActivityId;
        let huntBeginTime = tempData.huntBeginTime;
        let huntEndTime = tempData.huntEndTime;
        let huntRoundIndex = tempData.huntRoundIndex;
        let activity = await ActivityModel.findActivity(tempData.huntActivityId);
        if (activity) {
            let playerData = new TreasureHuntData(activity, createTime);
            playerData.beginTime = moment(huntBeginTime).valueOf();
            playerData.endTime = moment(huntEndTime).valueOf();
            playerData.roundIndex = huntRoundIndex;
            let taskArray = playerData.tasks.findItemByTaskType(taskType);
            for (let task of taskArray) {
                let taskRecord: ActivityTreasureHuntTaskModelType = await ActivityTreasureHuntTaskModel.findDataByCellIndex(serverId, activity.activityId, roleId, huntRoundIndex, task.cellIndex);
                if (!taskRecord || !taskRecord.isPush) {
                    let recordData = taskRecord && taskRecord.data ? JSON.parse(taskRecord.data) : null
                    let { addCount, record } = isComplete(roleId, task.taskType, task.taskParam, count, activity.activityId, parma, recordData);
                    if (addCount) {
                        let playerRecord = await ActivityTreasureHuntTaskModel.addTreasureHuntTaskCount(serverId, activity.activityId, roleId, huntRoundIndex, task.cellIndex, addCount);
                        //推送
                        if (task.condition <= playerRecord.totalCount) {//已经完成
                            playerRecord = await ActivityTreasureHuntTaskModel.pushMessage(serverId, activity.activityId, roleId, huntRoundIndex, task.cellIndex);
                            task.totalCount = playerRecord.totalCount;
                            pushMessage = pushMessage.concat(Object.assign(task, { activityId: activity.activityId }));
                        } else {//没有完成
                            task.totalCount = playerRecord.totalCount;
                            pushMessage = pushMessage.concat(Object.assign(task, { activityId: activity.activityId }));
                        }
                    }
                    if (record) {
                        await ActivityTreasureHuntTaskModel.addTreasureHuntTaskRecord(serverId, activity.activityId, roleId, huntRoundIndex, task.cellIndex, JSON.stringify(record));
                    }
                }
            }
        }
    }
    // console.log('***** hunt after', Date.now());


    // console.log('***** thirtyDay before', Date.now());
    //30天任务统计
    if (taskType === TASK_TYPE.HERO_QUALITY_STAR_UP ||
        taskType === TASK_TYPE.HERO_QUALITY_TO_QUALITY_COUNT ||
        taskType === TASK_TYPE.HERO_QUALITY_WAKE_UP_COUNT ||
        taskType === TASK_TYPE.HERO_WAKE_UP_STAR_UP_COUNT ||
        taskType === TASK_TYPE.HERO_WAKE_UP_COUNT ||
        taskType === TASK_TYPE.HERO_QUALITY ||
        taskType === TASK_TYPE.GUILD_TRAIN_COUNT ||
        taskType === TASK_TYPE.HERO_UNLOCK ||
        taskType === TASK_TYPE.GACHA_QUALITY_COUNT ||
        taskType === TASK_TYPE.ROLE_TERAPH_STAGE_UP ||
        taskType === TASK_TYPE.EQUIP_QUALITY_COUNT ||

        taskType === TASK_TYPE.EQUIP_STRENGTHEN ||
        taskType === TASK_TYPE.EQUIP_REFINE_LV ||
        taskType === TASK_TYPE.HERO_STAGE_UP ||
        taskType === TASK_TYPE.EQUIP_JEWEL_SUM ||
        taskType === TASK_TYPE.EQUIP_JEWEL_STAGE ||
        taskType === TASK_TYPE.EQUIP_SUIT_JEWEL_STAGE ||
        taskType === TASK_TYPE.EQUIP_QUALITY
    ) {
        allActivity = await findActivitiesByTypes([ACTIVITY_TYPE.THIRTY_DAYS]);
        for (let activity of allActivity) {
            let thirtyDaysActivity = new ThirtyDaysData(activity, createTime);
            let playerRecords: ActivityThirtyDaysModelType[] = await ActivityThirtyDaysModel.findData(serverId, activity.activityId, roleId);
            thirtyDaysActivity.setPlayerRecords(playerRecords);
            let taskArray = thirtyDaysActivity.findUncompleteTaskByType(taskType);
            for (let task of taskArray) {
                let taskRecord = await ActivityThirtyDaysModel.findDataByCellIndex(serverId, thirtyDaysActivity.activityId, roleId, task.pageIndex, task.cellIndex, task.tab, task.taskType)
                let recordData = taskRecord && taskRecord.data ? JSON.parse(taskRecord.data) : null
                let { addCount, record } = isComplete(roleId, task.taskType, task.taskParam, count, thirtyDaysActivity.activityId, parma, recordData);
                if (addCount) {
                    let playerRecord = await ActivityThirtyDaysModel.addTaskCount(serverId, thirtyDaysActivity.activityId, roleId, task.pageIndex, task.cellIndex, task.tab, task.taskType, addCount);
                    //推送
                    if (task.condition <= playerRecord.totalCount) {//已经完成
                        playerRecord = await ActivityThirtyDaysModel.pushMessage(serverId, thirtyDaysActivity.activityId, roleId, task.pageIndex, task.cellIndex, task.tab, task.taskType);
                        task.totalCount = playerRecord.totalCount;
                        task.isComplete = true;
                        pushMessage = pushMessage.concat(Object.assign(task, { activityId: thirtyDaysActivity.activityId }));
                    } else {//没有完成
                        task.totalCount = playerRecord.totalCount;
                        pushMessage = pushMessage.concat(Object.assign(task, { activityId: thirtyDaysActivity.activityId }));
                    }
                }
                if (record) {
                    await ActivityThirtyDaysModel.addTaskRecord(serverId, thirtyDaysActivity.activityId, roleId, task.pageIndex, task.cellIndex, task.tab, task.taskType, JSON.stringify(record));
                }

            }
        }
    }
    // console.log('***** thirtyDay after', Date.now());

    // console.log('***** popUpShop before', Date.now());
    //弹出商店
    {
        allActivity = await findActivitiesByTypes([ACTIVITY_TYPE.POP_UP_SHOP]);
        for (let activity of allActivity) {
            let allTaskData: any[] = JSON.parse(activity.data);
            for (let task of allTaskData) {
                if (task.taskType == taskType) {
                    let popShopData = new PopUpShopData(task, activity.activityId);
                    let beginTime = new Date();
                    let endTime = moment(new Date()).add(task.duration, 'h').toDate();
                    if (taskType == TASK_TYPE.ROLE_TERAPH_STAGE_UP) {//只要触发就弹出礼包商店
                        //推送
                        let playerRecord = await ActivityPopUpShopModel.addTaskPushMessage(serverId, activity.activityId, roleId, task.id, task.taskType, count, beginTime, endTime);
                        popShopData.setPlayerRecords(playerRecord)
                        pushMessage = pushMessage.concat(popShopData);
                    } else if (taskType == TASK_TYPE.EQUIP_QUALITY_COUNT || taskType == TASK_TYPE.GACHA_QUALITY_COUNT || taskType == TASK_TYPE.GUILD_ACTIVITY) {//每天统计
                        let recordDate = moment(new Date()).startOf('d').toDate()
                        let recordData: ActivityPopUpShopRecordModelType = await ActivityPopUpShopRecordModel.findRecordData(serverId, activity.activityId, roleId, task.id, task.taskType, recordDate)
                        let { addCount } = isComplete(roleId, task.taskType, task.taskParam, count, activity.activityId, parma, null);
                        let oldCount = (recordData && recordData.count) ? recordData.count : 0;
                        if (oldCount < task.condition && (oldCount + addCount >= task.condition)) {//完成当天任务
                            let playerRecord = await ActivityPopUpShopModel.addTaskPushMessage(serverId, activity.activityId, roleId, task.id, task.taskType, oldCount + addCount, beginTime, endTime);
                            popShopData.setPlayerRecords(playerRecord)
                            pushMessage = pushMessage.concat(popShopData);
                        }
                        await ActivityPopUpShopRecordModel.addRecord(serverId, activity.activityId, roleId, task.id, task.taskType, recordDate, addCount)
                    } else if (taskType == TASK_TYPE.GUILD_TRAIN_COUNT) {//军团练兵场通关层数推送所有团员
                        if (task.taskParam[0] == parma.trainId) {
                            let playerRecord = await ActivityPopUpShopModel.addTaskPushMessage(serverId, activity.activityId, roleId, task.id, task.taskType, count, beginTime, endTime);
                            popShopData.setPlayerRecords(playerRecord)
                            pushMessage = pushMessage.concat(popShopData);

                            //全服推送
                            let code = parma.code;
                            const guildData = await GuildModel.findByCode(code, serverId, 'members');
                            let members = guildData.members.filter(member => { return member != roleId })
                            await ActivityPopUpShopModel.addTaskArrayPushMessage(serverId, activity.activityId, members, task.id, task.taskType, count, beginTime, endTime);

                        }
                    } else {
                        let taskRecord = await ActivityPopUpShopModel.findDataByTaskId(serverId, activity.activityId, roleId, popShopData.id, popShopData.taskType)
                        let recordData = taskRecord && taskRecord.data ? JSON.parse(taskRecord.data) : null
                        if (!taskRecord || !taskRecord.isPush) {
                            let { addCount, record } = isComplete(roleId, task.taskType, task.taskParam, count, activity.activityId, parma, recordData);
                            if (addCount) {
                                if (taskType == TASK_TYPE.ROLE_LV || taskType == TASK_TYPE.ROLE_TITLE || taskType == TASK_TYPE.BATTLE_TOWER_LV) {
                                    let playerRecord = await ActivityPopUpShopModel.setTaskCount(serverId, activity.activityId, roleId, task.id, task.taskType, addCount);
                                    //推送
                                    if (task.condition <= playerRecord.totalCount) {
                                        playerRecord = await ActivityPopUpShopModel.pushMessage(serverId, activity.activityId, roleId, task.id, task.taskType, beginTime, endTime);
                                        popShopData.setPlayerRecords(playerRecord)
                                        pushMessage = pushMessage.concat(popShopData);
                                    }
                                } else {
                                    let playerRecord = await ActivityPopUpShopModel.addTaskCount(serverId, activity.activityId, roleId, task.id, task.taskType, addCount);
                                    //推送
                                    if (task.condition <= playerRecord.totalCount) {
                                        playerRecord = await ActivityPopUpShopModel.pushMessage(serverId, activity.activityId, roleId, task.id, task.taskType, beginTime, endTime);
                                        popShopData.setPlayerRecords(playerRecord)
                                        pushMessage = pushMessage.concat(popShopData);
                                    }
                                }
                            }
                            if (record) {
                                await ActivityPopUpShopModel.addTaskRecord(serverId, activity.activityId, roleId, task.id, task.taskType, JSON.stringify(record));
                            }
                        }
                    }
                }
            }
        }
    }
    // console.log('***** popUpShop after', Date.now());
    // console.log('***** growthFund before', Date.now());
    //主线成长基金
    if (taskType === TASK_TYPE.BATTLE_MAIN) {
        allActivity = await findActivitiesByTypes([ACTIVITY_TYPE.GROWTH_FUND_MAIN, ACTIVITY_TYPE.GROWTH_FUND_MAIN_VIP]);
        for (let activity of allActivity) {
            let growthFundActivity = new GrowthFundData(activity, createTime);
            let playerRecords: ActivityGrowthFundModelType[] = await ActivityGrowthFundModel.findData(activity.activityId, roleId);
            growthFundActivity.setPlayerRecords(playerRecords);
            if (growthFundActivity.isVipActivity()) {//vip高阶需要购买
                let buyRecords = await ActivityBuyRecordsModel.findRecordsByActivityId(activity.activityId, roleId);
                growthFundActivity.initBuyRecords(buyRecords);
            }
            let taskArray = growthFundActivity.unLockItem(parma.warId);
            //推送
            pushMessage = pushMessage.concat(taskArray);
        }
    }
    // console.log('***** growthFund after', Date.now());
    // console.log('***** growthFundTower before', Date.now());
    //镇念塔成长基金getRoleOnlineInfo
    if (taskType === TASK_TYPE.BATTLE_TOWER_LV) {
        allActivity = await findActivitiesByTypes([ACTIVITY_TYPE.GROWTH_FUND_TOWER, ACTIVITY_TYPE.GROWTH_FUND_TOWER_VIP]);
        for (let activity of allActivity) {
            let growthFundActivity = new GrowthFundData(activity, createTime);
            let playerRecords: ActivityGrowthFundModelType[] = await ActivityGrowthFundModel.findData(activity.activityId, roleId);
            growthFundActivity.setPlayerRecords(playerRecords);
            if (growthFundActivity.isVipActivity()) {//vip高阶需要购买
                let buyRecords = await ActivityBuyRecordsModel.findRecordsByActivityId(activity.activityId, roleId);
                growthFundActivity.initBuyRecords(buyRecords);
            }
            let taskArray = growthFundActivity.unLockItem(parma.towerLv);
            //推送
            pushMessage = pushMessage.concat(taskArray);
        }
    }
    // console.log('***** growthFundTower after', Date.now());
    // console.log('***** growthFundElite before', Date.now());
    //精英成长基金
    if (taskType === TASK_TYPE.BATTLE_MAIN_ELITE) {
        allActivity = await findActivitiesByTypes([ACTIVITY_TYPE.GROWTH_FUND_MAIN_ELITE, ACTIVITY_TYPE.GROWTH_FUND_MAIN_ELITE_VIP]);
        for (let activity of allActivity) {
            let growthFundActivity = new GrowthFundData(activity, createTime);
            let playerRecords: ActivityGrowthFundModelType[] = await ActivityGrowthFundModel.findData(activity.activityId, roleId);
            growthFundActivity.setPlayerRecords(playerRecords);
            if (growthFundActivity.isVipActivity()) {//vip高阶需要购买
                let buyRecords = await ActivityBuyRecordsModel.findRecordsByActivityId(activity.activityId, roleId);
                growthFundActivity.initBuyRecords(buyRecords);
            }
            let taskArray = growthFundActivity.unLockItem(parma.mainEliteWarId);
            //推送
            pushMessage = pushMessage.concat(taskArray);
        }
    }
    // console.log('***** growthFundElite after', Date.now());
    return pushMessage;
}

/**
   * 达成任务标准
   *
   * @param {string} roleId 角色Id
   * @param {number} taskType 任务类型
   * @param {number} taskParam 任务条件数据
   * @param {number} count 数据
   * @param {number} parma 参数
   *
   */

export function isComplete(_roleId: string, taskType: TASK_TYPE, taskParam: string, count: number, _activityId: number, paramObj?: any, recordData?: any): any {
    // console.log('达成任务标准', roleId, taskType, taskParam, count, activityId, paramObj)
    let param = splitString(taskParam, '&');
    let addCount: number = 0; // 条件是否满足
    let record: any = null;
    switch (taskType) {
        case TASK_TYPE.ROLE_LV://重置数据
            addCount = count;
            break;
        case TASK_TYPE.GUILD_JOIN:
            addCount = count;
            break;
        case TASK_TYPE.LOGIN_SUM:
            addCount = count;
            break;
        case TASK_TYPE.HERO_NUM:
            addCount = count;
            break;

        case TASK_TYPE.HERO_QUALITY_STAR_UP://herocount&quality&star&
            addCount = (param[1] == paramObj.quality) && (param[2] == paramObj.star) ? count : 0;
            break;
        case TASK_TYPE.HERO_QUALITY_TO_QUALITY_COUNT://herocount&quality&star& {oldQuality, quality: hero.quality}
            addCount = (param[1] == paramObj.oldQuality) && (param[2] == paramObj.quality) ? count : 0;
            break;
        case TASK_TYPE.HERO_QUALITY_WAKE_UP_COUNT://herocount&quality
            addCount = (param[1] == paramObj.quality) ? count : 0;
            break;
        case TASK_TYPE.HERO_WAKE_UP_STAR_UP_COUNT://herocount&colorStar& colorStar:彩星 1表示觉醒
            addCount = (param[1] == paramObj.colorStar) ? count : 0;
            break;
        case TASK_TYPE.HERO_STAGE_UP://herocount&star& 
            addCount = (param[1] == paramObj.job) ? count : 0;
            break;
        case TASK_TYPE.EQUIP_JEWEL_STAGE://count&stage& 
            addCount = (param[1] == paramObj.stage) ? count : 0;
            break;
        case TASK_TYPE.EQUIP_SUIT_JEWEL_STAGE://count&stage& 
            addCount = (param[1] == paramObj.stage) ? count : 0;
            break;
        case TASK_TYPE.EQUIP_QUALITY:
            addCount = param[1] == paramObj.quality ? count : 0;
            break;

        case TASK_TYPE.ROLE_TITLE://重置数据
            addCount = param[0] <= count ? count : 0;
            break;
        case TASK_TYPE.GASHA:
            addCount = count;
            break;
        case TASK_TYPE.EQUIP_STRENGTHEN:
            for (let obj of paramObj) {
                // obj.hid;//英雄di
                // obj.oldLv;//栏位升级前等级
                // obj.lv;//栏位升级后等级
                // obj.id;//栏位id
                if (param[1] > obj.oldLv && param[1] <= obj.lv) {
                    addCount++;
                }
            }
            break;
        case TASK_TYPE.EQUIP_REFINE_LV:
            addCount = (param[1] == paramObj.lv) ? count : 0;
            break;

        case TASK_TYPE.BATTLE_MAIN:
            addCount = (param[1] == paramObj.warId) ? 1 : 0;
            break;
        case TASK_TYPE.EQUIP_JEWEL_SUM:
            addCount = count;
            break;
        case TASK_TYPE.GUILD_TRAIN:
            addCount = count;
            break;
        case TASK_TYPE.ROLE_SCHOOL_PUT_HERO:
            addCount = count;
            break;
        case TASK_TYPE.GUILD_ACTIVITY:
            {
                let aid = paramObj.aid;
                if (param[0] == 0 || aid == param[0]) {
                    addCount = count;
                }
                break;
            }
        case TASK_TYPE.EQUIP_SUM:
            addCount = count;
            break;
        case TASK_TYPE.HERO_LV://{ hid, lv}
            {
                let hid = paramObj.hid;
                let lv = paramObj.lv;
                if (lv < param[1]) {
                    break;
                }
                if (recordData) {
                    record = recordData;
                    if (recordData.indexOf(hid) != -1) {
                        break;
                    }
                } else {
                    record = [];
                }

                addCount = count;
                record.push(hid)
                break;
            }
        case TASK_TYPE.HERO_TRAIN_SUM://训练X次是所有武将的训练次数的总和达到要求就好了
            {
                addCount = count;
                break;
            }
        case TASK_TYPE.HERO_TRAIN://X名武将训练Y次，要求单名武将训练Y次，这样的武将要有X名
            {
                let hid = paramObj.hid;
                if (recordData) {
                    record = recordData;
                    let oldCount = record[hid];
                    if (oldCount) {
                        if (oldCount < param[1] && (oldCount + count >= param[1])) {
                            addCount = count;
                            record[hid] = oldCount + count;
                            break;
                        }
                    } else {
                        record[hid] = count;
                        if (count >= param[1]) {
                            addCount = count;
                            break;
                        }
                    }
                } else {
                    record = {};
                    record[hid] = count;
                    if (count >= param[1]) {
                        addCount = count;
                        break;
                    }
                }
                break;
            }
        case TASK_TYPE.BATTLE_EXPEDITION:
            {
                addCount = count;
                break;
            }
        case TASK_TYPE.BATTLE_EXPEDITION_BOX:
            {
                addCount = count;
                break;
            }
        case TASK_TYPE.HERO_QUALITY:
            {
                let quality = param[1]
                let heroes = paramObj.heroes.filter(hero => { return hero.quality == quality })
                addCount = heroes.length;
                break;
            }
        case TASK_TYPE.PVP_WIN_SERIES:
            {
                addCount = count;
                break;
            }
        case TASK_TYPE.PVP_WIN:
            {
                addCount = count;
                break;
            }
        case TASK_TYPE.BATTLE_TOWER_LV://{towerLv}
            {
                let towerLv = paramObj.towerLv;
                if (recordData) {
                    if (recordData >= towerLv) {
                        break;
                    }
                }
                record = towerLv;
                addCount = towerLv;
                break;
            }
        case TASK_TYPE.BATTLE_MAIN_ELITE:
            {
                if (paramObj.mainEliteWarId == param[1]) {
                    addCount = count;
                }
                break;
            }
        case TASK_TYPE.BATTLE_DUNGEON_WAR:
            {
                if (paramObj.warId == param[1]) {
                    addCount = count;
                }
                break;
            }
        case TASK_TYPE.HERO_NUM:
            {
                addCount = count;
                break;
            }
        case TASK_TYPE.PVP:
            {
                addCount = count;
                break;
            }
        case TASK_TYPE.GUILD_TRAIN_COUNT://trainId  trainId&
            {
                if (paramObj.trainId == param[0]) {
                    addCount = count;
                }
                break;
            }
        case TASK_TYPE.HERO_UNLOCK://
            {
                let camp = param[1]
                let heroes = paramObj.dicHeroes.filter(hero => { return hero.camp == camp })
                addCount = heroes.length;
                break;
            }
        case TASK_TYPE.GACHA_QUALITY_COUNT://count&quality&
            {
                let quality = param[1]
                let heroes = paramObj.heroes.filter(hero => { return hero.quality == quality })
                addCount = heroes.length;
                break;
            }
        case TASK_TYPE.ROLE_TERAPH_STAGE_UP://
            {
                addCount = count;
                break;
            }

        case TASK_TYPE.HERO_WAKE_UP_COUNT:
            {

                let hid = paramObj.hid;
                if (recordData) {
                    record = recordData;
                    if (recordData.indexOf(hid) != -1) {
                        break;
                    }
                } else {
                    record = [];
                }

                addCount = count;
                record.push(hid)
                break;
            }
        case TASK_TYPE.EQUIP_QUALITY_COUNT:
            {
                let quality = param[1]
                let equips = paramObj.equips.filter(equip => { return equip.quality == quality })
                addCount = equips.length;
                break;
            }
        case TASK_TYPE.COM_BATTLE:
            {
                addCount = count;
                break;
            }
        case TASK_TYPE.COM_BATTLE_ASSIST_TEAM:
            {
                addCount = count;
                break;
            }
        case TASK_TYPE.GUILD_JOIN_ACTIVITY_END:
            {
                addCount = count;
                break;
            }
        case TASK_TYPE.ACTIVITY_RMB:
            {
                addCount = count;
                break;
            }
        case TASK_TYPE.BATTLE_EVENT:
            {
                if (param[0] == 0 || param[0] == paramObj.eventType) {
                    addCount = count;
                }
                break;
            }
        case TASK_TYPE.GUILD_DONATE:
            {
                addCount = count;
                break;
            }
        case TASK_TYPE.CHAT:
            {
                if (param[0] == paramObj.chatType) {
                    addCount = count;
                }
                break;
            }
        case TASK_TYPE.BATTLE_TOWER:
            {
                addCount = count;
                break;
            }
        case TASK_TYPE.BATTLE_COST_AP:
            {
                addCount = count;
                break;
            }
        case TASK_TYPE.BATTLE_MAIN_SWEEP:
            {
                addCount = count;
                break;
            }
        case TASK_TYPE.BATTLE_DAILY:
            {
                if (param[0] == 0 || param[0] == paramObj.warId) {
                    addCount = count;
                }
                break;
            }
        case TASK_TYPE.FRIEND_SEND_HEART:
            {
                addCount = count;
                break;
            }
        default:
            addCount = 0;
            break;

    }
    // console.log('dddddddddddd', addCount, record)
    return { addCount, record };
}