// priority: 0

PlayerEvents.respawned(event => {
    let player = event.player
    let pData = player.persistentData
    // 自动攀爬配置恢复
    if (pData.getInt('task_sha') === 1) {
        player.setAttributeBaseValue("forge:step_height_addition", 1)
    }
})

EntityEvents.death('minecraft:player', event => {
    let player = event.entity
    let pData = player.persistentData
    let pSoldierData = pData.getCompound("soldier")
    // 遍历玩家数据库中的所有士兵
    pSoldierData.getAllKeys().forEach(soldierUuid => {
        let soldierData = pSoldierData.getCompound(soldierUuid)
        // 检查士兵是否有Legion数据
        if (soldierData.contains("Legion")) {
            // 尝试获取士兵实体
            let soldier = player.level.getEntity(soldierUuid)
            if (!soldier) return
            // 检查士兵与玩家的距离
            if (soldier.distanceToEntity(player) > 120) return
            let returnedSoldiers = 0
            let sSoldierData = soldier.persistentData.getCompound("soldier")
            soldier.unRide()
            // 从士兵数据库中获取Home位置
            let homeX = sSoldierData.getInt("HomePosX")
            let homeY = sSoldierData.getInt("HomePosY")
            let homeZ = sSoldierData.getInt("HomePosZ")
            let homeDim = sSoldierData.getString("HomePosDim")
            // 传送士兵回家
            soldier.teleportTo(homeDim, homeX, homeY, homeZ, 0, 0)
            // 设置士兵行为为警戒模式（原地驻守）
            let commandData = soldier.persistentData.getCompound("command")
            commandData.putInt("Behavior", 1)
            commandData.putInt("PosX", homeX)
            commandData.putInt("PosY", homeY)
            commandData.putInt("PosZ", homeZ)
            soldier.persistentData.put("command", commandData)
            // 调用全局行为翻译函数
            global.BehaviorTranslation(soldier, player)
            // 更新玩家数据库中的士兵记录
            let sUuid = soldier.uuid.toString()
            if (pSoldierData.contains(sUuid)) {
                let sUuidData = pSoldierData.getCompound(sUuid)
                sUuidData.putInt("Behavior", 1)
                pSoldierData.put(sUuid, sUuidData)
            }
            returnedSoldiers++
        }
    })
    // 更新玩家数据
    pData.put("soldier", pSoldierData)
    if (returnedSoldiers > 0) {
        player.tell(`§6阵亡时，${returnedSoldiers}名远征军士兵已自动返回驻地`)
    }
})