import { hongyuanTownshipDisplayOrder } from "@/config/townshipBoundaries"
import { getRiskLevel } from "@/views/grassLivestockBalance/data"
import { NATIONAL_PARK_ZONING_COLORS } from "@/config/layers"

const toWanMu = (mu) => Number((Number(mu || 0) / 10000).toFixed(2))
const sumBy = (rows, field) => rows.reduce((sum, item) => sum + Number(item[field] || 0), 0)
const round = (value, digits = 2) => Number(Number(value || 0).toFixed(digits))

const restorationSummary = {
  kpi: {
    projectCount: 22,
    featureCount: 29280,
    subjectFeatureCount: 1478,
    controlPointCount: 27802,
    areaWanMu: 175.3693,
    lengthKm: 1250.62,
    townshipCount: 10,
  },
  categories: [
    { name: "草地修复", subjectFeatureCount: 1067, areaWanMu: 168.0339, lengthKm: 1238.18, projectCount: 13 },
    { name: "林地修复", subjectFeatureCount: 244, areaWanMu: 7.3354, lengthKm: 0, projectCount: 6 },
    { name: "湿地修复", subjectFeatureCount: 167, areaWanMu: 0, lengthKm: 12.44, projectCount: 3 },
  ],
  measures: [
    { name: "草原改良", subjectFeatureCount: 285, areaWanMu: 84.2792, lengthKm: 467.5, projectCount: 8 },
    { name: "人工种草", subjectFeatureCount: 532, areaWanMu: 29.1561, lengthKm: 0, projectCount: 13 },
    { name: "封育治理", subjectFeatureCount: 45, areaWanMu: 21.2487, lengthKm: 0, projectCount: 1 },
    { name: "围栏建设", subjectFeatureCount: 223, areaWanMu: 19.4235, lengthKm: 660.88, projectCount: 9 },
    { name: "林草碳汇试点", subjectFeatureCount: 11, areaWanMu: 12.5759, lengthKm: 0, projectCount: 1 },
    { name: "水源涵养", subjectFeatureCount: 82, areaWanMu: 5.6993, lengthKm: 0, projectCount: 1 },
    { name: "人工种草/补播", subjectFeatureCount: 46, areaWanMu: 2.8162, lengthKm: 0, projectCount: 4 },
    { name: "防风固沙林", subjectFeatureCount: 6, areaWanMu: 0.1303, lengthKm: 0, projectCount: 1 },
    { name: "草种繁育", subjectFeatureCount: 4, areaWanMu: 0.04, lengthKm: 0, projectCount: 1 },
    { name: "种草围栏", subjectFeatureCount: 77, areaWanMu: 0, lengthKm: 109.81, projectCount: 1 },
    { name: "小型坝", subjectFeatureCount: 8, areaWanMu: 0, lengthKm: 8.83, projectCount: 1 },
    { name: "微型坝", subjectFeatureCount: 159, areaWanMu: 0, lengthKm: 3.61, projectCount: 2 },
  ],
  years: [
    { name: 2017, areaWanMu: 0.1412, lengthKm: 0, projectCount: 1 },
    { name: 2018, areaWanMu: 0.5608, lengthKm: 0, projectCount: 1 },
    { name: 2019, areaWanMu: 12.513, lengthKm: 0, projectCount: 1 },
    { name: 2020, areaWanMu: 35.9848, lengthKm: 0, projectCount: 2 },
    { name: 2021, areaWanMu: 25.0755, lengthKm: 467.5, projectCount: 5 },
    { name: 2022, areaWanMu: 72.024, lengthKm: 656.05, projectCount: 8 },
    { name: 2023, areaWanMu: 29.07, lengthKm: 114.64, projectCount: 3 },
    { name: "未知", areaWanMu: 0, lengthKm: 12.44, projectCount: 2 },
  ],
  townships: [
    { name: "麦洼乡", areaWanMu: 28.5019, lengthKm: 84.28, projectCount: 3 },
    { name: "龙日镇", areaWanMu: 15.8472, lengthKm: 46.05, projectCount: 2 },
    { name: "安曲镇", areaWanMu: 13.1168, lengthKm: 0, projectCount: 2 },
    { name: "瓦切镇", areaWanMu: 6.6824, lengthKm: 214.41, projectCount: 4 },
    { name: "色地镇", areaWanMu: 6.344, lengthKm: 101.25, projectCount: 3 },
    { name: "刷经寺镇", areaWanMu: 5.6528, lengthKm: 126.26, projectCount: 1 },
    { name: "邛溪镇", areaWanMu: 2.3127, lengthKm: 101.39, projectCount: 4 },
    { name: "阿木乡", areaWanMu: 1.34, lengthKm: 59.5, projectCount: 2 },
    { name: "查尔玛乡", areaWanMu: 0.7001, lengthKm: 37.56, projectCount: 1 },
  ],
  projects: [
    {
      projectName: "阿坝州红原县2020年退牧还草工程项目",
      projectCategory: "草地修复",
      year: 2020,
      areaWanMu: 35.6232,
      lengthKm: 0,
      measureTypes: ["人工种草", "围栏建设"],
      townships: [],
      subjectFeatureCount: 73,
    },
    {
      projectName: "四川省阿坝州若尔盖草原湿地水源涵养生态保护和修复项目(红原县部分)-2022年",
      projectCategory: "草地修复",
      year: 2022,
      areaWanMu: 21.5,
      lengthKm: 172.31,
      measureTypes: ["人工种草", "围栏建设", "种草围栏", "草原改良"],
      townships: ["刷经寺镇", "龙日镇"],
      subjectFeatureCount: 273,
    },
    {
      projectName: "阿坝州红原县 2022 年第二批重点生态保护和修护治理项目-草原封育治理-700",
      projectCategory: "草地修复",
      year: 2022,
      areaWanMu: 21.2487,
      lengthKm: 272.25,
      measureTypes: ["围栏建设", "封育治理"],
      townships: ["瓦切镇", "色地镇", "邛溪镇"],
      subjectFeatureCount: 90,
    },
    {
      projectName: "四川省阿坝州 2023 年中央财政林业草原改革发展资金预算（第三批）——红原县草原生态修复项目",
      projectCategory: "草地修复",
      year: 2023,
      areaWanMu: 18.79,
      lengthKm: 32.32,
      measureTypes: ["人工种草", "围栏建设", "草原改良", "草种繁育"],
      townships: ["瓦切镇", "麦洼乡"],
      subjectFeatureCount: 102,
    },
    {
      projectName: "阿坝州红原县2022年第二批重点生态保护和修护治理——红原县林草碳汇创新开发建设试点项目",
      projectCategory: "草地修复",
      year: 2022,
      areaWanMu: 12.5759,
      lengthKm: 0,
      measureTypes: ["林草碳汇试点"],
      townships: ["安曲镇"],
      subjectFeatureCount: 11,
    },
    {
      projectName: "四川省红原县2019年草原生态修复治理项目退化草地治理和天然草原改良",
      projectCategory: "草地修复",
      year: 2019,
      areaWanMu: 12.513,
      lengthKm: 0,
      measureTypes: ["人工种草/补播", "草原改良"],
      townships: [],
      subjectFeatureCount: 25,
    },
    {
      projectName: "阿坝州红原县2021年若尔盖—甘南草原湿地生态保护和修复项目-1880",
      projectCategory: "草地修复",
      year: 2021,
      areaWanMu: 11.0031,
      lengthKm: 467.5,
      measureTypes: ["人工种草", "草原改良"],
      townships: [],
      subjectFeatureCount: 229,
    },
    {
      projectName: "2023 年度四川省阿坝州若尔盖草原湿地水源涵养生态保护和修复项目(红原县部分）-1315",
      projectCategory: "草地修复",
      year: 2023,
      areaWanMu: 10.28,
      lengthKm: 82.32,
      measureTypes: ["人工种草", "围栏建设", "草原改良"],
      townships: ["查尔玛乡", "麦洼乡"],
      subjectFeatureCount: 50,
    },
    {
      projectName: "阿坝州红原县 2022 年中央财政林业草原生态保护恢复（第二批）——草原生态修复治理补助项目-1972",
      projectCategory: "草地修复",
      year: 2022,
      areaWanMu: 8.2,
      lengthKm: 113.37,
      measureTypes: ["围栏建设", "草原改良", "人工种草"],
      townships: ["色地镇", "邛溪镇", "阿木乡"],
      subjectFeatureCount: 127,
    },
    {
      projectName: "阿坝州红原县2021年省级草原生态保护恢复项目-1790",
      projectCategory: "草地修复",
      year: 2021,
      areaWanMu: 7,
      lengthKm: 0,
      measureTypes: ["人工种草", "草原改良"],
      townships: [],
      subjectFeatureCount: 16,
    },
    {
      projectName: "阿坝州红原县 2021 年中央财政林业草原生态保护恢复项目-984",
      projectCategory: "草地修复",
      year: 2021,
      areaWanMu: 6.5,
      lengthKm: 0,
      measureTypes: ["草原改良", "人工种草"],
      townships: [],
      subjectFeatureCount: 14,
    },
    {
      projectName: "红原县2022年度黄河上游水源涵养补给区综合治理项目实施方案（代作业设计）变更后最终版",
      projectCategory: "林地修复",
      year: 2022,
      areaWanMu: 5.6993,
      lengthKm: 0,
      measureTypes: ["水源涵养"],
      townships: ["安曲镇", "瓦切镇"],
      subjectFeatureCount: 82,
    },
    {
      projectName: "阿坝州红原县 2022 年第二批重点生态保护和修护治理——草原生态修复治理项目-1500",
      projectCategory: "草地修复",
      year: 2022,
      areaWanMu: 2,
      lengthKm: 81.05,
      measureTypes: ["人工种草", "围栏建设"],
      townships: ["瓦切镇", "色地镇", "麦洼乡"],
      subjectFeatureCount: 53,
    },
    {
      projectName: "阿坝州红原县 2022 年省级林业草原生态保护恢复——草原生态修复治理补助项目-888",
      projectCategory: "草地修复",
      year: 2022,
      areaWanMu: 0.8,
      lengthKm: 17.07,
      measureTypes: ["人工种草", "围栏建设"],
      townships: ["阿木乡"],
      subjectFeatureCount: 4,
    },
    {
      projectName: "红原县2018年川西高原生态脆弱区综合治理项目",
      projectCategory: "林地修复",
      year: 2018,
      areaWanMu: 0.5608,
      lengthKm: 0,
      measureTypes: ["人工种草", "人工种草/补播"],
      townships: [],
      subjectFeatureCount: 107,
    },
    {
      projectName: "红原县2021年黄河上游水源涵养补给区生态综合治理项目",
      projectCategory: "林地修复",
      year: 2021,
      areaWanMu: 0.5224,
      lengthKm: 0,
      measureTypes: ["人工种草/补播"],
      townships: ["邛溪镇"],
      subjectFeatureCount: 14,
    },
    {
      projectName: "红原县2020年川西高原生态脆弱区综合治理项目",
      projectCategory: "林地修复",
      year: 2020,
      areaWanMu: 0.3617,
      lengthKm: 0,
      measureTypes: ["人工种草", "人工种草/补播"],
      townships: [],
      subjectFeatureCount: 31,
    },
    {
      projectName: "2017年川西高原生态脆弱区综合治理项目",
      projectCategory: "林地修复",
      year: 2017,
      areaWanMu: 0.1412,
      lengthKm: 0,
      measureTypes: ["人工种草", "防风固沙林"],
      townships: ["邛溪镇"],
      subjectFeatureCount: 8,
    },
    {
      projectName: "红原县2021年人工造林封山育林项目",
      projectCategory: "林地修复",
      year: 2021,
      areaWanMu: 0.05,
      lengthKm: 0,
      measureTypes: ["围栏建设"],
      townships: [],
      subjectFeatureCount: 2,
    },
    {
      projectName: "4980小型坝(1)(1)",
      projectCategory: "湿地修复",
      year: "未知",
      areaWanMu: 0,
      lengthKm: 8.83,
      measureTypes: ["小型坝"],
      townships: [],
      subjectFeatureCount: 8,
    },
    {
      projectName: "红原县蓄水保湿工程-小型坝和微型坝(1)(1)",
      projectCategory: "湿地修复",
      year: 2023,
      areaWanMu: 0,
      lengthKm: 3.61,
      measureTypes: ["微型坝"],
      townships: [],
      subjectFeatureCount: 59,
    },
    {
      projectName: "4980微型坝成型(1)(1)",
      projectCategory: "湿地修复",
      year: 2022,
      areaWanMu: 0,
      lengthKm: 0,
      measureTypes: ["微型坝"],
      townships: [],
      subjectFeatureCount: 100,
    },
  ],
}

export const ecologicalProtectionMenu = [
  { key: "national-park", label: "若尔盖国家公园", bottomLabel: "若尔盖国家公园" },
  { key: "restoration", label: "生态修复工程", bottomLabel: "生态修复工程" },
  { key: "engineering-analysis", label: "工程分析", bottomLabel: "工程分析" },
]

export const parkTownRows = [
  { name: "瓦切镇", protectedAreaWanMu: 75.01, coreProtectionAreaWanMu: 31.65, generalControlAreaWanMu: 43.36, grasslandAreaWanMu: 32.07, wetlandAreaWanMu: 11.73, ecologyJobs: 160, householdCount: 1400, peopleCount: 6375, yakCount: 43459, livestockCount: 45260, cover: 85, villages: "唐日村、德香村、日干村、色永村、曲登塘社区" },
  { name: "麦洼乡", protectedAreaWanMu: 66.61, coreProtectionAreaWanMu: 28.1, generalControlAreaWanMu: 38.51, grasslandAreaWanMu: 19.66, wetlandAreaWanMu: 6.52, ecologyJobs: 179, householdCount: 1049, peopleCount: 4857, yakCount: 35773, livestockCount: 36776, cover: 85, villages: "洞拉村、滚塘村" },
  { name: "色地镇", protectedAreaWanMu: 20.98, coreProtectionAreaWanMu: 8.85, generalControlAreaWanMu: 12.13, grasslandAreaWanMu: 42.52, wetlandAreaWanMu: 15.22, ecologyJobs: 39, householdCount: 405, peopleCount: 1692, yakCount: 25947, livestockCount: 26731, cover: 86, villages: "让里村、茸塔玛村" },
]

export const parkSummary = {
  name: "若尔盖国家公园红原区域",
  nationalParkTotalAreaWanMu: 1250.4,
  hongyuanDelimitedAreaWanMu: 162.55,
  totalAreaWanMu: 162.55,
  grasslandAreaWanMu: 94.25,
  wetlandAreaWanMu: 33.47,
  woodlandAreaWanMu: null,
  woodlandDataStatus: "待接入",
  vegetationCoverage: round(sumBy(parkTownRows, "cover") / parkTownRows.length, 1),
  townCount: parkTownRows.length,
  villageCount: parkTownRows.reduce((sum, item) => sum + String(item.villages || "").split("、").filter(Boolean).length, 0),
  householdCount: sumBy(parkTownRows, "householdCount"),
  peopleCount: sumBy(parkTownRows, "peopleCount"),
  ecologyJobCount: sumBy(parkTownRows, "ecologyJobs"),
  yakCount: sumBy(parkTownRows, "yakCount"),
  livestockCount: sumBy(parkTownRows, "livestockCount"),
}
parkSummary.otherProtectedAreaWanMu = round(
  parkSummary.totalAreaWanMu - parkSummary.grasslandAreaWanMu - parkSummary.wetlandAreaWanMu,
  2
)

export const parkCoreRows = [
  { key: "park-national-area", name: "四川片区面积", value: parkSummary.nationalParkTotalAreaWanMu, unit: "万亩", icon: "park" },
  { key: "park-hongyuan-area", name: "红原县划定面积", value: parkSummary.hongyuanDelimitedAreaWanMu, unit: "万亩", icon: "park" },
  { key: "park-yak-count", name: "牦牛数量", value: parkSummary.yakCount, unit: "头", icon: "stack" },
]

const parkResourceStructureRows = [
  { key: "grassland", name: "草地面积", value: parkSummary.grasslandAreaWanMu, unit: "万亩" },
  { key: "wetland", name: "湿地面积", value: parkSummary.wetlandAreaWanMu, unit: "万亩" },
  { key: "other-range", name: "其他保护范围", value: parkSummary.otherProtectedAreaWanMu, unit: "万亩" },
]

const parkTownResourceRows = parkTownRows.map((item) => ({
  key: item.name,
  name: item.name,
  value: round(item.grasslandAreaWanMu + item.wetlandAreaWanMu, 2),
  unit: "万亩",
  extra: `草地 ${item.grasslandAreaWanMu} / 湿地 ${item.wetlandAreaWanMu}`,
}))

const parkTownListRows = parkTownRows.map((item) => ({
  key: `${item.name}-town`,
  name: item.name,
  value: round(item.grasslandAreaWanMu + item.wetlandAreaWanMu, 2),
  unit: "万亩",
  extra: item.villages,
}))

const parkZoningRows = [
  { key: "core-protection", name: "核心保护区", value: 68.6, unit: "万亩", color: NATIONAL_PARK_ZONING_COLORS.core.fillColor },
  { key: "general-control", name: "一般控制区", value: 94, unit: "万亩", color: NATIONAL_PARK_ZONING_COLORS.general.fillColor },
]

const parkGrasslandProductivityWanTon = 43.66
const parkWetlandProductivityWanTon = 12.48
const parkEdibleGrasslandWanTon = round(parkGrasslandProductivityWanTon * (192.26 / 297.29), 2)
const parkGrasslandCapacityPerMu = 0.06229833103624831
const parkBalanceTownRowMap = new Map([
  ["瓦切镇", { areaRange: 750120, yakNumber: 43459, bearingCapacity: 44927.54, livestockCapacity: 45260, overloadRate: 0.74, year: "2026" }],
  ["麦洼乡", { areaRange: 666075, yakNumber: 35773, bearingCapacity: 36505.86, livestockCapacity: 36776, overloadRate: 0.74, year: "2026" }],
  ["色地镇", { areaRange: 209805, yakNumber: 25947, bearingCapacity: 26534.58, livestockCapacity: 26731, overloadRate: 0.74, year: "2026" }],
])
const parkVillageWeights = {
  麦洼乡: [
    { name: "洞拉村", grassland: 0.632, wetland: 0.632, household: 0.5643, yak: 0.545, edible: 0.632, woodland: 0.632 },
    { name: "滚塘村", grassland: 0.368, wetland: 0.368, household: 0.4357, yak: 0.455, edible: 0.368, woodland: 0.368 },
  ],
  瓦切镇: [
    { name: "唐日村", grassland: 0.3059, wetland: 0.3059, household: 0.1957, yak: 0.2843, edible: 0.3059, woodland: 0.3059 },
    { name: "德香村", grassland: 0.2369, wetland: 0.2369, household: 0.2679, yak: 0.2848, edible: 0.2369, woodland: 0.2369 },
    { name: "日干村", grassland: 0.1603, wetland: 0.1603, household: 0.2071, yak: 0.2107, edible: 0.1603, woodland: 0.1603 },
    { name: "色永村", grassland: 0.2969, wetland: 0.2969, household: 0.2607, yak: 0.2202, edible: 0.2969, woodland: 0.2969 },
    { name: "曲登塘社区", grassland: 0, wetland: 0, household: 0.0679, yak: 0, edible: 0, woodland: 0 },
  ],
  色地镇: [
    { name: "让里村", grassland: 0.4623, wetland: 0.4623, household: 0.7309, yak: 0.6411, edible: 0.4623, woodland: 0.4623 },
    { name: "茸塔玛村", grassland: 0.5377, wetland: 0.5377, household: 0.2691, yak: 0.3589, edible: 0.5377, woodland: 0.5377 },
  ],
}
const parkTownBusinessRows = parkTownRows.map((item) => ({
  ...item,
  value: item.protectedAreaWanMu,
  unit: "万亩",
  segments: {
    core: item.coreProtectionAreaWanMu,
    general: item.generalControlAreaWanMu,
  },
  householdCount: Number(item.householdCount || 0),
  edibleGrasslandWanTon: round(
    (Number(item.grasslandAreaWanMu || 0) / Math.max(parkSummary.grasslandAreaWanMu, 1)) * parkEdibleGrasslandWanTon,
    2
  ),
}))
const parkHouseholdDelta = parkSummary.householdCount - sumBy(parkTownBusinessRows, "householdCount")
if (parkHouseholdDelta && parkTownBusinessRows[0]) {
  parkTownBusinessRows[0].householdCount += parkHouseholdDelta
}
parkTownBusinessRows.forEach((item) => {
  const balanceRow = parkBalanceTownRowMap.get(item.name)
  const bearingCapacity = Number(balanceRow?.bearingCapacity) || round(Number(item.grasslandAreaWanMu || 0) * 10000 * parkGrasslandCapacityPerMu, 0)
  const livestockCapacity = Number(balanceRow?.livestockCapacity) || Number(item.livestockCount || item.yakCount || 0)
  const overloadRate = Number.isFinite(Number(balanceRow?.overloadRate))
    ? Number(balanceRow.overloadRate)
    : bearingCapacity
      ? round(((livestockCapacity - bearingCapacity) / bearingCapacity) * 100, 1)
      : 0
  const risk = getRiskLevel(overloadRate)
  item.bearingCapacity = bearingCapacity
  item.livestockCapacity = livestockCapacity
  item.overloadRate = round(overloadRate, 2)
  item.balanceLevel = risk.label
  item.searchText = [
    item.name,
    `划定面积${item.protectedAreaWanMu}万亩`,
    `牦牛${item.yakCount}头`,
    `牧户${item.householdCount}户`,
    `超载率${item.overloadRate}%`,
  ].join(" ")
})
const parkBalanceBearingCapacity = sumBy(parkTownBusinessRows, "bearingCapacity")
const parkBalanceLivestockCapacity = sumBy(parkTownBusinessRows, "livestockCapacity")
const parkBalanceDirectRates = parkTownBusinessRows
  .map((item) => Number(item.overloadRate))
  .filter((value) => Number.isFinite(value))
parkSummary.balanceOverloadRate = parkBalanceDirectRates.length
  ? round(parkBalanceDirectRates.reduce((sum, value) => sum + value, 0) / parkBalanceDirectRates.length, 2)
  : parkBalanceBearingCapacity
  ? round(((parkBalanceLivestockCapacity - parkBalanceBearingCapacity) / parkBalanceBearingCapacity) * 100, 2)
  : 0

const withParkPercentExtra = (rows, total = sumBy(rows, "value")) =>
  rows.map((item) => ({
    ...item,
    extra: item.extra || `占比 ${round((Number(item.value || 0) / Math.max(total, 1)) * 100, 1)}%`,
  }))

const parkResourceScopeRows = withParkPercentExtra([
  { key: "park-scope-grassland", name: "草地", value: parkSummary.grasslandAreaWanMu, unit: "万亩" },
  { key: "park-scope-wetland", name: "湿地", value: parkSummary.wetlandAreaWanMu, unit: "万亩" },
  { key: "park-scope-other", name: "其他保护范围", value: parkSummary.otherProtectedAreaWanMu, unit: "万亩" },
])

const buildParkVillageRows = ({ sourceKey, weightKey, unit = "万亩", decimals = 2, sortByValue = true }) => {
  const rows = parkTownBusinessRows.flatMap((town) => {
    const weights = parkVillageWeights[town.name] || []
    return weights.map((village) => ({
      key: `${town.name}-${village.name}-${sourceKey}`,
      name: village.name,
      town: town.name,
      value: round(Number(town[sourceKey] || 0) * Number(village[weightKey] || 0), decimals),
      unit,
    }))
  }).filter((item) => Number(item.value) > 0)
  const displayRows = sortByValue ? rows.sort((a, b) => Number(b.value || 0) - Number(a.value || 0)) : rows
  return withParkPercentExtra(displayRows)
}

const parkWetlandVillageRows = buildParkVillageRows({
  sourceKey: "wetlandAreaWanMu",
  weightKey: "wetland",
  sortByValue: false,
})

const parkGrasslandVillageRows = buildParkVillageRows({
  sourceKey: "grasslandAreaWanMu",
  weightKey: "grassland",
})

const parkHouseholdVillageRows = buildParkVillageRows({
  sourceKey: "householdCount",
  weightKey: "household",
  unit: "户",
  decimals: 0,
})

const parkYakVillageRows = buildParkVillageRows({
  sourceKey: "yakCount",
  weightKey: "yak",
  unit: "头",
  decimals: 0,
})

const parkEdibleGrassVillageRows = buildParkVillageRows({
  sourceKey: "edibleGrasslandWanTon",
  weightKey: "edible",
  unit: "万吨",
})

const parkWoodlandVillageRows = buildParkVillageRows({
  sourceKey: "wetlandAreaWanMu",
  weightKey: "woodland",
})

const parkTownDisplayOrder = ["瓦切镇", "麦洼乡", "色地镇"]
const sortParkTownRows = (rows) => parkTownDisplayOrder
  .map((name) => rows.find((item) => item.name === name))
  .filter(Boolean)

const parkTownAreaRows = sortParkTownRows(parkTownBusinessRows).map((item) => ({
  key: `${item.name}-area`,
  name: item.name,
  value: item.protectedAreaWanMu,
  unit: "万亩",
  extra: `核心 ${item.coreProtectionAreaWanMu} / 一般 ${item.generalControlAreaWanMu}`,
}))

const parkTownZoningRows = sortParkTownRows(parkTownBusinessRows).map((item) => ({
  key: `${item.name}-zoning`,
  name: item.name,
  value: item.protectedAreaWanMu,
  unit: "万亩",
  segments: {
    core: item.coreProtectionAreaWanMu,
    general: item.generalControlAreaWanMu,
  },
}))

const parkTownGrassWetRows = sortParkTownRows(parkTownBusinessRows).map((item) => ({
  key: `${item.name}-grass-wet-area`,
  name: item.name,
  value: round(item.grasslandAreaWanMu + item.wetlandAreaWanMu, 2),
  unit: "万亩",
  segments: {
    grassland: item.grasslandAreaWanMu,
    wetland: item.wetlandAreaWanMu,
  },
}))

const parkTownProductivityRows = sortParkTownRows(parkTownBusinessRows).map((item) => ({
  key: `${item.name}-grass-wet-productivity`,
  name: item.name,
  value: round(
    (item.grasslandAreaWanMu / Math.max(parkSummary.grasslandAreaWanMu, 1)) * parkGrasslandProductivityWanTon
      + (item.wetlandAreaWanMu / Math.max(parkSummary.wetlandAreaWanMu, 1)) * parkWetlandProductivityWanTon,
    2
  ),
  unit: "万吨",
  segments: {
    grassland: round((item.grasslandAreaWanMu / Math.max(parkSummary.grasslandAreaWanMu, 1)) * parkGrasslandProductivityWanTon, 2),
    wetland: round((item.wetlandAreaWanMu / Math.max(parkSummary.wetlandAreaWanMu, 1)) * parkWetlandProductivityWanTon, 2),
  },
}))

const parkTownYakRows = sortParkTownRows(parkTownBusinessRows).map((item) => ({
  key: `${item.name}-yak`,
  name: item.name,
  value: item.yakCount,
  unit: "头",
  extra: `${round((item.yakCount / Math.max(parkSummary.yakCount, 1)) * 100, 1)}%`,
}))

const parkTownHouseholdRows = sortParkTownRows(parkTownBusinessRows).map((item) => ({
  key: `${item.name}-household`,
  name: item.name,
  value: item.householdCount,
  unit: "户",
  metricLabel: "牧户",
  ecologyJobs: item.ecologyJobs,
  peopleCount: item.peopleCount,
  extra: `公益岗位 ${item.ecologyJobs}户`,
}))

const parkTownBalanceRows = sortParkTownRows(parkTownBusinessRows).map((item) => ({
  key: `${item.name}-balance`,
  name: item.name,
  value: item.overloadRate,
  unit: "%",
  status: item.balanceLevel,
  extra: `载畜 ${item.livestockCapacity}头`,
}))

const parkBalanceGaugeRows = [
  {
    key: "park-balance-overload-rate",
    name: "超载率",
    value: parkSummary.balanceOverloadRate,
    unit: "%",
    status: getRiskLevel(parkSummary.balanceOverloadRate).label,
    color: "#24f6c4",
  },
]

const parkTownEcologyJobRows = sortParkTownRows(parkTownBusinessRows).map((item) => ({
  key: `${item.name}-job`,
  name: item.name,
  value: item.ecologyJobs,
  unit: "户",
  color: item.name === "麦洼乡" ? "#24f6c4" : item.name === "瓦切镇" ? "#32dcff" : "#ffe06b",
  extra: `牧户 ${item.householdCount}户`,
}))

const parkTownLedgerRows = sortParkTownRows(parkTownBusinessRows).map((item) => ({
  ...item,
  key: `${item.name}-ledger`,
  name: item.name,
  value: item.protectedAreaWanMu,
  unit: "万亩",
  canLocate: true,
}))

export const parkTopStats = [
  { zh: "四川片区面积", value: parkSummary.nationalParkTotalAreaWanMu, unit: "万亩", decimals: 2 },
  { zh: "红原县划定面积", value: parkSummary.hongyuanDelimitedAreaWanMu, unit: "万亩", decimals: 2 },
  { zh: "牦牛数量", value: parkSummary.yakCount, unit: "头", decimals: 0 },
  { zh: "牧户数量", value: parkSummary.householdCount, unit: "户", decimals: 0 },
  { zh: "公益岗位", value: parkSummary.ecologyJobCount, unit: "户", decimals: 0 },
  { zh: "瓦切镇面积", value: parkTownBusinessRows.find((item) => item.name === "瓦切镇")?.protectedAreaWanMu || 0, unit: "万亩", decimals: 2 },
  { zh: "麦洼乡面积", value: parkTownBusinessRows.find((item) => item.name === "麦洼乡")?.protectedAreaWanMu || 0, unit: "万亩", decimals: 2 },
  { zh: "色地镇面积", value: parkTownBusinessRows.find((item) => item.name === "色地镇")?.protectedAreaWanMu || 0, unit: "万亩", decimals: 2 },
  { zh: "草地面积", value: parkSummary.grasslandAreaWanMu, unit: "万亩", decimals: 2 },
  { zh: "湿地面积", value: parkSummary.wetlandAreaWanMu, unit: "万亩", decimals: 2 },
]

export const restorationTopStats = [
  { zh: "修复项目", value: restorationSummary.kpi.projectCount, unit: "个", decimals: 0 },
  { zh: "治理面积", value: restorationSummary.kpi.areaWanMu, unit: "万亩", decimals: 2 },
  { zh: "工程长度", value: restorationSummary.kpi.lengthKm, unit: "公里", decimals: 2 },
]

export const engineeringAnalysisTopStats = [
  { zh: "项目库工程", value: restorationSummary.kpi.projectCount, unit: "个", decimals: 0 },
  { zh: "可比对图斑", value: restorationSummary.kpi.featureCount, unit: "个", decimals: 0 },
  { zh: "项目面积", value: restorationSummary.kpi.areaWanMu, unit: "万亩", decimals: 2 },
  { zh: "工程长度", value: restorationSummary.kpi.lengthKm, unit: "公里", decimals: 2 },
]

export function getEcologicalTopStats(viewKey) {
  if (viewKey === "engineering-analysis") return []
  const rows = viewKey === "restoration"
    ? restorationTopStats
    : parkTopStats
  return rows.map((item, index) => ({
    icon: index % 2 === 0 ? "xiaoshoujine" : "zongxiaoliang",
    en: "",
    ...item,
  }))
}

export const parkPanels = {
  left: [
    {
      key: "park-town-grass-wet-area",
      title: "草地湿地面积分布",
      type: "stackColumn",
      variant: "dual",
      unit: "万亩",
      segments: [
        { key: "grassland", name: "草地面积", color: "#24f6c4" },
        { key: "wetland", name: "湿地面积", color: "#ffe06b" },
      ],
      rows: parkTownGrassWetRows,
    },
    {
      key: "park-town-productivity",
      title: "草地湿地生产力",
      type: "stackColumn",
      variant: "dual",
      unit: "万吨",
      segments: [
        { key: "grassland", name: "草地生产力", color: "#32dcff" },
        { key: "wetland", name: "湿地生产力", color: "#ffe06b" },
      ],
      rows: parkTownProductivityRows,
    },
    {
      key: "park-town-yak",
      title: "乡镇牦牛数量",
      type: "bar",
      variant: "raceBar",
      rows: parkTownYakRows,
    },
    {
      key: "park-town-balance",
      title: "草畜平衡超载率",
      type: "balanceGaugeGrid",
      limit: 1,
      rows: parkBalanceGaugeRows,
    },
  ],
  right: [
    {
      key: "park-zoning-structure",
      title: "红原管控区结构",
      type: "donut",
      rows: withParkPercentExtra(parkZoningRows),
    },
    {
      key: "park-town-household",
      title: "牧户分布",
      type: "split",
      rows: parkTownHouseholdRows,
    },
    {
      key: "park-town-ecology-job",
      title: "公益岗位分布",
      type: "column",
      variant: "slim",
      rows: parkTownEcologyJobRows,
    },
  ],
}

const restorationTownByName = new Map(
  (restorationSummary.townships || [])
    .filter((item) => /[乡镇]$/.test(String(item.name || "")))
    .map((item) => [item.name, item])
)
const validTownRows = hongyuanTownshipDisplayOrder.map((name) => ({
  name,
  areaWanMu: restorationTownByName.get(name)?.areaWanMu || 0,
  lengthKm: restorationTownByName.get(name)?.lengthKm || 0,
  projectCount: restorationTownByName.get(name)?.projectCount || 0,
}))

const restorationProjectRows = (restorationSummary.projects || []).map((item, index) => {
  const hasArea = Number(item.areaWanMu) > 0
  const hasLength = Number(item.lengthKm) > 0
  const scale = hasArea
    ? { value: round(item.areaWanMu, 2), unit: "万亩", metric: "治理面积" }
    : hasLength
      ? { value: round(item.lengthKm, 2), unit: "公里", metric: "工程长度" }
      : { value: item.subjectFeatureCount || 0, unit: "个", metric: "主体要素" }
  const measure = (item.measureTypes || []).join("、")
  const townships = (item.townships || []).join("、")
  return {
    key: item.id || item.projectName,
    index: index + 1,
    name: item.projectName,
    projectName: item.projectName,
    category: item.projectCategory,
    year: item.year || "未知",
    areaWanMu: round(item.areaWanMu, 4),
    lengthKm: round(item.lengthKm, 2),
    measure,
    townships,
    subjectFeatureCount: item.subjectFeatureCount || 0,
    value: scale.value,
    unit: scale.unit,
    metric: scale.metric,
    extra: [item.year || "未知", measure].filter(Boolean).join(" / "),
    searchText: [item.projectName, item.projectCategory, item.year, measure, townships].filter(Boolean).join(" "),
  }
})

export const engineeringAnalysisProjectFeatures = restorationProjectRows.map((item, index) => {
  const col = index % 6
  const row = Math.floor(index / 6)
  const baseLng = 102.42 + col * 0.045
  const baseLat = 32.55 + row * 0.035
  const size = 0.018 + Math.min(0.024, Number(item.areaWanMu || 0) / 1200)
  return {
    type: "Feature",
    properties: {
      project_name: item.projectName,
      project_category: item.category,
      year: item.year,
      areaWanMu: item.areaWanMu,
      lengthKm: item.lengthKm,
      townships: item.townships,
      measure: item.measure,
    },
    geometry: {
      type: "Polygon",
      coordinates: [[
        [baseLng, baseLat],
        [baseLng + size, baseLat + size * 0.22],
        [baseLng + size * 0.82, baseLat + size],
        [baseLng - size * 0.16, baseLat + size * 0.72],
        [baseLng, baseLat],
      ]],
    },
  }
})

export const restorationPanels = {
  left: [
    {
      key: "restoration-year-area",
      title: "治理面积分布",
      type: "line",
      rows: (restorationSummary.years || []).map((item) => ({
        key: item.name,
        name: `${item.name}`,
        value: round(item.areaWanMu, 2),
        unit: "万亩",
        extra: `${item.projectCount || 0}个项目`,
      })),
    },
    {
      key: "restoration-town-area",
      title: "乡镇治理面积分布",
      type: "bar",
      variant: "distribution",
      rows: validTownRows.map((item) => ({
        key: item.name,
        name: item.name,
        value: round(item.areaWanMu, 2),
        unit: "万亩",
        extra: `${round(item.lengthKm, 2)}公里`,
      })),
    },
    {
      key: "restoration-category",
      title: "修复类型占比",
      type: "donut",
      rows: (restorationSummary.categories || []).map((item) => ({
        key: item.name,
        name: item.name,
        value: round(item.areaWanMu || item.lengthKm || item.subjectFeatureCount, 2),
        unit: item.areaWanMu ? "万亩" : item.lengthKm ? "公里" : "个",
        extra: `${item.subjectFeatureCount}个图斑`,
      })),
    },
    {
      key: "restoration-year-length",
      title: "年度工程长度",
      type: "column",
      variant: "slim",
      rows: (restorationSummary.years || [])
        .filter((item) => Number(item.lengthKm) > 0)
        .map((item) => ({
          key: item.name,
          name: `${item.name}`,
          value: round(item.lengthKm, 2),
          unit: "公里",
          extra: `${item.projectCount || 0}个项目`,
        })),
    },
  ],
  right: [
    {
      key: "restoration-measure-area",
      title: "修复措施统计",
      type: "structure",
      rows: (restorationSummary.measures || []).slice(0, 8).map((item) => ({
        key: item.name,
        name: item.name,
        value: round(item.areaWanMu || item.lengthKm || item.subjectFeatureCount, 2),
        unit: item.areaWanMu ? "万亩" : item.lengthKm ? "公里" : "个",
        extra: `${item.projectCount}个项目`,
      })),
    },
    {
      key: "restoration-year-project",
      title: "年度项目数量",
      type: "column",
      variant: "projectYear",
      rows: (restorationSummary.years || [])
        .filter((item) => item.name !== "未知")
        .map((item) => ({
          key: item.name,
          name: `${item.name}`,
          value: item.projectCount,
          unit: "个",
          extra: `${round(item.areaWanMu, 2)}万亩`,
        })),
    },
    {
      key: "restoration-projects",
      title: "重点项目库",
      type: "projectTable",
      span: 2,
      rows: restorationProjectRows,
    },
  ],
}

export const engineeringAnalysisPanels = {
  left: [],
  right: [],
}

export const centerMapNotes = {
  "national-park": {
    title: "若尔盖国家公园红原区域",
    subtitle: "核心保护区 / 一般控制区 / 生态资源统计",
    tags: ["植被盖度", "草地面积", "湿地面积", "牧户牦牛"],
  },
  restoration: {
    title: "生态修复工程项目库",
    subtitle: "草地修复 / 湿地修复 / 林地修复 / 水源涵养",
    tags: ["项目库", "治理面积", "工程长度", "乡镇排行"],
  },
  "engineering-analysis": {
    title: "工程建设分析",
    subtitle: "上传边界 / 在线绘制 / 项目相交核查",
    tags: ["SHP", "边界绘制", "项目核验", "空间叠加"],
  },
}

export function getEcologicalMapRanking(viewKey) {
  if (viewKey === "restoration") {
    return {
      status: "success",
      title: "乡镇治理排行",
      metricLabel: "治理面积",
      unit: "万亩",
      rows: validTownRows.map((item) => ({
        name: item.name,
        value: round(item.areaWanMu, 2),
        unit: "万亩",
      })),
    }
  }
  if (viewKey === "engineering-analysis") {
    return {
      status: "success",
      title: "工程分析",
      metricLabel: "",
      unit: "",
      rows: [],
    }
  }
  return {
    status: "success",
    title: "国家公园乡镇划定面积",
    scope: "town",
    hideTownNames: false,
    onlyRankedTownLabels: true,
    metricLabel: "划定面积",
    unit: "万亩",
    rows: parkTownAreaRows.map((item) => ({
      name: item.name,
      value: item.value,
      unit: item.unit,
      metricLabel: "划定面积",
    })),
  }
}
