/**
 * 体力系统
 */

import { EPlace, HeroModel, HeroType, HeroUpdate } from '../db/Hero';

import { RoleUpdate, RoleType, RoleModel } from '../db/Role';
import { Rank } from './rankService';
import { HERO_SYSTEM_TYPE, PUSH_ROUTE, REDIS_KEY } from '../consts';
import { saveLadderDefCe, saveLadderDefCeByData, updateRoleOnlineInfo, updateUserInfo } from './redisService';
import { GuildModel, GuildType } from '../db/Guild';
import { CalCe } from './role/calCe';
import { RoleCeModel, RoleCeUpdate } from '../db/RoleCe';
import { PvpDefenseModel } from '../db/PvpDefense';
import { saveCeChangeLog } from '../pubUtils/logUtil';
import { JewelType } from '../db/Jewel';
import { SchoolModel, SchoolType } from '../db/School';
import { AttributeCal } from '../domain/roleField/attribute';
import { sendMessageToUserWithSuc } from './pushService';
import { SkinType } from '../db/Skin';
import { LadderMatchModel } from '../db/LadderMatch';
import { ArtifactModelType } from '../db/Artifact';
import { GVGVestigeRankModel } from '../db/GVGVestigeRank';

interface Param {
    isInitRole?: boolean,
    hid?: number,
    hero?: HeroType,
    isUpStar?: boolean,
    shipId?: number,
    isFavourLvUp?: boolean,
    ePlaceId?: number,
    ePlaceIds?: number[],
    jewels?: JewelType[],
    jewel?: JewelType,
    teraphId?: number,
    schoolId?: number,
    schoolHid?: number,
    preSchoolHid?: number,
    skinId?: number,
    roleUpdate?: RoleUpdate,
    role?: RoleType,
    roleIncUpdate?: RoleUpdate;
    heroes?: HeroType[],
    schools?: SchoolType[];
    skins?: SkinType[],
    stonesId?: number,
    talentId?: number,
    artifact?: ArtifactModelType,
    artifacts?: ArtifactModelType[],
    job?: number,
}

export async function calculateCeWithHero(type: HERO_SYSTEM_TYPE, roleId: string, serverId: number, sid: string, hid: number, heroUpdate: HeroUpdate, param: Param = {}) {
    let heroUpdates = new Map<number, HeroUpdate>();
    heroUpdates.set(hid, heroUpdate);
    let { heroes, curRole } = await calculateCes(type, roleId, serverId, sid, heroUpdates, param.roleUpdate||{}, param.roleIncUpdate||{}, param);
    let curHero = heroes.find(cur => cur.hid == hid);
    return { heroes, curHero, curRole }
}

export async function calculateCeWithRole(type: HERO_SYSTEM_TYPE, roleId: string, serverId: number, sid: string, roleUpdate: RoleUpdate, param: Param = {}) {
    let { heroes, curRole } = await calculateCes(type, roleId, serverId, sid, new Map(), roleUpdate, {}, param);
    return { heroes, curRole };
}

export async function calculateCes(type: HERO_SYSTEM_TYPE, roleId: string, serverId: number, sid: string, heroUpdates: Map<number, HeroUpdate>, roleUpdate: RoleUpdate, roleIncUpdate: RoleUpdate, param: Param = {}) {
    const ceChangeTxt: string[] = [];
    let calCe = new CalCe(roleId);
    let roleCe = await RoleCeModel.findByRoleId(roleId);
    calCe.setRoleCe(roleCe);
    switch (type) {
        case HERO_SYSTEM_TYPE.INIT:
            {
                for(let [hid, { skinId, lv, quality, star, starStage, colorStar, colorStarStage, job, jobStage, skins }] of heroUpdates) {
                    ceChangeTxt.push(`获得武将 ${hid}`);
                    calCe.setHeroBase(hid, skinId);
                    calCe.setHeroLv(hid, lv);
                    calCe.setHeroStar(hid, job, quality, star, starStage, colorStar, colorStarStage);
                    calCe.setJob(hid, job, jobStage);
                    calCe.setTalent(hid, skins)
                }
                // console.log('####### roleUpdate', param.isInitRole, roleUpdate)
                if(param.isInitRole) {
                    let { title, teraphs, lv } = roleUpdate;
                    calCe.setRoleLv(lv)
                    calCe.setTitle(title);
                    calCe.setTeraph(teraphs);
                }
                break;
            }
        case HERO_SYSTEM_TYPE.LVUP: // 1. 升级
            {
                for(let [hid, { lv }] of heroUpdates) {
                    ceChangeTxt.push(`武将 ${hid} 升级到 ${lv}`);
                    calCe.setHeroLv(hid, lv);
                }
                break;
            }
        case HERO_SYSTEM_TYPE.STAR: // 2. 升星
            {
                for(let [hid, { star, starStage }] of heroUpdates) {
                    ceChangeTxt.push(`武将 ${hid} 升星到 ${star} 星 ${starStage} 阶`);
                    let { hero: { quality, job, colorStar, colorStarStage }, isUpStar } = param;
                    await treatHeroStar(calCe, roleId, hid, star, starStage, quality, colorStar, colorStarStage, job, isUpStar);
                }
                break;
            }
        case HERO_SYSTEM_TYPE.QUALITY: // 3. 升品
            {
                for(let [hid, { quality }] of heroUpdates) {
                    ceChangeTxt.push(`武将 ${hid} 升品到 ${quality} 品`);
                    let { hero: { star, starStage, colorStar, colorStarStage, job } } = param;
                    await treatHeroStar(calCe, roleId, hid, star, starStage, quality, colorStar, colorStarStage, job, true);
                }
                break;
            }
        case HERO_SYSTEM_TYPE.COLORSTAR: // 4. 觉醒
            {
                for(let [hid, { quality, colorStar, colorStarStage }] of heroUpdates) {
                    ceChangeTxt.push(`武将 ${hid} 升彩星到 ${quality} 星`);
                    let { hero: { star, starStage, job }, isUpStar } = param;
                    await treatHeroStar(calCe, roleId, hid, star, starStage, quality, colorStar, colorStarStage, job, isUpStar);
                }
                break;
            }
        case HERO_SYSTEM_TYPE.TRAIN: // 5. 训练
        case HERO_SYSTEM_TYPE.STAGEUP: // 6. 职业进阶    
            {
                for(let [hid, { job, jobStage }] of heroUpdates) {
                    ceChangeTxt.push(`武将 ${hid} 的职业升到 ${job} ${jobStage} 阶`);
                    calCe.setJob(hid, job, jobStage);
                }
                break;
            }
        case HERO_SYSTEM_TYPE.SKIN: // 7. 穿皮肤
            {
                let { hero: { quality, star, starStage, colorStar, colorStarStage, jobStage }, artifact } = param;
                for(let [hid, { skinId, job, ePlace, skins }] of heroUpdates) {
                    ceChangeTxt.push(`武将 ${hid} 穿上了皮肤 ${skinId}`);
                    calCe.setHeroBase(hid, skinId);
                    calCe.setHeroStar(hid, job, quality, star, starStage, colorStar, colorStarStage);
                    calCe.setJob(hid, job, jobStage);
                    for(let { id, equipId, quality, qualityStage, lv, star, starStage } of ePlace) {
                        calCe.setEquipQuality(hid, id, equipId, quality, qualityStage);
                        calCe.setEquipStrength(hid, id, equipId, lv);
                        calCe.setEquipStar(hid, id, equipId, star, starStage);
                    }
                    calCe.setEquipSuit(hid, skinId, ePlace);
                    calCe.setTalent(hid, skins);
                    if(artifact) calCe.setArtifactSeid(hid, skinId, job, artifact.artifactId);
                }
                break;
            }
        case HERO_SYSTEM_TYPE.CONNECT: // 9. 羁绊
            {
                let { shipId } = param;
                for(let [ hid, { connections } ] of heroUpdates) {
                    let curConnect = connections?.find(cur => cur.shipId);
                    ceChangeTxt.push(`武将 ${hid} 的羁绊 ${shipId} 升级到 ${curConnect?.level} 级`);
                    calCe.setConnection(hid, connections);
                }
                break;
            }
        case HERO_SYSTEM_TYPE.ADD_SKIN: // 15. 第一次获得皮肤
            {
                let { skinId } = param;
                calCe.setAddSkin(skinId);
                ceChangeTxt.push(`获得皮肤 ${skinId}`);
                break;
            }
        case HERO_SYSTEM_TYPE.SCHOOL: // 16. 放百家学宫
            {
                let { schoolId, schoolHid, preSchoolHid, hero } = param;
                if(preSchoolHid) {
                    calCe.setSchool(false, preSchoolHid, schoolId, 0, 0, 0);
                    ceChangeTxt.push(`将武将 ${preSchoolHid} 从百家学宫移除`);
                }
                if(schoolHid) {
                    let { star, colorStar, quality } = hero;
                    calCe.setSchool(true, schoolHid, schoolId, star, colorStar, quality);
                    ceChangeTxt.push(`将武将 ${schoolHid} 放置到百家学宫`);
                }
                break;
            }
        case HERO_SYSTEM_TYPE.SCROLL: // 17. 名将谱
            {
                for(let [hid, { scrollStar, scrollQuality, scrollColorStar }] of heroUpdates) {
                    calCe.setScroll(hid, scrollStar, scrollQuality, scrollColorStar);
                    ceChangeTxt.push(`将武将 ${hid} 的名将谱激活至 ${scrollStar}星 ${scrollQuality}品 ${scrollColorStar}彩星`);
                }                
                break;
            }
        case HERO_SYSTEM_TYPE.TITLE: // 18. 爵位
            {
                let { title } = roleUpdate;
                calCe.setTitle(title);
                ceChangeTxt.push(`爵位升级至 ${title}`);
                break;
            }
        case HERO_SYSTEM_TYPE.TERAPH: // 19. 神像
        case HERO_SYSTEM_TYPE.TERAPH_UP: // 20. 神像进阶
            {
                let { teraphId } = param;
                let { teraphs } = roleUpdate;
                calCe.setTeraph(teraphs);
                ceChangeTxt.push(`神像 ${teraphId} 升级或进阶`);
                break;
            }
        case HERO_SYSTEM_TYPE.COMPOSE_EQUIP: // 21. 合成装备
            {
                let { ePlaceId, skinId } = param;
                for(let [hid, { ePlace = [] }] of heroUpdates) {
                    for(let { id, equipId, quality, qualityStage, lv, star, starStage } of ePlace) {
                        if(ePlaceId == id) {
                            calCe.setEquipQuality(hid, id, equipId, quality, qualityStage);
                            calCe.setEquipStrength(hid, id, equipId, lv);
                            calCe.setEquipStar(hid, id, equipId, star, starStage);
                            ceChangeTxt.push(`武将 ${hid} 的 ${equipId} 装备合成装备`);
                        }
                    }
                    calCe.setEquipSuit(hid, skinId, ePlace);
                }
                break;
            }
        case HERO_SYSTEM_TYPE.EQUIP_STRENGTH: // 22. 装备强化
            {
                let { ePlaceIds } = param;
                for(let [hid, { ePlace = [] }] of heroUpdates) {
                    for(let { id, equipId, lv } of ePlace) {
                        if(ePlaceIds.indexOf(id) != -1) {
                            calCe.setEquipStrength(hid, id, equipId, lv);
                            ceChangeTxt.push(`武将 ${hid} 的 ${equipId} 装备升级到 ${lv} 级`);
                        }
                    }
                }
                break;
            }
        case HERO_SYSTEM_TYPE.EQUIP_QUALITY: // 23. 装备升品
            {
                let { ePlaceId } = param;
                for(let [hid, { ePlace = [] }] of heroUpdates) {
                    for(let { id, equipId, quality, qualityStage } of ePlace) {
                        if(ePlaceId == id) {
                            calCe.setEquipQuality(hid, id, equipId, quality, qualityStage);
                            ceChangeTxt.push(`武将 ${hid} 的 ${equipId} 装备升级到 ${quality} 品 ${qualityStage} 阶`);
                        }
                    }
                }
                break;
            }
        case HERO_SYSTEM_TYPE.EQUIP_STAR: // 24. 装备升星
            {
                let { ePlaceId, skinId } = param;
                for(let [hid, { ePlace = [] }] of heroUpdates) {
                    for(let { id, equipId, star, starStage } of ePlace) {
                        if(ePlaceId == id) {
                            calCe.setEquipStar(hid, id, equipId, star, starStage);
                            ceChangeTxt.push(`武将 ${hid} 的 ${equipId} 装备精炼到 ${star} 星 ${starStage} 阶`);
                        }
                    }
                    calCe.setEquipSuit(hid, skinId, ePlace);
                }
                break;
            }
        case HERO_SYSTEM_TYPE.EQUIP_JEWEL: // 25. 装备天晶
        case HERO_SYSTEM_TYPE.JEWEL_RESET_RANDSE: // 27. 洗练
        case HERO_SYSTEM_TYPE.JEWEL_QUENCH: // 28. 淬炼
            {
                let { ePlaceId, jewel: curJewel, skinId } = param;
                for(let [hid, { ePlace = [] }] of heroUpdates) {
                    for(let { id, stones } of ePlace) {
                        if(ePlaceId == id) {
                            calCe.setJewel(hid, id, stones, curJewel);
                            ceChangeTxt.push(`武将 ${hid} 的 ${ePlaceId} 装备栏的天晶 ${curJewel?.id} 装备或洗练或淬炼`);
                        }
                    }
                    calCe.setEquipSuit(hid, skinId, ePlace);
                }
                break;
            }
        case HERO_SYSTEM_TYPE.EQUIP_STONE: // 26. 装备地玉
            {
                let { ePlaceId, jewel: curJewel, skinId, stonesId } = param;
                for(let [hid, { ePlace = [] }] of heroUpdates) {
                    for(let { id, stones } of ePlace) {
                        if(ePlaceId == id) {
                            calCe.setStone(hid, ePlaceId, stones);
                            calCe.setJewel(hid, id, stones, curJewel);
                            
                            ceChangeTxt.push(`武将 ${hid} 的 ${ePlaceId} 装备栏装备地玉 ${stonesId}`);
                        }
                    }
                    calCe.setEquipSuit(hid, skinId, ePlace);
                }
                break;
            }
        case HERO_SYSTEM_TYPE.REBIRTH: // 29. 重生
            {
                let { schoolId } = param;
                for(let [hid, { skinId, lv, quality, star, starStage, colorStar, colorStarStage, job, jobStage, skins, scrollStar, scrollQuality, scrollColorStar, connections }] of heroUpdates) {
                    calCe.setHeroBase(hid, skinId);
                    calCe.setHeroLv(hid, lv);
                    calCe.setHeroStar(hid, job, quality, star, starStage, colorStar, colorStarStage);
                    calCe.setJob(hid, job, jobStage);
                    calCe.clearEquip(hid);
                    calCe.setTalent(hid, skins);
                    calCe.setScroll(hid, scrollStar, scrollQuality, scrollColorStar);
                    calCe.setConnection(hid, connections);
                    if(schoolId) calCe.setSchool(true, hid, schoolId, star, colorStar, quality);

                    ceChangeTxt.push(`武将 ${hid} 重生`);
                }
                break;
            }
        case HERO_SYSTEM_TYPE.TALENT_UNLOCK: // 30. 天赋解锁
        case HERO_SYSTEM_TYPE.TALENT_LV: // 32. 天赋升级
        case HERO_SYSTEM_TYPE.TALENT_RESET: // 33. 天赋洗点
            {
                let { talentId } = param;
                for(let [hid, { skins }] of heroUpdates) {
                    calCe.setTalent(hid, skins);
                    ceChangeTxt.push(`武将 ${hid} 天赋 ${talentId} 解锁、升级、洗点`);
                }
                break;
            }
        case HERO_SYSTEM_TYPE.RE_CAL: // 31. 重新计算
            {
                let { role, schools, jewels, heroes, skins, artifacts } = param;
                calCe.clearRoleCe();
                for(let { hid, skinId, lv, quality, star, starStage, colorStar, colorStarStage, job, jobStage, connections, skins, scrollStar, scrollQuality, scrollColorStar, ePlace } of heroes) {
                    calCe.setHeroBase(hid, skinId);
                    calCe.setHeroLv(hid, lv);
                    calCe.setHeroStar(hid, job, quality, star, starStage, colorStar, colorStarStage);
                    calCe.setJob(hid, job, jobStage);
                    calCe.setConnection(hid, connections);
                    calCe.setTalent(hid, skins);
                    for(let { id, equipId, star, starStage, quality, qualityStage, lv: equipLv, stones, jewel } of ePlace) {
                        calCe.setEquipQuality(hid, id, equipId, quality, qualityStage);
                        calCe.setEquipStrength(hid, id, equipId, equipLv);
                        calCe.setEquipStar(hid, id, equipId, star, starStage);
                        let curJewel = jewels.find(cur => cur.seqId == jewel);
                        calCe.setJewel(hid, id, stones, curJewel);
                        calCe.setStone(hid, id, stones);
                        calCe.setTitle(role.title);
                        calCe.setTeraph(role.teraphs);
                    }
                    let artifact = artifacts.find(cur => cur.hid == hid);
                    if(artifact) calCe.setPutArtifact(hid, skinId, job, artifact);
                    calCe.setEquipSuit(hid, skinId, ePlace);
                    calCe.setScroll(hid, scrollStar, scrollQuality, scrollColorStar);
                }

                for(let { schoolId, hid, } of schools) {
                    let curHero = heroes.find(cur => cur.hid == hid);
                    if(curHero) calCe.setSchool(true, hid, schoolId, curHero.star, curHero.colorStar, curHero.quality);
                }

                for(let { id } of skins) {
                    calCe.setAddSkin(id);
                }
                ceChangeTxt.push(`后台重新计算`);
                break;
            }
        case HERO_SYSTEM_TYPE.PUT_ARTIFACT: // 34. 装备宝物
        {
            let { artifact, job, skinId } = param;
            if(!artifact) break;
            for(let [hid ] of heroUpdates) {
                calCe.setPutArtifact(hid, skinId, job, artifact);
                // calCe.setArtifactQuality(hid, artifact.artifactId);
                // calCe.setArtifactSeid(hid, skinId, job, artifact.artifactId);
                ceChangeTxt.push(`武将 ${hid} 装备宝物 ${artifact.artifactId}`);
            }
            break;
        }
        case HERO_SYSTEM_TYPE.PUT_OFF_ARTIFACT: // 35. 卸下
        {
            for(let [hid ] of heroUpdates) {
                calCe.setPutOffArtifact(hid);
                ceChangeTxt.push(`武将 ${hid} 卸下宝物`);
            }
            break;
        }
        case HERO_SYSTEM_TYPE.ARTIFACT_LV: // 36.宝物升级
        {
            let { artifact } = param;
            if(!artifact) break;
            for(let [hid ] of heroUpdates) {
                calCe.setArtifactLv(hid, artifact.artifactId, artifact.lv);
                ceChangeTxt.push(`武将 ${hid} 装备的宝物 ${artifact.seqId} ${artifact.artifactId} 升至 ${artifact.lv} 级`);
            }
            break;
        }
        case HERO_SYSTEM_TYPE.ARTIFACT_QUALITY: // 37. 宝物升品
        {
            let { artifact, job, skinId } = param;
            if(!artifact) break;
            for(let [hid ] of heroUpdates) {
                calCe.setArtifactQuality(hid, artifact.artifactId);
                calCe.setArtifactSeid(hid, skinId, job, artifact.artifactId);
                ceChangeTxt.push(`武将 ${hid} 装备的宝物 ${artifact.seqId} 升至 ${artifact.artifactId}`);
            }
            break;
        }
        case HERO_SYSTEM_TYPE.ARTIFACT_TRANSFER: // 38. 宝物转换
        {
            let { artifact, job, skinId } = param;
            if(!artifact) break;
            for(let [hid ] of heroUpdates) {
                calCe.setArtifactLv(hid, artifact.artifactId, artifact.lv);
                calCe.setArtifactQuality(hid, artifact.artifactId);
                calCe.setArtifactSeid(hid, skinId, job, artifact.artifactId);
                ceChangeTxt.push(`武将 ${hid} 装备的宝物 ${artifact.seqId} 转换至 ${artifact.artifactId}`);
            }
            break;
        }
        
    }
    let { heroCe, roleInc } = calCe.getCeInc(); // 计算战力，获得有变化的武将战力
    let changeHids: number[] = [];
    let pushHeros = new Array<{ hid: number, ce: number, incHeroCe: number }>();
    let heroes: HeroType[] = [];

    for(let [hid, heroUpdate] of heroUpdates) {
        if(heroCe.has(hid)) {
            let { ce, inc } = heroCe.get(hid);
            let heroUpdate = heroUpdates.get(hid)||{};
            let hero = await HeroModel.updateHeroInfo(roleId, hid, { ...heroUpdate, ce });
            calCe.setResultHero(hero);
            heroes.push(hero);
            await PvpDefenseModel.updateCe(roleId, hid, ce); // 更新pvp防守阵战力
            await LadderMatchModel.updateCe(roleId, hid, ce);
            await GVGVestigeRankModel.updateCe(roleId, hid, ce);
            pushHeros.push({ hid, ce, incHeroCe: inc });
        } else {
            let hero = await HeroModel.updateHeroInfo(roleId, hid, heroUpdate);
            heroes.push(hero);
        }
    }
    for(let [hid, { ce, inc }] of heroCe) {
        if(changeHids.indexOf(hid) == -1) {
            let hero = await HeroModel.updateHeroInfo(roleId, hid, { ce });
            await PvpDefenseModel.updateCe(roleId, hid, ce); // 更新pvp防守阵战力
            await LadderMatchModel.updateCe(roleId, hid, ce);
            await GVGVestigeRankModel.updateCe(roleId, hid, ce);
            pushHeros.push({ hid, ce: hero.ce, incHeroCe: inc });
        }
    }
    
    let { topLineup, topLineupCe, hasTopCeChange } = calCe.getTopLineup();
    let roleCeUpdate: RoleCeUpdate = calCe.getRoleCeTable();
    if(topLineupCe > (roleCe?.historyLineupCe||0)) {
        roleCeUpdate = { ...roleCeUpdate, historyLineupCe: topLineupCe };
    }

    roleCe = await RoleCeModel.updateRoleCe(roleId, roleCeUpdate);
    let role = await RoleModel.incRoleInfo(roleId, { ...roleIncUpdate, ce: roleInc }, { ...roleUpdate, topLineup, topLineupCe });
    let guild = await GuildModel.updateCe(roleId, roleInc); // 公会更新战力

    saveCeChangeLog(role, roleInc, role.ce, type, ceChangeTxt);
    updateRank(roleId, serverId, topLineupCe, role, pushHeros, guild);
    sendMessageToUserWithSuc(roleId, PUSH_ROUTE.PLAYER_CE_UPDATE, { ce: role.ce, heros: pushHeros, topLineupCe }, sid);
    if(hasTopCeChange) await updateRoleOnlineInfo(roleId, { topLineupCe });
    if(guild) {
        await updateUserInfo(REDIS_KEY.GUILD_INFO, guild.code, [{ field: 'guildCe', value: guild.guildCe }]);
    }
    return { heroes, curRole: role }
}

async function treatHeroStar(calCe: CalCe, roleId: string, hid: number, star: number, starStage: number, quality: number, colorStar: number, colorStarStage: number, job: number, isUpStar: boolean) {
    calCe.setHeroStar(hid, job, quality, star, starStage, colorStar, colorStarStage);
    if(isUpStar) {
        let school = await SchoolModel.findByHid(roleId, hid);
        if(school) calCe.setSchool(true, hid, school.schoolId, star, colorStar, quality);
    }
}

// 更新排行榜数据
async function updateRank(roleId: string, serverId: number, topLineupCe: number, role: RoleType, pushHeros: {hid: number, ce: number}[], guild?: GuildType) {
    
    // 最强阵容
    let r = new Rank(REDIS_KEY.TOP_LINEUP_RANK, { serverId });
    await r.setRankWithRoleInfo(roleId, topLineupCe, 0, role);

    // 最强武将
    for(let { hid, ce } of pushHeros) {
        let r2 = new Rank(REDIS_KEY.TOP_HERO_RANK, { serverId });
        await r2.setRankWithHeroInfo(roleId, hid, ce, 0);

        let r4 = new Rank(REDIS_KEY.HERO_RANK, { serverId, hid });
        await r4.setRankWithHeroInfo(roleId, hid, ce, 0);
    }

    // 总战力
    let r3 = new Rank(REDIS_KEY.SUM_CE_RANK, { serverId });
    await r3.setRankWithRoleInfo(roleId, role.ce, 0, role);

    // 更新最强五人阵容信息
    let r5 = new Rank(REDIS_KEY.TOP_LINEUP_INFO, { serverId });
    await r5.generParamAndSet(REDIS_KEY.TOP_LINEUP_INFO, { roleId }, { role });

    if(guild) {
        await updateUserInfo(REDIS_KEY.GUILD_INFO, guild.code, [{ field: 'guildCe', value: guild.guildCe }]);
    }
    
    // 武将数量
    let r6 = new Rank(REDIS_KEY.HERO_NUM_RANK, { serverId });
    await r6.setRankWithRoleInfo(roleId, role.heroNum, role.heroNumUpdatedAt, role);

    await saveLadderDefCeByData(roleId);
}

export async function getSumCe(roleId: string) {
    let roleCe = await RoleCeModel.findByRoleId(roleId);
    if(roleCe && roleCe.historyLineupCe) return roleCe.historyLineupCe;

    let role = await RoleModel.findByRoleId(roleId);
    return role.topLineupCe||0; 
}

export async function getHeroesAttributes(roleId: string) {
    let roleCe = await RoleCeModel.findByRoleId(roleId);
    let attrByHid = new Map<number, AttributeCal>();
    let heroAttrs = roleCe?.heroAttrs??[];
    for(let { hid, attrs } of roleCe?.attributes??[]) {
        let cal = new AttributeCal();
        let heroAttr = heroAttrs.find(cur => cur.hid == hid);
        if(heroAttr) cal.setLv(heroAttr.lv);
        cal.setByCeArr(attrs);
        attrByHid.set(hid, cal);
    }
    return attrByHid;
}