// 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 pUUID = player.nbt.UUID
    let team = player.team.name
    let legion = pData.getInt("legion") || 1

    //全军上马
    if (event.input === "nothing 9") {
      if (!global.CoolDownTime(player, "RidingInstructions", 100, true)) {
        player.tell("§c请不要频繁指挥骑乘")
        return
      }
      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
            // 跳过已经骑乘的士兵
            if (soldier.vehicle) return
            cheak = true
            // 加载数据库
            let sData = soldier.persistentData
            let rideData = sData.getCompound("ride")
            // 设置行为
            // 有替换ID标记时进行替换
            if (rideData.getBoolean("replace")) {
              let newSoldier = player.level.createEntity(rideData.getString("rideID"))
              newSoldier.setPosition(soldier.x, soldier.y, soldier.z)
              newSoldier.mergeNbt(soldier.nbt)
              // 有副武器信息时正确储存武器
              if (rideData.getCompound("ChargeWeapon")) {
                newSoldier.mergeNbt({
                  MainWeapon: soldier.nbt.HandItems[0],
                  ChargeWeapon: rideData.ChargeWeapon
                })
                rideData.put("PedestrianWeapon", soldier.nbt.HandItems[0])
              }
              // 存入原始ID
              newSoldier.persistentData.putString("Pedestrian", soldier.type)
              // 删除步行士兵
              soldier.mergeNbt({ Health: 0, DeathTime: 19 })
              newSoldier.server.scheduleInTicks(2, () => {
                // 召唤骑兵
                newSoldier.spawn()
                // 将骑兵和马匹加入团队
                event.server.runCommandSilent(`execute as ${newSoldier.uuid} run team join ${team} @s`)
                newSoldier.server.scheduleInTicks(2, () => {
                  event.server.runCommandSilent(`execute as ${newSoldier.vehicle.uuid} run team join ${team} @s`)
                })
              })
            } else {
              let newride = 0
              if (rideData.getString("riding")) {
                newride = player.level.createEntity(rideData.getString("riding"))
              } else {
                newride = player.level.createEntity("minecraft:horse")
              }
              newride.setPosition(soldier.x, soldier.y, soldier.z)
              newride.mergeNbt({ Tame: 1, Owner: pUUID, SaddleItem: { Count: 1, id: "minecraft:saddle" } })
              newride.spawn()
              event.server.runCommandSilent(`execute as ${newride.uuid} run team join ${team} @s`)
              soldier.server.scheduleInTicks(5, () => {
                soldier.startRiding(newride)
              })
            }
          }
        }
      })
      // 消息反馈
      if (cheak) {
        player.tell(`军团${legion}听令，骑乘战马！`)
      } else {
        player.tell("§c没有找到可指挥的远征军士兵")
      }
    }
    // 全军下马
    if (event.input === "nothing 10") {
      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
            // 跳过已经下马的士兵
            if (!soldier.vehicle) return
            cheak = true
            soldier.unRide()
          }
        }
      })
      // 消息反馈
      if (cheak) {
        player.tell(`军团${legion}听令，步行作战！`)
      } else {
        player.tell("§c没有找到可指挥的远征军士兵")
      }

    }
    // 玩家骑乘
    if (event.input === "nothing 50") {
      if (player.vehicle) return
      event.server.entities.forEach((mount) => {
        if (!(
          mount.tags.contains("snk_mount") &&
          mount.nbt.Owner &&
          pUUID.equals(mount.nbt.Owner)
        )) return
        mount.teleportTo(player.level.dimension.path, player.x, player.y, player.z, 0, 0)
        player.server.scheduleInTicks(5, () => {
          player.startRiding(mount)
        })
      })
    }
  }
})