/** 交易销售大屏 ECharts 配置（对齐 doc/大屏/交易销售 v1.3 滚动 12 月） */

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 DESTINATION_COLOR = ['#5ef0c8', '#ecd27b', '#6eb5ff']
const GRADE_COLOR = ['#6eb5ff', '#ecd27b', '#5ef0c8', '#0f8f72']

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/>')}`
}

function formatQuoteDate(quoteDate) {
  if (!quoteDate) {
    return ''
  }
  const parts = String(quoteDate).split('-')
  if (parts.length >= 3) {
    const mm = String(parts[1]).padStart(2, '0')
    const dd = String(parts[2]).padStart(2, '0')
    return `${mm}-${dd}`
  }
  return quoteDate
}

/** 产地行情 — 近 7 日最低/最高/均价三曲线 */
export function buildOriginQuoteOption(originQuote) {
  if (!originQuote?.hasQuoteData || !originQuote.dailyTrend?.length) {
    return emptyOption('暂无行情数据')
  }
  const dates = originQuote.dailyTrend.map((d) => formatQuoteDate(d.quoteDate))
  const minPrices = originQuote.dailyTrend.map((d) => Number(d.minPrice ?? 0))
  const maxPrices = originQuote.dailyTrend.map((d) => Number(d.maxPrice ?? 0))
  const avgPrices = originQuote.dailyTrend.map((d) => Number(d.avgPrice ?? 0))
  if (![...minPrices, ...maxPrices, ...avgPrices].some((v) => v > 0)) {
    return emptyOption('暂无行情数据')
  }
  const unit = originQuote.priceUnitLabel || ''
  return {
    color: ['#6eb5ff', '#ecd27b', '#5ef0c8'],
    tooltip: {
      trigger: 'axis',
      formatter: (params) => {
        if (!Array.isArray(params) || !params.length) {
          return ''
        }
        const row = originQuote.dailyTrend[params[0].dataIndex]
        const title = row?.quoteDate || params[0]?.name || ''
        const lines = params.map((p) => `${p.marker}${p.seriesName} ${p.value}${unit}`)
        return `${title}<br/>${lines.join('<br/>')}`
      }
    },
    legend: {
      bottom: 0,
      left: 'center',
      textStyle: { color: '#a8d4c8', fontSize: 9 },
      itemWidth: 12,
      itemHeight: 6
    },
    grid: { ...GRID, top: 8, bottom: 30 },
    xAxis: {
      type: 'category',
      data: dates,
      axisLabel: { ...AXIS_LABEL, fontSize: 9 },
      axisLine: AXIS_LINE
    },
    yAxis: {
      type: 'value',
      axisLabel: AXIS_LABEL,
      axisLine: AXIS_LINE,
      splitLine: SPLIT_LINE
    },
    series: [
      {
        name: '最低价',
        type: 'line',
        smooth: true,
        symbol: 'circle',
        symbolSize: 3,
        data: minPrices
      },
      {
        name: '最高价',
        type: 'line',
        smooth: true,
        symbol: 'circle',
        symbolSize: 3,
        data: maxPrices
      },
      {
        name: '均价',
        type: 'line',
        smooth: true,
        symbol: 'circle',
        symbolSize: 3,
        areaStyle: { color: 'rgba(94, 240, 200, 0.18)' },
        data: avgPrices
      }
    ]
  }
}

/** 牦牛交易数额趋势 — 销售量(头)柱 + 销售额(元)折线（滚动 12 月） */
export function buildTradeMonthlyOption(tradeMonthlyTrend) {
  if (!tradeMonthlyTrend?.length) {
    return emptyOption('暂无交易数据')
  }
  const axis = buildRollingAxis(tradeMonthlyTrend)
  const heads = rollingSeries(tradeMonthlyTrend, 'tradeHeads')
  const amounts = rollingSeries(tradeMonthlyTrend, 'tradeAmount')
  return {
    color: ['#5ef0c8', '#ecd27b'],
    tooltip: {
      trigger: 'axis',
      formatter: (params) =>
        rollingAxisTooltip(params, axis, (p) => {
          if (p.seriesName === '销售额') {
            return `${Number(p.value).toFixed(2)} 万元`
          }
          return `${p.value ?? 0} 头`
        })
    },
    legend: {
      top: 0,
      left: 'center',
      textStyle: { color: '#a8d4c8', fontSize: 10 },
      itemWidth: 14,
      itemHeight: 8
    },
    grid: { ...GRID, bottom: 10 },
    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 },
        minInterval: 1,
        axisLabel: AXIS_LABEL,
        axisLine: AXIS_LINE,
        splitLine: SPLIT_LINE
      },
      {
        type: 'value',
        name: '万元',
        nameTextStyle: { color: '#6a9f90', fontSize: 10 },
        axisLabel: {
          ...AXIS_LABEL,
          formatter: (v) => Number(v).toFixed(0)
        },
        axisLine: AXIS_LINE,
        splitLine: { show: false }
      }
    ],
    series: [
      {
        name: '销售量',
        type: 'bar',
        barMaxWidth: 10,
        itemStyle: { color: 'rgba(94, 240, 200, 0.75)', borderRadius: [3, 3, 0, 0] },
        data: heads
      },
      {
        name: '销售额',
        type: 'line',
        yAxisIndex: 1,
        smooth: true,
        symbol: 'circle',
        symbolSize: 4,
        lineStyle: { width: 2, color: '#ecd27b' },
        data: amounts.map((v) => Number(v) / 10000)
      }
    ]
  }
}

/** 牦牛销售去向 — 柱图 */
export function buildSalesDestinationBarOption(salesDestination) {
  if (!salesDestination?.length) {
    return emptyOption('暂无去向数据')
  }
  const sorted = [...salesDestination].sort((a, b) => a.salesDestination - b.salesDestination)
  const names = sorted.map((r) => r.salesDestinationName || '')
  const values = sorted.map((r) => r.tradeHeads ?? 0)
  return {
    color: DESTINATION_COLOR,
    tooltip: {
      trigger: 'axis',
      axisPointer: { type: 'shadow' },
      formatter: (params) => {
        const p = params[0]
        const row = sorted[p.dataIndex]
        const ratio = row?.ratio != null ? `${Number(row.ratio).toFixed(1)}%` : '—'
        return `${p.name}<br/>${p.value} 头 (${ratio})`
      }
    },
    grid: { ...GRID, top: 12, bottom: 10 },
    xAxis: {
      type: 'category',
      data: names,
      axisLabel: { ...AXIS_LABEL, interval: 0 },
      axisLine: AXIS_LINE
    },
    yAxis: {
      type: 'value',
      minInterval: 1,
      axisLabel: AXIS_LABEL,
      axisLine: AXIS_LINE,
      splitLine: SPLIT_LINE
    },
    series: [
      {
        type: 'bar',
        barMaxWidth: 36,
        itemStyle: {
          color: (params) => DESTINATION_COLOR[params.dataIndex % DESTINATION_COLOR.length],
          borderRadius: [4, 4, 0, 0]
        },
        data: values
      }
    ]
  }
}

/** 品质等级占比 — 饼图 */
export function buildQualityGradePieOption(qualityGrade) {
  if (!qualityGrade?.hasGradeData || !qualityGrade.items?.length) {
    return emptyOption('暂无等级数据')
  }
  const data = qualityGrade.items
    .map((item, i) => ({
      name: item.gradeName || item.gradeCode,
      value: item.tradeHeads ?? 0,
      itemStyle: { color: GRADE_COLOR[i % GRADE_COLOR.length] }
    }))
  if (!data.length || !data.some((item) => item.value > 0)) {
    return emptyOption('暂无等级数据')
  }
  return {
    tooltip: {
      trigger: 'item',
      formatter: (p) => {
        const row = qualityGrade.items.find(
          (it) => (it.gradeName || it.gradeCode) === p.name
        )
        const ratio = row?.ratio != null ? `${Number(row.ratio).toFixed(1)}%` : `${p.percent}%`
        return `${p.name}: ${p.value}头 (${ratio})`
      }
    },
    series: [
      {
        type: 'pie',
        radius: ['0%', '62%'],
        center: ['50%', '52%'],
        label: {
          color: '#e8eef5',
          fontSize: 10,
          formatter: (p) => {
            const row = qualityGrade.items.find(
              (it) => (it.gradeName || it.gradeCode) === p.name
            )
            const ratio = row?.ratio != null ? Number(row.ratio).toFixed(1) : p.percent
            return `${p.name}\n${ratio}%`
          }
        },
        labelLine: { length: 8, length2: 6 },
        data
      }
    ]
  }
}

const MALL_BAR_COLOR = ['#5ef0c8', '#6eb5ff', '#ecd27b', '#0f8f72', '#c9a227']
const WORD_COLORS = ['#5ef0c8', '#ecd27b', '#6eb5ff', '#98e9aa', '#0f8f72', '#c9a227']
const MALL_UNAVAILABLE_TEXT = '商城统计未接入'

function resolveMallEmptyText(mallStatsAvailable, defaultText = '暂无数据') {
  if (mallStatsAvailable === false) {
    return MALL_UNAVAILABLE_TEXT
  }
  return defaultText
}

/** 农资品类销售占比 — 2D 环形饼图 */
export function buildCategorySalesPieOption(categorySales, mallStatsAvailable = true) {
  if (mallStatsAvailable === false) {
    return emptyOption(MALL_UNAVAILABLE_TEXT)
  }
  if (!categorySales?.items?.length || !(categorySales.totalQty > 0)) {
    return emptyOption(resolveMallEmptyText(mallStatsAvailable, '暂无品类数据'))
  }
  const data = categorySales.items
    .filter((item) => (item.qty ?? 0) > 0)
    .map((item) => ({
      name: item.categoryName || '未分类',
      value: item.qty ?? 0
    }))
  if (!data.length) {
    return emptyOption('暂无品类数据')
  }
  const totalQty = categorySales.totalQty ?? data.reduce((sum, d) => sum + d.value, 0)
  return buildMallPie2DOption(data, {
    summaryTitle: String(totalQty),
    summarySubtext: '总销量(件)',
    legend: {
      formatter: (name) => (name.length > 6 ? `${name.slice(0, 5)}…` : name)
    },
    tooltipFormatter: (p) => {
      const row = categorySales.items.find((it) => (it.categoryName || '未分类') === p.name)
      const ratio = row?.ratio != null ? `${Number(row.ratio).toFixed(1)}%` : `${p.percent}%`
      return `${p.name}<br/>${p.value} 件 (${ratio})`
    }
  })
}

/** 商城订单趋势 — 曲线（滚动 12 月） */
export function buildMallOrderTrendOption(mallOrderTrend, mallStatsAvailable = true) {
  if (mallStatsAvailable === false) {
    return emptyOption(MALL_UNAVAILABLE_TEXT)
  }
  const items = mallOrderTrend?.items || []
  if (!items.length) {
    return emptyOption(resolveMallEmptyText(mallStatsAvailable, '暂无订单数据'))
  }
  const axis = buildRollingAxis(items)
  const counts = rollingSeries(items, 'orderCount')
  return {
    color: ['#6eb5ff'],
    tooltip: {
      trigger: 'axis',
      formatter: (params) =>
        rollingAxisTooltip(params, axis, (p) => `${p.value ?? 0} 单`)
    },
    grid: { ...GRID, top: 12, bottom: 10 },
    xAxis: {
      type: 'category',
      data: axis.categories,
      axisLabel: { ...AXIS_LABEL, rotate: 35, interval: 0, 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(110, 181, 255, 0.22)' },
        data: counts
      }
    ]
  }
}

/** 店铺入驻 — 2D 环形饼图（按月占比） */
export function buildShopEntryPieOption(shopEntry, mallStatsAvailable = true) {
  if (mallStatsAvailable === false) {
    return emptyOption(MALL_UNAVAILABLE_TEXT)
  }
  if (!shopEntry?.items?.length || !(shopEntry.yearTotal > 0)) {
    return emptyOption(resolveMallEmptyText(mallStatsAvailable, '暂无入驻数据'))
  }
  const data = shopEntry.items
    .filter((item) => (item.shopCount ?? 0) > 0)
    .map((item) => ({
      name: `${item.month}月`,
      value: item.shopCount ?? 0
    }))
  if (!data.length) {
    return emptyOption('暂无入驻数据')
  }
  const yearTotal = shopEntry.yearTotal ?? data.reduce((sum, d) => sum + d.value, 0)
  return buildMallPie2DOption(data, {
    summaryTitle: String(yearTotal),
    summarySubtext: '年入驻(家)',
    legend: { itemGap: 4 },
    tooltipFormatter: (p) => {
      const row = shopEntry.items.find((it) => `${it.month}月` === p.name)
      const ratio = row?.ratio != null ? `${Number(row.ratio).toFixed(1)}%` : `${p.percent}%`
      return `${p.name}<br/>${p.value} 家 (${ratio})`
    }
  })
}

/** 消费区域排名 Top5 — 柱图（万元） */
export function buildRegionRankBarOption(regionRank, mallStatsAvailable = true) {
  if (mallStatsAvailable === false) {
    return emptyOption(MALL_UNAVAILABLE_TEXT)
  }
  if (!regionRank?.items?.length) {
    return emptyOption(resolveMallEmptyText(mallStatsAvailable, '暂无区域数据'))
  }
  const sorted = [...regionRank.items].sort((a, b) => a.rank - b.rank)
  const names = sorted.map((r) => r.city || '')
  const values = sorted.map((r) => Number(r.amountWan ?? 0))
  if (!values.some((v) => v > 0)) {
    return emptyOption('暂无区域数据')
  }
  return {
    color: MALL_BAR_COLOR,
    tooltip: {
      trigger: 'axis',
      axisPointer: { type: 'shadow' },
      formatter: (params) => {
        const p = params[0]
        return `${p.name}<br/>${Number(p.value).toFixed(2)} 万元`
      }
    },
    grid: { ...GRID, top: 12, bottom: 10 },
    xAxis: {
      type: 'category',
      data: names,
      axisLabel: { ...AXIS_LABEL, interval: 0, fontSize: 9 },
      axisLine: AXIS_LINE
    },
    yAxis: {
      type: 'value',
      axisLabel: AXIS_LABEL,
      axisLine: AXIS_LINE,
      splitLine: SPLIT_LINE
    },
    series: [
      {
        type: 'bar',
        barMaxWidth: 28,
        itemStyle: {
          color: (params) => MALL_BAR_COLOR[params.dataIndex % MALL_BAR_COLOR.length],
          borderRadius: [4, 4, 0, 0]
        },
        data: values
      }
    ]
  }
}

/** 消费者评价词云 */
export function buildReviewWordCloudOption(reviewWordCloud, mallStatsAvailable = true) {
  if (mallStatsAvailable === false) {
    return emptyOption(MALL_UNAVAILABLE_TEXT)
  }
  const list = reviewWordCloud?.items || []
  if (!list.length) {
    return emptyOption(resolveMallEmptyText(mallStatsAvailable, '暂无评价数据'))
  }
  const data = list
    .filter((item) => item.word)
    .map((item) => ({
      name: item.word,
      value: Number(item.count ?? 0)
    }))
  if (!data.length) {
    return emptyOption('暂无评价数据')
  }
  return {
    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(110, 181, 255, 0.6)'
          }
        },
        data
      }
    ]
  }
}
