// priority: 50

ServerEvents.command(event => {
  if (event.input.match(/nothing (\d+)/)) {
    let player = event.parseResults.context.source.entity
    let pData = player.persistentData
    let pSoldierData = pData.getCompound("soldier")
    let team = player.team.name
    let legion = pData.getInt("legion") || 1

    //远征军跟随
    if (event.input === "nothing 2") {
      let cheak = false
      // 遍历玩家数据库中的所有士兵
      pSoldierData.getAllKeys().forEach(soldierUuid => {
        let soldierData = pSoldierData.getCompound(soldierUuid)
        // 检查士兵是否有Legion数据且在当前队伍中
        if (soldierData.contains("Legion")) {
          let legionCompound = soldierData.getCompound("Legion")
          if (legionCompound.getBoolean(`Legion_${legion}`)) {
            // 尝试获取士兵实体
            let soldier = player.level.getEntity(soldierUuid)
            if (!soldier) return
            // 检查士兵与玩家的距离
            if (soldier.distanceToEntity(player) > 120) return
            // 设置行为为跟随模式
            let commandData = soldier.persistentData.getCompound("command")
            commandData.putInt("Behavior", 2)
            soldier.persistentData.put("command", commandData)
            // 更新玩家对士兵的行为记录
            let sUuid = soldier.uuid.toString()
            let sUuidData = pSoldierData.getCompound(sUuid)
            sUuidData.putInt("Behavior", 2)
            pSoldierData.put(sUuid, sUuidData)
            pData.put("soldier", pSoldierData)
            // 调用全局行为翻译函数
            global.BehaviorTranslation(soldier, player)
            cheak = true
          }
        }
      })
      // 消息反馈
      if (cheak) {
        player.tell(`军团${legion}听令，跟随我！`)
      } else {
        player.tell("§c没有找到可指挥的远征军士兵")
      }
    }

    //远征军原地驻守
    if (event.input === "nothing 6") {
      let cheak = false
      // 遍历玩家数据库中的所有士兵
      pSoldierData.getAllKeys().forEach(soldierUuid => {
        let soldierData = pSoldierData.getCompound(soldierUuid)
        // 检查士兵是否有Legion数据且在当前队伍中
        if (soldierData.contains("Legion")) {
          let legionCompound = soldierData.getCompound("Legion")
          if (legionCompound.getBoolean(`Legion_${legion}`)) {
            // 尝试获取士兵实体
            let soldier = player.level.getEntity(soldierUuid)
            if (!soldier) return
            // 检查士兵与玩家的距离
            if (soldier.distanceToEntity(player) > 120) return
            // 设置行为
            let commandData = soldier.persistentData.getCompound("command")
            commandData.putInt("Behavior", 1)
            commandData.putInt("PosX", Math.floor(soldier.x))
            commandData.putInt("PosY", Math.floor(soldier.y))
            commandData.putInt("PosZ", Math.floor(soldier.z))
            soldier.persistentData.put("command", commandData)
            // 更新玩家对士兵的行为记录
            let sUuid = soldier.uuid.toString()
            let sUuidData = pSoldierData.getCompound(sUuid)
            sUuidData.putInt("Behavior", 1)
            pSoldierData.put(sUuid, sUuidData)
            pData.put("soldier", pSoldierData)
            // 调用全局行为翻译函数
            global.BehaviorTranslation(soldier, player)
            cheak = true
          }
        }
      })
      if (cheak) {
        player.tell(`军团${legion}听令，原地驻守！`)
      } else {
        player.tell("§c没有找到可指挥的远征军士兵")
      }
    }

    // 直接指挥
    if (event.input === "nothing 8") {

      // 获取指挥坐标
      let rayTraceResult = player.rayTrace(80)
      if (!rayTraceResult || !rayTraceResult.block) {
        player.tell("§c前方没有合适的位置")
        return
      }
      let block = rayTraceResult.block
      let [centerX, centerY, centerZ] = [block.x, block.y, block.z]

      let spacing = 2.0 // 士兵间距（2格）

      // 收集符合条件的士兵
      let soldiers = []

      // 从玩家数据库读取士兵UUID
      pSoldierData.getAllKeys().forEach(soldierUuid => {
        let soldierData = pSoldierData.getCompound(soldierUuid)

        // 检查士兵是否有Legion数据且在当前队伍中
        if (soldierData.contains("Legion")) {
          let legionCompound = soldierData.getCompound("Legion")
          if (legionCompound.getBoolean(`Legion_${legion}`)) {
            // 尝试获取士兵实体
            let soldier = player.level.getEntity(soldierUuid)
            if (!soldier) return

            // 检查士兵与玩家的距离（120格范围内）
            if (soldier.distanceToEntity(player) > 120) return

            soldiers.push(soldier)

            // 如果有骑兵，调整间距
            if (soldier.vehicle && spacing === 2.0) {
              spacing = 4.0
            }
          }
        }
      })

      // 没有士兵则返回
      if (soldiers.length === 0) {
        player.tell("§c没有找到可指挥的士兵！")
        return
      }

      // 计算方阵参数
      let formationSize = Math.ceil(Math.sqrt(soldiers.length)) // 方阵边长
      let startX = centerX - Math.floor(formationSize / 2) * spacing
      let startZ = centerZ - Math.floor(formationSize / 2) * spacing
      let currentIndex = 0

      // 按方阵排列士兵
      for (let row = 0; row < formationSize; row++) {
        for (let col = 0; col < formationSize; col++) {
          if (currentIndex >= soldiers.length) break

          let soldier = soldiers[currentIndex]
          let targetX = startX + col * spacing + 0.5
          let targetZ = startZ + row * spacing + 0.5
          let targetY = centerY + 1

          // 设置士兵行为为警戒模式
          let commandData = soldier.persistentData.getCompound("command")
          commandData.putInt("Behavior", 1)
          commandData.putInt("PosX", targetX)
          commandData.putInt("PosY", targetY)
          commandData.putInt("PosZ", targetZ)
          soldier.persistentData.put("command", commandData)
          // 更新玩家对士兵的行为记录
          let sUuid = soldier.uuid.toString()
          let sUuidData = pSoldierData.getCompound(sUuid)
          sUuidData.putInt("Behavior", 1)
          pSoldierData.put(sUuid, sUuidData)
          pData.put("soldier", pSoldierData)
          // 调用全局行为翻译函数
          global.BehaviorTranslation(soldier, player)

          currentIndex++
        }
      }

      player.tell(`军团${legion}听令，前进！`)
    }
  }
})
