import { STATUS } from '../../../consts/statusCode';
import { RoleModel, RoleUpdate } from './../../../db/Role';
import { HeroModel, HeroType, HeroUpdate } from '../../../db/Hero';
import { resResult, decodeIdCntArrayStr, parseGoodStr, genCode } from '../../../pubUtils/util';
import { Application, BackendSession, pinus, HandlerService, } from 'pinus';
import { handleCost, addItems, getGoldObject, getCoinObject } from '../../../services/role/rewardService';
import { getTitle, getTeraph, gameData, getScollByStar, getFriendLvByExp, getHeroExpByLv, getExpByLv } from '../../../pubUtils/data';
import { SCHOOL, SCROLL, EXTERIOR, SCRIPT } from '../../../pubUtils/dicParam';
import { getAtrrNameById } from '../../../consts/constModules/abilityConst'
import { findIndex, pick } from 'underscore';
import { SclResultInter, SclPosInter } from '../../../pubUtils/interface';
import { SchoolModel } from '../../../db/School';
import { getTeraphStrengthenResult, getSchoolList } from '../../../services/roleService'
import { HERO_SYSTEM_TYPE, LINEUP_NUM, ROLE_SELECT, REDIS_KEY, TASK_TYPE, DEFAULT_HEROES, DEFAULT_HERO_LV, DEFAULT_ITEMS, DEFAULT_EQUIPS, DEFAULT_GOLD, DEFAULT_COIN, DEBUG_MAGIC_WORD, COUNTER, DEFAULT_LV, ITEM_CHANGE_REASON, PUSH_ROUTE, POP_UP_SHOP_CONDITION_TYPE, LEAGUE_AUTH } from '../../../consts';
import { checkBattleHeroesByHid, roleLevelup } from '../../../services/normalBattleService';
import { Rank } from '../../../services/rankService';
import { updateUserInfo } from '../../../services/redisService';
import { checkTask, checkTaskInActiveScroll } from '../../../services/task/taskService';
import { RScriptRecordModel } from '../../../db/RScriptRecord';
import * as dicParam from '../../../pubUtils/dicParam';
import Counter from '../../../db/Counter';
import { UserModel } from '../../../db/User';
import { checkFilterWords, reportTAEvent, treatRoleName } from '../../../services/sdkService';
import { createHeroes } from '../../../services/role/createHero';
import { calculateCeWithHero, calculateCeWithRole } from '../../../services/playerCeService';
import { sendMessageToUserWithSuc } from '../../../services/pushService';
import { GuildLeader, LeagueLeader } from '../../../domain/rank';
import { checkPopUpCondition } from '../../../services/activity/popUpShopService';
import { isGoodsHidden, isHeroHidden } from '../../../services/dataService';
import { updateGVGBattleRoleInfo, getMyAuth } from '../../../services/gvg/gvgTeamService';
import { GVGLeagueModel } from '../../../db/GVGLeague';

export default function (app: Application) {
    new HandlerService(app, {});
    return new RoleHandler(app);
}

export class RoleHandler {
    constructor(private app: Application) {
    }

    async initRole(msg: { roleName: string }, session: BackendSession) {
        // console.log('******** initRole start', Date.now());
        let roleId = session.get('roleId');
        let serverId = session.get('serverId');
        let sid: string = session.get('sid');
        

        let { roleName } = msg;
        let role = await RoleModel.findByRoleId(roleId, 'roleName hasInit title teraphs lv', true);
        if (role.hasInit) return resResult(STATUS.ROLE_HAS_INIT);

        let checkName = await RoleModel.checkName(roleName, serverId);
        if (checkName) return resResult(STATUS.NAME_HAS_USED);

        let { resultHeroes: heroes } = await createHeroes(roleId, roleName, sid, serverId, DEFAULT_HEROES.map(hid => ({hid, count: 1})), { roleName, hasInit: true, title: role.title, teraphs: role.teraphs, lv: role.lv });
        // role = await RoleModel.updateRoleInfo(roleId, { roleName, hasInit: true }); // 在算战力的时候一起更新
        session.set('roleName', roleName);
        session.push('roleName', () => { });

        let items = [].concat(DEFAULT_ITEMS, DEFAULT_EQUIPS, [getGoldObject(DEFAULT_GOLD)], [getCoinObject(DEFAULT_COIN)]);
        await addItems(roleId, roleName, sid, items, ITEM_CHANGE_REASON.DEFAULT_ITEMS);

        let battleId = SCRIPT.SCRIPT_BATTLE_ID;
        let warInfo = gameData.war.get(battleId);
        await RScriptRecordModel.setScript(roleId, battleId, warInfo.warType, 2, SCRIPT.SCRIPT_NAME);

        // console.log('******** initRole end', Date.now());
        return resResult(STATUS.SUCCESS, {
            roleId, roleName, heroes
        })
    }

    async getRoleInfo(msg: { targetRoleId: string }, session: BackendSession) {
        let { targetRoleId } = msg;
        let { roleId, roleName, head = EXTERIOR.EXTERIOR_FACE, frame = EXTERIOR.EXTERIOR_FACECASE, spine = EXTERIOR.EXTERIOR_APPEARANCE, ce = 0, topLineup, topLineupCe = 0 } = await RoleModel.findByRoleId(targetRoleId);
        return resResult(STATUS.SUCCESS, { roleId, roleName, head, frame, spine, ce, topLineup, topLineupCe });
    }

    //爵位
    async roleTitleLevelUp(msg: {}, session: BackendSession) {
        let roleId = session.get('roleId');
        let sid: string = session.get('sid');
        const serverId = session.get('serverId');
        

        let role = await RoleModel.findByRoleId(roleId);

        let { title } = role;
        let titleInfo = getTitle(title + 1);
        if (!titleInfo)
            return resResult(STATUS.DIC_DATA_NOT_FOUND)
        if (titleInfo.lvLimited > role.lv)
            return resResult(STATUS.COM_BATTLE_LV_NOT_ENOUGH)
        let consumes = titleInfo.material;
        let result = await handleCost(roleId, sid, consumes, ITEM_CHANGE_REASON.TITLE_LEVEL_UP);
        if (!result)
            return resResult(STATUS.BATTLE_CONSUMES_NOT_ENOUGH);

        let update = { title: title + 1 }
        let { curRole } = await calculateCeWithRole(HERO_SYSTEM_TYPE.TITLE, roleId, serverId, sid, update);

        // 任务
        await checkTask(serverId, roleId, sid, TASK_TYPE.ROLE_TITLE, { oldTitle: title, title: update.title });        // 弹出礼包
        await checkPopUpCondition(serverId, roleId, POP_UP_SHOP_CONDITION_TYPE.TITLE, { oldLv: title, newLv: update.title });
        return resResult(STATUS.SUCCESS, { roleId, title: curRole.title });
    }

    //神像强化
    async roleTeraphStrengthen(msg: { id: number, count: number }, session: BackendSession) {
        let { id, count } = msg;
        let roleId = session.get('roleId');
        let sid: string = session.get('sid');
        let serverId: number = session.get('serverId');
        

        let role = await RoleModel.findByRoleId(roleId, 'roleId teraphs gold coin');
        let teraphs = role.teraphs;
        let index = findIndex(teraphs, { id });
        if (index < 0)
            return resResult(STATUS.WRONG_PARMS);
        let teraph = teraphs[index];
        let dicTeraph = getTeraph(id, teraph.grade);
        if (!dicTeraph)
            return resResult(STATUS.DIC_DATA_NOT_FOUND);

        let { times, consumes, criAttr } = await getTeraphStrengthenResult(role, count, dicTeraph, teraph);
        if (times == 0)
            return resResult(STATUS.ROLE_TERAPH_NOT_STRENGTHEN);

        let result = await handleCost(roleId, sid, consumes, ITEM_CHANGE_REASON.TERAPH_STRENGTHEN);
        if (!result)
            return resResult(STATUS.BATTLE_CONSUMES_NOT_ENOUGH);

        let { curRole } = await calculateCeWithRole(HERO_SYSTEM_TYPE.TERAPH, roleId, serverId, sid, { teraphs }, { teraphId: id });

        // 任务
        await checkTask(serverId, roleId, sid, TASK_TYPE.ROLE_TERAPH_STRENGTHEN, { count });

        return resResult(STATUS.SUCCESS, { roleId, teraphs: curRole.teraphs, criAttr });
    }

    //神像进阶
    async roleTeraphQualityUp(msg: { id: number }, session: BackendSession) {
        let { id } = msg;
        let roleId = session.get('roleId');
        let sid: string = session.get('sid');
        const serverId = session.get('serverId');
        

        let role = await RoleModel.findByRoleId(roleId);
        let teraphs = role.teraphs;
        let index = findIndex(teraphs, { id });
        if (index < 0)
            return resResult(STATUS.WRONG_PARMS);
        let teraph = teraphs[index];
        let teraphInfo = getTeraph(id, teraph.grade);
        if (!teraphInfo)
            return resResult(STATUS.DIC_DATA_NOT_FOUND)

        for (let [attrId, val] of teraph.attr) {
            if (val < teraphInfo.mainAttrMax.get(attrId))
                return resResult(STATUS.ROLE_TERAPH_NOT_QUILITY);

            teraph.attr.set(attrId, 0);
        }
        teraph.grade++;


        let nextTeraphInfo = getTeraph(id, teraph.grade)
        if (!nextTeraphInfo)
            return resResult(STATUS.DIC_DATA_NOT_FOUND);

        let consumes = teraphInfo.upGradeMaterial;
        let result = await handleCost(roleId, sid, consumes, ITEM_CHANGE_REASON.TERAPH_QUALITY_UP);
        if (!result)
            return resResult(STATUS.BATTLE_CONSUMES_NOT_ENOUGH);
        let { curRole } = await calculateCeWithRole(HERO_SYSTEM_TYPE.TERAPH_UP, roleId, serverId, sid, { teraphs }, { teraphId: id });

        // 神像进阶，进阶一次就触发一次礼包弹框
        await checkTask(serverId, roleId, sid, TASK_TYPE.ROLE_TERAPH_STAGE_UP);

        return resResult(STATUS.SUCCESS, { roleId, teraphs: curRole.teraphs });
    }

    // 获得百家学宫
    async getSchoolList(msg: {}, session: BackendSession) {
        let roleId = session.get('roleId');
        let school = await getSchoolList(roleId);

        return resResult(STATUS.SUCCESS, { school });

    }

    // 摆放/替换/卸下武将
    async changeSchoolHero(msg: { schoolId: number, positionId: number, hid: number }, session: BackendSession) {
        let roleId = session.get('roleId');
        let sid = session.get('sid');
        
        const serverId = session.get('serverId');

        let { schoolId, positionId, hid } = msg;

        if(isHeroHidden(hid)) return resResult(STATUS.HERO_IS_HIDDEN);

        if (!gameData.school.has(schoolId)) {
            return resResult(STATUS.DIC_DATA_NOT_FOUND);
        }
        const dicPosition = decodeIdCntArrayStr(SCHOOL.SCHOOL_POSITION, 1); // id(str) => isOpen
        if (!dicPosition.has(positionId.toString())) {
            return resResult(STATUS.DIC_DATA_NOT_FOUND);
        }
        let isOpen = !!dicPosition.get(positionId.toString()); // 该位置是否解锁
        let curHero: HeroType = null;
        if (hid > 0) {
            let findHero = await SchoolModel.findByHid(roleId, hid);
            if (!!findHero) {
                return resResult(STATUS.ROLE_SCHOOL_HERO_USED);
            }

            curHero = await HeroModel.findByHidAndRole(hid, roleId);
            if (!curHero) return resResult(STATUS.HERO_NOT_FIND);
        }

        let curSchool = await SchoolModel.findBySclAndPos(roleId, schoolId, positionId);
        let preHid = 0; // 原先在该位置上的武将
        if (curSchool) {
            isOpen = curSchool.isOpen;
            preHid = curSchool.hid;
        }


        if (!isOpen) {
            return resResult(STATUS.ROLE_SCHOOL_POSITION_LOCKED);
        }

        await SchoolModel.updateBySclAndPos(roleId, schoolId, positionId, { hid, isOpen, star: curHero?.star??0, quality: curHero?.quality??0, colorStar: curHero?.colorStar??0 });
        await calculateCeWithRole(HERO_SYSTEM_TYPE.SCHOOL, roleId, serverId, sid, {}, { schoolId, hero: curHero, schoolHid: hid, preSchoolHid: preHid });

        // 任务
        await checkTask(serverId, roleId, sid, TASK_TYPE.ROLE_SCHOOL_PUT_HERO, { hid, preHid });

        return resResult(STATUS.SUCCESS, {
            schoolId, positionId, hid, preHid, isOpen
        });

    }

    // 解锁位置
    async unlockSchoolPosition(msg: { schoolId: number, positionId: number }, session: BackendSession) {
        let roleId = session.get('roleId');
        let sid = session.get('sid');
        let serverId = session.get('serverId');

        let { schoolId, positionId } = msg;
        if (!gameData.school.has(schoolId)) {
            return resResult(STATUS.DIC_DATA_NOT_FOUND);
        }
        const dicPosition = decodeIdCntArrayStr(SCHOOL.SCHOOL_POSITION, 1); // id(str) => isOpen
        if (!dicPosition.has(positionId.toString())) {
            return resResult(STATUS.DIC_DATA_NOT_FOUND);
        }
        let isOpen = !!dicPosition.get(positionId.toString()); // 该位置是否解锁
        if (isOpen) {
            return resResult(STATUS.ROLE_SCHOOL_POSITION_UNLOCK_NOT_NEED);
        }
        let curSchool = await SchoolModel.findBySclAndPos(roleId, schoolId, positionId);
        if (curSchool && curSchool.isOpen) {
            return resResult(STATUS.ROLE_SCHOOL_POSITION_UNLOCK_NOT_NEED);
        }

        const cost = parseGoodStr(SCHOOL.SCHOOL_UNLOCK_COIN);
        const costResult = await handleCost(roleId, sid, cost, ITEM_CHANGE_REASON.UNLOCK_SCHOOL_POSITION);
        if (!costResult) return resResult(STATUS.ROLE_MATERIAL_NOT_ENOUGH);

        curSchool = await SchoolModel.updateBySclAndPos(roleId, schoolId, positionId, { isOpen: true })

        // 任务
        await checkTask(serverId, roleId, sid, TASK_TYPE.ROLE_SCHOOL_UNLOCK);

        return resResult(STATUS.SUCCESS, {
            schoolId, positionId, hid: curSchool.hid, isOpen: curSchool.isOpen
        });
    }

    // 激活/升级名将谱
    async activeHeroScroll(msg: { hid: number }, session: BackendSession) {
        let roleId = session.get('roleId');
        let sid = session.get('sid');
        
        let serverId: number = session.get('serverId');

        let { hid } = msg;

        if(isHeroHidden(hid)) return resResult(STATUS.HERO_IS_HIDDEN);

        let dicHero = gameData.hero.get(hid);
        if (!dicHero) return resResult(STATUS.DIC_DATA_NOT_FOUND);

        let hero = await HeroModel.findByHidAndRole(hid, roleId, 'hid lv star colorStar quality scrollId scrollActive scrollStar scrollColorStar scrollQuality connections attr ce');
        if (!hero) return resResult(STATUS.HERO_NOT_FIND);

        let { star, colorStar, quality, scrollId, scrollActive, scrollStar, scrollColorStar, scrollQuality } = hero;

        let update = {
            scrollActive, scrollId, scrollStar, scrollColorStar, scrollQuality
        };
        if (!scrollActive) { // 初次激活
            update.scrollActive = true;
            update.scrollStar = dicHero.initialStar;
            update.scrollQuality = dicHero.quality;
            update.scrollColorStar = dicHero.initialColorStar;
        } else {
            if (star > scrollStar) { // 可以升星
                update.scrollStar++;
            } else if (quality > scrollQuality && (quality != 4 || scrollQuality != 3)) { // 可以升品
                update.scrollQuality++;
            } else if (colorStar > scrollColorStar) { // 可以升彩星
                update.scrollColorStar++;
                update.scrollQuality = 4;
            } else {
                return resResult(STATUS.ROLE_SCROLL_REACH_MAX);
            }

        }

        let dicHeroScroll = getScollByStar(dicHero.quality, update.scrollStar, update.scrollQuality, update.scrollColorStar);
        update.scrollId = dicHeroScroll ? dicHeroScroll.id : 0;

        let { curHero } = await calculateCeWithHero(HERO_SYSTEM_TYPE.SCROLL, roleId, serverId, sid, hid, update);

        // 任务
        await checkTaskInActiveScroll(serverId, roleId, sid, scrollActive, hero);

        return resResult(STATUS.SUCCESS, {
            curHero: pick(curHero, ['hid', 'scrollActive', 'scrollId', 'scrollStar', 'scrollColorStar', 'scrollQuality'])
        });
    }

    // 保存展示阵容
    async saveShowLineup(msg: { showLineup: number[] }, session: BackendSession) {
        let { showLineup } = msg;
        let roleId = session.get('roleId');
        let serverId = session.get('serverId');

        if(isHeroHidden(...showLineup)) return resResult(STATUS.HERO_IS_HIDDEN);

        let checkHeroes = await checkBattleHeroesByHid(roleId, showLineup);
        if (showLineup.length > 0 && !checkHeroes) return resResult(STATUS.BATTLE_HERO_NOT_FOUND);

        if (showLineup.length > LINEUP_NUM) {
            return resResult(STATUS.LINEUP_MAX);
        }

        let role = await RoleModel.updateRoleInfo(roleId, { showLineup });
        let r = new Rank(REDIS_KEY.SHOW_LINEUP, {});
        await r.generParamAndSet(REDIS_KEY.SHOW_LINEUP, { roleId }, { role });

        return resResult(STATUS.SUCCESS, { showLineup: role.showLineup });
    }

    // 更换头像
    async setHead(msg: { id: number }, session: BackendSession) {
        let { id } = msg;
        let roleId = session.get('roleId');
        let guildCode = session.get('guildCode');

        if(isGoodsHidden(id)) return resResult(STATUS.ITEM_IS_HIDDEN);

        let role = await RoleModel.findByRoleId(roleId, ROLE_SELECT.GET_HEADS);
        if (!role) return resResult(STATUS.ROLE_NOT_FOUND);

        let { heads } = role;
        let curHead = heads.find(cur => cur.id == id);
        if (!curHead) return resResult(STATUS.HEAD_NOT_FOUND);
        if (curHead.enable) return resResult(STATUS.HEAD_IS_WEARING);
        if (!curHead.status) return resResult(STATUS.HEAD_IS_LOCKED);

        let oldHead = heads.find(cur => cur.enable); // 穿戴中的头像
        if (oldHead) {
            oldHead.enable = false;
        }
        curHead.enable = true;

        role = await RoleModel.updateRoleInfo(roleId, { heads });
        await updateUserInfo(REDIS_KEY.USER_INFO, roleId, [{ field: 'head', value: id }]);
        if(role.isGuildLeader) {
            await updateUserInfo(REDIS_KEY.GUILD_INFO, guildCode, [{ field: 'leader', value: new GuildLeader(role) }]);
        }

        return resResult(STATUS.SUCCESS, { heads: role.heads, head: role.head });
    }

    // 更换相框
    async setFrame(msg: { id: number }, session: BackendSession) {
        let { id } = msg;
        let roleId = session.get('roleId');
        let guildCode = session.get('guildCode');

        if(isGoodsHidden(id)) return resResult(STATUS.ITEM_IS_HIDDEN);

        let role = await RoleModel.findByRoleId(roleId, ROLE_SELECT.GET_HEADS);
        if (!role) return resResult(STATUS.ROLE_NOT_FOUND);

        let { frames } = role;
        let curFrame = frames.find(cur => cur.id == id);
        if (!curFrame) return resResult(STATUS.FRAME_NOT_FOUND);
        if (curFrame.enable) return resResult(STATUS.FRAME_IS_WEARING);
        if (!curFrame.status) return resResult(STATUS.FRAME_IS_LOCKED);

        let oldHead = frames.find(cur => cur.enable); // 穿戴中的头像
        if (oldHead) {
            oldHead.enable = false;
        }
        curFrame.enable = true;

        role = await RoleModel.updateRoleInfo(roleId, { frames });
        await updateUserInfo(REDIS_KEY.USER_INFO, roleId, [{ field: 'frame', value: id }]);
        if(role.isGuildLeader) {
            await updateUserInfo(REDIS_KEY.GUILD_INFO, guildCode, [{ field: 'leader', value: new GuildLeader(role) }]);
        }

        return resResult(STATUS.SUCCESS, { frames: role.frames, frame: role.frame });
    }

    // 更换形象
    async setSpine(msg: { id: number }, session: BackendSession) {
        let { id } = msg;
        let roleId = session.get('roleId');
        let guildCode = session.get('guildCode');

        if(isGoodsHidden(id)) return resResult(STATUS.ITEM_IS_HIDDEN);

        let role = await RoleModel.findByRoleId(roleId, ROLE_SELECT.GET_HEADS);
        if (!role) return resResult(STATUS.ROLE_NOT_FOUND);

        let { spines } = role;
        let curSpine = spines.find(cur => cur.id == id);
        if (!curSpine) return resResult(STATUS.SPINE_NOT_FOUND);
        if (curSpine.enable) return resResult(STATUS.SPINE_IS_WEARING);
        if (!curSpine.status) return resResult(STATUS.SPINE_IS_LOCKED);

        let oldHead = spines.find(cur => cur.enable); // 穿戴中的头像
        if (oldHead) {
            oldHead.enable = false;
        }
        curSpine.enable = true;

        role = await RoleModel.updateRoleInfo(roleId, { spines });
        await updateUserInfo(REDIS_KEY.USER_INFO, roleId, [{ field: 'spine', value: id }]);
        if(role.isGuildLeader) {
            await updateUserInfo(REDIS_KEY.GUILD_INFO, guildCode, [{ field: 'leader', value: new GuildLeader(role) }]);
        }

        return resResult(STATUS.SUCCESS, { spines: role.spines, spine: role.spine });
    }

    // 改名
    async rename(msg: { roleName: string }, session: BackendSession) {
        let { roleName } = msg;
        let roleId = session.get('roleId');
        let serverId = session.get('serverId');
        let guildCode = session.get('guildCode');
        let sid = session.get('sid');
        if(!roleName) return resResult(STATUS.WRONG_PARMS);

        let checkName = await RoleModel.checkName(roleName, serverId);
        if (checkName) return resResult(STATUS.NAME_HAS_USED);

        let role = await RoleModel.findByRoleId(roleId, 'renameCnt');
        let costGold = role.renameCnt >= dicParam.NAMEPLATE.NAMEPLATE_FREECOST? dicParam.NAMEPLATE.NAMEPLATE_FEECOST: 0;
        if(costGold > 0) {
            let result = await handleCost(roleId, sid, [getGoldObject(costGold)], ITEM_CHANGE_REASON.RENAME);
            if(!result) return resResult(STATUS.BATTLE_GOLD_NOT_ENOUGH);
        }

        role = await RoleModel.incRoleInfo(roleId, { renameCnt: 1 }, { roleName });
        session.set('roleName', role.roleName);
        session.push('roleName', () => { });
        await updateUserInfo(REDIS_KEY.USER_INFO, roleId, [{ field: 'roleName', value: roleName }]);
        if(role.isGuildLeader) {
            await updateUserInfo(REDIS_KEY.GUILD_INFO, guildCode, [{ field: 'leader', value: new GuildLeader(role) }]);
            let myLeague = await GVGLeagueModel.findLeagueByGuild(guildCode);
            if(myLeague && getMyAuth(myLeague, roleId) == LEAGUE_AUTH.LEADER) {
                await updateUserInfo(REDIS_KEY.LEAGUE_INFO, myLeague.leagueCode, [{ field: 'leader', value: new LeagueLeader(role) }]);
            }
    
        }
        await updateGVGBattleRoleInfo(serverId, roleId, { roleName });

        return resResult(STATUS.SUCCESS, { roleName: role.roleName, renameCnt: role.renameCnt });
    }

    async saveGuide(msg: { ids: number[] }, session: BackendSession) {
        let roleId = session.get('roleId');
        let { ids } = msg;
        if(ids == undefined || ids.length <= 0) {
            return resResult(STATUS.WRONG_PARMS);
        }
        let role = await RoleModel.saveGuide(roleId, ids);
        return resResult(STATUS.SUCCESS, {
            guide: role.guide
        });
    }

    // 防沉迷调试用，推送窗口
    async debugPlayerTime(msg: { type: number }, session: BackendSession) {
        let { type } = msg;
        let roleId = session.get('roleId');
        let sid = session.get('sid');

        if (type == 1) {
            sendMessageToUserWithSuc(roleId, PUSH_ROUTE.PLAY_TIME, {
                isGuest: true,
                guestTime: 60 * 60,         // 游客已体验时间
                hasAuthenticated: false,     // 是否进行过实名认证
                isAdult: false,                                // 是否已成年
                todayPlayTime: 60 * 60,            // 今天已游戏时长
                type: 1
            }, sid);
        } else if (type == 2) {
            sendMessageToUserWithSuc(roleId, PUSH_ROUTE.PLAY_TIME, {
                isGuest: false,
                guestTime: 0,         // 游客已体验时间
                hasAuthenticated: true,     // 是否进行过实名认证
                isAdult: false,                                // 是否已成年
                todayPlayTime: 60 * 60,            // 今天已游戏时长
                type: 2
            }, sid);
        } else if (type == 3) {
            sendMessageToUserWithSuc(roleId, PUSH_ROUTE.PLAY_TIME, {
                isGuest: false,
                guestTime: 0,         // 游客已体验时间
                hasAuthenticated: true,     // 是否进行过实名认证
                isAdult: false,                                // 是否已成年
                todayPlayTime: 3 * 60 * 60,            // 今天已游戏时长
                type: 3
            }, sid);
        } else if (type == 4) {
            sendMessageToUserWithSuc(roleId, PUSH_ROUTE.PLAY_TIME, {
                isGuest: false,
                guestTime: 0,         // 游客已体验时间
                hasAuthenticated: true,     // 是否进行过实名认证
                isAdult: false,                                // 是否已成年
                todayPlayTime: 1.5 * 60 * 60,            // 今天已游戏时长
                type: 4
            }, sid);
        }

        return resResult(STATUS.SUCCESS);
    }

    // debug接口，清空某个角色
    async debugClearRole(msg: { magicWord: string }, session: BackendSession) {
        const { magicWord } = msg;
        if (magicWord !== DEBUG_MAGIC_WORD) {
            return resResult(STATUS.TOKEN_ERR);
        }

        let roleId = session.get('roleId');
        let role = await RoleModel.findByRoleId(roleId);
        if(!role) return resResult(STATUS.ROLE_NOT_FOUND);
        if(role.hasInit) {
            let userInfo = role.userInfo;
            let newRoleId = genCode(10);
            const seqId = await Counter.getNewCounter(COUNTER.ROLE) || -1;
            await RoleModel.findOneAndUpdate({ roleId }, { $set: { 'userInfo.uid': 0, roleName: 'deletedRole' } });
            role = await RoleModel.createRole(userInfo.uid, role.serverId, { roleId: newRoleId, code: role.code, roleName: newRoleId, seqId, lv: DEFAULT_LV, exp: (getExpByLv(DEFAULT_LV - 1) || { sum: 0 }).sum || 0 }, '');
        
            session.set('roleId', newRoleId);
            session.push('roleId', () => {});
        }
        
        return resResult(STATUS.SUCCESS, { roleId: role?.roleId });
    }

    async debugRoleLvUp(msg: { magicWord: string, lv: number }, session: BackendSession) {
        const { magicWord, lv } = msg;
        if (magicWord !== DEBUG_MAGIC_WORD) {
            return resResult(STATUS.TOKEN_ERR);
        }

        let roleId = session.get('roleId');
        let roleLvInfo = gameData.kingexp.get(lv - 1);
        let role = await RoleModel.updateRoleInfo(roleId, { lv, exp: roleLvInfo.sum });

        return resResult(STATUS.SUCCESS, { lv: role.lv });
    }

    public async debugSetRole(msg: { magicWord: string, params: RoleUpdate }, session: BackendSession) {
        let roleId: string = session.get('roleId');

        let { magicWord, params } = msg;
        if (magicWord !== DEBUG_MAGIC_WORD) {
            return resResult(STATUS.TOKEN_ERR);
        }
        let role = await RoleModel.updateRoleInfo(roleId, params);
        
        return resResult(STATUS.SUCCESS, { role });

    }

    public async test(msg: { magicWord: string }, session: BackendSession) {
        let roleId: string = session.get('roleId');
        let serverId: string = session.get('serverId');

        let { magicWord } = msg;
        if (magicWord !== DEBUG_MAGIC_WORD) {
            return resResult(STATUS.TOKEN_ERR);
        }
        let role = await RoleModel.findByRoleId(roleId);
        let user = await UserModel.findUserByUid(role.userInfo.uid);

        reportTAEvent(roleId, 'test', { serverId }, user.ip);

        return resResult(STATUS.SUCCESS);

    }

    async debugTreatRoleName(msg: { magicWord: string }, session: BackendSession) {
        let roleId: string = session.get('roleId');

        let { magicWord } = msg;
        if (magicWord !== DEBUG_MAGIC_WORD) {
            return resResult(STATUS.TOKEN_ERR);
        }

        await treatRoleName(roleId, true);
        return resResult(STATUS.SUCCESS);
    }
}
