/** 畜牧资源大屏 ECharts 配置（对齐 doc/大屏/畜牧资源 技术方案） */
import 'echarts-wordcloud'
import { buildMallPie2DOption } from '@/utils/mallPie2d'

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 }

const PIE_COLORS = ['#5ef0c8', '#ecd27b', '#6eb5ff', '#0f8f72', '#8a9fb0']
const BAR_COLORS = ['#5ef0c8', '#ecd27b', '#6eb5ff', '#98e9aa']
const WORD_COLORS = ['#5ef0c8', '#98e9aa', '#ecd27b', '#6eb5ff', '#a8d4c8', '#0f8f72']

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

function formatShortDate(dateStr) {
  if (!dateStr) {
    return ''
  }
  const parts = String(dateStr).split('-')
  if (parts.length >= 3) {
    return `${parts[1]}-${parts[2]}`
  }
  return dateStr
}

function toNum(val) {
  const n = Number(val)
  return Number.isNaN(n) ? 0 : n
}

function chartBase() {
  return { title: { show: false } }
}

/** 活跃度趋势 — 7 日会话数 + 提问量堆叠面积图 */
export function buildActivityTrendOption(activityTrend) {
  const series = activityTrend?.dailySeries || []
  if (!series.length) {
    return emptyOption('暂无活跃数据')
  }
  const dates = series.map((d) => formatShortDate(d.date))
  const sessions = series.map((d) => toNum(d.sessionCount))
  const questions = series.map((d) => toNum(d.questionCount))
  return {
    ...chartBase(),
    color: ['#5ef0c8', '#ecd27b'],
    tooltip: {
      trigger: 'axis',
      formatter: (params) => {
        if (!Array.isArray(params) || !params.length) {
          return ''
        }
        const idx = params[0].dataIndex
        const row = series[idx] || {}
        const title = row.date || dates[idx] || ''
        const lines = params.map((p) => `${p.marker}${p.seriesName}: ${p.value ?? 0}`)
        return `${title}<br/>${lines.join('<br/>')}`
      }
    },
    legend: {
      top: 0,
      right: 8,
      textStyle: { color: '#a8d4c8', fontSize: 10 },
      itemWidth: 12,
      itemHeight: 8
    },
    grid: { ...GRID, top: 28, bottom: 24 },
    xAxis: {
      type: 'category',
      boundaryGap: false,
      data: dates,
      axisLabel: { ...AXIS_LABEL, fontSize: 9 },
      axisLine: AXIS_LINE
    },
    yAxis: {
      type: 'value',
      minInterval: 1,
      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.35)' },
        data: sessions
      },
      {
        name: '提问量',
        type: 'line',
        smooth: true,
        symbol: 'circle',
        symbolSize: 4,
        areaStyle: { color: 'rgba(236, 210, 123, 0.35)' },
        data: questions
      }
    ]
  }
}

/** 用户结构 — 新老用户对比柱图 */
export function buildUserStructureOption(userStructure) {
  if (!userStructure) {
    return emptyOption('暂无用户数据')
  }
  const newCount = toNum(userStructure.newUserCount)
  const oldCount = toNum(userStructure.oldUserCount)
  // if (newCount === 0 && oldCount === 0) {
  //   return emptyOption('暂无用户数据')
  // }
  const newRatio = userStructure?.newUserRatio != null ? Number(userStructure.newUserRatio).toFixed(1) : null
  const oldRatio = userStructure?.oldUserRatio != null ? Number(userStructure.oldUserRatio).toFixed(1) : null
  return {
    ...chartBase(),
    color: ['#5ef0c8', '#ecd27b'],
    tooltip: {
      trigger: 'axis',
      axisPointer: { type: 'shadow' },
      formatter: (params) => {
        const p = params[0]
        const ratio = p.dataIndex === 0 ? newRatio : oldRatio
        const ratioText = ratio != null ? ` (${ratio}%)` : ''
        return `${p.name}<br/>${p.value} 人${ratioText}`
      }
    },
    grid: { ...GRID, top: 16, bottom: 24 },
    xAxis: {
      type: 'category',
      data: ['新用户', '老用户'],
      axisLabel: { ...AXIS_LABEL, fontSize: 10 },
      axisLine: AXIS_LINE
    },
    yAxis: {
      type: 'value',
      minInterval: 1,
      axisLabel: AXIS_LABEL,
      axisLine: AXIS_LINE,
      splitLine: SPLIT_LINE
    },
    series: [
      {
        type: 'bar',
        barMaxWidth: 48,
        itemStyle: {
          borderRadius: [4, 4, 0, 0],
          color: (params) => BAR_COLORS[params.dataIndex % BAR_COLORS.length]
        },
        data: [newCount, oldCount]
      }
    ]
  }
}

/** 提问分类占比 — 2D 环形饼图（对齐交易销售店铺入驻样式） */
export function buildCategoryShareOption(categoryShare) {
  const items = categoryShare?.items || []
  const data = items
    .filter((item) => (item.count ?? 0) > 0)
    .map((item) => ({
      name: item.categoryName || item.categoryCode || '未分类',
      value: item.count ?? 0
    }))
  if (!data.length) {
    return emptyOption('暂无分类数据')
  }
  const total =
    categoryShare?.totalAskerMessages ?? data.reduce((sum, item) => sum + item.value, 0)
  if (!(total > 0)) {
    return emptyOption('暂无分类数据')
  }
  return buildMallPie2DOption(data, {
    summaryTitle: String(total),
    summarySubtext: '提问量(条)',
    legend: {
      formatter: (name) => (name.length > 6 ? `${name.slice(0, 5)}…` : name),
      itemGap: 4
    },
    tooltipFormatter: (p) => {
      const row = items.find((it) => (it.categoryName || it.categoryCode || '未分类') === p.name)
      const ratio = row?.ratio != null ? `${Number(row.ratio).toFixed(1)}%` : `${p.percent}%`
      return `${p.name}<br/>${p.value} 条 (${ratio})`
    }
  })
}

/** 模型调用分析 — 分类条数柱图 */
export function buildModelCallOption(modelCallAnalysis) {
  const list = modelCallAnalysis || []
  if (!list.length) {
    return emptyOption('暂无调用数据')
  }
  const names = list.map((r) => r.categoryName || r.categoryCode || '')
  const values = list.map((r) => toNum(r.count))
  return {
    ...chartBase(),
    color: BAR_COLORS,
    tooltip: {
      trigger: 'axis',
      axisPointer: { type: 'shadow' }
    },
    grid: { ...GRID, top: 12, bottom: 28 },
    xAxis: {
      type: 'category',
      data: names,
      axisLabel: {
        ...AXIS_LABEL,
        interval: 0,
        fontSize: 9,
        rotate: names.some((n) => n.length > 4) ? 20 : 0
      },
      axisLine: AXIS_LINE
    },
    yAxis: {
      type: 'value',
      minInterval: 1,
      axisLabel: AXIS_LABEL,
      axisLine: AXIS_LINE,
      splitLine: SPLIT_LINE
    },
    series: [
      {
        type: 'bar',
        barMaxWidth: 28,
        itemStyle: {
          borderRadius: [4, 4, 0, 0],
          color: (params) => BAR_COLORS[params.dataIndex % BAR_COLORS.length]
        },
        data: values
      }
    ]
  }
}

/** 分时使用热度 — 最近 24 整点小时（会话柱 + 提问量折线） */
export function buildHourlyHeatOption(hourlyHeat) {
  const series = hourlyHeat?.hourlySeries || []
  if (!series.length) {
    return emptyOption('暂无热度数据')
  }
  const labels = series.map((d) => d.bucketStart || d.bucket_start || '')
  const sessions = series.map((d) => toNum(d.sessionCount ?? d.session_count))
  const questions = series.map((d) => toNum(d.questionCount ?? d.question_count))
  return {
    ...chartBase(),
    color: ['#5ef0c8', '#ecd27b'],
    tooltip: {
      trigger: 'axis',
      formatter: (params) => {
        if (!Array.isArray(params) || !params.length) {
          return ''
        }
        const idx = params[0].dataIndex
        const row = series[idx] || {}
        const title = row.bucketDateTime || row.bucket_date_time || row.bucketStart || ''
        const lines = params.map((p) => `${p.marker}${p.seriesName}: ${p.value ?? 0}`)
        return `${title}<br/>${lines.join('<br/>')}`
      }
    },
    legend: {
      top: 0,
      right: 8,
      textStyle: { color: '#a8d4c8', fontSize: 10 },
      itemWidth: 12,
      itemHeight: 8
    },
    grid: { ...GRID, top: 28, bottom: 24, left: 36, right: 36 },
    xAxis: {
      type: 'category',
      data: labels,
      axisLabel: {
        ...AXIS_LABEL,
        fontSize: 8,
        interval: (idx) => idx % 3 === 0
      },
      axisLine: AXIS_LINE
    },
    yAxis: [
      {
        type: 'value',
        minInterval: 1,
        axisLabel: { ...AXIS_LABEL, fontSize: 9 },
        axisLine: AXIS_LINE,
        splitLine: SPLIT_LINE
      },
      {
        type: 'value',
        minInterval: 1,
        axisLabel: { ...AXIS_LABEL, fontSize: 9 },
        axisLine: AXIS_LINE,
        splitLine: { show: false }
      }
    ],
    series: [
      {
        name: '会话数',
        type: 'bar',
        barMaxWidth: 8,
        itemStyle: { color: 'rgba(94, 240, 200, 0.75)', borderRadius: [2, 2, 0, 0] },
        data: sessions
      },
      {
        name: '提问量',
        type: 'line',
        yAxisIndex: 1,
        smooth: true,
        symbol: 'none',
        lineStyle: { width: 2, color: '#ecd27b' },
        data: questions
      }
    ]
  }
}

/** 单次会话提问数量分布 — 环形图 */
export function buildSessionReplyOption(sessionReplyDistribution) {
  const list = sessionReplyDistribution || []
  if (!list.length) {
    return emptyOption('暂无分布数据')
  }
  const data = list
    .map((item, i) => ({
      name: item.bandName || item.bandCode,
      value: toNum(item.sessionCount),
      itemStyle: { color: PIE_COLORS[i % PIE_COLORS.length] }
    }))
  if (!data.length) {
    return emptyOption('暂无分布数据')
  }
  return {
    ...chartBase(),
    tooltip: {
      trigger: 'item',
      formatter: (p) => {
        const row = list.find((it) => (it.bandName || it.bandCode) === p.name)
        const ratio = row?.ratio != null ? `${Number(row.ratio).toFixed(1)}%` : `${p.percent}%`
        return `${p.name}<br/>${p.value} 会话 (${ratio})`
      }
    },
    series: [
      {
        type: 'pie',
        radius: ['42%', '68%'],
        center: ['50%', '54%'],
        label: {
          color: '#e8eef5',
          fontSize: 9,
          formatter: (p) => {
            const row = list.find((it) => (it.bandName || it.bandCode) === p.name)
            const ratio = row?.ratio != null ? Number(row.ratio).toFixed(1) : p.percent
            return `${p.name}\n${ratio}%`
          }
        },
        labelLine: { length: 6, length2: 4 },
        data
      }
    ]
  }
}

/** 会话状态分布 — 柱图（正常应答 / 调用失败） */
export function buildReplyStatusOption(replyStatusDistribution) {
  const items = replyStatusDistribution?.items || []
  if (!items.length) {
    return emptyOption('暂无状态数据')
  }
  const names = items.map((r) => r.statusName || r.statusCode || '')
  const values = items.map((r) => toNum(r.count))
  return {
    ...chartBase(),
    color: ['#5ef0c8', '#f56c6c'],
    tooltip: {
      trigger: 'axis',
      axisPointer: { type: 'shadow' },
      formatter: (params) => {
        const p = params[0]
        const row = items[p.dataIndex]
        const ratio = row?.ratio != null ? `${Number(row.ratio).toFixed(1)}%` : ''
        return `${p.name}<br/>${p.value} 条${ratio ? ` (${ratio})` : ''}`
      }
    },
    grid: { ...GRID, top: 12, bottom: 28 },
    xAxis: {
      type: 'category',
      data: names,
      axisLabel: { ...AXIS_LABEL, interval: 0, fontSize: 9 },
      axisLine: AXIS_LINE
    },
    yAxis: {
      type: 'value',
      minInterval: 1,
      axisLabel: AXIS_LABEL,
      axisLine: AXIS_LINE,
      splitLine: SPLIT_LINE
    },
    series: [
      {
        type: 'bar',
        barMaxWidth: 36,
        itemStyle: {
          borderRadius: [4, 4, 0, 0],
          color: (params) => (params.dataIndex === 0 ? '#5ef0c8' : '#f56c6c')
        },
        data: values
      }
    ]
  }
}

/** 高频关键词 — ECharts 词云 */
export function buildWordCloudOption(topKeywords) {
  const list = topKeywords || []
  if (!list.length) {
    return emptyOption('暂无关键词')
  }
  const data = list
    .filter((item) => item.keyword)
    .map((item) => ({
      name: item.keyword,
      value: toNum(item.count)
    }))
  if (!data.length) {
    return emptyOption('暂无关键词')
  }
  return {
    ...chartBase(),
    tooltip: {
      show: true,
      formatter: (p) => `${p.name}: ${p.value}`
    },
    series: [
      {
        type: 'wordCloud',
        shape: 'circle',
        left: 'center',
        top: 'center',
        width: '96%',
        height: '96%',
        sizeRange: [10, 26],
        rotationRange: [-15, 15],
        rotationStep: 15,
        gridSize: 7,
        drawOutOfBound: false,
        textStyle: {
          fontFamily: 'Microsoft YaHei, sans-serif',
          fontWeight: 'bold',
          color: () => WORD_COLORS[Math.floor(Math.random() * WORD_COLORS.length)]
        },
        emphasis: {
          textStyle: {
            shadowBlur: 8,
            shadowColor: 'rgba(94, 240, 200, 0.6)'
          }
        },
        data
      }
    ]
  }
}
