import {
  townRecognitionRows,
  tradeImpactRows as baseTradeImpactRows,
  YAK_DRONE_RECOGNITION_TOTAL,
  YAK_EXPERT_CORRECTION,
  YAK_STOCK_TOTAL,
  yakForecastRows,
} from "@/views/gdMap/livestockData"

export {
  YAK_STOCK_TOTAL,
  yakForecastRows,
}

export const recognitionTotal = YAK_DRONE_RECOGNITION_TOTAL
export const expertCorrection = YAK_EXPERT_CORRECTION
export const tradeDeduction = 0
export const estimatedStock = YAK_STOCK_TOTAL

export function canonicalTownName(name) {
  return name
}

export function scaleTownRowsToTotal(rows = [], total = YAK_STOCK_TOTAL) {
  const sourceRows = rows
    .map((item) => ({
      ...item,
      name: canonicalTownName(item.name || item.label || item.town || ""),
      count: Number(item.count ?? item.value ?? item.total ?? 0),
    }))
    .filter((item) => item.name && Number.isFinite(item.count) && item.count >= 0)
  const sourceTotal = sourceRows.reduce((sum, item) => sum + item.count, 0)
  if (!sourceTotal || !total) return sourceRows.map((item) => ({ ...item, count: 0 }))
  const scaledRows = sourceRows.map((item) => ({
    ...item,
    count: Math.round((item.count / sourceTotal) * total),
  }))
  const delta = total - scaledRows.reduce((sum, item) => sum + item.count, 0)
  if (delta && scaledRows[0]) scaledRows[0].count += delta
  return scaledRows
}

export const townRows = scaleTownRowsToTotal(townRecognitionRows, estimatedStock)
  .sort((a, b) => b.count - a.count)

export const yakStructureBaselineRows = [
  { key: "fertileCow", name: "适龄能繁母牛", ratio: 45, source: "畜群结构比例表" },
  { key: "meatBull", name: "肉公牛", ratio: 15, source: "畜群结构比例表" },
  { key: "breedingBull", name: "种公牛", ratio: 3, source: "畜群结构比例表" },
  { key: "femaleCalf", name: "母犊牛", ratio: 15, source: "畜群结构比例表" },
  { key: "maleCalf", name: "公犊牛", ratio: 15, source: "畜群结构比例表" },
  { key: "overageCow", name: "过龄能繁母牛", ratio: 7, source: "畜群结构比例表" },
]

export const yakStructureRatioRows = [
  { key: "fertileCow", name: "适龄能繁母牛", ratio: 44.8, source: "畜群结构比例表" },
  { key: "meatBull", name: "肉公牛", ratio: 15.2, source: "畜群结构比例表" },
  { key: "breedingBull", name: "种公牛", ratio: 3.1, source: "畜群结构比例表" },
  { key: "femaleCalf", name: "母犊牛", ratio: 14.9, source: "畜群结构比例表" },
  { key: "maleCalf", name: "公犊牛", ratio: 15.1, source: "畜群结构比例表" },
  { key: "overageCow", name: "过龄能繁母牛", ratio: 6.9, source: "畜群结构比例表" },
]

export const structureRows = withStockCounts(yakStructureRatioRows, estimatedStock)

export const tradeImpactRows = baseTradeImpactRows.map((item, index) => ({
  ...item,
  color: ["#ff8f6b", "#30dcff", "#ffd76c", "#7aa7ff"][index % 4],
}))

export const genderAgeRows = [
  { age: "≤1岁", cow: 38586, bull: 40861 },
  { age: "1-2岁", cow: 27124, bull: 27549 },
  { age: "2-4岁", cow: 93355, bull: 49265 },
  { age: "4-8岁", cow: 106679, bull: 32655 },
  { age: "8岁以上", cow: 28671, bull: 13485 },
]

export const forecastPeriods = [
  {
    key: "2026",
    label: "2026年底",
    shortLabel: "2026",
    months: 7,
    stock: 462850,
    births: 24680,
    outflow: 19020,
    correction: -1040,
    structure: { fertileCow: 45.1, meatBull: 15, breedingBull: 3, femaleCalf: 15.2, maleCalf: 14.9, overageCow: 6.8 },
  },
  {
    key: "2027",
    label: "2027年底",
    shortLabel: "2027",
    months: 19,
    stock: 468920,
    births: 67420,
    outflow: 55180,
    correction: -1550,
    structure: { fertileCow: 45.5, meatBull: 14.8, breedingBull: 3.1, femaleCalf: 15.1, maleCalf: 14.8, overageCow: 6.7 },
  },
  {
    key: "2028",
    label: "2028年底",
    shortLabel: "2028",
    months: 31,
    stock: 475360,
    births: 109680,
    outflow: 90140,
    correction: -2410,
    structure: { fertileCow: 45.9, meatBull: 14.5, breedingBull: 3.1, femaleCalf: 15.3, maleCalf: 14.7, overageCow: 6.5 },
  },
]

export const forecastFactorRows = [
  { name: "繁殖补充", value: 86 },
  { name: "出栏周转", value: 62 },
  { name: "死亡淘汰", value: 48 },
  { name: "母牛基础", value: 91 },
  { name: "幼畜存活", value: 73 },
]

export function getForecastPeriod(key) {
  return forecastPeriods.find((item) => item.key === key) || forecastPeriods[1]
}

export function getForecastStructureRows(period) {
  const ratios = period?.structure || {}
  return withStockCounts(yakStructureBaselineRows.map((item) => ({
    ...item,
    ratio: ratios[item.key] ?? item.ratio,
    source: "预测模型",
  })), period.stock)
}

export function getTownForecastRows(period) {
  const scale = period.stock / estimatedStock
  const rows = townRows.map((item, index) => ({
    ...item,
    forecast: Math.round(item.count * scale + (index % 3 - 1) * period.months * 18),
  }))
  const delta = period.stock - rows.reduce((sum, item) => sum + item.forecast, 0)
  if (delta) {
    const target = rows.reduce((prev, item) => (item.count > prev.count ? item : prev), rows[0])
    target.forecast += delta
  }
  return rows
    .map((item) => ({
      ...item,
      change: item.forecast - item.count,
    }))
    .sort((a, b) => b.forecast - a.forecast)
}

export function buildForecastSeries(period) {
  const count = period.months + 1
  const labels = Array.from({ length: count }, (_, index) => {
    if (index === 0) return "2026-06"
    if (index === period.months) return period.label
    return `+${index}月`
  })
  const stock = labels.map((_, index) => {
    const ratio = index / period.months
    const seasonal = Math.sin(index / 2.6) * Math.sin(Math.PI * ratio) * Math.min(360, period.months * 18)
    return Math.round(estimatedStock + (period.stock - estimatedStock) * ratio + seasonal)
  })
  const births = labels.map((_, index) => Math.round((period.births / period.months) * index))
  const outflow = labels.map((_, index) => Math.round((period.outflow / period.months) * index))
  return { labels, stock, births, outflow }
}

function withStockCounts(rows, total) {
  const baseRows = rows.map((item, index) => {
    const exact = (total * item.ratio) / 100
    return {
      ...item,
      index,
      exact,
      count: Math.floor(exact),
      remainder: exact - Math.floor(exact),
    }
  })
  let delta = total - baseRows.reduce((sum, item) => sum + item.count, 0)
  baseRows
    .slice()
    .sort((a, b) => b.remainder - a.remainder || a.index - b.index)
    .forEach((item) => {
      if (delta <= 0) return
      item.count += 1
      delta -= 1
    })
  return baseRows.map(({ index, exact, remainder, ...item }) => ({
    ...item,
    count: Math.round(item.count),
  }))
}

export function aggregateTownRows(rows) {
  const map = new Map()
  rows.forEach((row) => {
    const name = canonicalTownName(row.name)
    const current = map.get(name) || { name, count: 0 }
    current.count += Number(row.count || 0)
    map.set(name, current)
  })
  return [...map.values()].sort((a, b) => b.count - a.count)
}
