/**
 * ECharts 工具函数和配置
 *
 * 提供统一的 ECharts 主题、配置和工具函数
 */

import type { EChartOption } from 'echarts'

/**
 * ECharts 主题配置 - 青灰色系
 */
export const echartsTheme = {
  // 颜色系列
  color: [
    '#475569', // 主色（青灰）
    '#64748b', // 次要色
    '#94a3b8', // 辅助色
    '#cbd5e1', // 浅灰色
    '#f59e0b', // 强调色（橙黄）
    '#10b981', // 成功色（绿）
    '#ef4444', // 危险色（红）
    '#3b82f6', // 信息色（蓝）
  ],

  // 背景色
  bgColor: '#ffffff',

  // 文字颜色
  textColor: '#1e293b',
  textColor2: '#64748b',

  // 边框颜色
  borderColor: '#e2e8f0',
  borderColor2: '#cbd5e1',

  // 分隔线颜色
  splitLineColor: '#f1f5f9',

  // 图表内边距
  padding: [20, 20, 20, 20],

  // 字体
  fontFamily: '-apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, "Helvetica Neue", Arial, sans-serif',
}

/**
 * 资产状态颜色映射
 */
export const assetStatusColors: Record<string, string> = {
  pending: '#94a3b8',        // 待入账 - 灰色
  in_stock: '#3b82f6',       // 库存中 - 蓝色
  in_use: '#10b981',         // 在用 - 绿色
  transferring: '#f59e0b',   // 调拨中 - 橙色
  maintenance: '#ef4444',    // 维修中 - 红色
  pending_scrap: '#8b5cf6',  // 待报废 - 紫色
  scrapped: '#64748b',       // 已报废 - 深灰
  lost: '#dc2626',           // 丢失 - 深红
}

/**
 * 资产状态名称映射
 */
export const assetStatusNames: Record<string, string> = {
  pending: '待入账',
  in_stock: '库存中',
  in_use: '在用',
  transferring: '调拨中',
  maintenance: '维修中',
  pending_scrap: '待报废',
  scrapped: '已报废',
  lost: '已丢失',
}

/**
 * 基础图表配置
 */
export const baseChartOption: EChartOption = {
  backgroundColor: echartsTheme.bgColor,
  textStyle: {
    fontFamily: echartsTheme.fontFamily,
    color: echartsTheme.textColor,
  },
  title: {
    textStyle: {
      color: echartsTheme.textColor,
      fontSize: 16,
      fontWeight: 600,
    },
    subtextStyle: {
      color: echartsTheme.textColor2,
      fontSize: 12,
    },
    left: 'center',
    top: 10,
  },
  tooltip: {
    trigger: 'axis',
    backgroundColor: 'rgba(255, 255, 255, 0.95)',
    borderColor: echartsTheme.borderColor,
    borderWidth: 1,
    textStyle: {
      color: echartsTheme.textColor,
      fontSize: 12,
    },
    extraCssText: 'box-shadow: 0 2px 8px rgba(0,0,0,0.1); border-radius: 4px;',
  },
  legend: {
    textStyle: {
      color: echartsTheme.textColor,
      fontSize: 12,
    },
    top: 40,
    left: 'center',
  },
  grid: {
    left: '3%',
    right: '4%',
    bottom: '3%',
    top: 80,
    containLabel: true,
  },
}

/**
 * 饼图配置
 */
export const pieChartOption: EChartOption = {
  ...baseChartOption,
  tooltip: {
    ...baseChartOption.tooltip,
    trigger: 'item',
    formatter: '{b}: {c} ({d}%)',
  },
  legend: {
    ...baseChartOption.legend,
    orient: 'horizontal',
    itemGap: 20,
  },
  series: [
    {
      type: 'pie',
      radius: ['40%', '70%'],
      avoidLabelOverlap: true,
      itemStyle: {
        borderRadius: 8,
        borderColor: '#fff',
        borderWidth: 2,
      },
      label: {
        show: true,
        formatter: '{b}: {d}%',
        color: echartsTheme.textColor,
        fontSize: 12,
      },
      emphasis: {
        label: {
          show: true,
          fontSize: 14,
          fontWeight: 'bold',
        },
        itemStyle: {
          shadowBlur: 10,
          shadowOffsetX: 0,
          shadowColor: 'rgba(0, 0, 0, 0.2)',
        },
      },
      labelLine: {
        show: true,
        length: 15,
        length2: 10,
        smooth: true,
      },
    },
  ],
}

/**
 * 柱状图配置
 */
export const barChartOption: EChartOption = {
  ...baseChartOption,
  tooltip: {
    ...baseChartOption.tooltip,
    trigger: 'axis',
    axisPointer: {
      type: 'shadow',
    },
  },
  xAxis: {
    type: 'category',
    axisLine: {
      lineStyle: {
        color: echartsTheme.borderColor,
      },
    },
    axisTick: {
      alignWithLabel: true,
    },
    axisLabel: {
      color: echartsTheme.textColor2,
      fontSize: 12,
      interval: 0,
      rotate: 0,
    },
  },
  yAxis: {
    type: 'value',
    axisLine: {
      show: false,
    },
    axisTick: {
      show: false,
    },
    axisLabel: {
      color: echartsTheme.textColor2,
      fontSize: 12,
    },
    splitLine: {
      lineStyle: {
        color: echartsTheme.splitLineColor,
        type: 'dashed',
      },
    },
  },
  series: [
    {
      type: 'bar',
      barMaxWidth: 50,
      itemStyle: {
        borderRadius: [4, 4, 0, 0],
      },
    },
  ],
}

/**
 * 折线图配置
 */
export const lineChartOption: EChartOption = {
  ...baseChartOption,
  tooltip: {
    ...baseChartOption.tooltip,
    trigger: 'axis',
  },
  xAxis: {
    type: 'category',
    boundaryGap: false,
    axisLine: {
      lineStyle: {
        color: echartsTheme.borderColor,
      },
    },
    axisLabel: {
      color: echartsTheme.textColor2,
      fontSize: 12,
    },
  },
  yAxis: {
    type: 'value',
    axisLine: {
      show: false,
    },
    axisTick: {
      show: false,
    },
    axisLabel: {
      color: echartsTheme.textColor2,
      fontSize: 12,
    },
    splitLine: {
      lineStyle: {
        color: echartsTheme.splitLineColor,
        type: 'dashed',
      },
    },
  },
  series: [
    {
      type: 'line',
      smooth: true,
      symbol: 'circle',
      symbolSize: 6,
      lineStyle: {
        width: 2,
      },
      areaStyle: {
        opacity: 0.1,
      },
    },
  ],
}

/**
 * 仪表盘配置
 */
export const gaugeChartOption: EChartOption = {
  ...baseChartOption,
  series: [
    {
      type: 'gauge',
      startAngle: 180,
      endAngle: 0,
      min: 0,
      max: 100,
      splitNumber: 10,
      radius: '80%',
      center: ['50%', '60%'],
      itemStyle: {
        color: echartsTheme.color[4],
      },
      progress: {
        show: true,
        roundCap: true,
        width: 18,
      },
      pointer: {
        show: false,
      },
      axisLine: {
        roundCap: true,
        lineStyle: {
          width: 18,
          color: [[1, echartsTheme.borderColor2]],
        },
      },
      axisTick: {
        splitNumber: 5,
        lineStyle: {
          width: 2,
          color: '#999',
        },
      },
      splitLine: {
        length: 12,
        lineStyle: {
          width: 3,
          color: '#999',
        },
      },
      axisLabel: {
        distance: 25,
        color: echartsTheme.textColor2,
        fontSize: 12,
      },
      detail: {
        backgroundColor: echartsTheme.color[0],
        borderColor: echartsTheme.color[0],
        width: '60%',
        lineHeight: 40,
        height: 40,
        borderRadius: 20,
        offsetCenter: [0, '15%'],
        valueAnimation: true,
        formatter: '{value}%',
        textStyle: {
          fontSize: 24,
          fontWeight: 'bold',
          color: '#fff',
        },
      },
      data: [
        {
          value: 0,
        },
      ],
    },
  ],
}

/**
 * 漏斗图配置
 */
export const funnelChartOption: EChartOption = {
  ...baseChartOption,
  tooltip: {
    ...baseChartOption.tooltip,
    trigger: 'item',
    formatter: '{b}: {c}',
  },
  series: [
    {
      type: 'funnel',
      left: '10%',
      top: 60,
      bottom: 60,
      width: '80%',
      minSize: '0%',
      maxSize: '100%',
      sort: 'descending',
      gap: 2,
      label: {
        show: true,
        position: 'inside',
        formatter: '{b}: {c}',
        fontSize: 12,
        color: '#fff',
      },
      labelLine: {
        length: 10,
        lineStyle: {
          width: 1,
          type: 'solid',
        },
      },
      itemStyle: {
        borderColor: '#fff',
        borderWidth: 1,
      },
      emphasis: {
        label: {
          fontSize: 14,
        },
      },
    },
  ],
}

/**
 * 格式化数值
 * @param value 数值
 * @param decimals 小数位数
 */
export function formatNumber(value: number, decimals: number = 2): string {
  if (value === 0) return '0'
  if (value < 1000) return value.toFixed(decimals)
  if (value < 10000) return (value / 1000).toFixed(decimals) + 'K'
  if (value < 1000000) return (value / 10000).toFixed(decimals) + '万'
  return (value / 1000000).toFixed(decimals) + 'M'
}

/**
 * 格式化金额
 * @param value 金额
 */
export function formatCurrency(value: number): string {
  if (value === 0) return '¥0.00'
  if (value < 10000) return `¥${value.toFixed(2)}`
  if (value < 100000000) return `¥${(value / 10000).toFixed(2)}万`
  return `¥${(value / 100000000).toFixed(2)}亿`
}

/**
 * 格式化百分比
 * @param value 数值
 * @param total 总数
 */
export function formatPercentage(value: number, total: number): string {
  if (total === 0) return '0%'
  return ((value / total) * 100).toFixed(1) + '%'
}

/**
 * 生成图表颜色
 * @param index 索引
 */
export function getColor(index: number): string {
  return echartsTheme.color[index % echartsTheme.color.length]
}

/**
 * 获取资产状态颜色
 * @param status 资产状态
 */
export function getAssetStatusColor(status: string): string {
  return assetStatusColors[status] || echartsTheme.color[0]
}

/**
 * 获取资产状态名称
 * @param status 资产状态
 */
export function getAssetStatusName(status: string): string {
  return assetStatusNames[status] || status
}

/**
 * 适配图表尺寸
 * @param chartRef 图表容器引用
 * @param delay 延迟时间（ms）
 */
export function resizeChart(chartRef: any, delay: number = 300) {
  setTimeout(() => {
    if (chartRef && chartRef.resize) {
      chartRef.resize()
    }
  }, delay)
}

/**
 * 合并图表配置
 * @param target 目标配置
 * @param source 源配置
 */
export function mergeOption(target: any, source: any): EChartOption {
  return {
    ...target,
    ...source,
    series: source.series || target.series,
  }
}
