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

import type { HrmStatisticsApi } from '#/api/hrm/statistics';

/** 统一色板，保证同一页面的图表观感一致 */
const PALETTE = [
  '#3b82f6',
  '#10b981',
  '#f59e0b',
  '#ef4444',
  '#8b5cf6',
  '#06b6d4',
  '#ec4899',
  '#84cc16',
];

const BASE_TEXT_STYLE = {
  fontSize: 12,
};

interface AxisTooltipParams {
  dataIndex: number;
}

const TITLE_STYLE = {
  textStyle: { fontSize: 14, fontWeight: 'bold' as const },
  left: 'center' as const,
};

/** 柱状图：适用于固定区间分布（工龄、年龄） */
function getBarOption(title: string, data: HrmStatisticsApi.Item[]): EChartsOption {
  return {
    title: { text: title, ...TITLE_STYLE },
    color: PALETTE,
    grid: { bottom: 40, left: 50, right: 20, top: 60 },
    tooltip: {
      trigger: 'axis',
      axisPointer: { type: 'shadow' },
      formatter: '{b}<br/>{a}：{c} 人',
    },
    xAxis: {
      type: 'category',
      data: data.map((item) => item.name),
      axisLabel: { ...BASE_TEXT_STYLE, interval: 0 },
    },
    yAxis: {
      type: 'value',
      name: '人数',
      minInterval: 1,
      axisLabel: BASE_TEXT_STYLE,
    },
    series: [
      {
        name: title,
        type: 'bar',
        barMaxWidth: 42,
        itemStyle: { borderRadius: [6, 6, 0, 0] },
        label: { show: true, position: 'top', ...BASE_TEXT_STYLE },
        data: data.map((item) => item.value),
      },
    ],
  };
}

/** 横向条形图：适用于人数按名称排名（部门、岗位） */
function getRankingBarOption(
  title: string,
  data: HrmStatisticsApi.Item[],
  unit: string,
  seriesName: string,
): EChartsOption {
  return {
    title: { text: title, ...TITLE_STYLE },
    color: PALETTE,
    grid: { bottom: 30, left: 110, right: 50, top: 60 },
    tooltip: {
      trigger: 'axis',
      axisPointer: { type: 'shadow' },
      formatter: `{b}<br/>${seriesName}：{c} ${unit}`,
    },
    xAxis: {
      type: 'value',
      name: unit,
      axisLabel: BASE_TEXT_STYLE,
    },
    yAxis: {
      type: 'category',
      inverse: true,
      data: data.map((item) => item.name),
      axisLabel: BASE_TEXT_STYLE,
    },
    series: [
      {
        name: seriesName,
        type: 'bar',
        barMaxWidth: 26,
        itemStyle: { borderRadius: [0, 6, 6, 0] },
        label: {
          show: true,
          position: 'right',
          formatter: `{c} ${unit}`,
          ...BASE_TEXT_STYLE,
        },
        data: data.map((item) => item.value),
      },
    ],
  };
}

/** 环形图：适用于占比类分布（学历、性别、状态、婚姻、政治面貌） */
function getPieOption(title: string, data: HrmStatisticsApi.Item[]): EChartsOption {
  return {
    title: { text: title, ...TITLE_STYLE },
    color: PALETTE,
    tooltip: { trigger: 'item', formatter: '{b}：{c} 人（{d}%）' },
    legend: {
      type: 'scroll',
      orient: 'vertical',
      left: 10,
      top: 50,
      textStyle: BASE_TEXT_STYLE,
    },
    series: [
      {
        name: title,
        type: 'pie',
        radius: ['42%', '68%'],
        center: ['58%', '58%'],
        avoidLabelOverlap: false,
        itemStyle: { borderRadius: 8, borderColor: '#fff', borderWidth: 2 },
        label: { show: true, formatter: '{b}\n{c} 人' },
        labelLine: { show: true },
        data: data.map((item) => ({ name: item.name, value: item.value })),
      },
    ],
  };
}

/** 合同到期预警：按紧急程度着色 */
function getContractWarningOption(
  data: HrmStatisticsApi.Item[],
): EChartsOption {
  const colorMap: Record<string, string> = {
    已到期: '#ef4444',
    '30天内到期': '#f59e0b',
    '31-90天到期': '#3b82f6',
    '90天以上': '#10b981',
    无固定期限: '#9ca3af',
  };
  return {
    title: { text: '合同到期预警', ...TITLE_STYLE },
    grid: { bottom: 40, left: 50, right: 20, top: 60 },
    tooltip: {
      trigger: 'axis',
      axisPointer: { type: 'shadow' },
      formatter: '{b}<br/>{c} 份',
    },
    xAxis: {
      type: 'category',
      data: data.map((item) => item.name),
      axisLabel: { ...BASE_TEXT_STYLE, interval: 0 },
    },
    yAxis: {
      type: 'value',
      name: '合同数',
      minInterval: 1,
      axisLabel: BASE_TEXT_STYLE,
    },
    series: [
      {
        name: '合同到期预警',
        type: 'bar',
        barMaxWidth: 42,
        label: { show: true, position: 'top', ...BASE_TEXT_STYLE },
        data: data.map((item) => ({
          name: item.name,
          value: item.value,
          itemStyle: {
            color: colorMap[item.name] ?? '#3b82f6',
            borderRadius: [6, 6, 0, 0],
          },
        })),
      },
    ],
  };
}

export function getTenureDistributionOption(data: HrmStatisticsApi.Item[]) {
  return getBarOption('工龄分布', data);
}

export function getAgeDistributionOption(data: HrmStatisticsApi.Item[]) {
  return getBarOption('年龄分布', data);
}

export function getStatusDistributionOption(data: HrmStatisticsApi.Item[]) {
  return getPieOption('人员状态构成', data);
}

export function getDeptDistributionOption(data: HrmStatisticsApi.Item[]) {
  return getRankingBarOption('部门人数分布', data, '人', '在岗人数');
}

export function getPostDistributionOption(data: HrmStatisticsApi.Item[]) {
  return getRankingBarOption('岗位分布', data, '人', '在岗人数');
}

export function getDeptTenureOption(data: HrmStatisticsApi.DeptTenure[]) {
  return {
    title: { text: '部门平均工龄', ...TITLE_STYLE },
    color: PALETTE,
    grid: { bottom: 30, left: 110, right: 50, top: 60 },
    tooltip: {
      trigger: 'axis',
      axisPointer: { type: 'shadow' },
      formatter: (params: AxisTooltipParams | AxisTooltipParams[]) => {
        const item = Array.isArray(params) ? params[0] : params;
        if (!item) {
          return '';
        }
        const dept = data[item.dataIndex];
        return `${dept?.deptName ?? ''}<br/>平均工龄：${dept?.averageTenureYears ?? 0} 年<br/>在岗人数：${dept?.count ?? 0} 人`;
      },
    },
    xAxis: {
      type: 'value',
      name: '年',
      axisLabel: BASE_TEXT_STYLE,
    },
    yAxis: {
      type: 'category',
      inverse: true,
      data: data.map((item) => item.deptName),
      axisLabel: BASE_TEXT_STYLE,
    },
    series: [
      {
        name: '平均工龄',
        type: 'bar',
        barMaxWidth: 26,
        itemStyle: { borderRadius: [0, 6, 6, 0] },
        label: {
          show: true,
          position: 'right',
          formatter: '{c} 年',
          ...BASE_TEXT_STYLE,
        },
        data: data.map((item) => item.averageTenureYears),
      },
    ],
  } as EChartsOption;
}

export function getEducationDistributionOption(data: HrmStatisticsApi.Item[]) {
  return getPieOption('学历分布', data);
}

export function getGenderDistributionOption(data: HrmStatisticsApi.Item[]) {
  return getPieOption('性别分布', data);
}

export function getMarriageDistributionOption(data: HrmStatisticsApi.Item[]) {
  return getPieOption('婚姻状况分布', data);
}

export function getPoliticalDistributionOption(data: HrmStatisticsApi.Item[]) {
  return getPieOption('政治面貌分布', data);
}

export function getHireResignTrendOption(data: HrmStatisticsApi.Trend[]) {
  return {
    title: { text: '近 12 个月入职 / 离职趋势', ...TITLE_STYLE },
    color: ['#10b981', '#ef4444'],
    grid: { bottom: 50, left: 50, right: 30, top: 70 },
    tooltip: { trigger: 'axis', formatter: '{b}<br/>{a}：{c} 人' },
    legend: { top: 30, data: ['入职', '离职'] },
    xAxis: {
      type: 'category',
      boundaryGap: false,
      data: data.map((item) => item.month.slice(2)),
      axisLabel: { ...BASE_TEXT_STYLE, rotate: 30 },
    },
    yAxis: {
      type: 'value',
      name: '人数',
      minInterval: 1,
      axisLabel: BASE_TEXT_STYLE,
    },
    series: [
      {
        name: '入职',
        type: 'line',
        smooth: true,
        symbolSize: 6,
        data: data.map((item) => item.hireCount),
      },
      {
        name: '离职',
        type: 'line',
        smooth: true,
        symbolSize: 6,
        data: data.map((item) => item.resignCount),
      },
    ],
  } as EChartsOption;
}

export function getContractWarningChartOption(data: HrmStatisticsApi.Item[]) {
  return getContractWarningOption(data);
}
