/** 大屏首页 ECharts 配置（深色主题，与 screen-theme 一致） */

const AXIS_LABEL = { color: '#9fb0c3', fontSize: 10 }
/** 12 个月横轴：不旋转，略缩小字号以适配窄图 */
const MONTH_AXIS_LABEL = { color: '#9fb0c3', fontSize: 9, margin: 6 }
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: 22, right: 8, top: 24, bottom: 6, containLabel: true }
const MONTHS = ['1月', '2月', '3月', '4月', '5月', '6月', '7月', '8月', '9月', '10月', '11月', '12月']

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

function sortByMonth(list) {
  return [...(list || [])].sort((a, b) => (a.month || 0) - (b.month || 0))
}

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
}

function monthSeries(list, field, altFields = []) {
  const fields = [field, ...altFields]
  const map = new Map(
    sortByMonth(list).map((row) => [Number(row.month), pickNumber(row, fields)])
  )
  return MONTHS.map((_, i) => map.get(i + 1) ?? 0)
}

/** 牦牛存栏变动：公牛 / 母牛折线 */
export function buildInventoryTrendOption(monthlyTrend) {
  if (!monthlyTrend?.length) {
    return emptyOption()
  }
  return {
    color: ['#5ef0c8', '#ecd27b'],
    tooltip: { trigger: 'axis' },
    legend: {
      top: 0,
      right: 8,
      textStyle: { color: '#a8d4c8', fontSize: 10 },
      itemWidth: 12,
      itemHeight: 8
    },
    grid: GRID,
    xAxis: {
      type: 'category',
      data: MONTHS,
      axisLabel: { ...MONTH_AXIS_LABEL, interval: 0 },
      axisLine: AXIS_LINE,
      axisTick: { show: false }
    },
    yAxis: {
      type: 'value',
      axisLabel: AXIS_LABEL,
      axisLine: AXIS_LINE,
      splitLine: SPLIT_LINE
    },
    series: [
      {
        name: '公牛',
        type: 'line',
        smooth: true,
        symbol: 'circle',
        symbolSize: 4,
        data: monthSeries(monthlyTrend, 'bullCount')
      },
      {
        name: '母牛',
        type: 'line',
        smooth: true,
        symbol: 'circle',
        symbolSize: 4,
        data: monthSeries(monthlyTrend, 'cowCount')
      }
    ]
  }
}

/** 年龄三档配色（对齐 doc/首页/耗牛年龄结构.png） */
const AGE_BAND_COLOR = {
  M1_6: '#45c997',
  M7_12: '#6eb5ff',
  M13_PLUS: '#ecd27b'
}

const AGE_BAND_ORDER = ['M1_6', 'M7_12', 'M13_PLUS']

function sortAgeBands(ageStructure) {
  const map = new Map((ageStructure || []).map((item) => [item.bandCode, item]))
  const ordered = AGE_BAND_ORDER.map((code) => map.get(code)).filter(Boolean)
  return ordered.length ? ordered : [...(ageStructure || [])]
}

function formatAgeRatio(ratio, percent) {
  if (ratio != null && ratio !== '') {
    return `${Number(ratio).toFixed(0)}%`
  }
  return `${Math.round(percent)}%`
}

/** 牦牛年龄结构（环形图 + 右侧图例，固定三档） */
export function buildAgeStructureOption(ageStructure) {
  if (!ageStructure?.length) {
    return emptyOption()
  }
  const bands = sortAgeBands(ageStructure)
  const data = bands.map((item) => ({
    name: item.bandLabel || item.bandCode,
    value: pickNumber(item, ['count']),
    ratio: item.ratio,
    itemStyle: {
      color: AGE_BAND_COLOR[item.bandCode] || '#45f0b8',
      shadowBlur: 8,
      shadowColor: 'rgba(0, 0, 0, 0.45)',
      shadowOffsetY: 2
    }
  }))
  const hasSlice = data.some((d) => d.value > 0)
  const centerGraphic = hasSlice
    ? []
    : [
        {
          type: 'text',
          left: '26%',
          top: '46%',
          style: {
            text: '暂无存栏',
            fill: '#6a9f90',
            fontSize: 11,
            textAlign: 'center'
          }
        }
      ]
  return {
    color: Object.values(AGE_BAND_COLOR),
    tooltip: {
      trigger: 'item',
      formatter: (p) => {
        const row = bands[p.dataIndex]
        const ratio =
          row?.ratio != null ? `${Number(row.ratio).toFixed(1)}%` : `${p.percent?.toFixed(1)}%`
        return `${p.name}<br/>${p.value} 头 (${ratio})`
      }
    },
    legend: {
      orient: 'vertical',
      right: '2%',
      top: 'middle',
      icon: 'circle',
      itemWidth: 8,
      itemHeight: 8,
      itemGap: 12,
      textStyle: { color: '#e8eef5', fontSize: 10 }
    },
    graphic: [
      {
        type: 'circle',
        left: '22%',
        top: '38%',
        shape: { r: 52 },
        style: {
          fill: 'transparent',
          stroke: 'rgba(61, 217, 176, 0.22)',
          lineWidth: 1
        },
        z: 0
      },
      {
        type: 'circle',
        left: '20%',
        top: '36%',
        shape: { r: 58 },
        style: {
          fill: 'transparent',
          stroke: 'rgba(61, 217, 176, 0.12)',
          lineWidth: 1
        },
        z: 0
      },
      ...centerGraphic
    ],
    series: [
      {
        type: 'pie',
        radius: ['42%', '68%'],
        center: ['34%', '54%'],
        avoidLabelOverlap: true,
        stillShowZeroSum: false,
        itemStyle: {
          borderColor: 'rgba(2, 22, 18, 0.9)',
          borderWidth: 2
        },
        label: {
          show: hasSlice,
          position: 'inside',
          color: '#fff',
          fontSize: 10,
          fontWeight: 'bold',
          formatter: (p) => formatAgeRatio(p.data.ratio, p.percent)
        },
        labelLine: { show: false },
        emphasis: {
          scale: true,
          scaleSize: 5
        },
        data: hasSlice ? data : []
      }
    ]
  }
}

/** 出栏柱图金色渐变（对齐 doc/首页/耗牛出栏统计.png） */
const OUTBOUND_BAR_GRADIENT = {
  type: 'linear',
  x: 0,
  y: 1,
  x2: 0,
  y2: 0,
  colorStops: [
    { offset: 0, color: '#6b4f18' },
    { offset: 0.45, color: '#b8923a' },
    { offset: 1, color: '#f7d547' }
  ]
}

const OUTBOUND_GRID = { left: 36, right: 8, top: 28, bottom: 6, containLabel: true }
const OUTBOUND_SPLIT_LINE = {
  lineStyle: { color: 'rgba(120, 140, 160, 0.28)', type: 'dashed' }
}

/** 牦牛出栏按月（柱 + 折线，设计稿样式） */
export function buildOutboundOption(outboundMonthly) {
  if (!outboundMonthly?.length) {
    return emptyOption()
  }
  const values = monthSeries(outboundMonthly, 'outboundCount', ['outbound_count', 'count'])
  return {
    tooltip: {
      trigger: 'axis',
      axisPointer: { type: 'shadow' },
      formatter: (params) => {
        const bar = params.find((p) => p.seriesType === 'bar') || params[0]
        return `${bar.name}<br/>出栏 ${bar.value} 头`
      }
    },
    legend: {
      top: 4,
      left: 8,
      itemWidth: 8,
      itemHeight: 8,
      textStyle: { color: '#a8d4c8', fontSize: 10 },
      data: ['出栏', '趋势']
    },
    grid: OUTBOUND_GRID,
    xAxis: {
      type: 'category',
      data: MONTHS,
      axisLabel: { ...MONTH_AXIS_LABEL, interval: 0 },
      axisLine: { lineStyle: { color: 'rgba(150, 170, 190, 0.45)' } },
      axisTick: { show: false }
    },
    yAxis: {
      type: 'value',
      minInterval: 1,
      axisLabel: AXIS_LABEL,
      axisLine: { show: false },
      axisTick: { show: false },
      splitLine: OUTBOUND_SPLIT_LINE
    },
    series: [
      {
        name: '出栏',
        type: 'bar',
        barWidth: '46%',
        z: 1,
        itemStyle: {
          color: OUTBOUND_BAR_GRADIENT,
          borderRadius: [10, 10, 10, 10]
        },
        data: values
      },
      {
        name: '趋势',
        type: 'line',
        smooth: true,
        symbol: 'none',
        z: 2,
        lineStyle: { color: '#b8e86a', width: 2 },
        data: values
      }
    ]
  }
}

/** 草场退化五档配色（对齐 doc/首页/草场类型占比.png） */
const GRASSLAND_DEGRADATION_COLOR = {
  1: '#3b66d1',
  2: '#5dc3a1',
  3: '#547233',
  4: '#f7b538',
  5: '#3e5388'
}

function formatGrasslandRatio(ratio, percent) {
  if (ratio != null && ratio !== '') {
    return `${Number(ratio).toFixed(0)}%`
  }
  return `${Math.round(percent)}%`
}

/** 草场退化占比（环形图 + 右侧图例 + 扇区内占比） */
export function buildGrasslandOption(grassland) {
  const degradationStats = grassland?.degradationStats
  if (!degradationStats?.length) {
    return emptyOption()
  }
  const hasData = degradationStats.some(
    (item) => pickNumber(item, ['count']) > 0 || pickNumber(item, ['ratio']) > 0
  )
  if (!hasData) {
    return emptyOption()
  }
  const data = degradationStats.map((item) => ({
    name: item.degradationLabel || `等级${item.degradationLevel}`,
    value: pickNumber(item, ['count']),
    ratio: item.ratio,
    itemStyle: {
      color: GRASSLAND_DEGRADATION_COLOR[item.degradationLevel] || '#45f0b8',
      shadowBlur: 10,
      shadowColor: 'rgba(0, 0, 0, 0.5)',
      shadowOffsetY: 3
    }
  }))
  return {
    color: Object.values(GRASSLAND_DEGRADATION_COLOR),
    tooltip: {
      trigger: 'item',
      formatter: (p) => {
        const row = degradationStats[p.dataIndex]
        const ratio =
          row?.ratio != null ? `${Number(row.ratio).toFixed(1)}%` : `${p.percent?.toFixed(1)}%`
        return `${p.name}<br/>${p.value}个 (${ratio})`
      }
    },
    legend: {
      orient: 'vertical',
      right: '2%',
      top: 'middle',
      icon: 'circle',
      itemWidth: 8,
      itemHeight: 8,
      itemGap: 10,
      textStyle: { color: '#e8eef5', fontSize: 10 }
    },
    series: [
      {
        type: 'pie',
        radius: ['42%', '68%'],
        center: ['34%', '54%'],
        avoidLabelOverlap: true,
        itemStyle: {
          borderColor: 'rgba(2, 22, 18, 0.9)',
          borderWidth: 2
        },
        label: {
          show: true,
          position: 'inside',
          color: '#fff',
          fontSize: 10,
          fontWeight: 'bold',
          formatter: (p) => formatGrasslandRatio(p.data.ratio, p.percent)
        },
        labelLine: { show: false },
        emphasis: {
          scale: true,
          scaleSize: 5,
          itemStyle: { shadowBlur: 14, shadowColor: 'rgba(0, 0, 0, 0.55)' }
        },
        data
      }
    ]
  }
}

/** 预约堆叠柱配色（对齐 doc/首页/线下服务预约.png，自下而上：机构蓝 / 兽医青 / 专家金） */
const APPOINTMENT_MONTHS = [
  '一月',
  '二月',
  '三月',
  '四月',
  '五月',
  '六月',
  '七月',
  '八月',
  '九月',
  '十月',
  '十一月',
  '十二月'
]

const APPOINTMENT_ORG_GRADIENT = {
  type: 'linear',
  x: 0,
  y: 1,
  x2: 0,
  y2: 0,
  colorStops: [
    { offset: 0, color: '#1e479b' },
    { offset: 1, color: '#3a6bc4' }
  ]
}

const APPOINTMENT_EXPERT_GRADIENT = {
  type: 'linear',
  x: 0,
  y: 1,
  x2: 0,
  y2: 0,
  colorStops: [
    { offset: 0, color: '#8e763d' },
    { offset: 1, color: '#d4a84a' }
  ]
}

const APPOINTMENT_GRID = { left: 44, right: 8, top: 26, bottom: 6, containLabel: true }
const APPOINTMENT_SPLIT_LINE = {
  lineStyle: { color: 'rgba(120, 140, 160, 0.28)', type: 'dashed' }
}

/** 线下服务预约堆叠柱 */
export function buildAppointmentStackedOption(monthlyStacked) {
  if (!monthlyStacked?.length) {
    return emptyOption()
  }
  return {
    tooltip: {
      trigger: 'axis',
      axisPointer: { type: 'shadow' },
      formatter: (params) => {
        const lines = params.map((p) => `${p.marker}${p.seriesName} ${p.value} 人次`)
        return `${params[0]?.name}<br/>${lines.join('<br/>')}`
      }
    },
    legend: {
      top: 4,
      right: 8,
      itemWidth: 10,
      itemHeight: 8,
      textStyle: { color: '#e8eef5', fontSize: 10 },
      data: ['诊疗机构', '兽医', '专家']
    },
    grid: APPOINTMENT_GRID,
    xAxis: {
      type: 'category',
      data: APPOINTMENT_MONTHS,
      axisLabel: { ...MONTH_AXIS_LABEL, interval: 0 },
      axisLine: { lineStyle: { color: 'rgba(150, 170, 190, 0.45)' } },
      axisTick: { show: false }
    },
    yAxis: {
      type: 'value',
      minInterval: 1,
      axisLabel: AXIS_LABEL,
      axisLine: { show: false },
      axisTick: { show: false },
      splitLine: APPOINTMENT_SPLIT_LINE
    },
    series: [
      {
        name: '诊疗机构',
        type: 'bar',
        stack: 'apt',
        barMaxWidth: 10,
        itemStyle: { color: APPOINTMENT_ORG_GRADIENT },
        data: monthSeries(monthlyStacked, 'orgCount', ['org_count'])
      },
      {
        name: '兽医',
        type: 'bar',
        stack: 'apt',
        barMaxWidth: 10,
        itemStyle: { color: '#52b89f' },
        data: monthSeries(monthlyStacked, 'vetCount', ['vet_count'])
      },
      {
        name: '专家',
        type: 'bar',
        stack: 'apt',
        barMaxWidth: 10,
        itemStyle: { color: APPOINTMENT_EXPERT_GRADIENT },
        data: monthSeries(monthlyStacked, 'expertCount', ['expert_count'])
      }
    ]
  }
}

/** 三类柱图配色（与线下服务预约堆叠柱一致：蓝 / 青 / 金） */
const STACK_BAR_COLORS = [APPOINTMENT_ORG_GRADIENT, '#52b89f', APPOINTMENT_EXPERT_GRADIENT]

/** 惠农补贴（万元） */
export function buildSubsidyOption(typeStats, hasSubsidyData) {
  if (!hasSubsidyData || !typeStats?.length) {
    return emptyOption('暂无补贴数据')
  }
  const categories = typeStats.map(
    (item) => item.subsidyTypeName || `类型${item.subsidyType}`
  )
  return {
    tooltip: {
      trigger: 'axis',
      axisPointer: { type: 'shadow' },
      formatter: (params) => {
        const p = Array.isArray(params) ? params[0] : params
        if (!p) {
          return ''
        }
        const val = p.value != null ? Number(p.value) : 0
        return `${p.name}<br/>补贴金额 ${val.toLocaleString('zh-CN', {
          minimumFractionDigits: 2,
          maximumFractionDigits: 2
        })} 万元`
      }
    },
    grid: GRID,
    xAxis: {
      type: 'category',
      data: categories,
      axisLabel: { ...AXIS_LABEL, interval: 0, fontSize: 9, margin: 6 },
      axisLine: AXIS_LINE,
      axisTick: { show: false }
    },
    yAxis: {
      type: 'value',
      name: '万元',
      nameTextStyle: { color: '#6a9f90', fontSize: 10 },
      axisLabel: AXIS_LABEL,
      axisLine: AXIS_LINE,
      splitLine: SPLIT_LINE
    },
    series: [
      {
        name: '补贴金额',
        type: 'bar',
        barMaxWidth: 28,
        data: typeStats.map((item, index) => ({
          value: Number(item.amountWan ?? 0),
          itemStyle: { color: STACK_BAR_COLORS[index % STACK_BAR_COLORS.length] }
        }))
      }
    ]
  }
}

/** 实战培训面积图配色（对齐 doc/首页/实战培训占比.png） */
const TRAINING_ACTIVITY_LINE = '#ff9f43'
const TRAINING_ACTIVITY_AREA = {
  type: 'linear',
  x: 0,
  y: 0,
  x2: 0,
  y2: 1,
  colorStops: [
    { offset: 0, color: 'rgba(255, 159, 67, 0.55)' },
    { offset: 1, color: 'rgba(255, 159, 67, 0.04)' }
  ]
}

const TRAINING_ENROLL_LINE = '#40e0d0'
const TRAINING_ENROLL_AREA = {
  type: 'linear',
  x: 0,
  y: 0,
  x2: 0,
  y2: 1,
  colorStops: [
    { offset: 0, color: 'rgba(64, 224, 208, 0.5)' },
    { offset: 1, color: 'rgba(64, 224, 208, 0.04)' }
  ]
}

const TRAINING_GRID = { left: 36, right: 36, top: 30, bottom: 6, containLabel: true }
const TRAINING_SPLIT_LINE = {
  lineStyle: { color: 'rgba(120, 140, 160, 0.28)', type: 'dashed' }
}

/** 实战培训报名趋势（双面积折线：活动数 + 报名人数） */
export function buildTrainingOption(trainingTrend) {
  if (!trainingTrend?.hasTrainingData) {
    return emptyOption('暂无培训数据')
  }
  const monthly = trainingTrend.monthly || []
  return {
    tooltip: {
      trigger: 'axis',
      formatter: (params) => {
        if (!Array.isArray(params) || !params.length) {
          return ''
        }
        const lines = params.map((p) => {
          const unit = p.seriesName === '活动数' ? '个' : '人'
          return `${p.marker}${p.seriesName} ${p.value ?? 0} ${unit}`
        })
        return `${params[0].name}<br/>${lines.join('<br/>')}`
      }
    },
    legend: {
      top: 4,
      left: 'center',
      itemWidth: 14,
      itemHeight: 4,
      textStyle: { color: '#e8eef5', fontSize: 10 }
    },
    grid: TRAINING_GRID,
    xAxis: {
      type: 'category',
      data: MONTHS,
      axisLabel: { ...MONTH_AXIS_LABEL, interval: 0, color: '#e8eef5' },
      axisLine: { lineStyle: { color: 'rgba(150, 170, 190, 0.45)' } },
      axisTick: { show: false }
    },
    yAxis: [
      {
        type: 'value',
        name: '个',
        nameTextStyle: { color: '#9fb0c3', fontSize: 10 },
        minInterval: 1,
        axisLabel: { ...AXIS_LABEL, color: '#9fb0c3' },
        axisLine: { show: false },
        axisTick: { show: false },
        splitLine: TRAINING_SPLIT_LINE
      },
      {
        type: 'value',
        name: '人',
        nameTextStyle: { color: '#9fb0c3', fontSize: 10 },
        minInterval: 1,
        axisLabel: { ...AXIS_LABEL, color: '#9fb0c3' },
        axisLine: { show: false },
        axisTick: { show: false },
        splitLine: { show: false }
      }
    ],
    series: [
      {
        name: '活动数',
        type: 'line',
        smooth: true,
        symbol: 'none',
        yAxisIndex: 0,
        lineStyle: {
          color: TRAINING_ACTIVITY_LINE,
          width: 2,
          shadowColor: 'rgba(255, 159, 67, 0.65)',
          shadowBlur: 10
        },
        areaStyle: { color: TRAINING_ACTIVITY_AREA },
        data: monthSeries(monthly, 'activityCount', ['activity_count'])
      },
      {
        name: '报名人数',
        type: 'line',
        yAxisIndex: 1,
        smooth: true,
        symbol: 'none',
        lineStyle: {
          color: TRAINING_ENROLL_LINE,
          width: 2,
          shadowColor: 'rgba(64, 224, 208, 0.65)',
          shadowBlur: 10
        },
        areaStyle: { color: TRAINING_ENROLL_AREA },
        data: monthSeries(monthly, 'enrolledCount', ['enrolled_count'])
      }
    ]
  }
}
