import type { EChartsOption } from '@vben/plugins/echarts';

/** 科技蓝暗色主题色板 */
const C = {
  cyan: '#00E5FF',
  green: '#00FF88',
  yellow: '#FFC107',
  red: '#FF3860',
  blue: '#3366FF',
  purple: '#8B5CF6',
  orange: '#FF6B35',
  textPrimary: 'rgba(235, 240, 252, 0.95)',
  textSecondary: 'rgba(180, 196, 220, 0.65)',
  border: 'rgba(56, 128, 237, 0.12)',
  splitLine: 'rgba(56, 128, 237, 0.08)',
};

const darkAxis = {
  axisLabel: { color: C.textSecondary, fontSize: 10 },
  axisLine: { lineStyle: { color: C.border } },
  axisTick: { show: false },
  splitLine: { lineStyle: { color: C.splitLine } },
};

const techTooltip = {
  backgroundColor: 'rgba(6, 18, 42, 0.94)',
  borderColor: 'rgba(0, 229, 255, 0.28)',
  borderWidth: 1,
  padding: [10, 14],
  textStyle: { color: C.textPrimary, fontSize: 11 },
};

/** 渐变柱状图（出入库趋势） */
export function getWarehouseBarOptions(
  xData: string[],
  series: Array<{ name: string; data: number[] }>,
): EChartsOption {
  const colors = [C.cyan, C.green];
  return {
    grid: { bottom: 40, left: 48, right: 16, top: 16 },
    legend: { bottom: 0, itemGap: 12, textStyle: { color: C.textSecondary, fontSize: 10 } },
    tooltip: { ...techTooltip, axisPointer: { type: 'shadow' }, trigger: 'axis' },
    xAxis: { ...darkAxis, data: xData, type: 'category' },
    yAxis: { ...darkAxis, type: 'value' },
    series: series.map((s, i) => ({
      barGap: '30%',
      barMaxWidth: 24,
      data: s.data,
      emphasis: { itemStyle: { shadowBlur: 10, shadowColor: colors[i] } },
      itemStyle: {
        borderRadius: [4, 4, 0, 0],
        color: { colorStops: [{ color: colors[i], offset: 0 }, { color: `${colors[i]}22`, offset: 1 }], type: 'linear', x: 0, y: 0, x2: 0, y2: 1 },
      },
      name: s.name,
      type: 'bar',
    })),
  };
}

/** 渐变面积折线图（库存趋势） */
export function getWarehouseAreaLineOptions(
  xData: string[],
  series: Array<{ name: string; data: number[] }>,
): EChartsOption {
  const colors = [C.cyan, C.purple, C.green];
  return {
    grid: { bottom: 40, left: 48, right: 16, top: 16 },
    legend: { bottom: 0, itemGap: 12, textStyle: { color: C.textSecondary, fontSize: 10 } },
    tooltip: { ...techTooltip, axisPointer: { type: 'cross' }, trigger: 'axis' },
    xAxis: { ...darkAxis, boundaryGap: false, data: xData, type: 'category' },
    yAxis: { ...darkAxis, type: 'value' },
    series: series.map((s, i) => ({
      areaStyle: { color: { colorStops: [{ color: `${colors[i]}22`, offset: 0 }, { color: `${colors[i]}02`, offset: 1 }], type: 'linear', x: 0, y: 0, x2: 0, y2: 1 } },
      data: s.data,
      itemStyle: { color: colors[i] },
      lineStyle: { width: 2 },
      name: s.name,
      smooth: true,
      symbol: 'circle',
      symbolSize: 4,
      type: 'line',
    })),
  };
}

/** 环形饼图（库存结构） */
export function getWarehouseDonutOptions(
  data: Array<{ name: string; value: number }>,
  colors: string[] = [C.cyan, C.blue, C.purple, C.green, C.yellow, C.orange],
): EChartsOption {
  return {
    legend: { bottom: 0, itemGap: 8, textStyle: { color: C.textSecondary, fontSize: 9 }, type: 'scroll' },
    series: [{
      avoidLabelOverlap: true,
      data,
      emphasis: {
        itemStyle: { shadowBlur: 16, shadowColor: 'rgba(0,229,255,0.3)' },
        label: { fontSize: 12, fontWeight: 'bold', show: true },
        scaleSize: 8,
      },
      itemStyle: {
        borderColor: '#06152F',
        borderRadius: 3,
        borderWidth: 3,
        color: (params: { dataIndex: number }) => colors[params.dataIndex % colors.length],
      },
      label: { show: false },
      radius: ['55%', '78%'],
      type: 'pie',
    }],
    tooltip: { ...techTooltip, formatter: '{b}: {c} ({d}%)', trigger: 'item' },
  };
}

/** 中国地图 + 仓库节点 */
export function getChinaMapOptions(
  warehouseNodes: Array<{ name: string; value: number[]; stock: number }>,
  flyLines: Array<{ from: string; to: string }> = [],
): EChartsOption {
  return {
    geo: {
      map: 'china',
      roam: false,
      label: { show: false },
      itemStyle: {
        areaColor: {
          type: 'linear',
          x: 0, y: 0, x2: 0, y2: 1,
          colorStops: [
            { offset: 0, color: '#0d1f42' },
            { offset: 0.5, color: '#0a1835' },
            { offset: 1, color: '#081028' },
          ],
        },
        borderColor: 'rgba(0, 229, 255, 0.22)',
        borderWidth: 1.2,
        shadowColor: 'rgba(0, 229, 255, 0.08)',
        shadowOffsetX: 0,
        shadowOffsetY: 3,
      },
      emphasis: {
        itemStyle: {
          areaColor: '#132848',
          borderColor: 'rgba(0, 229, 255, 0.45)',
          borderWidth: 1.5,
        },
      },
    },
    series: [
      {
        type: 'effectScatter',
        coordinateSystem: 'geo',
        data: warehouseNodes.map((n) => ({
          name: n.name,
          value: [...n.value, n.stock],
        })),
        symbolSize: (val: number[]) => Math.max(8, Math.min(22, (val[2] || 1) / 1500)),
        showEffectOn: 'render',
        rippleEffect: { brushType: 'stroke', scale: 4, period: 4.5 },
        label: {
          show: true,
          position: 'bottom',
          distance: 8,
          formatter: '{b}',
          fontSize: 10,
          color: C.textPrimary,
        },
        itemStyle: {
          color: {
            type: 'radial',
            x: 0.5, y: 0.5, r: 0.5,
            colorStops: [
              { offset: 0, color: '#fff' },
              { offset: 0.3, color: C.cyan },
              { offset: 1, color: 'rgba(0,229,255,0.3)' },
            ],
          },
          shadowBlur: 20,
          shadowColor: C.cyan,
        },
        zlevel: 1,
      },
      {
        type: 'lines',
        coordinateSystem: 'geo',
        data: flyLines.map((f) => {
          const from = warehouseNodes.find((n) => n.name === f.from);
          const to = warehouseNodes.find((n) => n.name === f.to);
          return { coords: [from?.value, to?.value].filter(Boolean) };
        }),
        lineStyle: {
          color: {
            type: 'linear',
            x: 0, y: 0, x2: 1, y2: 1,
            colorStops: [
              { offset: 0, color: C.cyan },
              { offset: 1, color: C.green },
            ],
          },
          curveness: 0.25,
          width: 1.2,
          opacity: 0.5,
        },
        effect: {
          show: true,
          period: 3,
          trailLength: 0.4,
          symbol: 'arrow',
          symbolSize: 6,
          color: C.green,
        },
        zlevel: 1,
      },
    ],
    tooltip: {
      backgroundColor: 'rgba(6, 18, 42, 0.94)',
      borderColor: 'rgba(0, 229, 255, 0.3)',
      borderWidth: 1,
      padding: [10, 14],
      textStyle: { color: C.textPrimary, fontSize: 12, fontFamily: 'monospace' },
      formatter: (params: { name?: string; value?: number[] }) => {
        if (!params.value || params.value.length < 3) return '';
        return `<div style="font-size:13px;font-weight:600;margin-bottom:6px;color:${C.cyan}">${params.name}</div>
          <div style="display:flex;justify-content:space-between;gap:20px">
            <span style="color:${C.textSecondary}">库存量</span>
            <span style="font-weight:700">${params.value[2].toLocaleString()}</span>
          </div>`;
      },
      trigger: 'item',
    },
  };
}

/** 仪表盘（库存周转率） */
export function getWarehouseGaugeOptions(value: number, max = 2): EChartsOption {
  return {
    series: [{
      anchor: { show: true, showAbove: true, size: 12 },
      axisLine: {
        lineStyle: {
          color: [[0.3, C.red], [0.7, C.yellow], [1, C.green]],
          width: 12,
        },
      },
      axisTick: { distance: -16, length: 4, lineStyle: { width: 1, color: C.textSecondary } },
      data: [{ name: '周转率', value }],
      detail: {
        color: C.cyan,
        fontSize: 22,
        fontWeight: 'bold',
        formatter: '{value}',
        offsetCenter: [0, '55%'],
        valueAnimation: true,
      },
      pointer: { length: '65%', width: 4, itemStyle: { color: C.cyan } },
      progress: { itemStyle: { color: C.cyan }, show: true, width: 12 },
      radius: '100%',
      splitLine: { distance: -18, length: 10, lineStyle: { width: 2, color: C.textSecondary } },
      title: { fontSize: 11, offsetCenter: [0, '80%'], color: C.textSecondary },
      type: 'gauge',
      max,
    }],
    tooltip: { ...techTooltip, formatter: '周转率: {c}', trigger: 'item' },
  };
}

/** 迷你趋势线（KPI 卡片内） */
export function getMiniTrendOptions(data: number[], color = C.green): EChartsOption {
  return {
    grid: { top: 4, bottom: 4, left: 0, right: 0 },
    xAxis: { show: false, data: data.map((_, i) => i) },
    yAxis: { show: false, min: Math.min(...data) * 0.9 },
    series: [{
      areaStyle: { color: { colorStops: [{ color: `${color}22`, offset: 0 }, { color: `${color}02`, offset: 1 }], type: 'linear', x: 0, y: 0, x2: 0, y2: 1 } },
      data,
      itemStyle: { color },
      lineStyle: { width: 1.5 },
      showSymbol: false,
      smooth: true,
      type: 'line',
    }],
  };
}

/** 时间轴动态列表 */
export function getTimelineOptions(events: Array<{ time: string; type: string; title: string }>): EChartsOption {
  const typeColor: Record<string, string> = { '到货': C.green, '出货': C.cyan, '预警': C.yellow, '调拨': C.purple };
  return {
    grid: { top: 8, bottom: 8, left: 16, right: 16 },
    xAxis: { show: false, min: 0, max: 1 },
    yAxis: { show: false, type: 'category', inverse: true, data: events.map((e) => e.title) },
    series: [{
      type: 'scatter',
      symbol: 'roundRect',
      symbolSize: [8, 8],
      data: events.map((_, i) => [0, i]),
      itemStyle: { color: (p: { dataIndex: number }) => typeColor[events[p.dataIndex]?.type] || C.cyan },
    }],
    tooltip: { ...techTooltip, formatter: (p: { dataIndex: number }) => {
      const e = events[p.dataIndex];
      return `<div style="font-size:12px;font-weight:600;margin-bottom:4px;color:${typeColor[e?.type] || C.cyan}">${e?.type}</div>
        <span style="color:${C.textSecondary}">${e?.time}</span>&nbsp;&nbsp;${e?.title}`;
    }, trigger: 'item' },
  };
}
