/** 共同富裕大屏 ECharts 配置（对齐 doc/大屏/共同富裕 v1.1 滚动 12 月） */

const AXIS_LABEL = { color: '#9fb0c3', fontSize: 10 }
const AXIS_LINE = { lineStyle: { color: 'rgba(61, 217, 176, 0.35)' } }
const SPLIT_LINE = { lineStyle: { color: 'rgba(61, 217, 176, 0.12)' } }
const GRID = { left: 40, right: 16, top: 28, bottom: 28, containLabel: true }

const PROJECT_TYPE_COLOR = ['#45f0b8', '#6eb5ff', '#ecd27b']

const ACHIEVEMENT_EMPTY = '暂无该年度共富成果数据'

function emptyOption(text = '暂无数据') {
  return {
    title: {
      text,
      left: 'center',
      top: 'middle',
      textStyle: { color: '#6a9f90', fontSize: 13, fontWeight: 'normal' }
    }
  }
}

function pickNumber(row, fields) {
  for (const key of fields) {
    const raw = row?.[key]
    if (raw != null && raw !== '') {
      const n = Number(raw)
      if (!Number.isNaN(n)) {
        return n
      }
    }
  }
  return 0
}

/** 滚动最近 12 月：按 statYear、month 升序 */
function sortRollingMonths(list) {
  return [...(list || [])].sort((a, b) => {
    const ak = (Number(a.statYear) || 0) * 100 + (Number(a.month) || 0)
    const bk = (Number(b.statYear) || 0) * 100 + (Number(b.month) || 0)
    return ak - bk
  })
}

function rollingMonthLabel(row) {
  return `${Number(row.month)}月`
}

function rollingTooltipTitle(row) {
  if (!row) {
    return ''
  }
  return `${row.statYear}年${Number(row.month)}月`
}

function buildRollingAxis(list) {
  const rows = sortRollingMonths(list)
  return {
    rows,
    categories: rows.map(rollingMonthLabel),
    titleAt: (dataIndex) => rollingTooltipTitle(rows[dataIndex])
  }
}

function rollingSeries(list, field, altFields = []) {
  const fields = [field, ...altFields]
  return sortRollingMonths(list).map((row) => pickNumber(row, fields))
}

function rollingAxisTooltip(params, axis, valueFormatter) {
  if (!Array.isArray(params) || !params.length) {
    return ''
  }
  const title = axis.titleAt(params[0].dataIndex)
  const lines = params.map((p) => {
    const val = valueFormatter ? valueFormatter(p) : `${p.value ?? 0}`
    return `${p.marker}${p.seriesName}：${val}`
  })
  return `${title}<br/>${lines.join('<br/>')}`
}

/** 经济收入对比 — 横向柱（集体经济收入，万元，滚动 12 月） */
export function buildCollectiveIncomeBarOption(monthly, hasData) {
  if (!hasData || !monthly?.length) {
    return emptyOption(ACHIEVEMENT_EMPTY)
  }
  const axis = buildRollingAxis(monthly)
  const values = rollingSeries(monthly, 'collectiveEconomyIncome')
  const maxVal = Math.max(...values, 1)
  return {
    color: ['#ecd27b'],
    tooltip: {
      trigger: 'axis',
      axisPointer: { type: 'shadow' },
      formatter: (params) => {
        const list = Array.isArray(params) ? params : [params]
        const row = list.find((p) => p.seriesName === '收入')
        if (!row) {
          return ''
        }
        const title = axis.titleAt(row.dataIndex)
        return `${title}<br/>收入：${Number(row.value).toFixed(1)} 万元`
      }
    },
    grid: { left: 4, right: 36, top: 10, bottom: 0, containLabel: true },
    xAxis: {
      type: 'value',
      max: maxVal,
      show: false
    },
    yAxis: {
      type: 'category',
      data: axis.categories,
      inverse: true,
      boundaryGap: false,
      axisLabel: {
        color: '#e8eef5',
        fontSize: 9,
        interval: 0,
        hideOverlap: false,
        margin: 2
      },
      axisLine: { show: false },
      axisTick: { show: false }
    },
    series: [
      {
        name: '背景',
        type: 'bar',
        barWidth: 9,
        barGap: '-100%',
        barCategoryGap: '6%',
        silent: true,
        tooltip: { show: false },
        itemStyle: { color: 'rgba(15, 80, 68, 0.55)', borderRadius: [0, 4, 4, 0] },
        data: axis.categories.map(() => maxVal),
        z: 1
      },
      {
        name: '收入',
        type: 'bar',
        barWidth: 9,
        itemStyle: {
          borderRadius: [0, 4, 4, 0],
          color: {
            type: 'linear',
            x: 0,
            y: 0,
            x2: 1,
            y2: 0,
            colorStops: [
              { offset: 0, color: '#0f8f72' },
              { offset: 1, color: '#ecd27b' }
            ]
          }
        },
        label: {
          show: true,
          position: 'right',
          color: '#e8eef5',
          fontSize: 9,
          formatter: (p) => Number(p.value).toFixed(1)
        },
        data: values,
        z: 2
      }
    ]
  }
}

/** 就业带动 — 带动就业人数 + 新增就业岗位双折线（滚动 12 月） */
export function buildEmploymentOption(monthly, hasData) {
  if (!hasData || !monthly?.length) {
    return emptyOption(ACHIEVEMENT_EMPTY)
  }
  const axis = buildRollingAxis(monthly)
  return {
    color: ['#ecd27b', '#5ef0c8'],
    tooltip: {
      trigger: 'axis',
      formatter: (params) => rollingAxisTooltip(params, axis)
    },
    legend: {
      top: 4,
      left: 'center',
      textStyle: { color: '#a8d4c8', fontSize: 10 },
      itemWidth: 14,
      itemHeight: 8
    },
    grid: { ...GRID, left: 10, top: 36, bottom: 8 },
    xAxis: {
      type: 'category',
      data: axis.categories,
      axisLabel: { ...AXIS_LABEL, fontSize: 9, interval: 0 },
      axisLine: AXIS_LINE
    },
    yAxis: [
      {
        type: 'value',
        name: '人',
        nameTextStyle: { color: '#6a9f90', fontSize: 10 },
        minInterval: 1,
        axisLabel: AXIS_LABEL,
        axisLine: AXIS_LINE,
        splitLine: SPLIT_LINE
      },
      {
        type: 'value',
        name: '个',
        nameTextStyle: { color: '#6a9f90', fontSize: 10 },
        minInterval: 1,
        axisLabel: AXIS_LABEL,
        axisLine: AXIS_LINE,
        splitLine: { show: false }
      }
    ],
    series: [
      {
        name: '带动就业人数',
        type: 'line',
        smooth: true,
        symbol: 'circle',
        symbolSize: 4,
        areaStyle: { color: 'rgba(236, 210, 123, 0.2)' },
        data: rollingSeries(monthly, 'employmentDrivenCount')
      },
      {
        name: '新增就业岗位',
        type: 'line',
        yAxisIndex: 1,
        smooth: true,
        symbol: 'circle',
        symbolSize: 4,
        areaStyle: { color: 'rgba(94, 240, 200, 0.15)' },
        data: rollingSeries(monthly, 'newJobPositions')
      }
    ]
  }
}

/** 环境治理 — 项目数月度柱图（滚动 12 月） */
export function buildEnvGovernanceOption(monthly, hasData) {
  if (!hasData || !monthly?.length) {
    return emptyOption(ACHIEVEMENT_EMPTY)
  }
  const axis = buildRollingAxis(monthly)
  return {
    color: ['#ecd27b'],
    tooltip: {
      trigger: 'axis',
      formatter: (params) => rollingAxisTooltip(params, axis, (p) => `${p.value ?? 0} 个`)
    },
    grid: { ...GRID, left: 10, right: 8, top: 36, bottom: 20, containLabel: true },
    xAxis: {
      type: 'category',
      data: axis.categories,
      axisLabel: {
        ...AXIS_LABEL,
        fontSize: 9,
        interval: 0,
        hideOverlap: false,
        margin: 6
      },
      axisLine: AXIS_LINE
    },
    yAxis: {
      type: 'value',
      minInterval: 1,
      axisLabel: AXIS_LABEL,
      axisLine: AXIS_LINE,
      splitLine: SPLIT_LINE
    },
    series: [
      {
        name: '项目数',
        type: 'bar',
        barMaxWidth: 8,
        barCategoryGap: '35%',
        itemStyle: { color: '#ecd27b', borderRadius: [3, 3, 0, 0] },
        data: rollingSeries(monthly, 'envProjectCount')
      }
    ]
  }
}

/** 绿化建设 — 新增绿化面积折线面积图（滚动 12 月） */
export function buildGreenAreaOption(monthly, hasData) {
  if (!hasData || !monthly?.length) {
    return emptyOption(ACHIEVEMENT_EMPTY)
  }
  const axis = buildRollingAxis(monthly)
  return {
    color: ['#5ef0c8'],
    tooltip: {
      trigger: 'axis',
      formatter: (params) => rollingAxisTooltip(params, axis, (p) => `${p.value ?? 0} 亩`)
    },
    grid: { ...GRID, left: 10, bottom: 8 },
    xAxis: {
      type: 'category',
      data: axis.categories,
      axisLabel: { ...AXIS_LABEL, rotate: 35, interval: 0, fontSize: 9 },
      axisLine: AXIS_LINE
    },
    yAxis: {
      type: 'value',
      name: '亩',
      nameTextStyle: { color: '#6a9f90', fontSize: 10 },
      axisLabel: AXIS_LABEL,
      axisLine: AXIS_LINE,
      splitLine: SPLIT_LINE
    },
    series: [
      {
        name: '新增绿化面积',
        type: 'line',
        smooth: true,
        symbol: 'circle',
        symbolSize: 4,
        areaStyle: { color: 'rgba(94, 240, 200, 0.3)' },
        data: rollingSeries(monthly, 'newGreenArea')
      }
    ]
  }
}

/** 文化传承 — 月度柱图（滚动 12 月） */
export function buildCulturalHeritageOption(monthly, hasData) {
  if (!hasData || !monthly?.length) {
    return emptyOption(ACHIEVEMENT_EMPTY)
  }
  const axis = buildRollingAxis(monthly)
  return {
    color: ['#5ef0c8'],
    tooltip: {
      trigger: 'axis',
      formatter: (params) => rollingAxisTooltip(params, axis, (p) => `${p.value ?? 0} 人`)
    },
    grid: { ...GRID, left: 10, right: 8, bottom: 20, containLabel: true },
    xAxis: {
      type: 'category',
      data: axis.categories,
      axisLabel: {
        ...AXIS_LABEL,
        fontSize: 9,
        interval: 0,
        hideOverlap: false,
        margin: 6
      },
      axisLine: AXIS_LINE
    },
    yAxis: {
      type: 'value',
      minInterval: 1,
      axisLabel: AXIS_LABEL,
      axisLine: AXIS_LINE,
      splitLine: SPLIT_LINE
    },
    series: [
      {
        name: '文化传承人数',
        type: 'bar',
        barMaxWidth: 8,
        barCategoryGap: '35%',
        itemStyle: { color: '#5ef0c8', borderRadius: [3, 3, 0, 0] },
        data: rollingSeries(monthly, 'culturalHeritageCount')
      }
    ]
  }
}

/** 民族团结 — 堆叠柱（滚动 12 月） */
export function buildEthnicUnityStackedOption(monthly, hasData) {
  if (!hasData || !monthly?.length) {
    return emptyOption(ACHIEVEMENT_EMPTY)
  }
  const axis = buildRollingAxis(monthly)
  return {
    color: ['#5ef0c8', '#1a4a6e'],
    tooltip: {
      trigger: 'axis',
      axisPointer: { type: 'shadow' },
      formatter: (params) => rollingAxisTooltip(params, axis, (p) => `${p.value ?? 0} 个`)
    },
    legend: {
      top: 4,
      left: 'center',
      textStyle: { color: '#a8d4c8', fontSize: 10 },
      itemWidth: 12,
      itemHeight: 8
    },
    grid: { ...GRID, left: 10, right: 8, top: 36, bottom: 20, containLabel: true },
    xAxis: {
      type: 'category',
      data: axis.categories,
      axisLabel: {
        ...AXIS_LABEL,
        fontSize: 9,
        interval: 0,
        hideOverlap: false,
        margin: 6
      },
      axisLine: AXIS_LINE
    },
    yAxis: {
      type: 'value',
      minInterval: 1,
      axisLabel: AXIS_LABEL,
      axisLine: AXIS_LINE,
      splitLine: SPLIT_LINE
    },
    series: [
      {
        name: '民族融合项目数',
        type: 'bar',
        stack: 'ethnic',
        barMaxWidth: 8,
        barCategoryGap: '35%',
        data: rollingSeries(monthly, 'ethnicIntegrationProjectCount')
      },
      {
        name: '民族团结活动数',
        type: 'bar',
        stack: 'ethnic',
        barMaxWidth: 8,
        data: rollingSeries(monthly, 'ethnicUnityActivityCount')
      }
    ]
  }
}

/** 共富项目分类 — 饼图 */
export function buildProjectTypePieOption(projectTypeStats, hasProjectData) {
  if (!hasProjectData || !projectTypeStats?.length) {
    return emptyOption('本年度暂无共富项目')
  }
  const data = projectTypeStats
    .filter((item) => (item.count ?? 0) > 0)
    .map((item, i) => ({
      name: item.projectTypeName,
      value: item.count ?? 0,
      itemStyle: { color: PROJECT_TYPE_COLOR[i % PROJECT_TYPE_COLOR.length] }
    }))
  if (!data.length) {
    return emptyOption('本年度暂无共富项目')
  }
  return {
    tooltip: {
      trigger: 'item',
      formatter: (p) => {
        const row = projectTypeStats.find((it) => it.projectTypeName === p.name)
        const ratio = row?.ratio != null ? (Number(row.ratio) * 100).toFixed(1) : p.percent
        return `${p.name}: ${p.value}个 (${ratio}%)`
      }
    },
    legend: {
      orient: 'vertical',
      right: 4,
      top: 'center',
      textStyle: { color: '#e8eef5', fontSize: 10 },
      itemWidth: 10,
      itemHeight: 10
    },
    series: [
      {
        type: 'pie',
        radius: ['42%', '62%'],
        center: ['38%', '52%'],
        label: { show: false },
        data
      }
    ]
  }
}
