/*
文件名:GameManagerClass.nut
路径:BaseClass/GameManagerClass/GameManagerClass.nut
创建日期:2024-04-09	20:30
文件用途:游戏管理器类
*/
class GameManager extends Base_C_Object {

    constructor() {
        local CObject = Sq_GameManager_GameManager();
        base.constructor(CObject);
    }

    function GetParty() {
        local C_Party = Sq_GameManager_GetParty(C_Object);
        return Party(C_Party);
    }

    //设置游戏最大等级
    function SetGameMaxLevel(MaxLevel) {
        NativePointer("0x8360C38").add(3).writeU8(MaxLevel);
        NativePointer("0x8360C76").add(3).writeU8(MaxLevel);
        NativePointer("0x8360CC1").add(3).writeU8(MaxLevel);
        NativePointer("0x84EF802").add(3).writeU8(MaxLevel);
        NativePointer("0x858F002").add(3).writeU8(MaxLevel);
        NativePointer("0x865A5C0").add(1).writeU8(MaxLevel);
        NativePointer("0x865B091").add(4).writeU8(MaxLevel);
        NativePointer("0x865B757").add(4).writeU8(MaxLevel);
        NativePointer("0x8662F53").add(2).writeU8(MaxLevel);
        NativePointer("0x86630F0").add(3).writeU8(MaxLevel);
        NativePointer("0x86638F4").add(2).writeU8(MaxLevel);
        NativePointer("0x8665D24").add(4).writeU8(MaxLevel);
        NativePointer("0x8666E9A").add(2).writeU8(MaxLevel);
        NativePointer("0x866A4A6").add(2).writeU8(MaxLevel);
        NativePointer("0x866A657").add(2).writeU8(MaxLevel);
        NativePointer("0x866A926").add(3).writeU8(MaxLevel);
        NativePointer("0x866A93F").add(2).writeU8(MaxLevel);
        NativePointer("0x867AEC0").add(2).writeU8(MaxLevel);
        NativePointer("0x8689D48").add(3).writeU8(MaxLevel);
        NativePointer("0x868fecb").add(3).writeU8(MaxLevel);
        NativePointer("0x868fed4").add(6).writeU8(MaxLevel);
    }

    //设置装备解锁需要时间
    function SetItemLockTime(UnLockTime) {
        NativePointer("0x854242F").writeInt(UnLockTime);
        NativePointer("0x8402D29").writeInt(UnLockTime);
        NativePointer("0x854274D").writeInt(UnLockTime);
        NativePointer("0x854296F").writeInt(UnLockTime);
        NativePointer("0x8542AD9").writeInt(UnLockTime);
        NativePointer("0x8542BDE").writeInt(UnLockTime);
        NativePointer("0x85F3EB9").writeInt(UnLockTime);
        Cb_CItemLock_DoItemUnlock_Leave_Func["DPS装备解锁定时器注册任务"] <- function(args) {
            if (UnLockTime > 0) {
                local SUser = User(args[1]);
                Timer.SetTimeOut(function(SUser) {
                    Sq_CallFunc(S_Ptr("0x08646912"), "int", ["pointer"], SUser.C_Object);
                }, UnLockTime * 1000, SUser)
            } else {
                Sq_CallFunc(S_Ptr("0x08646912"), "int", ["pointer"], SUser.C_Object);
            }
        }
    }

    //开启创建鼠标妹
    function OpenCreateJob_CreatorMage() {
        Sq_WriteByteArr(S_Ptr("0x81C029F"), [0xf]);
    }

    //开启获得魔法封印时自动解除魔法封印
    function OpenRandomAutomaticUnblocking() {
        Cb_User_Insert_Item_Leave_Func.Rindro <- function(args) {
            local SUser = User(NativePointer(args[0]).readPointer());
            local InvenObj = SUser.GetInven();
            local idx = args.pop();
            if (idx > 0) {
                local inven_item = InvenObj.GetSlot(1, idx);
                local item_id = inven_item.GetIndex();
                local pvfitem = PvfItem.GetPvfItemById(item_id);
                //如果是魔法封印装备
                if (!pvfitem || !pvfitem.IsRandomOption()) {
                    return;
                }
                local random_option = NativePointer(inven_item.C_Object).add(37);
                if (random_option.readU32() || random_option.add(4).readU32() || random_option.add(8).readShort()) {
                    return;
                }
                NativePointer(inven_item.C_Object).add(37).add(0).writeU8(1);
            }
            SUser.SendItemSpace(0);
            return null;
        }
    }

    //开启自动热重载
    function OpenHotFix(Path = "/dp_s/MyProject") {
        if (getroottable()._HotFixPath_.rawin(Path)) return;
        print("DP-S开启自动重载脚本功能,重载目录为: " + Path + " .");
        print("请注意如果你不处于DP-S开发环境，请关闭此功能，以免对性能造成影响");
        Sq_AutoReload(Path);
        getroottable()._HotFixPath_.rawset(Path, true);
    }

    //开启时装镶嵌
    function FixAvatarUseJewel() {
        //时装镶嵌修复
        _AvatarUseJewel_Object <- AvatarUseJewel();
    }

    //开启装备镶嵌
    function FixEquipUseJewel() {
        //装备镶嵌修复
        _EquimentUseJewel_Object <- EquimentUseJewel();
    }

    //修复14技能
    function Fix14Skill() {
        Sq_WriteByteArr(S_Ptr("0x08604B1E"), [0x83, 0x7D, 0xEC, 0x07]);
        Sq_WriteByteArr(S_Ptr("0x08604B8C"), [0xC7, 0x45, 0xE4, 0x08, 0x00, 0x00, 0x00]);
        Sq_WriteByteArr(S_Ptr("0x08604A09"), [0x83, 0x7D, 0x0C, 0x07]);
        Sq_WriteByteArr(S_Ptr("0x086050b1"), [0xC7, 0x45, 0xEC, 0x08, 0x00, 0x00, 0x00]);
        Sq_WriteByteArr(S_Ptr("0x0860511c"), [0xC7, 0x45, 0xE8, 0x08, 0x00, 0x00, 0x00]);
        Sq_WriteByteArr(S_Ptr("0x08608D7B"), [0x83, 0xF8, 0x0B]);
    }

    //修复下线卡城镇
    function FixSaveTown() {
        Cb_Set_Charac_Info_Detail_Enter_Func._FixSaveTown_ <- function(arg) {
            local curArea = NativePointer(arg[3]).add(34).readS8();
            if (curArea == 12 || curArea == 13) {
                NativePointer(arg[3]).add(34).writeS8(11);
            }
        }
    }

    //修复绝望金币异常
    function FixDespairGold() {
        getroottable()._FixDespairGold_Data_ <- {};
        Cb_UseAncientDungeonItems_Enter_Func._FixDespairGold_ <- function(arg) {
            local DgnObj = Dungeon(arg[1]);
            local DgnIndex = DgnObj.GetId();
            if ((DgnIndex >= 11008) && (DgnIndex <= 11107)) {
                getroottable()._FixDespairGold_Data_[arg[1]] <- NativePointer(arg[1]).add(2044).readS8();
                NativePointer(arg[1]).add(2044).writeS8(0);
            }
        }
        Cb_UseAncientDungeonItems_Leave_Func._FixDespairGold_ <- function(arg) {
            local DgnObj = Dungeon(arg[1]);
            local DgnIndex = DgnObj.GetId();
            if ((DgnIndex >= 11008) && (DgnIndex <= 11107)) {
                //绝望之塔 不再扣除金币
                NativePointer(arg[1]).add(2044).writeS8(getroottable()._FixDespairGold_Data_[arg[1]]);
                getroottable()._FixDespairGold_Data_.rawdelete(arg[1]);
            }
        }
    }

    //修复绝望之塔通关后可以用门票继续进入
    function FixDespairDungeon() {
        Cb_User_CheckDailyScheduleTime_Leave_Func.DailyScheduleTime <- function(args) {
            return true;
        };

        Cb_User_TOD_UserState_getLastClearTime_Leave_Func.DailyScheduleTime <- function(args) {
            return 0;
        };
    }

    //修改交易金币上限
    function FixGlodTradeDaily(Count) {
        local Arr = [0xB8];
        local BlobObj = blob(0);
        BlobObj.writen(Count, 'i');
        for (local i = 0; i< 4; i++) {
            Arr.append(BlobObj[i]);
        }
        Arr.append(0x90);
        Sq_WriteByteArr(S_Ptr("0x86464CE"), Arr);
    }

    //+13免刷新
    function Fix_13Upgrade() {
        Haker.LoadHook("0x080FC850", ["pointer", "pointer", "pointer", "int", "void"],
            function(args) {
                return null;
            },
            function(args) {
                local Pos = NativePointer(args[2]).add(27).readU16();
                local SUser = User(args[1]);
                SUser.SendUpdateItemList(1, 0, Pos);
                return null;
            });
    }

    //副本可丢弃品级 传入一个值 3为神器
    function FixDungeonDropGrade(Level) {
        NativePointer("0x085A69F2").writeS8(Level);
    }

    //邮件去除验证
    function FixEmailRemovalVerification() {
        local HexCode = Haker.AsmGenerateMcd(
            "mov eax, 0x0",
            "ret");
        Sq_WriteByteArr(S_Ptr("0x0868A51A"), HexCode);
    }

    //修复拍卖行消耗品上架,设置最大总价,建议值2E
    function Fix_Auction_Regist_Item() {
        Haker.LoadHook("0x08213E40", ["int", "int", "bool"],
            function(args) {
                return null;
            },
            function(args) {
                return true;
            });
    }

    //开启独立掉落模式  此功能需要传入一个回调函数  参数为 //角色 怪物ID 怪物等级 坐标X 坐标Y 副本名称 副本ID 副本等级 副本难度 深渊标识
    function OpenIndependenceDropMode(Func) {
        Haker.LoadHook("0x0830BC78", ["pointer", "pointer", "pointer", "pointer", "pointer", "int"],
            function(args) {
                return null;
            },
            function(args) {
                getroottable().LashKillMonsterId <- NativePointer(args[2]).add(3 * 4).readInt();
                return null;
            });

        Haker.LoadHook("0x085A27E8", ["pointer", "pointer", "short", "pointer", "pointer", "int"],
            function(args) {
                return null;
            },
            function(args) {
                //杀死怪物了 要判断是否掉落
                //获取队伍
                local PartyObj = Party(args[0]);
                //获取战斗对象
                local BattleFieldObj = PartyObj.GetBattleField();
                //怪物等级
                local MonsterLevel = NativePointer(args[4]).add(2605).readInt();
                //怪物ID
                local MonsterId = getroottable().LashKillMonsterId;
                //坐标
                local Xpos = NativePointer(args[4]).add(2596).readShort();
                local Ypos = NativePointer(args[4]).add(2598).readShort();
                local DgnObj = BattleFieldObj.GetDgn();
                //副本名称
                local DgnName = DgnObj.GetName();
                //副本ID
                local DgnId = DgnObj.GetId();
                //副本等级
                local DgnLevel = DgnObj.GetMinLevel();
                //副本难度
                local DgnDiff = Sq_CallFunc(S_Ptr("0x080F981C"), "int", ["pointer"], BattleFieldObj.C_Object);
                //深渊标识
                local HellDiff = BattleFieldObj.GetHellDifficulty();

                for (local i = 0; i< 4; i++) {
                    local SUser = PartyObj.GetUser(i);
                    if (SUser) {
                        //角色 怪物ID 怪物等级 坐标X 坐标Y 副本名称 副本ID 副本等级 副本难度 深渊标识
                        Func(SUser, MonsterId, MonsterLevel, Xpos, Ypos, DgnName, DgnId, DgnLevel, DgnDiff, HellDiff);
                    }
                }
                return null;
            });

        //修改独立掉落原逻辑为不掉落
        local HexCode = Haker.AsmGenerateMcd(
            "mov eax, 0x830CD5D",
            "jmp eax");
        Haker.InsertCode("0x830CCE2", HexCode);
    }



    //开启防入侵
    function FixInvasion() {
        NativePointer("0x81DB4EA").writeS8(0x00);

        getroottable()._TH_MEM_K_ <- Memory.allocUtf8String("/"); {
            local _Execve_Address = Module.getExportByName(null, "execve");
            local _Execve_Address_Str = "" + _Execve_Address;
            _Execve_Address_Str = _Execve_Address_Str.slice(_Execve_Address_Str.find("0x0x") + 2, -1);

            Haker.LoadHook(_Execve_Address_Str, ["pointer", "pointer", "pointer", "int"],
                function(args) {
                    args[0] = getroottable()._TH_MEM_K_.C_Object;
                    return args;
                },
                function(args) {
                    return -1;
                });
        } {
            local _System_Address = Module.getExportByName(null, "system");
            local _System_Address_Str = "" + _System_Address;
            _System_Address_Str = _System_Address_Str.slice(_System_Address_Str.find("0x0x") + 2, -1);

            Haker.LoadHook(_System_Address_Str, ["pointer", "int"],
                function(args) {
                    args[0] = getroottable()._TH_MEM_K_.C_Object;
                    return args;
                },
                function(args) {
                    return -1;
                });
        }
    }

    //修复练习模式
    function FixPracticemode() {
        Sq_WriteByteArr(S_Ptr("0x81C820A"), [0xE9, 0xC6, 0x0, 0x0, 0x0, 0x90]);
    }

    //修复黑暗武士技能
    function FixDarkWarriorSkillBar() 
    {
        Cb_CheckMoveComboSkillSlot_Leave_Func["DPSOFF"] <- function (args) 
        {
            return true;
        }
    }

    // //调用群助手发送消息
    // function GroupAssistantSendAMessage() {
    //     //私有方法 发送带参数的Post请求
    //     local SO = Http("129.211.27.104", "9080");
    //     local Res = SO.Post("/dof/chat", Json.Encode({
    //         username = "倾泪寒",
    //         text = "倾泪寒爆史诗了！",
    //         groupId = 416424738
    //     }), "application/json");
    // }
}
//热重载
getroottable()._HotFixPath_ <- {};
getroottable()._HotFixPathChangeTimer_ <- {};

function _Reload_List_Write_(Path) {
    local NowTime = Sq_GetTimestampString().slice(-9).tointeger();
    if (!getroottable()._HotFixPathChangeTimer_.rawin(Path) || NowTime - getroottable()._HotFixPathChangeTimer_[Path] > 1000) {
        Timer.SetTimeOut(function() {
            //判断类型
            if (endswith(Path, ".nut")) {
                dofile(Path);
                print("位于 [" + Path + "] 的脚本已重载")
            } else if (endswith(Path, ".json")) {
                try {
                    local PArr = split(Path, "/");
                    local RealName = PArr[PArr.len() - 1];

                    //在载入新配置之前 先拿到旧配置保存起来
                    local OldConfig = GlobalConfig.Get(RealName);
                    GlobalConfig.LoadJson(RealName, Path);

                    //如果存在项目 并且有重载入口 则调用重载入口
                    if (_GlobalOfficial_Project.ReloadProjectMap.rawin(RealName)) {
                        local ProjectStartFunc = _GlobalOfficial_Project.ReloadProjectMap[RealName];
                        if (getroottable().rawin(ProjectStartFunc + "Reload_")) {
                            getroottable()[ProjectStartFunc + "Reload_"](OldConfig);
                        }
                    }
                    print("位于 [" + Path + "] 的配置已重载");

                } catch (exception) {

                }
            }
        }, 500)
        getroottable()._HotFixPathChangeTimer_[Path] <- NowTime;
    }
}