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' },
  };
}

function generateStardust(nodes: Array<{ value: number[] }>, count = 50): Array<{ value: number[] }> {
  const particles: Array<{ value: number[] }> = [];
  // 中国地理范围：经度 73~135，纬度 18~54
  const lngRange = [75, 132];
  const latRange = [20, 52];
  for (let i = 0; i < count; i++) {
    // 种子式分布：部分粒子靠近仓库节点，部分随机
    if (i < count * 0.4 && nodes.length > 0) {
      const seed = nodes[i % nodes.length];
      const [lng, lat] = seed.value;
      particles.push({
        value: [lng + (Math.random() - 0.5) * 6, lat + (Math.random() - 0.5) * 4],
      });
    } else {
      particles.push({
        value: [
          lngRange[0] + Math.random() * (lngRange[1] - lngRange[0]),
          latRange[0] + Math.random() * (latRange[1] - latRange[0]),
        ],
      });
    }
  }
  return particles;
}

/** 中国地图 + 仓库节点（高级光态特效版） */
export function getChinaMapOptions(
  warehouseNodes: Array<{ name: string; value: number[]; stock: number }>,
  flyLines: Array<{ from: string; to: string }> = [],
): EChartsOption {
  const nodeData = warehouseNodes.map((n) => ({
    name: n.name,
    value: [...n.value, n.stock],
  }));

  const maxStock = Math.max(1, ...warehouseNodes.map((n) => Math.abs(n.stock)));

  // 节点光晕尺寸映射
  function glowSize(stock: number, base: number, range: number) {
    return base + (Math.abs(stock) / maxStock) * range;
  }

  const stardust = generateStardust(warehouseNodes, 50);

  return {
    geo: {
      map: 'china',
      roam: false,
      label: { show: false },
      // 底层区域发光：用两层 geo 实现，这里增强主 geo 样式
      itemStyle: {
        areaColor: {
          type: 'linear',
          x: 0, y: 0, x2: 0, y2: 1,
          colorStops: [
            { offset: 0, color: '#0d1f4a' },
            { offset: 0.4, color: '#0a1838' },
            { offset: 0.7, color: '#08102a' },
            { offset: 1, color: '#060e20' },
          ],
        },
        borderColor: 'rgba(0, 229, 255, 0.28)',
        borderWidth: 1.5,
        shadowBlur: 18,
        shadowColor: 'rgba(0, 180, 255, 0.25)',
        shadowOffsetX: 0,
        shadowOffsetY: 0,
      },
      emphasis: {
        disabled: true,
      },
      // 第二层 outline 通过 zlevel 更高的 border 模拟
      regions: [],
    },
    series: [
      // ====== Series 0: 外层光晕（大尺寸、极低透明度） ======
      {
        name: 'outerGlow',
        type: 'scatter',
        coordinateSystem: 'geo',
        data: nodeData,
        symbolSize: (val: number[]) => glowSize(val[2] || 0, 50, 30),
        silent: true,
        itemStyle: {
          color: {
            type: 'radial',
            x: 0.5, y: 0.5, r: 0.5,
            colorStops: [
              { offset: 0, color: 'rgba(0,229,255,0.12)' },
              { offset: 0.3, color: 'rgba(0,229,255,0.05)' },
              { offset: 1, color: 'rgba(0,229,255,0)' },
            ],
          },
        },
        emphasis: { disabled: true },
        zlevel: 1,
      },
      // ====== Series 1: 内层光晕（中等尺寸，脉动式） ======
      {
        name: 'innerGlow',
        type: 'scatter',
        coordinateSystem: 'geo',
        data: nodeData,
        symbolSize: (val: number[]) => glowSize(val[2] || 0, 26, 18),
        silent: true,
        itemStyle: {
          color: {
            type: 'radial',
            x: 0.5, y: 0.5, r: 0.5,
            colorStops: [
              { offset: 0, color: 'rgba(0,255,200,0.22)' },
              { offset: 0.4, color: 'rgba(0,229,255,0.1)' },
              { offset: 1, color: 'rgba(0,150,255,0)' },
            ],
          },
        },
        emphasis: { disabled: true },
        zlevel: 2,
      },
      // ====== Series 2: 主节点（effectScatter 涟漪光效） ======
      {
        name: 'warehouseNodes',
        type: 'effectScatter',
        coordinateSystem: 'geo',
        data: nodeData,
        symbolSize: (val: number[]) => Math.max(10, Math.min(26, glowSize(val[2] || 0, 10, 12))),
        showEffectOn: 'render',
        rippleEffect: {
          brushType: 'stroke',
          scale: 5.5,
          period: 3.5,
          color: {
            type: 'radial',
            x: 0.5, y: 0.5, r: 0.5,
            colorStops: [
              { offset: 0, color: C.cyan },
              { offset: 0.4, color: 'rgba(0,229,255,0.5)' },
              { offset: 1, color: 'rgba(0,100,255,0)' },
            ],
          },
        },
        label: {
          show: true,
          position: 'bottom',
          distance: 14,
          formatter: '{b}',
          fontSize: 11,
          fontWeight: 'bold',
          color: C.textPrimary,
          textShadowBlur: 8,
          textShadowColor: 'rgba(0,229,255,0.5)',
        },
        itemStyle: {
          color: {
            type: 'radial',
            x: 0.5, y: 0.5, r: 0.5,
            colorStops: [
              { offset: 0, color: '#ffffff' },
              { offset: 0.15, color: '#b5f0ff' },
              { offset: 0.45, color: C.cyan },
              { offset: 1, color: 'rgba(0,120,220,0.3)' },
            ],
          },
          shadowBlur: 28,
          shadowColor: C.cyan,
        },
        emphasis: {
          scale: 1.6,
          itemStyle: {
            shadowBlur: 40,
            shadowColor: '#fff',
          },
          label: {
            fontSize: 13,
            textShadowBlur: 14,
            textShadowColor: 'rgba(0,229,255,0.8)',
          },
        },
        zlevel: 3,
      },
      // ====== Series 3: 亮核（白色高亮核心） ======
      {
        name: 'nodeCores',
        type: 'scatter',
        coordinateSystem: 'geo',
        data: nodeData,
        symbolSize: (val: number[]) => Math.max(3, Math.min(7, glowSize(val[2] || 0, 3, 3))),
        silent: true,
        itemStyle: {
          color: {
            type: 'radial',
            x: 0.5, y: 0.5, r: 0.5,
            colorStops: [
              { offset: 0, color: '#ffffff' },
              { offset: 0.5, color: 'rgba(255,255,255,0.7)' },
              { offset: 1, color: 'rgba(255,255,255,0)' },
            ],
          },
          shadowBlur: 14,
          shadowColor: '#fff',
        },
        emphasis: { disabled: true },
        zlevel: 4,
      },
      // ====== Series 4: 飞线（光流） ======
      {
        name: 'flyLines',
        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: 0.5, color: '#5ce6ff' },
              { offset: 1, color: C.green },
            ],
          },
          curveness: 0.28,
          width: 1.5,
          opacity: 0.6,
          shadowBlur: 8,
          shadowColor: 'rgba(0,229,255,0.4)',
        },
        effect: {
          show: true,
          period: 2.5,
          trailLength: 0.5,
          symbol: 'arrow',
          symbolSize: 7,
          color: {
            type: 'radial',
            x: 0.5, y: 0.5, r: 0.5,
            colorStops: [
              { offset: 0, color: '#fff' },
              { offset: 0.5, color: C.green },
              { offset: 1, color: 'rgba(0,255,136,0)' },
            ],
          },
        },
        zlevel: 2,
      },
      // ====== Series 5: 环境光尘（背景粒子） ======
      {
        name: 'stardust',
        type: 'scatter',
        coordinateSystem: 'geo',
        data: stardust,
        symbolSize: 2,
        silent: true,
        itemStyle: {
          color: 'rgba(100,200,255,0.5)',
          shadowBlur: 4,
          shadowColor: 'rgba(100,180,255,0.5)',
        },
        emphasis: { disabled: true },
        zlevel: 0,
      },
    ],
    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' },
  };
}
