import React, { useState, useEffect, useCallback } from 'react';
import { getWantedPositionStaticsCount } from '@/services/analysis/user';
import { Card, Row, Col, Select, Empty, Spin, Tag, Statistic } from 'antd';
import { Column } from '@ant-design/charts';

const { Option } = Select;

interface PositionItem {
  jobId: number;
  jobName: string;
  sexCode?: string; // 可能为 '男' 或 '女'
  staticsCount?: number;
}

interface PositionStatics {
  jobId: number;
  jobName: string;
  count: number;
  percentage: number;
}

const WantedPositionStatics: React.FC = () => {
  const [malePositions, setMalePositions] = useState<PositionStatics[]>([]);
  const [femalePositions, setFemalePositions] = useState<PositionStatics[]>([]);
  const [loading, setLoading] = useState(false);
  const [topCount, setTopCount] = useState<10 | 15 | 20>(10);
  const [totalMale, setTotalMale] = useState(0);
  const [totalFemale, setTotalFemale] = useState(0);
  const [allPositions, setAllPositions] = useState<PositionItem[]>([]);

  const fetchStatics = useCallback(async () => {
    setLoading(true);
    try {
      const resData = await getWantedPositionStaticsCount();
      if (resData.code === 200) {
        const positions = resData.data as PositionItem[];
        setAllPositions(positions);
        
        // 统计每个岗位的男女数量
        const maleCounts: Record<number, number> = {};
        const femaleCounts: Record<number, number> = {};
        
        positions.forEach((item,index) => {
          if (item.sexCode === '男') {
            maleCounts[item.jobId] = (maleCounts[item.jobId] || 0) + 1;
          } else if (item.sexCode === '女') {
            femaleCounts[item.jobId] = (femaleCounts[item.jobId] || 0) + 1;
          }
        });

        // 计算总数
        const maleTotal = Object.values(maleCounts).reduce((a, b) => a + b, 0);
        const femaleTotal = Object.values(femaleCounts).reduce((a, b) => a + b, 0);
        
        setTotalMale(maleTotal);
        setTotalFemale(femaleTotal);

        // 获取所有岗位的唯一列表
        const uniqueJobs = Array.from(
          new Map(positions.map(item => [item.jobId, item])).values()
        );

        // 处理男性数据
        const processedMale = uniqueJobs
          .map(job => ({
            jobId: job.jobId,
            jobName: job.jobName,
            count: maleCounts[job.jobId] || 0,
            percentage: maleTotal > 0 ? Math.round(((maleCounts[job.jobId] || 0) / maleTotal) * 100) : 0
          }))
          .filter(item => item.count > 0) // 只显示有数据的岗位
          .sort((a, b) => b.count - a.count)
          .slice(0, topCount);

        // 处理女性数据
        const processedFemale = uniqueJobs
          .map(job => ({
            jobId: job.jobId,
            jobName: job.jobName,
            count: femaleCounts[job.jobId] || 0,
            percentage: femaleTotal > 0 ? Math.round(((femaleCounts[job.jobId] || 0) / femaleTotal) * 100) : 0
          }))
          .filter(item => item.count > 0) // 只显示有数据的岗位
          .sort((a, b) => b.count - a.count)
          .slice(0, topCount);

          console.log(processedMale,processedFemale,'++++++++')

        setMalePositions(processedMale);
        setFemalePositions(processedFemale);
      }
    } catch (error) {
      console.error('获取期望岗位数据失败:', error);
    } finally {
      setLoading(false);
    }
  }, [topCount]);

  useEffect(() => {
    fetchStatics();
  }, [fetchStatics]);

  // 横向柱状图配置 - 男性
  const maleColumnConfig = {
    data: malePositions,
    xField: 'count',
    yField: 'jobName',
    seriesField: 'jobName',
    isGroup: false,
    isStack: false,
    height: 280,
    autoFit: true,
    columnWidthRatio: 0.6,
    color: '#1890ff',
    labels: [
      {
        text: 'count',
        style: {
          fill: '#666',
          fontSize: 12,
          fontWeight: 600,
        },
        position: 'right',
        formatter: (datum: any) => `${datum.count}人`,
      }
    ],
    xAxis: {
      title: {
        text: '人数',
        style: {
          fontSize: 14,
          fill: '#333',
          fontWeight: 'bold',
        },
      },
      label: {
        style: {
          fontSize: 12,
          fill: '#666',
        },
      },
      grid: {
        line: {
          style: {
            stroke: '#e8e8e8',
            lineWidth: 1,
            lineDash: [3, 3],
          },
        },
        alignTick: true,
      },
    },
    yAxis: {
      title: null,
      label: {
        style: {
          fontSize: 12,
          fill: '#666',
        },
        formatter: (text: string) => {
          return text.length > 10 ? `${text.substring(0, 10)}...` : text;
        },
      },
      grid: {
        line: {
          style: {
            stroke: '#e8e8e8',
            lineWidth: 1,
            lineDash: [3, 3],
          },
        },
        alignTick: true,
      },
    },
    tooltip: {
      title: '男性期望岗位',
      items: [
        { field: 'jobName', name: '岗位名称' },
        { field: 'count', name: '人数', valueFormatter: (v) => `${v} 人` },
        { field: 'percentage', name: '占比', valueFormatter: (v) => `${v}%` },
      ],
    },
    interactions: [{ type: 'element-active' }],
    animation: {
      appear: {
        animation: 'scale-in-x',
        duration: 1000,
      },
    },
  };

  // 横向柱状图配置 - 女性
  const femaleColumnConfig = {
    data: femalePositions,
    xField: 'count',
    yField: 'jobName',
    seriesField: 'jobName',
    isGroup: false,
    isStack: false,
    height: 280,
    autoFit: true,
    columnWidthRatio: 0.6,
    color: '#eb2f96',
    labels: [
      {
        text: 'count',
        style: {
          fill: '#666',
          fontSize: 12,
          fontWeight: 600,
        },
        position: 'right',
        formatter: (datum: any) => `${datum.count}人`,
      }
    ],
    xAxis: {
      title: {
        text: '人数',
        style: {
          fontSize: 14,
          fill: '#333',
          fontWeight: 'bold',
        },
      },
      label: {
        style: {
          fontSize: 12,
          fill: '#666',
        },
      },
      grid: {
        line: {
          style: {
            stroke: '#e8e8e8',
            lineWidth: 1,
            lineDash: [3, 3],
          },
        },
        alignTick: true,
      },
    },
    yAxis: {
      title: null,
      label: {
        style: {
          fontSize: 12,
          fill: '#666',
        },
        formatter: (text: string) => {
          return text.length > 10 ? `${text.substring(0, 10)}...` : text;
        },
      },
      grid: {
        line: {
          style: {
            stroke: '#e8e8e8',
            lineWidth: 1,
            lineDash: [3, 3],
          },
        },
        alignTick: true,
      },
    },
    tooltip: {
      title: '女性期望岗位',
      items: [
        { field: 'jobName', name: '岗位名称' },
        { field: 'count', name: '人数', valueFormatter: (v) => `${v} 人` },
        { field: 'percentage', name: '占比', valueFormatter: (v) => `${v}%` },
      ],
    },
    interactions: [{ type: 'element-active' }],
    animation: {
      appear: {
        animation: 'scale-in-x',
        duration: 1000,
      },
    },
  };

  // 如果没有数据，显示所有岗位的占位图
  const showPlaceholder = malePositions.length === 0 && femalePositions.length === 0;

  return (
    <Spin spinning={loading} tip="数据加载中...">
      <Card
        title={
          <div style={{ display: 'flex', alignItems: 'center', gap: 8 }}>
            <span>🎯 期望岗位统计分析</span>
            <Tag color="orange">岗位分析</Tag>
          </div>
        }
        style={{ 
          borderRadius: 12,
          boxShadow: '0 4px 12px rgba(0,0,0,0.1)',
          marginBottom: 16
        }}
        bodyStyle={{ 
          padding: '16px',
          background: 'linear-gradient(135deg, #f8f9fa 0%, #e9ecef 100%)',
          borderRadius: 8
        }}
        extra={
          <Select
            value={topCount}
            onChange={setTopCount}
            style={{ width: 120 }}
            size="middle"
          >
            <Option value={10}>显示前10</Option>
            <Option value={15}>显示前15</Option>
            <Option value={20}>显示前20</Option>
          </Select>
        }
      >
        {/* 统计数据行 */}
        <Row gutter={[16, 16]} style={{ marginBottom: 24 }}>
          <Col xs={8} md={8} lg={8}>
            <Card size="small" style={{ background: 'rgba(24, 144, 255, 0.1)', textAlign: 'center' }}>
              <Statistic 
                title="男性用户" 
                value={totalMale}
                suffix="人"
                valueStyle={{ color: '#1890ff' }}
              />
            </Card>
          </Col>
          <Col xs={8} md={8} lg={8}>
            <Card size="small" style={{ background: 'rgba(235, 47, 150, 0.1)', textAlign: 'center' }}>
              <Statistic 
                title="女性用户" 
                value={totalFemale}
                suffix="人"
                valueStyle={{ color: '#eb2f96' }}
              />
            </Card>
          </Col>
          <Col xs={8} md={8} lg={8}>
            <Card size="small" style={{ background: 'rgba(82, 196, 26, 0.1)', textAlign: 'center' }}>
              <Statistic 
                title="总用户数" 
                value={totalMale + totalFemale}
                suffix="人"
                valueStyle={{ color: '#52c41a' }}
              />
            </Card>
          </Col>
        </Row>

        {showPlaceholder ? (
          <Row gutter={[16, 16]}>
            <Col xs={24} md={12} lg={12}>
              <Card 
                title={
                  <div style={{ display: 'flex', alignItems: 'center', gap: 8 }}>
                    <span style={{ color: '#1890ff' }}>👨 男性热门岗位</span>
                    <Tag color="blue">TOP {topCount}</Tag>
                  </div>
                }
                size="small"
                style={{ height: '100%' }}
              >
                <Empty
                  description="暂无男性期望岗位数据"
                  style={{ margin: '40px 0' }}
                />
              </Card>
            </Col>
            <Col xs={24} md={12} lg={12}>
              <Card 
                title={
                  <div style={{ display: 'flex', alignItems: 'center', gap: 8 }}>
                    <span style={{ color: '#eb2f96' }}>👩 女性热门岗位</span>
                    <Tag color="pink">TOP {topCount}</Tag>
                  </div>
                }
                size="small"
                style={{ height: '100%' }}
              >
                <Empty
                  description="暂无女性期望岗位数据"
                  style={{ margin: '40px 0' }}
                />
              </Card>
            </Col>
          </Row>
        ) : (
          <Row gutter={[16, 16]}>
            {/* 男性期望岗位 - 横向柱状图 */}
            <Col xs={24} md={12} lg={12}>
              <Card 
                title={
                  <div style={{ display: 'flex', alignItems: 'center', gap: 8 }}>
                    <span style={{ color: '#1890ff' }}>👨 男性热门岗位</span>
                    <Tag color="blue">TOP {topCount}</Tag>
                  </div>
                }
                size="small"
                style={{ height: '100%' }}
                bodyStyle={{ padding: '12px', height: '100%' }}
              >
                {malePositions.length > 0 ? (
                  <div style={{ height: 250 }}>
                    <Column {...maleColumnConfig} />
                  </div>
                ) : (
                  <Empty
                    description="暂无男性期望岗位数据"
                    style={{ margin: '40px 0' }}
                  />
                )}
              </Card>
            </Col>

            {/* 女性期望岗位 - 横向柱状图 */}
            <Col xs={24} md={12} lg={12}>
              <Card 
                title={
                  <div style={{ display: 'flex', alignItems: 'center', gap: 8 }}>
                    <span style={{ color: '#eb2f96' }}>👩 女性热门岗位</span>
                    <Tag color="pink">TOP {topCount}</Tag>
                  </div>
                }
                size="small"
                style={{ height: '100%' }}
                bodyStyle={{ padding: '12px', height: '100%' }}
              >
                {femalePositions.length > 0 ? (
                  <div style={{ height:250 }}>
                    <Column {...femaleColumnConfig} />
                  </div>
                ) : (
                  <Empty
                    description="暂无女性期望岗位数据"
                    style={{ margin: '40px 0' }}
                  />
                )}
              </Card>
            </Col>
          </Row>
        )}
      </Card>
    </Spin>
  );
};

export default WantedPositionStatics;