// priority: 0

//tag记录：
//登记的塔防   snk_td_registered
//登记的坐骑   snk_mount

// 姓名生成函数
function generateRandomName(gender) {
  let randomLastName = familyName[Math.floor(Math.random() * familyName.length)]
  let randomFirstName

  if (gender === "male") {
    randomFirstName = maleName[Math.floor(Math.random() * maleName.length)]
  } else {
    randomFirstName = femaleName[Math.floor(Math.random() * femaleName.length)]
  }

  if (familyNameFront) {
    return `${randomLastName}${randomFirstName}`
  } else {
    return `${randomFirstName} ${randomLastName}`
  }
}

// 函数：应用属性修饰器到士兵
function attributeModifier(mark, soldier) {
  let mData = mark.persistentData
  let Type = soldier.persistentData.getString("type")
  CAPABILITY.forEach((config) => {
    if (mData.getInt(config.prefix)) {
      // 跳过玩家专属属性
      if (config.target === "player") return
      // 检查是否指定了士兵类型且当前士兵类型不匹配
      if (config.soldierTypes && !config.soldierTypes.includes(Type)) return
      let level = mData.getInt(config.prefix)
      // 使用新的属性加成函数
      let value = config.baseValue * level
      global.AttributeEnhancement(soldier, config.Attribute, config.prefix, value, config.Operation)
    }
  })
}

// 函数：召回士兵，使用新的数据库系统
function recallSoldiers(event, player, mark, callback) {
  let mData = mark.persistentData
  let [mx, my, mz] = mData.getIntArray("soldier_pos")
  let soldierUuid = mData.getString("Resident")

  if (!soldierUuid) {
    player.tell("§c这个盔甲架没有绑定士兵")
    if (callback) callback(null)
    return
  }

  // 使用新的全局函数获取士兵
  global.GetGlobalEntity(soldierUuid, player, (soldier, usedForceLoad) => {
    if (!soldier) {
      player.tell("§c无法找到绑定的士兵")
      if (callback) callback(null)
      return
    }
    // 更新属性
    attributeModifier(mark, soldier)
    soldier.setHealth(9999)

    // 召回士兵到募兵地点并设置警戒行为
    player.server.scheduleInTicks(2, () => {
      soldier.teleportTo(mark.level.dimension.path, mx + 0.5, my + 1, mz + 0.5, 0, 0);

      // 设置士兵行为为警戒模式（原地驻守）
      let commandData = soldier.persistentData.getCompound("command")
      commandData.putInt("Behavior", 1)
      commandData.putInt("PosX", mx)
      commandData.putInt("PosY", my)
      commandData.putInt("PosZ", mz)
      soldier.persistentData.put("command", commandData)

      // 更新玩家数据库中的士兵行为记录
      let pData = player.persistentData
      let pSoldierData = pData.getCompound("soldier")
      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)

      player.tell("士兵已召回并驻守")
      if (callback) callback(soldier)
    })
  })
}

// 函数：通用招募/转职处理
function handleRecruitment(event, config) {
  let player = event.player
  let pUUID = player.nbt.UUID
  let team = player.team.name
  global.posMark(event, (mark, building) => {
    let mData = mark.persistentData
    let [mx, my, mz] = mData.getIntArray("soldier_pos")
    let oldSoldier = null

    // 转职检测

    if (mData.getString("Resident")) {
      // 使用新的召回函数
      recallSoldiers(event, player, mark, (soldier) => {
        if (!soldier) {
          player.tell(`§c这个盔甲架已经绑定了士兵，但未找到绑定的士兵`)
          player.tell(`§c士兵可能已经死亡，但盔甲架还有残留信息，正在清空……`)
          mark.persistentData.remove("Resident")
          player.tell(`§c成功清除信息，开始招募流程`)
          completeRecruitment(event, config, player, mark, mData, mx, my, mz, pUUID, team, null)
          return
        }
        if (soldier.vehicle) {
          player.tell(`§c在转职前，请先让士兵下马`)
          return
        }
        // 用tag判断职业
        let oldType = soldier.persistentData.getString("type")
        let oldConfig = Object.values(RECRUIT_CONFIGS).find(
          (cfg) => cfg.type === oldType
        )
        if (!oldConfig) {
          player.tell(`§c无法识别原士兵职业`)
          return
        }

        // occupation限制
        if (config.occupation < oldConfig.occupation) {
          player.tell(`§c只能转职为相同或更高等级兵种`)
          return
        }

        // 已注册同职业士兵，跳过代码
        if (oldType === config.type) {
          player.tell(`§c这位士兵的职业已经是${config.displayName}`)
          return
        }

        // 继续转职流程
        completeRecruitment(event, config, player, mark, mData, mx, my, mz, pUUID, team, soldier)
      })
    } else {
      // 新招募流程
      completeRecruitment(event, config, player, mark, mData, mx, my, mz, pUUID, team, null)
    }
  })
}
// 函数：完成招募或转职流程
function completeRecruitment(event, config, player, mark, mData, mx, my, mz, pUUID, team, oldSoldier) {
  // 构建成本数组
  let costs = [{ id: config.costItem, count: config.costAmount }]

  // 添加第二个费用项（如果存在）
  if (config.costItem2 && config.costAmount2) {
    costs.push({ id: config.costItem2, count: config.costAmount2 })
  }

  // 添加武器费用（如果需要）
  if (config.ProvideWeapons === true) {
    costs.push({ id: config.weapon, count: 1 })
  }

  // 使用新函数扣除物品
  if (!global.ConsumableItems(player, costs)) return

  //各职业初始加成
  mData.putInt("cb_initial_health", 1)
  mData.putInt("cb_initial_health2", 1)
  mData.putInt("cb_initial_crit_rate", 1)
  mData.putInt("cb_initial_attack", 1)
  mData.putInt("cb_initial_attack2", 1)
  mData.putInt("cb_initial_attack3", 1)
  mData.putInt("cb_initial_hunter", 1)

  let newSoldier = event.level.createEntity(config.entityId)
  let newData = newSoldier.persistentData
  newSoldier.setPosition(mx + 0.5, my + 1, mz + 0.5)

  /////////////数据库重构开始/////////////
  // 士兵数据库
  let sSoldierData = newData.getCompound("soldier")
  sSoldierData.putString("Home", mark.uuid.toString())
  sSoldierData.putInt("HomePosX", mx)
  sSoldierData.putInt("HomePosY", my + 1)
  sSoldierData.putInt("HomePosZ", mz)
  sSoldierData.putString("HomePosDim", mark.level.dimension.path)
  sSoldierData.putString("Owner", player.uuid.toString())
  sSoldierData.putInt("Occupation", config.occupation)
  sSoldierData.putString("Type", config.type)

  // 百年战争士兵命名处理
  let displayName
  let fullName
  let gender

  if (oldSoldier) {
    // 转职情况：从旧士兵数据读取姓名和性别
    let oldSoldierData = oldSoldier.persistentData.getCompound("soldier")
    fullName = oldSoldierData.getString("FullName")
    gender = oldSoldierData.getString("Gender")

    // 如果没有存储的姓名，使用当前名字（去掉职业前缀）
    if (!fullName && oldSoldier.name) {
      let oldName = oldSoldier.name.string
      // 尝试移除职业前缀格式 [职业]姓名
      let match = oldName.match(/\[.*?\](.+)/)
      fullName = match ? match[1] : oldName
    }

    // 如果还是没有，生成新的随机姓名
    if (!fullName) {
      gender = gender || (Math.random() < 0.5 ? "male" : "female")
      fullName = generateRandomName(gender)
    }

    // 如果没有性别，随机分配
    if (!gender) {
      gender = Math.random() < 0.5 ? "male" : "female"
    }

    displayName = `[${config.displayName}]${fullName}`
  } else {
    // 新招募：生成随机性别和姓名
    gender = Math.random() < 0.5 ? "male" : "female"
    fullName = generateRandomName(gender)
    displayName = `[${config.displayName}]${fullName}`
  }

  // 存储个人信息到士兵数据
  sSoldierData.putString("Gender", gender)
  sSoldierData.putString("FullName", fullName)
  sSoldierData.putString("Profession", config.type)
  sSoldierData.putString("ProfessionDisplay", config.displayName)

  newData.put("soldier", sSoldierData)

  let commandData = newData.getCompound("command")
  commandData.putInt("Behavior", 1)
  commandData.putInt("PosX", mx)
  commandData.putInt("PosY", my)
  commandData.putInt("PosZ", mz)
  newData.put("command", commandData)

  // 玩家数据库
  let pData = player.persistentData
  let pSoldierData = pData.getCompound("soldier")
  let newUuid = newSoldier.uuid.toString()
  let newUuidData = pSoldierData.getCompound(newUuid)
  newUuidData.putString("uuid", newUuid)
  newUuidData.putInt("Behavior", 1) // 记录行为模式
  pSoldierData.put(newUuid, newUuidData)
  pData.put("soldier", pSoldierData)

  // 盔甲架数据库
  mData.putString("Resident", newSoldier.uuid.toString())
  if (!mData.getString("Owner")) {
    mData.putString("Owner", player.uuid.toString())
  }
  /////////////数据库重构结束/////////////
  newSoldier.spawn()

  newData.putString("pUuid", player.uuid.toString())
  newData.putString("type", config.type)
  if (config.entityId != "hundred_years_war:priest") {
    newData.putString(`team`, `${team}`)
  }

  // 转职士兵
  if (oldSoldier) {
    let sNbt = oldSoldier.nbt
    let sName = oldSoldier.name.string
    //复制旧士兵数据到新士兵
    newSoldier.mergeNbt({
      OwnerUUID: pUUID,
      Skin: sNbt.Skin,
      ArmorItems: sNbt.ArmorItems,
      MaxHealth: sNbt.MaxHealth,
      AttackDamage: sNbt.AttackDamage,
      Level: sNbt.Level,
      ExperiencePoints: sNbt.ExperiencePoints,
    })
    //如果有重命名则复制名字
    if (sNbt.CustomName) {
      newSoldier.mergeNbt({ CustomName: sNbt.CustomName })
    }
    // 删除旧士兵
    oldSoldier.mergeNbt({ Health: 0, DeathTime: 19 })
    player.tell(`${sName}已转职为${config.displayName}！`)
    // 召唤士兵
  } else {
    newSoldier.mergeNbt({ OwnerUUID: pUUID })
  }

  // 设置实体名称（百年战争士兵命名）
  newSoldier.setCustomName(Component.of(displayName))

  // 使用BehaviorTranslation设置原地驻守行为
  global.BehaviorTranslation(newSoldier, player)

  // 复制装备
  global.weaponUtils.syncEquipment(mark, newSoldier)

  // 加入玩家团队
  if (config.entityId != "hundred_years_war:priest") {
    event.server.runCommandSilent(`execute as ${newSoldier.uuid} run team join ${team} @s`)
  }

  // 完成标签
  if (!oldSoldier) {
    player.tell(`${config.displayName}已应召入伍！`)
  }

  // 应用属性修饰
  attributeModifier(mark, newSoldier)
  newSoldier.setHealth(9999)
}

//遍历
FTBQuestsEvents.customReward(event => {
  Object.keys(RECRUIT_CONFIGS).forEach((type) => {
    if (event.reward.tags.contains(type)) {
      handleRecruitment(event, RECRUIT_CONFIGS[type])
    }
  })
})

//同步属性功能
FTBQuestsEvents.customReward(event => {
  let player = event.player
  if (!event.reward.tags.contains("snk_synchronous")) return
  global.posMark(event, (mark, building) => {
    let mData = mark.persistentData
    if (!mData.getString("Resident")) return
    let soldierUuid = mData.getString("Resident")
    if (!soldierUuid) {
      player.tell(`§c这个盔甲架没有绑定士兵`)
      return
    }
    // 直接获取士兵并应用属性
    global.GetGlobalEntity(soldierUuid, player, (soldier, usedForceLoad) => {
      if (soldier) {
        attributeModifier(mark, soldier)
        soldier.setHealth(9999)
        player.tell(`属性已同步`)
      } else {
        player.tell(`未找到士兵`)
      }
    })
  })
})

//再登记功能
FTBQuestsEvents.customReward((event) => {
  if (!event.reward.tags.contains("snk_redo")) return
  let player = event.player
  let pData = player.persistentData
  let pUUID = player.uuid.toString()
  let legion = pData.getInt("legion") || 1
  global.posMark(event, (mark, building) => {

    let mData = mark.persistentData
    let [mx, my, mz] = mData.getIntArray("soldier_pos")
    let sAABB = mark.boundingBox.inflate(50, 10, 50)
    let dimension = mark.level.dimension.path

    mark.level.getEntitiesWithin(sAABB).forEach((soldier) => {
      if (mData.getString("Resident")) return
      if (soldier.type === "guardvillagers:guard") return

      // 使用新数据库判定条件：检查士兵是否有Owner且没有home数据
      let sData = soldier.persistentData
      let soldierData = sData.getCompound("soldier")
      let soldierOwner = soldierData.getString("Owner")
      let hasHomeData = soldierData.contains("Home") && soldierData.getString("Home") !== ""
      let legionCompound = soldierData.getCompound("Legion")
      if (legionCompound.getBoolean(`Legion_${legion}`)) {
        // 检查是否属于该玩家且没有home数据（未注册状态）
        if (soldierOwner === pUUID && !hasHomeData) {
          soldier.teleportTo(dimension, mx + 0.5, my + 1, mz + 0.5, 0, 0)

          // 更新士兵数据库
          soldierData.putString("Home", mark.uuid.toString())
          soldierData.putInt("HomePosX", mx)
          soldierData.putInt("HomePosY", my + 1)
          soldierData.putInt("HomePosZ", mz)
          soldierData.putString("HomePosDim", dimension)
          sData.put("soldier", soldierData)

          // 更新士兵命令数据
          let commandData = sData.getCompound("command")
          commandData.putInt("Behavior", 1) // 警戒模式
          commandData.putInt("PosX", mx)
          commandData.putInt("PosY", my)
          commandData.putInt("PosZ", mz)
          sData.put("command", commandData)

          // 更新玩家数据库
          let pData = player.persistentData
          let pSoldierData = pData.getCompound("soldier")
          let sUuid = soldier.uuid.toString()
          let sUuidData = pSoldierData.getCompound(sUuid)
          sUuidData.putString("uuid", sUuid)
          sUuidData.putInt("Behavior", 1) // 记录行为模式
          pSoldierData.put(sUuid, sUuidData)
          pData.put("soldier", pSoldierData)

          // 更新盔甲架数据库
          mData.putString("Resident", sUuid)

          player.tell(`${soldier.name.string}已重新登记`)

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

          // 应用属性修饰
          attributeModifier(mark, soldier)
          soldier.setHealth(9999)
          global.weaponUtils.syncEquipment(mark, soldier)
        }
      }
    })
  })
})

FTBQuestsEvents.customReward(event => {
  if (!event.reward.tags.contains("snk_recall")) return
  let player = event.player
  global.posMark(event, (mark, building) => {
    let mData = mark.persistentData
    if (mData.getString("Resident")) {
      recallSoldiers(event, player, mark)
    }
  })
})