EntityEvents.death(event => {
    let soldier = event.entity
    let entityName = soldier.name.string
    let sData = soldier.persistentData

    // 从士兵数据库中获取数据
    let sSoldierData = sData.getCompound("soldier")
    let ownerUuid = sSoldierData.getString("Owner")

    if (!ownerUuid) return

    let ownerPlayer = event.server.getPlayer(ownerUuid)
    if (!ownerPlayer) return

    let pData = ownerPlayer.persistentData
    let pSoldierData = pData.getCompound("soldier")

    // 获取command复合标签
    let pCommandData = pData.getCompound("command")
    let currentLegion = pCommandData.getInt("legion") || 1

    // 检查士兵是否属于任何队伍
    if (sSoldierData.contains("Legion")) {
        let legionCompound = sSoldierData.getCompound("Legion")
        let occupation = sSoldierData.getInt("Occupation") || 1

        // 遍历所有队伍，更新规模
        for (let i = 1; i <= 9; i++) {
            if (legionCompound.getBoolean(`Legion_${i}`)) {
                // 从command复合标签中获取和更新军团规模
                let currentScale = pCommandData.getInt(`Legion_${i}`) || 0
                let newScale = Math.max(0, currentScale - occupation)
                pCommandData.putInt(`Legion_${i}`, newScale)

                // 如果士兵是当前活跃队伍的，给玩家额外提示
                if (i === currentLegion) {
                    ownerPlayer.tell(`§7队伍${currentLegion}规模降至: §e${newScale}`)
                }
            }
        }

        ownerPlayer.tell(`§6你的士兵 §e${entityName} §6已阵亡`)
    }

    // 从玩家数据库中移除士兵信息,此操作需要延迟到士兵尸体消失以保证最后的信息同步删除
    ownerPlayer.server.scheduleInTicks(25, () => {
        pSoldierData.remove(soldier.uuid.toString())
        pData.put("soldier", pSoldierData)

        // 保存更新后的command数据
        pData.put("command", pCommandData)
    })
    // 从盔甲架中移除登记信息
    let markUuid = sSoldierData.getString("Home")
    if (markUuid) {
        let dimension = sSoldierData.getString("HomePosDim")
        let x = sSoldierData.getInt("HomePosX")
        let z = sSoldierData.getInt("HomePosZ")
        let level = event.server.getLevel(dimension)
        // 使用票证系统短暂加载区块
        global.ShortLoadChunks(level, x, z, 20) // 20 tick = 1秒
        // 延迟执行以等待区块加载
        event.server.scheduleInTicks(5, () => {
            // 在加载的区块中查找盔甲架
            let mark = level.getEntity(markUuid)
            if (mark) {
                mark.persistentData.remove("Resident")
            } else {
                ownerPlayer.tell(`§6士兵盔甲架信息处理失败，可在募兵时自动处理`)
            }
        })

        // 士兵与召唤战马同命
        if (soldier.vehicle) {
            soldier.vehicle.mergeNbt({ Health: 0, DeathTime: 19 })
        }
    }
})