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 structureRows = withStockCounts(
  [
    { key: "adultCow", name: "成年母牛", ratio: 47, source: "专家共识模型" },
    { key: "otherAdult", name: "其他成年牛", ratio: 22, source: "专家共识模型" },
    { key: "calf", name: "幼畜（≤1岁）", ratio: 16, source: "专家共识模型" },
    { key: "yearling", name: "育成牛（1-2岁）", ratio: 11, source: "专家共识模型" },
    { key: "bull", name: "公牛", ratio: 4, source: "专家共识模型" },
  ],
  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: { adultCow: 47, otherAdult: 22, calf: 16, yearling: 11, bull: 4 },
  },
  {
    key: "2027",
    label: "2027年底",
    shortLabel: "2027",
    months: 19,
    stock: 468920,
    births: 67420,
    outflow: 55180,
    correction: -1550,
    structure: { adultCow: 47, otherAdult: 21, calf: 17, yearling: 11, bull: 4 },
  },
  {
    key: "2028",
    label: "2028年底",
    shortLabel: "2028",
    months: 31,
    stock: 475360,
    births: 109680,
    outflow: 90140,
    correction: -2410,
    structure: { adultCow: 46, otherAdult: 22, calf: 17, yearling: 11, bull: 4 },
  },
]

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 || {}
  const rows = [
    { key: "adultCow", name: "成年母牛", ratio: ratios.adultCow ?? 47 },
    { key: "otherAdult", name: "其他成年牛", ratio: ratios.otherAdult ?? 22 },
    { key: "calf", name: "幼畜（≤1岁）", ratio: ratios.calf ?? 16 },
    { key: "yearling", name: "育成牛（1-2岁）", ratio: ratios.yearling ?? 11 },
    { key: "bull", name: "公牛", ratio: ratios.bull ?? 4 },
  ].map((item) => ({
    ...item,
    count: Math.round((period.stock * item.ratio) / 100),
    source: "预测模型",
  }))
  const delta = period.stock - rows.reduce((sum, item) => sum + item.count, 0)
  if (delta && rows[1]) rows[1].count += delta
  return rows
}

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 nextRows = rows.map((item) => ({
    ...item,
    count: Math.round((total * item.ratio) / 100),
  }))
  const delta = total - nextRows.reduce((sum, item) => sum + item.count, 0)
  if (delta && nextRows[1]) nextRows[1].count += delta
  return nextRows
}

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)
}
