// priority: 50

// 内存数据：召唤CD
var TPsoldiers = {}

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

    // 召唤远征军
    if (event.input === "nothing 1") {
      // 获取当前队伍的所有士兵UUID
      let soldierUUIDs = []
      let totalScale = 0

      pSoldierData.getAllKeys().forEach(soldierUuid => {
        let soldierData = pSoldierData.getCompound(soldierUuid)
        if (soldierData.contains("Legion")) {
          let legionCompound = soldierData.getCompound("Legion")
          if (legionCompound.getBoolean(`Legion_${legion}`)) {
            soldierUUIDs.push(soldierUuid)
            // 累加士兵的规模值
            let occupation = soldierData.getInt("Occupation") || 1
            totalScale += occupation
          }
        }
      })
      let TPsoldiersCD = totalScale * TPsoldiersTimes

      // 使用冷却函数
      if (!global.CoolDownTime(player, "summon_legion", TPsoldiersCD * 20, true)) return
      if (soldierUUIDs.length === 0) {
        player.tell("§c当前队伍没有可召唤的士兵！")
        return
      }

      // 使用新的召唤系统，传递总规模
      global.AssembleSoldiers(player, soldierUUIDs, totalScale)
    }

    //送回远征军
    if (event.input === "nothing 5") {

      let returnedSoldiers = 0
      let messengerNotified = 0

      // 创建处理队列
      let soldierQueue = []

      // 收集需要处理的士兵
      pSoldierData.getAllKeys().forEach(soldierUuid => {
        let soldierData = pSoldierData.getCompound(soldierUuid)

        // 检查士兵是否有Legion数据且在当前队伍中
        if (soldierData.contains("Legion")) {
          let legionCompound = soldierData.getCompound("Legion")
          if (legionCompound.getBoolean(`Legion_${legion}`)) {

            soldierQueue.push({
              uuid: soldierUuid,
              data: soldierData
            })
          }
        }
      })

      // 如果没有士兵需要处理
      if (soldierQueue.length === 0) {
        player.tell(`军团${legion}没有需要送回远征军`)
        return
      }

      // 递归处理队列中的每个士兵
      let processNextSoldier = (index) => {
        if (index >= soldierQueue.length) {
          // 所有士兵处理完成
          let message = `已送回${returnedSoldiers}名远征军士兵`
          if (messengerNotified > 0) {
            message += `，其中${messengerNotified}名由信使通知返回`
          }
          player.tell(message)
          return
        }

        let soldierInfo = soldierQueue[index]
        let soldierUuid = soldierInfo.uuid

        global.GetGlobalEntity(soldierUuid, player, (soldier, usedForceLoad) => {
          if (soldier) {

            // 从士兵数据库中获取Home位置
            let sSoldierData = soldier.persistentData.getCompound("soldier")
            let homeX = sSoldierData.getInt("HomePosX")
            let homeY = sSoldierData.getInt("HomePosY")
            let homeZ = sSoldierData.getInt("HomePosZ")
            let homeDim = sSoldierData.getString("HomePosDim")
            let eUuid = soldier.uuid.toString()

            // 传送士兵回家
            soldier.server.scheduleInTicks(2, () => {

              // 使用全局行为翻译函数设置行为
              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)

              // 更新玩家对士兵的行为记录
              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)
              // 播放音效 - 使用传送门音效
              level.playSound(null, soldier.x, soldier.y, soldier.z, "minecraft:entity.enderman.teleport", 'hostile', 1.0, 0.8)
              // 添加一些火花粒子效果
              level.spawnParticles("minecraft:witch", false, soldier.x, soldier.y + 0.5, soldier.z, 0.3, 0.5, 0.3, 30, 0.01)

              soldier.teleportTo(homeDim, homeX + 0.5, homeY, homeZ + 0.5, 0, 0)
              returnedSoldiers++

              //记录正确的士兵读取位置
              player.server.scheduleInTicks(1, () => {
                let eUuidData = pSoldierData.getCompound(eUuid)
                eUuidData.putInt("TPPosX", homeX)
                eUuidData.putInt("TPPosZ", homeZ)
                eUuidData.putString("TPPosDim", homeDim)
              })

              // 如果是强加载获取的，额外提醒
              if (usedForceLoad) {
                messengerNotified++
                player.tell(`已派遣信使通知 ${soldier.name.string} 返回驻地`)
              }
            })
          }

          // 处理下一个士兵，间隔2 tick避免服务器压力
          event.server.scheduleInTicks(2, () => {
            processNextSoldier(index + 1)
          })
        })
      }

      // 开始处理队列
      processNextSoldier(0)
    }
  }
})