import { ChartConfig } from '@/types/analysis/industry';
import dayjs from 'dayjs';
import { formatDateForDisplay } from '../utils';

// 统一的颜色方案
const COLOR_PALETTE = [
  '#1890ff',
  '#36cfc9',
  '#faad14',
  '#f5222d',
  '#722ed1',
  '#fa8c16',
  '#52c41a',
  '#eb2f96',
  '#13c2c2',
  '#eb2f96',
];

export const getHeatmapConfig = (areaData: any[], timeDimension: string) => {
  const sortedData = [...areaData].sort((a, b) => {
    if (timeDimension === '年') {
      return parseInt(a.time) - parseInt(b.time);
    } else if (timeDimension === '季度') {
      const [yearA, quarterA] = a.time.split('-Q');
      const [yearB, quarterB] = b.time.split('-Q');
      return yearA === yearB
        ? parseInt(quarterA) - parseInt(quarterB)
        : parseInt(yearA) - parseInt(yearB);
    } else {
      return dayjs(a.time).valueOf() - dayjs(b.time).valueOf();
    }
  });

  return {
    data: sortedData,
    height: 280,
    autoFit: true,
    xField: 'name',
    yField: 'time',
    colorField: 'value',       
    shapeField: 'square',      
    sizeField: 'value',        
    xAxis: {
      title: {
        text: '区域',
        style: {
          fontSize: 12,
          fill: '#666',
        },
      },
      label: {
        style: {
          fontSize: 10,
          fill: '#666',
        },
        formatter: (text: string) => {
          return text.length > 4 ? `${text.substring(0, 3)}...` : text;
        },
      },
    },
    yAxis: {
      title: {
        text: '时间',
        style: {
          fontSize: 12,
          fill: '#666',
        },
      },
      label: {
        formatter: (text: string) => {
          if (timeDimension === '年') return `${text}年`;
          if (timeDimension === '季度') return text.replace('-Q', '年Q');
          return text.replace('-', '年').replace('-', '月');
        },
        style: {
          fontSize: 10,
          fill: '#666',
        },
      },
    },
    label: {
      text: (d: { value: number }) => (d.value > 0 ? d.value.toString() : ''),
      position: 'inside',
      style: {
        fill: '#fff',
        fontSize: 10,
        fontWeight: 'bold',
      },
    },
    // 关键配置：值越大，颜色越深；值越大，方块越大
    scale: {
      size: {
        range: [12, 20], // 小值对应小方块，大值对应大方块
      },
      color: {
        range: [
          '#b7c2c3ff', // 浅色，对应小值
          '#afd4fbff',
          '#8ecaf0ff',
          '#40a9ff',
          '#1890ff',
          '#0050b3',   // 深色，对应大值
        ],
      },
    },
    tooltip: {
      title: '区域岗位分布',
      items: [
        { field: 'name', name: '区域' },
        { field: 'time', name: '时间' },
        { field: 'value', name: '岗位数量', valueFormatter: (v) => `${v} 个` },
      ],
    },
    interactions: [{ type: 'element-active' }],
    responsive: true,
    animation: {
      appear: {
        animation: 'scale-in',
        duration: 1000,
      },
    },
  };
};

export const getIndustryChartConfig = (currentIndustryData: any[], type: string): ChartConfig => ({
  data: currentIndustryData,
  height: 280,
  xField: 'date',
  yField: 'value',
  seriesField: 'category',
  color: COLOR_PALETTE,
  xAxis: {
    type: 'cat',
    label: {
      formatter: (text: string) => text,
    },
  },
  yAxis: {
    label: {
      formatter: (val: string) => `${val}${type === '招聘增长率' ? '%' : ''}`,
    },
  },
  point: {
    size: 4,
    shape: 'circle',
  },
  line: {
    size: 3,
    style: {
      lineCap: 'round',
    },
  },
  animation: {
    appear: {
      animation: 'path-in',
      duration: 1500,
    },
  },
  smooth: true,
  legend: false,
  tooltip: {
    title: '行业趋势',
    items: [
      { field: 'category', name: '行业' },
      { field: 'date', name: '时间' },
      {
        field: 'value',
        name: type === '招聘增长率' ? '增长率' : '岗位数量',
        valueFormatter: (v) => `${v}${type === '招聘增长率' ? '%' : ''}`,
      },
    ],
  },
});

export const getSalaryChartConfig = (currentSalaryData: any[]): ChartConfig => ({
  data: currentSalaryData,
  height: 280,
  xField: 'date',
  yField: 'value',
  seriesField: 'category',
  xAxis: {
    type: 'cat',
    label: {
      formatter: (text: string) => text,
    },
  },
  yAxis: {
    label: {
      formatter: (val: string) => `${val}`,
    },
  },
  point: {
    size: 4,
    shape: 'circle',
  },
  animation: {
    appear: {
      animation: 'path-in',
      duration: 1000,
    },
  },
  smooth: true,
  interactions: [
    {
      type: 'tooltip',
      cfg: {
        render: (e, { title, items }) => {
          const list = items.filter((item) => item.value);
          return (
            <div key={title} style={{ padding: '8px 12px' }}>
              <h4 style={{ marginBottom: 8 }}>{title}</h4>
              {list.map((item, index) => {
                const { name, value, color } = item;
                return (
                  <div
                    key={index}
                    style={{ margin: '4px 0', display: 'flex', justifyContent: 'space-between' }}
                  >
                    <div style={{ display: 'flex', alignItems: 'center' }}>
                      <span
                        style={{
                          display: 'inline-block',
                          width: 8,
                          height: 8,
                          borderRadius: '50%',
                          backgroundColor: color,
                          marginRight: 8,
                        }}
                      ></span>
                      <span>{name}</span>
                    </div>
                    <b>{value}</b>
                  </div>
                );
              })}
            </div>
          );
        },
      },
    },
  ],
  legend: false,
  tooltip: {
    showTitle: undefined,
    title: undefined,
    customContent: undefined,
  },
});

export const getWorkYearPieConfig = (workYearData: any[], selectedWorkYearRange: string) => {
  const filteredData = workYearData
    .filter((item) => selectedWorkYearRange === '全部' || item.category === selectedWorkYearRange)
    .map((item) => ({
      ...item,
      date: formatDateForDisplay(item.date, '月'),
      value: item.value || 0,
      type: `${formatDateForDisplay(item.date, '月')} ${item.category}`,
    }));

  return {
    data: filteredData,
    angleField: 'value',
    colorField: 'category',
    radius: 0.2,
    innerRadius: 0.5,
    label: {
      text: (d: { type: any; value: any }) => `${d.type}\n ${d.value}`,
      position: 'spider',
      transform: [
        {
          type: 'overlapDodgeY',
        },
      ],
    },
    legend: false,
    tooltip: {
      title: '工作经验分布',
      items: [
        { field: 'date', name: '时间' },
        { field: 'category', name: '工作经验' },
        {
          field: 'value',
          name: '岗位数量',
          valueFormatter: (v) => `${v} 个`,
        },
      ],
    },
    interactions: [{ type: 'element-active' }],
    padding: [20, 0, 40, 0],
    autoFit: true,
    color: COLOR_PALETTE,
    animation: {
      appear: {
        animation: 'wave-in',
        duration: 1000,
      },
    },
  };
};

export const getEducationBarConfig = (educationData: any[], selectedEducationLevel: string) => {
  const educationLevelOrder = [
    '不限',
    '初中及以下',
    '中专/中技',
    '高中',
    '大专',
    '本科',
    '硕士',
    '博士',
  ];

  // 汇总数据
  const summaryData = educationData.reduce((acc, item) => {
    const existing = acc.find((d: any) => d.name === item.category);
    if (existing) {
      existing.value += item.value;
    } else {
      acc.push({
        name: item.category,
        value: item.value,
      });
    }
    return acc;
  }, [] as any[]);

  const barData = summaryData
    .filter((item) => item.value > 0)
    .sort((a, b) => educationLevelOrder.indexOf(a.name) - educationLevelOrder.indexOf(b.name));

  return {
    data: barData,
    height: 280,
    xField: 'value',
    yField: 'name',
    seriesField: 'name',
    color: COLOR_PALETTE,
    meta: {
      name: {
        alias: '学历要求',
      },
      value: {
        alias: '岗位数量',
      },
    },
    xAxis: {
      label: {
        style: {
          fill: '#666',
          fontSize: 11,
        },
      },
      grid: {
        line: {
          style: {
            stroke: '#f0f0f0',
            lineDash: [3, 3],
          },
        },
      },
    },
    yAxis: {
      label: {
        style: {
          fill: '#666',
          fontSize: 11,
        },
      },
    },
    barStyle: {
      radius: [4, 4, 0, 0],
    },
    tooltip: {
      title: '学历要求分布',
      items: [
        { field: 'name', name: '学历要求' },
        {
          field: 'value',
          name: '岗位数量',
          valueFormatter: (v) => `${v} 个`,
        },
      ],
    },
    interactions: [{ type: 'element-active' }],
    legend: false,
    animation: {
      appear: {
        animation: 'scale-in-x',
        duration: 1000,
      },
    },
  };
};
