/** 疫病风险大屏 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: 36, bottom: 28, containLabel: true }
/** 解除时效柱图：预留 y 轴单位「天」空间，下边距收紧 */
const RELIEVE_DURATION_GRID = { left: 40, right: 12, top: 30, bottom: 4, containLabel: true }
const LAB_GRID = { left: 28, right: 10, top: 30, bottom: 6, containLabel: true }
const LAB_MONTH_AXIS_LABEL = { color: '#9fb0c3', fontSize: 9, margin: 4 }

/** 样本来源展示顺序：日常→场点→调运→上报（与设计稿一致） */
const SAMPLE_SOURCE_ORDER = [4, 1, 3, 2]

/** 风险等级配色（对齐 doc/疫病风险/疾病风险.png：低危绿 / 中危蓝 / 高危金） */
const RISK_LEVEL_COLOR = {
  1: '#ecd27b',
  2: '#40d4f0',
  3: '#45c997'
}

/** 图例与扇区顺序：低危 → 中危 → 高危 */
const RISK_LEVEL_ORDER = [3, 2, 1]

const RISK_LEVEL_FALLBACK_NAME = {
  1: '高危',
  2: '中危',
  3: '低危'
}

/** 与主环形图同心（疾病风险设计稿） */
const RISK_PIE_CENTER = ['36%', '52%']

/** 主环外缘 68%；装饰环外移，与主图之间留出可见空隙 */
/** 同心装饰圆环（与主图同心，半径大于主环） */
function buildRiskLevelRingSeries() {
  const ringData = (stroke) => ({
    value: 1,
    name: '',
    itemStyle: {
      color: 'transparent',
      borderColor: stroke,
      borderWidth: 1
    }
  })
  return [
    {
      type: 'pie',
      radius: ['78%', '79%'],
      center: RISK_PIE_CENTER,
      silent: true,
      animation: false,
      label: { show: false },
      tooltip: { show: false },
      z: 0,
      data: [ringData('rgba(61, 217, 176, 0.2)')]
    },
    {
      type: 'pie',
      radius: ['72%', '73%'],
      center: RISK_PIE_CENTER,
      silent: true,
      animation: false,
      label: { show: false },
      tooltip: { show: false },
      z: 0,
      data: [ringData('rgba(61, 217, 176, 0.35)')]
    }
  ]
}

/** 轨道光点（落在两圈装饰环上） */
function buildRiskLevelGraphicBeads() {
  const outerR = 73
  const innerR = 67
  const deg = (d) => (d * Math.PI) / 180
  return [
    {
      type: 'group',
      left: RISK_PIE_CENTER[0],
      top: RISK_PIE_CENTER[1],
      bounding: 'raw',
      z: 1,
      children: [
        {
          type: 'ellipse',
          shape: {
            cx: outerR * Math.cos(deg(210)),
            cy: outerR * Math.sin(deg(210)),
            rx: 5,
            ry: 3
          },
          style: { fill: 'rgba(190, 220, 210, 0.55)' }
        },
        {
          type: 'ellipse',
          shape: {
            cx: innerR * Math.cos(deg(60)),
            cy: innerR * Math.sin(deg(60)),
            rx: 5,
            ry: 3
          },
          style: { fill: 'rgba(190, 220, 210, 0.45)' }
        }
      ]
    }
  ]
}

function buildRiskLevelPieData(riskLevelStats) {
  const map = new Map((riskLevelStats || []).map((row) => [row.riskLevel, row]))
  return RISK_LEVEL_ORDER.map((level) => {
    const row = map.get(level) || {}
    return {
      name: row.riskLevelName || RISK_LEVEL_FALLBACK_NAME[level],
      value: row.count ?? 0,
      riskLevel: level,
      ratio: row.ratio,
      itemStyle: {
        color: RISK_LEVEL_COLOR[level],
        shadowBlur: 10,
        shadowColor: 'rgba(0, 0, 0, 0.45)',
        shadowOffsetY: 2
      }
    }
  })
}

/** 疫病类型分布 — 对齐 doc/疫病风险/疫情类型分布.png */
const EPIDEMIC_TYPE_COLOR_BY_TYPE = {
  1: '#89D9AD', // 病毒性疫病
  2: '#E6B641', // 细菌性疫病
  3: '#2B59C3', // 寄生虫疫病
  4: '#43A08D' // 其他类疫病
}
const EPIDEMIC_TYPE_COLOR = Object.values(EPIDEMIC_TYPE_COLOR_BY_TYPE)

function epidemicTypeColor(item, index) {
  const type = item?.epidemicType ?? item?.epidemic_type
  if (type != null && EPIDEMIC_TYPE_COLOR_BY_TYPE[type]) {
    return EPIDEMIC_TYPE_COLOR_BY_TYPE[type]
  }
  return EPIDEMIC_TYPE_COLOR[index % EPIDEMIC_TYPE_COLOR.length]
}

const ROUTE_COLOR = ['#6eb5ff', '#c4a574', '#45f0b8', '#066b58']

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

/** 平均解除天数（兼容驼峰/下划线字段） */
function pickAvgRelieveDays(item) {
  for (const key of ['avgRelieveDays', 'avg_relieve_days']) {
    const raw = item?.[key]
    if (raw != null && raw !== '') {
      const n = Number(raw)
      if (!Number.isNaN(n)) {
        return n
      }
    }
  }
  return null
}

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 buildRollingAxis(list) {
  const rows = sortRollingMonths(list)
  return {
    rows,
    categories: rows.map((row) => `${Number(row.month)}月`),
    titleAt: (dataIndex) => {
      const row = rows[dataIndex]
      if (!row) {
        return ''
      }
      return `${row.statYear}年${Number(row.month)}月`
    }
  }
}

function rollingSeries(list, field) {
  return sortRollingMonths(list).map((row) => {
    const val = row?.[field]
    if (val == null || val === '') {
      return 0
    }
    const n = Number(val)
    return Number.isNaN(n) ? 0 : n
  })
}

function pickSampleSourceRows(stats) {
  if (!stats?.length) {
    return []
  }
  const map = new Map(stats.map((row) => [row.sampleSource, row]))
  return SAMPLE_SOURCE_ORDER.map((code) => map.get(code)).filter(Boolean)
}

/** 样本来源检测 — 横向条形图 */
export function buildSampleSourceBarOption(sampleSourceStats) {
  const rows = pickSampleSourceRows(sampleSourceStats)
  if (!rows.length || !rows.some((r) => (r.testQuantity ?? 0) > 0)) {
    return emptyOption('暂无检测数据')
  }
  const names = rows.map((r) => r.sampleSourceName || '')
  const values = rows.map((r) => r.testQuantity ?? 0)
  const maxVal = Math.max(...values, 1)
  return {
    color: ['#ecd27b'],
    tooltip: {
      trigger: 'axis',
      axisPointer: { type: 'shadow' },
      formatter: (params) => {
        const items = Array.isArray(params) ? params : [params]
        const row = items.find((p) => p.seriesName === '检测量')
        if (!row) {
          return ''
        }
        return `${row.name}<br/>检测量: ${row.value}`
      }
    },
    grid: { left: 72, right: 48, top: 8, bottom: 8, containLabel: false },
    xAxis: {
      type: 'value',
      max: maxVal,
      show: false
    },
    yAxis: {
      type: 'category',
      data: names,
      axisLabel: { color: '#e8eef5', fontSize: 11 },
      axisLine: { show: false },
      axisTick: { show: false }
    },
    series: [
      {
        name: '背景',
        type: 'bar',
        barWidth: 10,
        barGap: '-100%',
        silent: true,
        itemStyle: { color: 'rgba(15, 80, 68, 0.55)', borderRadius: [0, 6, 6, 0] },
        data: names.map(() => maxVal),
        z: 1
      },
      {
        name: '检测量',
        type: 'bar',
        barWidth: 10,
        itemStyle: {
          borderRadius: [0, 6, 6, 0],
          color: {
            type: 'linear',
            x: 0,
            y: 0,
            x2: 1,
            y2: 0,
            colorStops: [
              { offset: 0, color: '#b8923a' },
              { offset: 1, color: '#ecd27b' }
            ]
          }
        },
        label: {
          show: true,
          position: 'right',
          color: '#e8eef5',
          fontSize: 11
        },
        data: values,
        z: 2
      }
    ]
  }
}

/** 实验室检测 — 检测量折线 + 阳性数面积（滚动最近 12 月） */
export function buildLabDetectionOption(labDetection) {
  const monthly = labDetection?.monthly
  if (!monthly?.length) {
    return emptyOption('暂无实验室数据')
  }
  const axis = buildRollingAxis(monthly)
  return {
    color: ['#5ef0c8', '#ecd27b'],
    tooltip: {
      trigger: 'axis',
      formatter: (params) => {
        if (!Array.isArray(params) || !params.length) {
          return ''
        }
        const title = axis.titleAt(params[0].dataIndex)
        const lines = params.map((p) => `${p.marker}${p.seriesName}: ${p.value ?? 0} 份`)
        return `${title}<br/>${lines.join('<br/>')}`
      }
    },
    legend: {
      top: 2,
      left: 'center',
      textStyle: { color: '#a8d4c8', fontSize: 10 },
      itemWidth: 14,
      itemHeight: 8
    },
    grid: LAB_GRID,
    xAxis: {
      type: 'category',
      data: axis.categories,
      axisLabel: { ...LAB_MONTH_AXIS_LABEL, interval: 0 },
      axisLine: AXIS_LINE,
      axisTick: { show: false }
    },
    yAxis: {
      type: 'value',
      minInterval: 1,
      axisLabel: AXIS_LABEL,
      axisLine: AXIS_LINE,
      splitLine: SPLIT_LINE
    },
    series: [
      {
        name: '检测量',
        type: 'line',
        smooth: true,
        symbol: 'circle',
        symbolSize: 4,
        data: rollingSeries(monthly, 'testQuantity')
      },
      {
        name: '阳性数',
        type: 'line',
        smooth: true,
        symbol: 'circle',
        symbolSize: 4,
        areaStyle: { color: 'rgba(236, 210, 123, 0.25)' },
        data: rollingSeries(monthly, 'positiveCount')
      }
    ]
  }
}

/** 疫病风险 — 风险等级环形图（设计稿：三档色 + 外圈装饰线） */
export function buildRiskLevelPieOption(riskLevelStats, hasEpidemicData) {
  if (!hasEpidemicData || !riskLevelStats?.length) {
    return emptyOption('暂无疫情数据')
  }
  const data = buildRiskLevelPieData(riskLevelStats)
  const hasSlice = data.some((d) => d.value > 0)
  if (!hasSlice) {
    return emptyOption('暂无风险分布')
  }
  const legendNames = RISK_LEVEL_ORDER.map(
    (level) =>
      riskLevelStats.find((r) => r.riskLevel === level)?.riskLevelName ||
      RISK_LEVEL_FALLBACK_NAME[level]
  )
  return {
    color: RISK_LEVEL_ORDER.map((level) => RISK_LEVEL_COLOR[level]),
    tooltip: {
      trigger: 'item',
      formatter: (p) => {
        const row = riskLevelStats.find((r) => r.riskLevelName === p.name)
        const ratio =
          row?.ratio != null
            ? `${(Number(row.ratio) * 100).toFixed(1)}%`
            : `${p.percent?.toFixed(1)}%`
        return `${p.name}<br/>${p.value} 条 (${ratio})`
      }
    },
    legend: {
      orient: 'vertical',
      right: '4%',
      top: 'middle',
      icon: 'circle',
      itemWidth: 8,
      itemHeight: 8,
      itemGap: 14,
      data: legendNames,
      textStyle: { color: '#e8eef5', fontSize: 11 }
    },
    graphic: buildRiskLevelGraphicBeads(),
    series: [
      ...buildRiskLevelRingSeries(),
      {
        type: 'pie',
        radius: ['42%', '68%'],
        center: RISK_PIE_CENTER,
        z: 2,
        avoidLabelOverlap: true,
        itemStyle: {
          borderColor: 'rgba(2, 22, 18, 0.9)',
          borderWidth: 2
        },
        label: { show: false },
        emphasis: {
          scale: true,
          scaleSize: 5,
          itemStyle: { shadowBlur: 14, shadowColor: 'rgba(0, 0, 0, 0.55)' }
        },
        data: hasSlice ? data : []
      }
    ]
  }
}

/** 疫病类型分布 — 南丁格尔玫瑰图（疫情类型分布设计稿） */
export function buildEpidemicTypePieOption(epidemicTypeStats, hasEpidemicData) {
  if (!hasEpidemicData || !epidemicTypeStats?.length) {
    return emptyOption('暂无类型数据')
  }
  const data = epidemicTypeStats.map((item, i) => ({
    name: item.epidemicTypeName,
    value: item.count ?? 0,
    itemStyle: { color: epidemicTypeColor(item, i) }
  }))
  if (!data.some((d) => d.value > 0)) {
    return emptyOption('暂无类型数据')
  }
  return {
    tooltip: { trigger: 'item', formatter: '{b}: {c}条 ({d}%)' },
    series: [
      {
        type: 'pie',
        roseType: 'radius',
        radius: ['14%', '68%'],
        center: ['50%', '52%'],
        label: {
          position: 'outside',
          formatter: (params) => `{name|${params.name}}\n{pct|${params.percent}%}`,
          rich: {
            name: { color: '#89D9AD', fontSize: 10, lineHeight: 14 },
            pct: { color: '#ffffff', fontSize: 11, fontWeight: 600, lineHeight: 16 }
          }
        },
        labelLine: {
          length: 10,
          length2: 8,
          lineStyle: { color: 'rgba(137, 217, 173, 0.35)', width: 1 }
        },
        itemStyle: {
          borderColor: 'rgba(4, 30, 26, 0.55)',
          borderWidth: 1
        },
        emphasis: {
          scale: true,
          scaleSize: 4,
          itemStyle: { shadowBlur: 10, shadowColor: 'rgba(0, 0, 0, 0.35)' }
        },
        data
      }
    ]
  }
}

/** 疫病解除时效 — 按类型平均天数柱图（无数据柱体透明，tooltip 展示 --） */
export function buildRelieveDurationBarOption(relieveDurationByType, hasRelievedData) {
  const list = relieveDurationByType || []
  if (!list.length) {
    return emptyOption(hasRelievedData ? '暂无解除时效' : '暂无解除数据')
  }

  const names = list.map(
    (item) => item.epidemicTypeName || item.epidemic_type_name || ''
  )
  const numericValues = list
    .map((item) => pickAvgRelieveDays(item))
    .filter((v) => v != null)
  const barData = list.map((item) => {
    const days = pickAvgRelieveDays(item)
    if (days == null) {
      return {
        value: 0,
        itemStyle: { color: 'transparent', borderColor: 'transparent' },
        emphasis: { disabled: true }
      }
    }
    return { value: days }
  })

  return {
    color: ['#5ef0c8'],
    tooltip: {
      trigger: 'axis',
      formatter: (params) => {
        const p = params[0]
        const days = pickAvgRelieveDays(list[p.dataIndex])
        return `${p.name}<br/>平均 ${days != null ? `${days} 天` : '--'}`
      }
    },
    grid: RELIEVE_DURATION_GRID,
    xAxis: {
      type: 'category',
      data: names,
      axisLabel: { ...AXIS_LABEL, interval: 0, fontSize: 9, margin: 6 },
      axisLine: AXIS_LINE
    },
    yAxis: {
      type: 'value',
      name: '天',
      nameLocation: 'end',
      nameGap: 10,
      nameTextStyle: { color: '#6a9f90', fontSize: 10, padding: [0, 0, 4, 0] },
      min: 0,
      max: numericValues.length ? undefined : 1,
      minInterval: 1,
      axisLabel: AXIS_LABEL,
      axisLine: AXIS_LINE,
      splitLine: SPLIT_LINE
    },
    series: [
      {
        type: 'bar',
        barMaxWidth: 28,
        label: { show: false },
        itemStyle: {
          color: {
            type: 'linear',
            x: 0,
            y: 1,
            x2: 0,
            y2: 0,
            colorStops: [
              { offset: 0, color: '#0f8f72' },
              { offset: 1, color: '#ecd27b' }
            ]
          }
        },
        data: barData
      }
    ]
  }
}

/** 传播途径 — 环形图 */
export function buildTransmissionRoutePieOption(transmissionRouteStats, hasEpidemicData) {
  if (!hasEpidemicData || !transmissionRouteStats?.length) {
    return emptyOption('暂无途径数据')
  }
  const data = transmissionRouteStats.map((item, i) => ({
    name: item.transmissionRouteName,
    value: item.count ?? 0,
    itemStyle: { color: ROUTE_COLOR[i % ROUTE_COLOR.length] }
  }))
  if (!data.some((d) => d.value > 0)) {
    return emptyOption('暂无途径数据')
  }
  return {
    tooltip: { trigger: 'item', formatter: '{b}: {c}条 ({d}%)' },
    legend: {
      orient: 'vertical',
      right: 4,
      top: 'center',
      textStyle: { color: '#e8eef5', fontSize: 10 },
      itemWidth: 10,
      itemHeight: 10
    },
    series: [
      {
        type: 'pie',
        radius: ['48%', '68%'],
        center: ['38%', '52%'],
        label: { show: false },
        data
      }
    ]
  }
}

/** 风险因子指数 — 雷达图（含气象权重，仅展示配置值） */
export function buildRiskFactorRadarOption(riskFactorWeights) {
  if (!riskFactorWeights?.hasRiskFactorConfig || !riskFactorWeights.items?.length) {
    return emptyOption('暂无风险因子配置')
  }
  const items = riskFactorWeights.items
  const indicators = items.map((item) => ({
    name: item.factorName,
    max: 1
  }))
  const values = items.map((item) => Number(item.weight ?? 0))
  return {
    tooltip: {},
    radar: {
      center: ['50%', '54%'],
      radius: '58%',
      indicator: indicators,
      axisName: { color: '#a8d4c8', fontSize: 10 },
      splitLine: { lineStyle: { color: 'rgba(61, 217, 176, 0.2)' } },
      splitArea: { show: false },
      axisLine: { lineStyle: { color: 'rgba(61, 217, 176, 0.35)' } }
    },
    series: [
      {
        type: 'radar',
        symbol: 'none',
        emphasis: {
          symbol: 'none',
          lineStyle: { color: '#5ef0c8' }
        },
        data: [
          {
            value: values,
            name: '权重',
            symbol: 'none',
            areaStyle: { color: 'rgba(94, 240, 200, 0.25)' },
            lineStyle: { color: '#5ef0c8' }
          }
        ]
      }
    ]
  }
}
