/** 共同富裕大屏 ECharts 配置（对齐 doc/共同富裕 设计稿） */

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 MONTHS = ['一月', '二月', '三月', '四月', '五月', '六月', '七月', '八月', '九月', '十月', '十一月', '十二月']

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

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

function monthSeries(monthly, field) {
  if (!monthly?.length) {
    return MONTHS.map(() => 0)
  }
  const map = new Map(monthly.map((row) => [row.month, row[field] ?? 0]))
  return MONTHS.map((_, i) => {
    const val = map.get(i + 1) ?? 0
    return typeof val === 'object' && val !== null ? Number(val) : Number(val)
  })
}

function hasMonthlyData(monthly, field) {
  return monthly?.length && monthSeries(monthly, field).some((v) => v > 0)
}

/** 横轴为去掉「月」的类目时，tooltip 标题补回「月」 */
function formatMonthAxisTooltip(params) {
  const list = Array.isArray(params) ? params : [params]
  const raw = list[0]?.axisValue
  const title =
    raw != null && raw !== ''
      ? String(raw).endsWith('月')
        ? String(raw)
        : `${raw}月`
      : ''
  const body = list
    .map((p) =>
      p.seriesName ? `${p.marker}${p.seriesName}：${p.value}` : `${p.marker}${p.value}`
    )
    .join('<br/>')
  return title ? `${title}<br/>${body}` : body
}

/** 经济收入对比 — 横向柱（集体经济收入，万元） */
export function buildCollectiveIncomeBarOption(monthly, hasData) {
  if (!hasData || !hasMonthlyData(monthly, 'collectiveEconomyIncome')) {
    return emptyOption('暂无收入数据')
  }
  const values = monthSeries(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 ''
        }
        return `${row.name}<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: MONTHS,
      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: MONTHS.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
      }
    ]
  }
}

/** 就业带动 — 就业人数 + 就业岗位双折线 */
export function buildEmploymentOption(monthly, hasData) {
  if (
    !hasData ||
    (!hasMonthlyData(monthly, 'employmentDrivenCount') &&
      !hasMonthlyData(monthly, 'newJobPositions'))
  ) {
    return emptyOption('暂无就业数据')
  }
  return {
    color: ['#ecd27b', '#5ef0c8'],
    tooltip: { trigger: 'axis', formatter: formatMonthAxisTooltip },
    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: MONTHS.map((m) => m.replace('月', '')),
      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: monthSeries(monthly, 'employmentDrivenCount')
      },
      {
        name: '就业岗位',
        type: 'line',
        yAxisIndex: 1,
        smooth: true,
        symbol: 'circle',
        symbolSize: 4,
        areaStyle: { color: 'rgba(94, 240, 200, 0.15)' },
        data: monthSeries(monthly, 'newJobPositions')
      }
    ]
  }
}

/** 环境治理 — 项目数月度柱图 */
export function buildEnvGovernanceOption(monthly, hasData) {
  if (!hasData || !hasMonthlyData(monthly, 'envProjectCount')) {
    return emptyOption('暂无环境治理数据')
  }
  return {
    color: ['#ecd27b'],
    tooltip: { trigger: 'axis', formatter: formatMonthAxisTooltip },
    grid: { ...GRID, left: 10, right: 8, top: 36, bottom: 20, containLabel: true },
    xAxis: {
      type: 'category',
      data: MONTHS.map((m) => m.replace('月', '')),
      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: monthSeries(monthly, 'envProjectCount')
      }
    ]
  }
}

/** 绿化建设 — 新增绿化面积折线面积图 */
export function buildGreenAreaOption(monthly, hasData) {
  if (!hasData || !hasMonthlyData(monthly, 'newGreenArea')) {
    return emptyOption('暂无绿化数据')
  }
  return {
    color: ['#5ef0c8'],
    tooltip: { trigger: 'axis' },
    grid: {...GRID, left: 10,  bottom: 8},
    xAxis: {
      type: 'category',
      data: MONTHS,
      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: monthSeries(monthly, 'newGreenArea')
      }
    ]
  }
}

/** 文化传承 — 月度柱图 */
export function buildCulturalHeritageOption(monthly, hasData) {
  if (!hasData || !hasMonthlyData(monthly, 'culturalHeritageCount')) {
    return emptyOption('暂无文化传承数据')
  }
  return {
    color: ['#5ef0c8'],
    tooltip: { trigger: 'axis', formatter: formatMonthAxisTooltip },
    grid: { ...GRID, left: 10, right: 8, bottom: 20, containLabel: true },
    xAxis: {
      type: 'category',
      data: MONTHS.map((m) => m.replace('月', '')),
      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: monthSeries(monthly, 'culturalHeritageCount')
      }
    ]
  }
}

/** 民族团结 — 堆叠柱 */
export function buildEthnicUnityStackedOption(monthly, hasData) {
  if (
    !hasData ||
    (!hasMonthlyData(monthly, 'ethnicIntegrationProjectCount') &&
      !hasMonthlyData(monthly, 'ethnicUnityActivityCount'))
  ) {
    return emptyOption('暂无民族团结数据')
  }
  return {
    color: ['#5ef0c8', '#1a4a6e'],
    tooltip: {
      trigger: 'axis',
      axisPointer: { type: 'shadow' },
      formatter: formatMonthAxisTooltip
    },
    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: MONTHS.map((m) => m.replace('月', '')),
      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: monthSeries(monthly, 'ethnicIntegrationProjectCount')
      },
      {
        name: '民族团结活动',
        type: 'bar',
        stack: 'ethnic',
        barMaxWidth: 8,
        data: monthSeries(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
      }
    ]
  }
}
