// priority: 0

// 定义召唤配置映射表
let allyConfigs = {
  12: {
    // 荒原鹫
    checkUnlock: (pData) => pData.getInt("ally_umvuthana") > 0,
    unlockMessage: "§c你还未获得荒原鹫的支援",
    getConfig: (pData) => {
      let allyLevel = pData.getInt("ally_umvuthana")
      return allyUmvuthana[allyLevel]
    },
  },
  13: {
    // 亡灵军团
    checkUnlock: (pData) => pData.getInt("ally_undead") > 0,
    unlockMessage: "§c你还未学会复苏亡灵",
    getConfig: (pData) => {
      let allyLevel = pData.getInt("ally_undead")
      return allyUndead[allyLevel]
    },
  },
  14: {
    // 攻城武器
    checkUnlock: (pData) => pData.getInt("ally_siege") > 0,
    unlockMessage: "§c你还未招募机械师",
    getConfig: (pData) => {
      let allyLevel = pData.getInt("ally_siege")
      return allySiege[allyLevel]
    },
  },
  15: {
    // 钢铁的意志
    checkUnlock: (pData) => pData.getInt("ally_ferrouswroughtnaut") > 0,
    unlockMessage: "§c你还未征服钢铁的意志",
    getConfig: (pData) => {
      let allyLevel = pData.getInt("ally_ferrouswroughtnaut")
      return allyFerrousWroughtnaut[allyLevel]
    },
  },
  16: {
    // 凋灵骷髅死士
    checkUnlock: (pData) => pData.getInt("ally_witherskeleton") > 0,
    unlockMessage: "§c你还未得到凋灵骷髅死士的臣服",
    getConfig: (pData) => {
      let allyLevel = pData.getInt("ally_witherskeleton")
      return allyWitherSkeleton[allyLevel]
    },
  },
  17: {
    // 失落的灵魂
    checkUnlock: (pData) => pData.getInt("ally_collectedsouls") > 0,
    unlockMessage: "§c你还未收容任何失落的灵魂",
    getConfig: (pData) => {
      let allyLevel = pData.getInt("ally_collectedsouls")
      return allyCollectedSouls[allyLevel]
    },
  },
}

ServerEvents.command((event) => {
  let commandMatch = event.input.match(/nothing (\d+)/)
  if (!commandMatch) return

  let commandId = commandMatch[1]
  if (!allyConfigs[commandId]) return

  let player = event.parseResults.context.source.entity

  // 调用统一的召唤处理函数
  handleAllySummon(player, commandId)
})

// 统一的召唤处理函数
function handleAllySummon(player, commandId) {
  let pData = player.persistentData

  // 冷却
if (!global.CoolDownTime(player, "summon_ally", allyCD * 20, true)) return

  // 获取配置
  let configInfo = allyConfigs[commandId]
  if (!configInfo.checkUnlock(pData)) {
    player.tell(configInfo.unlockMessage)
    return
  }
  let config = configInfo.getConfig(pData)
  if (!config) return
  // 检查是否有足够的物品
  let totalCost = {}
  for (let unit of config.units) {
    if (!totalCost[unit.costItem]) {
      totalCost[unit.costItem] = 0
    }
    totalCost[unit.costItem] += unit.costAmount
  }

  // 构建成本数组
  let costArray = []
  for (let [item, amount] of Object.entries(totalCost)) {
    costArray.push({ id: item, count: amount })
  }

  if (!global.CountConsumableItems(player, costArray)) return

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

  // 为每个单位类型寻找位置并召唤
  let totalSpawned = 0
  for (let unit of config.units) {
    let spawnedCount = spawnUnit(player, unit, targetX, targetY, targetZ);
    totalSpawned += spawnedCount

    // 使用新的扣除函数扣除物品
    let unitCostArray = [
      {
        id: unit.costItem,
        count: (unit.costAmount * spawnedCount) / unit.count,
      },
    ]
    if (!global.ConsumableItems(player, unitCostArray)) {
      // 如果扣除失败，尝试回滚已召唤的单位
      player.tell("§c召唤过程中出现错误，部分单位可能已被召唤")
      break
    }
  }

  player.tell(`§a已召唤${totalSpawned}名援军，他们将在${global.duration}秒后离开`)
}
// 召唤单个单位类型的函数
function spawnUnit(player, unit, targetX, targetY, targetZ) {
  let validPositions = []
  let level = player.level
  let attempts = 0
  let radius = 6

  // 寻找安全位置
  while (validPositions.length < unit.count && attempts < 1000) {
    attempts++
    let offsetX = (Math.random() * 2 - 1) * radius
    let offsetZ = (Math.random() * 2 - 1) * radius
    let x = targetX + offsetX
    let z = targetZ + offsetZ
    let foundY = null
    // 搜索合适的Y坐标
    for (let dy = 0; dy >= -5; dy--) {
      let testY = Math.floor(targetY) + dy
      if (isValidPosition(level, x, testY, z, true)) {
        foundY = testY
        break
      }
    }
    if (foundY === null) {
      for (let dy = 1; dy <= 5; dy++) {
        let testY = Math.floor(targetY) + dy
        if (isValidPosition(level, x, testY, z, true)) {
          foundY = testY
          break
        }
      }
    }
    if (foundY !== null) {
      validPositions.push(BlockPos(x, foundY, z))
    }
  }

  if (validPositions.length < unit.count) {
    player.tell(`§c周围没有足够的空间召唤${unit.name}！`)
    return 0
  }
  // 召唤单位
  let team = player.team?.name || "default"
  let spawnedCount = 0

  for (let i = 0; i < Math.min(validPositions.length, unit.count); i++) {
    let pos = validPositions[i]
    let entity = level.createEntity(unit.entityType)

    if (!entity) continue

    entity.setPosition(pos.x + 0.5, pos.y, pos.z + 0.5)

    // 应用NBT配置
    entity.mergeNbt(unit.nbt)
    if (
      entity.type === "mowziesmobs:umvuthana_follower_player" ||
      entity.type === "mowziesmobs:umvuthana_crane_player"
    ) {
      entity.mergeNbt(`{leaderUUID:${player.uuid}}`)
    }
    if (
      entity.type === "hundred_years_war:hyw_skeleton_archer" ||
      entity.type === "hundred_years_war:mangonels" ||
      entity.type === "hundred_years_war:springald" ||
      entity.type === "hundred_years_war:nest_of_bees" ||
      entity.type === "minecraft:iron_golem" ||
      entity.type === "hundred_years_war:hyw_wither_skeleton"||
      entity.type === "dungeonnowloading:sealed_chaos"
    ) 
    {
      entity.mergeNbt(`{OwnerUUID:${player.nbt.UUID}}`)
      entity.addTag("snk_td_registered")
    }

    // 设置定时删除
    let eData = entity.persistentData
    let CDdata = eData.getCompound("CoolDownTime")
    CDdata.putInt("duration", level.time)
    eData.put("CoolDownTime", CDdata)
    entity.spawn()

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

    spawnedCount++
  }
  return spawnedCount
}

////////////////////
//援军等级
FTBQuestsEvents.customReward((event) => {
  if (event.reward.tags.contains("ally_umvuthana")) {
    let pData = event.player.persistentData
    if (!pData.getInt("ally_umvuthana")) {
      pData.putInt("ally_umvuthana", 0)
    }
    if (pData.getInt("ally_umvuthana") < 3) {
      pData.putInt("ally_umvuthana", pData.getInt("ally_umvuthana") + 1)
    }
  }
  if (event.reward.tags.contains("ally_undead")) {
    let pData = event.player.persistentData
    if (!pData.getInt("ally_undead")) {
      pData.putInt("ally_undead", 0)
    }
    if (pData.getInt("ally_undead") < 3) {
      pData.putInt("ally_undead", pData.getInt("ally_undead") + 1)
    }
  }
  if (event.reward.tags.contains("ally_siege")) {
    let pData = event.player.persistentData
    if (!pData.getInt("ally_siege")) {
      pData.putInt("ally_siege", 0)
    }
    if (pData.getInt("ally_siege") < 3) {
      pData.putInt("ally_siege", pData.getInt("ally_siege") + 1)
    }
  }
  if (event.reward.tags.contains("ally_ferrouswroughtnaut")) {
    let pData = event.player.persistentData
    if (!pData.getInt("ally_ferrouswroughtnaut")) {
      pData.putInt("ally_ferrouswroughtnaut", 0)
    }
    if (pData.getInt("ally_ferrouswroughtnaut") < 3) {
      pData.putInt("ally_ferrouswroughtnaut", pData.getInt("ally_ferrouswroughtnaut") + 1)
    }
  }
  if (event.reward.tags.contains("ally_witherskeleton")) {
    let pData = event.player.persistentData
    if (!pData.getInt("ally_witherskeleton")) {
      pData.putInt("ally_witherskeleton", 0)
    }
    if (pData.getInt("ally_witherskeleton") < 3) {
      pData.putInt("ally_witherskeleton", pData.getInt("ally_witherskeleton") + 1)
    }
  }
  if (event.reward.tags.contains("ally_collectedsouls")) {
    let pData = event.player.persistentData
    if (!pData.getInt("ally_collectedsouls")) {
      pData.putInt("ally_collectedsouls", 0)
    }
    if (pData.getInt("ally_collectedsouls") < 3) {
      pData.putInt("ally_collectedsouls", pData.getInt("ally_collectedsouls") + 1)
    }
  }
})

////////////////////
//援军降级
EntityEvents.death((event) => {
  let entity = event.entity;
  let type = entity.type;
  if (type === "mowziesmobs:umvuthi") {
    let AABB = entity.boundingBox.inflate(70, 35, 70);
    entity.level.getEntitiesWithin(AABB).forEach((player) => {
      if (player.type === "minecraft:player" && player.persistentData.getInt("ally_umvuthana")) {
        player.persistentData.remove("ally_umvuthana")
        let pName = player.name.string;
        player.server.runCommandSilent(
          `execute as ${pName} run ftbquests change_progress @s reset 7FFC68D4D335F2E1`
        )
        player.server.runCommandSilent(
          `execute as ${pName} run ftbquests change_progress @s reset 2E951991DFB68630`
        )
        player.server.runCommandSilent(
          `execute as ${pName} run ftbquests change_progress @s reset 466EDE85EF3D9D67`
        )
      }
    })
  }
})

////////////////////
//禁止与援军互动
ItemEvents.entityInteracted((event) => {
  let entity = event.target
  if (entity.persistentData.getLong("duration")) {
    event.cancel()
  }
})
