import React, { useEffect, useState, useMemo } from 'react';
import { Card, Select, Button, Space, Spin, Empty, Row, Col, message } from 'antd';
import { Line } from '@ant-design/charts';
import { getIndustryTrend } from '@/services/analysis/industry';
import dayjs from 'dayjs';
import { useRequest } from '@umijs/max';

const { Option } = Select;
type IndustryDataItem = {
  date: string;
  category: string;
  value: number;
};
const IndustryTrendPage: React.FC = () => {
  const [params, setParams] = useState({
    timeDimension: '月' as '月' | '季度' | '年',
    type: '岗位发布数量' as '岗位发布数量' | '招聘增长率',
    startTime: dayjs().subtract(6, 'month').format('YYYY-MM'),
    endTime: dayjs().format('YYYY-MM'),
    selectedIndustry: '' 
  });
  const [allData, setAllData] = useState<IndustryDataItem[]>([]);
  const [prevSelectedIndustry, setPrevSelectedIndustry] = useState('');
  const { loading, run } = useRequest(
    () => getIndustryTrend({
      ...params,
      startTime: formatTimeParam(params.startTime, params.timeDimension),
      endTime: formatTimeParam(params.endTime, params.timeDimension)
    }),
    {
      manual: true,
      onError: (error) => message.error('数据加载失败: ' + error.message),
      onSuccess: (responseData) => {
        const formattedData = convertApiData(responseData);
        setAllData(formattedData);
        const industryToSelect = prevSelectedIndustry || 
                                (formattedData.length > 0 ? formattedData[0].category : '');
        setParams(prev => ({ ...prev, selectedIndustry: industryToSelect }));
      }
    }
  );
  const convertApiData = (apiData: any): IndustryDataItem[] => {
    if (!apiData) return [];
    
    try {
      const result: IndustryDataItem[] = [];
      if (typeof apiData === 'object' && !Array.isArray(apiData)) {
        Object.entries(apiData).forEach(([month, monthData]) => {
          if (Array.isArray(monthData)) {
            (monthData as any[]).forEach(item => {
              const convertedItem = {
                date: month,
                category: item.name || item.category,
                value: Number(item.data || item.value) || 0
              };
              console.log('转换后的数据项:', convertedItem); 
              result.push(convertedItem);
            });
          }
        });
        return result;
      }
      if (Array.isArray(apiData)) {
        return apiData.map(item => {
          const convertedItem = {
            date: item.time || item.date,
            category: item.name || item.category,
            value: Number(item.data || item.value) || 0
          };
          console.log('转换后的数据项:', convertedItem); 
          return convertedItem;
        });
      }
      
      return [];
    } catch (error) {
      console.error('数据转换错误:', error);
      return [];
    }
  };
  const industries = useMemo(() => {
    if (allData.length === 0) return [];
    const categories = new Set<string>();
    allData.forEach(item => categories.add(item.category));
    return Array.from(categories).sort();
  }, [allData]);
  const formatTimeParam = (dateStr: string, dimension: string) => {
    const date = dayjs(dateStr);
    switch (dimension) {
      case '季度': return `${date.year()}-Q${Math.ceil((date.month() + 1) / 3)}`;
      case '年': return `${date.year()}`;
      default: return date.format('YYYY-MM');
    }
  };
  const handleIndustryChange = (value: string) => {
    setPrevSelectedIndustry(value);
    setParams(p => ({ ...p, selectedIndustry: value }));
  };

  const currentIndustryData = useMemo(() => {
    if (!params.selectedIndustry) return [];
   
    const  filteredData = allData
      .filter(item => item.category === params.selectedIndustry)
      .map(item => ({
        date: item.date,
        category: item.category,
        value: item.value ?? 0,
      }))
      .sort((a, b) => dayjs(a.date).valueOf() - dayjs(b.date).valueOf());
      console.log("当前行业数据 (过滤后):", filteredData);
      return filteredData;
  }, [allData, params.selectedIndustry]);
  console.log("最终图表数据:", currentIndustryData);
  const chartConfig = {
    data: currentIndustryData,
    height: 180,
    xField: 'date',
    yField: 'value',
    seriesField: 'category',
    xAxis: {
      type: 'cat',
      tickCount: 5,
      label: {
        formatter: (text: string) => {
          if (params.timeDimension === '年') return text.split('-')[0];
          if (params.timeDimension === '季度') return text.split('-')[1];
          return text.split('-')[1]; 
        },
      },
    },
    yAxis: {
      label: {
        formatter: (val: string) => `${val}${params.type === '招聘增长率' ? '%' : '个'}`,
      },
    },
    tooltip: false,
    point: {
      size: 4,
      shape: 'circle',
    },
    animation: {
      appear: {
        animation: 'path-in',
        duration: 1000,
      },
    },
  };
 

  useEffect(() => {
    run();
  }, [params.timeDimension, params.startTime, params.endTime]);

  return (
    <div style={{ padding: 16 }}>
      <Card 
        title="行业趋势分析"
        style={{ marginBottom: 24 }}
      >
        <div style={{ marginBottom: 16 }}>
          <Space size="middle" wrap>
            <Select
              value={params.selectedIndustry}
              onChange={handleIndustryChange}
              style={{ width: 180 }}
              loading={loading}
              placeholder="选择行业"
            >
              {industries.map(industry => (
                <Option key={industry} value={industry}>{industry}</Option>
              ))}
            </Select>

            <Select
              value={params.timeDimension}
              onChange={value => setParams(p => ({ ...p, timeDimension: value }))}
              style={{ width: 100 }}
            >
              <Option value="月">按月</Option>
              <Option value="季度">按季度</Option>
              <Option value="年">按年</Option>
            </Select>

            <Select
              value={params.type}
              onChange={value => setParams(p => ({ ...p, type: value }))}
              style={{ width: 120 }}
            >
              <Option value="岗位发布数量">岗位数量</Option>
              <Option value="招聘增长率">增长率</Option>
            </Select>

            <Button
              type="primary"
              onClick={() => run()}
              loading={loading}
              size="middle"
            >
              查询
            </Button>
          </Space>
        </div>

        
        <Card 
          title={`${params.selectedIndustry || '行业'}趋势`}
          style={{ marginBottom: 24 }}
          bodyStyle={{ 
            padding: 12,
            height: 180,
            display: 'flex',
            justifyContent: 'center',
            alignItems: 'center'
          }}
        >
          <Spin spinning={loading}>
            {currentIndustryData.length > 0 ? (
              <Line {...chartConfig} />
            ) : (
              <Empty description={loading ? '数据加载中...' : '请选择行业'} />
            )}
          </Spin>
        </Card>

        <Row gutter={[16, 16]}>
          <Col xs={24} sm={12} md={8} lg={8} xl={6}>
            <Card 
              title="区域分析" 
              bodyStyle={{ 
                padding: 12,
                height: 300,
                display: 'flex',
                justifyContent: 'center',
                alignItems: 'center'
              }}
            >
              <Empty description="热力地图预留位置" />
            </Card>
          </Col>
          <Col xs={24} sm={12} md={8} lg={8} xl={6}>
            <Card 
              title="薪资趋势" 
              bodyStyle={{ 
                padding: 12,
                height: 300,
                display: 'flex',
                justifyContent: 'center',
                alignItems: 'center'
              }}
            >
              <Empty description="薪资分析预留位置" />
            </Card>
          </Col>
          <Col xs={24} sm={12} md={8} lg={8} xl={6}>
            <Card 
              title="经验要求" 
              bodyStyle={{ 
                padding: 12,
                height: 300,
                display: 'flex',
                justifyContent: 'center',
                alignItems: 'center'
              }}
            >
              <Empty description="经验分析预留位置" />
            </Card>
          </Col>
          <Col xs={24} sm={12} md={8} lg={8} xl={6}>
            <Card 
              title="技能需求" 
              bodyStyle={{ 
                padding: 12,
                height: 300,
                display: 'flex',
                justifyContent: 'center',
                alignItems: 'center'
              }}
            >
              <Empty description="技能分析预留位置" />
            </Card>
          </Col>
        </Row>
      </Card>
    </div>
  );
};

export default IndustryTrendPage;