// priority: 50

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

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

    // 标记远征军
    if (event.input === "nothing 3") {
      let MAXScale = pData.getInt("MaxScale")

      // 计算总规模：所有远征军士兵的规模总和（每个士兵只计算一次）
      let totalOccupation = calculateTotalOccupation(pSoldierData)

      // 计算当前军团规模
      let currentLegionScale = pCommandData.getInt(`Legion_${legion}`) || 0

      let maxAllowed = MAXScale - totalOccupation
      let addedOccupation = 0

      let AABB = player.boundingBox.inflate(10, 10, 10)
      player.level.getEntitiesWithin(AABB).forEach((soldier) => {
        if (addedOccupation >= maxAllowed) return
        let sUuid = soldier.uuid.toString()
        let sData = soldier.persistentData
        let sSoldierData = sData.getCompound("soldier")

        // 检查士兵是否有Owner数据且属于当前玩家
        if (sSoldierData.getString("Owner") !== player.uuid.toString()) return

        // 从士兵数据库获取Occupation
        let occupation = sSoldierData.getInt("Occupation") || 1

        // 检查士兵是否已经在当前队伍中
        let alreadyInCurrentLegion = false
        if (sSoldierData.contains("Legion")) {
          let legionCompound = sSoldierData.getCompound("Legion")
          alreadyInCurrentLegion = legionCompound.getBoolean(`Legion_${legion}`) || false
        }

        // 如果士兵已经在当前队伍中，跳过
        if (alreadyInCurrentLegion) return

        // 检查士兵是否已经是远征军（属于其他军团）
        let isAlreadyLegionSoldier = false
        if (sSoldierData.contains("Legion")) {
          let legionCompound = sSoldierData.getCompound("Legion")
          let allKeys = legionCompound.getAllKeys()
          for (let key of allKeys) {
            if (legionCompound.getBoolean(key)) {
              isAlreadyLegionSoldier = true
              break
            }
          }
        }

        // 如果士兵已经是远征军但在其他队伍，添加到当前队伍
        if (sSoldierData.contains("Legion") && !alreadyInCurrentLegion) {
          let legionCompound = sSoldierData.getCompound("Legion")
          legionCompound.putBoolean(`Legion_${legion}`, true)
          sSoldierData.put("Legion", legionCompound)
          soldier.persistentData.put("soldier", sSoldierData)

          // 同时更新玩家数据库中的对应记录
          let pSoldierRecord = pSoldierData.getCompound(sUuid)
          let pLegionCompound = pSoldierRecord.getCompound("Legion")
          pLegionCompound.putBoolean(`Legion_${legion}`, true)
          pSoldierRecord.put("Legion", pLegionCompound)
          pSoldierData.put(sUuid, pSoldierRecord)
          pSoldierRecord.putInt("Occupation", occupation)

          player.tell(`${soldier.name.string}已加入军团${legion}`)

          // 更新行为为跟随
          let commandData = soldier.persistentData.getCompound("command")
          commandData.putInt("Behavior", 2)
          soldier.persistentData.put("command", commandData)
          global.BehaviorTranslation(soldier, player)

          // 更新玩家对士兵的行为记录
          let pSoldierRecord2 = pSoldierData.getCompound(sUuid)
          pSoldierRecord2.putInt("Behavior", 2)
          pSoldierData.put(sUuid, pSoldierRecord2)

          // 更新队伍规模（军团规模增加，总规模不变）
          currentLegionScale += occupation
          addedOccupation += 0 // 总规模不变，所以addedOccupation不增加
          return
        }

        // 新标记的士兵检查规模限制
        if (!isAlreadyLegionSoldier) {
          if (totalOccupation >= MAXScale) {
            player.tell(`§c无法标记${soldier.name.string}，远征军总规模已达上限！`)
            return
          }

          // 新加入远征军的士兵检查规模限制
          if (addedOccupation + occupation > maxAllowed) {
            player.tell(`§c无法标记${soldier.name.string}，超过远征军规模上限！`)
            return
          }
        }

        /////////////新士兵标记逻辑/////////////
        // 士兵数据库
        let sLegionCompound = sSoldierData.getCompound("Legion")
        sLegionCompound.putBoolean(`Legion_${legion}`, true)
        sSoldierData.put("Legion", sLegionCompound)
        soldier.persistentData.put("soldier", sSoldierData)

        // 玩家数据库
        let pSoldierRecord = pSoldierData.getCompound(sUuid)
        let pLegionCompound = pSoldierRecord.getCompound("Legion")
        pLegionCompound.putBoolean(`Legion_${legion}`, true)
        pSoldierRecord.put("Legion", pLegionCompound)
        pSoldierRecord.putInt("Behavior", 2)
        pSoldierRecord.putInt("Occupation", occupation)
        pSoldierData.put(sUuid, pSoldierRecord)

        // 设置行为数据并调用全局翻译函数
        let commandData = soldier.persistentData.getCompound("command")
        commandData.putInt("Behavior", 2)
        commandData.putInt("Hostility", 1)
        soldier.persistentData.put("command", commandData)
        global.BehaviorTranslation(soldier, player)

        addedOccupation += occupation
        currentLegionScale += occupation

        player.tell(`${soldier.name.string}已登记远征军至军团${legion}(总规模${totalOccupation + addedOccupation}/${MAXScale})`)
      })

      // 更新队伍规模和玩家数据
      if (addedOccupation > 0) {
        pCommandData.putInt(`Legion_${legion}`, currentLegionScale)
        pData.put("command", pCommandData)
        pData.put("soldier", pSoldierData)
      }
    }
    // 取消标记
    if (event.input === "nothing 4") {
      let totalRemoved = 0
      let messengerNotified = 0 // 记录通过信使通知的士兵数量
      let stillInOtherLegions = 0 // 记录仍然在其他团队的士兵数量
      let fullyRemoved = 0 // 记录完全移除的士兵数量

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

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

        // 检查士兵是否有Legion数据
        if (soldierData.contains("Legion")) {
          let legionCompound = soldierData.getCompound("Legion")
          let occupation = soldierData.getInt("Occupation") || 1

          // 如果士兵在当前队伍中
          if (legionCompound.getBoolean(`Legion_${legion}`)) {
            soldierQueue.push({
              uuid: soldierUuid,
              data: soldierData,
              occupation: occupation
            })
          }
        }
      })

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

      // 递归处理队列中的每个士兵
      let processNextSoldier = (index) => {
        if (index >= soldierQueue.length) {
          // 所有士兵处理完成
          pCommandData.putInt(`Legion_${legion}`, 0)
          pData.put("command", pCommandData)

          // 构建提示信息
          let message = `军团${legion}的远征军已解除登记，移除了${totalRemoved}规模`

          if (fullyRemoved > 0) {
            message += `，其中${fullyRemoved}名士兵完全从远征军移除`
          }

          if (stillInOtherLegions > 0) {
            message += `，${stillInOtherLegions}名士兵依然处于其他团队指挥下`
          }

          if (messengerNotified > 0) {
            message += `，${messengerNotified}名士兵由信使通知`
          }

          player.tell(message)
          return
        }

        let soldierInfo = soldierQueue[index]
        let soldierUuid = soldierInfo.uuid
        let soldierData = soldierInfo.data
        let occupation = soldierInfo.occupation

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

          let legionCompound = soldierData.getCompound("Legion")
          let wasInLegion = legionCompound.getBoolean(`Legion_${legion}`) || false

          if (wasInLegion) {
            // 移除当前队伍的标记
            legionCompound.putBoolean(`Legion_${legion}`, false)
            totalRemoved += occupation

            // 检查是否还有其他队伍标记
            let hasOtherLegions = false
            let allKeys = legionCompound.getAllKeys()
            for (let key of allKeys) {
              if (legionCompound.getBoolean(key)) {
                hasOtherLegions = true
                break
              }
            }

            if (!hasOtherLegions) {
              // 如果不再属于任何队伍，完全移除Legion数据
              soldierData.remove("Legion")
              fullyRemoved++
            } else {
              soldierData.put("Legion", legionCompound)
              stillInOtherLegions++
            }

            if (soldier) {
              // 设置行为
              let commandData = soldier.persistentData.getCompound("command")
              commandData.putInt("Behavior", 0)
              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", 0)
              pSoldierData.put(sUuid, sUuidData)
              pData.put("soldier", pSoldierData)
              // 调用全局行为翻译函数
              global.BehaviorTranslation(soldier, player)

              let sSoldierData = soldier.persistentData.getCompound("soldier")
              let sLegionCompound = sSoldierData.getCompound("Legion")
              sLegionCompound.putBoolean(`Legion_${legion}`, false)

              // 检查士兵是否还有其他队伍
              let sHasOtherLegions = false
              let sAllKeys = sLegionCompound.getAllKeys()
              for (let key of sAllKeys) {
                if (sLegionCompound.getBoolean(key)) {
                  sHasOtherLegions = true
                  break
                }
              }

              if (!sHasOtherLegions) {
                sSoldierData.remove("Legion")
              } else {
                sSoldierData.put("Legion", sLegionCompound)
              }
              soldier.persistentData.put("soldier", sSoldierData)

              // 如果是强加载获取的，额外提醒
              if (usedForceLoad) {
                messengerNotified++
                let statusMsg = hasOtherLegions ? "依然处于其他团队指挥下" : "已完全从远征军移除"
                player.tell(`已派遣信使通知 ${soldier.name.string} 从军团${legion}移除，${statusMsg}`)
              } else {
                // 即使不是强加载，也给出状态提示
                let statusMsg = hasOtherLegions ? "依然处于其他团队指挥下" : "已完全从远征军移除"
                player.tell(`${soldier.name.string} 从军团${legion}移除，${statusMsg}`)
              }
            } else {
              // 没有找到实体，但也记录状态
              if (hasOtherLegions) {
                stillInOtherLegions++
              } else {
                fullyRemoved++
              }
            }
          }

          // 更新玩家数据库
          pSoldierData.put(soldierUuid, soldierData)

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

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

    // 征募警卫村民为远征军
    if (event.input === "nothing 31") {
      let MAXScale = pData.getInt("MaxScale")

      // 计算总规模：所有远征军士兵的规模总和（每个士兵只计算一次）
      let totalOccupation = calculateTotalOccupation(pSoldierData)

      let currentLegionScale = pCommandData.getInt(`Legion_${legion}`) || 0
      let maxAllowed = MAXScale - totalOccupation
      let addedOccupation = 0
      let AABB = player.boundingBox.inflate(10, 10, 10)

      player.level.getEntitiesWithin(AABB).forEach((guard) => {
        if (addedOccupation >= maxAllowed) return

        if (!guard.type.toString().startsWith("guardvillagers")) return

        let gUuid = guard.uuid.toString()
        let gData = guard.persistentData

        // 检查是否已经初始化过
        let alreadyRecruited = gData.getBoolean("snk_recruited") || false

        // 如果已经征募过，告诉玩家可以使用另一个方法指挥
        if (alreadyRecruited) {
          player.tell(`${guard.name.string}已征募，请使用“编入远征军”指令进行军团分配`)
          return
        }

        // 新征募的警卫村民检查规模限制
        let gSoldierData = gData.getCompound("soldier")
        let occupation = gSoldierData.getInt("Occupation") || 2

        if (addedOccupation + occupation > maxAllowed) {
          player.tell(`§c无法征募${guard.name.string}，超过远征军规模上限！`)
          return
        }

        // 花费20紫水晶碎片
        if (!global.ConsumableItems(player, [{ id: "minecraft:amethyst_shard", count: 20 }])) return

        /////////////新警卫村民征募逻辑/////////////
        // 只设置必要的远征军属性，保留已有属性
        gSoldierData.putString("Owner", player.uuid.toString())

        // 标记为远征军
        let gLegionCompound = gSoldierData.getCompound("Legion")
        gLegionCompound.putBoolean(`Legion_${legion}`, true)
        gSoldierData.put("Legion", gLegionCompound)
        guard.persistentData.put("soldier", gSoldierData)

        // 设置Owner UUID（不覆盖其他NBT）
        guard.mergeNbt({ Owner: player.nbt.UUID })

        // 标记为已征募
        gData.putBoolean("snk_recruited", true)

        // 玩家数据库
        let pSoldierRecord = pSoldierData.getCompound(gUuid)
        pSoldierRecord.putString("uuid", gUuid)
        pSoldierRecord.putInt("Behavior", 2)
        pSoldierRecord.putInt("Occupation", occupation)
        let pLegionCompound = pSoldierRecord.getCompound("Legion")
        pLegionCompound.putBoolean(`Legion_${legion}`, true)
        pSoldierRecord.put("Legion", pLegionCompound)
        pSoldierData.put(gUuid, pSoldierRecord)

        // 设置行为数据并调用全局翻译函数
        let commandData = guard.persistentData.getCompound("command")
        commandData.putInt("Behavior", 2)
        commandData.putInt("Hostility", 1)
        guard.persistentData.put("command", commandData)

        // 调用全局行为翻译函数
        global.BehaviorTranslation(guard, player)

        addedOccupation += occupation
        currentLegionScale += occupation

        player.tell(`${guard.name.string}已征募为远征军至军团${legion}(总规模${totalOccupation + addedOccupation}/${MAXScale})`)

        // 加入玩家团队
        event.server.runCommandSilent(`execute as ${guard.uuid} run team join ${team} @s`)
      })

      // 更新队伍规模和玩家数据
      if (addedOccupation > 0) {
        pCommandData.putInt(`Legion_${legion}`, currentLegionScale)
        pData.put("command", pCommandData)
        pData.put("soldier", pSoldierData)
      } else {
        player.tell("§c范围内没有可征募的警卫村民！")
      }
    }
  }
})

function calculateTotalOccupation(pSoldierData) {
  let totalOccupation = 0
  let processedSoldiers = new Set() // 用于跟踪已处理的士兵UUID

  pSoldierData.getAllKeys().forEach(soldierUuid => {
    // 如果已经处理过这个士兵，跳过
    if (processedSoldiers.has(soldierUuid)) return

    let soldierData = pSoldierData.getCompound(soldierUuid)

    // 检查士兵是否有Legion数据
    if (soldierData.contains("Legion")) {
      let legionCompound = soldierData.getCompound("Legion")
      let occupation = soldierData.getInt("Occupation") || 1

      // 检查士兵是否属于至少一个军团
      let isInAnyLegion = false
      let allKeys = legionCompound.getAllKeys()
      for (let key of allKeys) {
        if (legionCompound.getBoolean(key)) {
          isInAnyLegion = true
          break
        }
      }

      // 如果士兵属于至少一个军团，计入总规模
      if (isInAnyLegion) {
        totalOccupation += occupation
        processedSoldiers.add(soldierUuid) // 标记为已处理
      }
    }
  })

  return totalOccupation
}

