import React, { useEffect, useState } from 'react';
import { useModel } from '@umijs/max';
import classNames from 'classnames';
import services from '@/services';
import { getStatusByScore, STATUS_COLORS } from '@/components/DimensionCard';
import styles from './index.less';
import ModuleTitleWithTabs from '@/pages/Home_v_2504/components/common/ModuleTitleWithTabs';
import CountUp from 'react-countup';

/**
 * 整体情况组件
 * 显示CQI总分、状态和变化趋势
 */
const OverallSituation: React.FC = () => {
  const { initialState } = useModel('@@initialState');
  const areaId = initialState?.areaId || '510100';
  
  const [loading, setLoading] = useState<boolean>(true);
  const [cqiData, setCqiData] = useState<any>(null);
  const [indexSystemData, setIndexSystemData] = useState<any>(null);
  const [lostItems, setLostItems] = useState<number>(0);

  // 获取CQI实时数据
  const fetchCqiData = async () => {
    try {
      const params = {
        physicalSignType: '1',
        indexType: '1',
        indexHierarchy: '1,2',
        objectId: areaId,
        indexId: '',
      };
      const res = await services.Physicalsign.getComparisonIndexInstance(params);
      if (res.code === 200) {
        setCqiData(res.data);
      }
    } catch (error) {
      console.error('Failed to fetch CQI data:', error);
    }
  };

  // 获取指标体系数据
  const fetchIndexSystemData = async () => {
    try {
      const params = {
        objectId: areaId,
        indexId: '1', // CQI的指标ID
      };
      
      const res = await services.Physicalsign.getIndexSystem(params);
      if (res.code === 200) {
        setIndexSystemData(res.data || {});
        
        // 计算失分项数量
        const lostItemsCount = countLostItems(res.data);
        setLostItems(lostItemsCount);
      }
    } catch (error) {
      console.error('Failed to fetch index system data:', error);
    } finally {
      setLoading(false);
    }
  };

  // 统计失分项数量
  const countLostItems = (data: any): number => {
    if (!data) return 0;
    
    let count = 0;
    
    // 检查当前节点是否为失分项
    if (data.indexType === '1' && parseFloat(data.lostScore) > 0) {
      count += 1;
    }
    
    // 递归检查子节点
    if (data.children && data.children.length > 0) {
      data.children.forEach((child: any) => {
        count += countLostItems(child);
      });
    }
    
    return count;
  };

  useEffect(() => {
    fetchCqiData();
    fetchIndexSystemData();
    
    // 设置定时刷新（2小时刷新一次）
    const intervalId = setInterval(() => {
      fetchCqiData();
      fetchIndexSystemData();
    }, 60000 * 60 * 2);
    
    return () => clearInterval(intervalId);
  }, [areaId]);

  // if (loading) {
  //   return <div className={styles.loading}>加载中...</div>;
  // }

  // 获取CQI分数和变化值
  const cqiScore = cqiData?.currentIndex?.cqi || 0;
  const cqiChange = cqiData?.currentIndex?.change || 0;
  const compareHours = 2; // 固定为2小时

  console.log('cqiData', cqiData, cqiScore);
  
  // 获取总指标数
  const totalItems = indexSystemData?.indexTotal || 0;
  
  // 获取状态
  const status = getStatusByScore(cqiScore);
  const statusColor = STATUS_COLORS[status];
  
  // 状态文本映射
  const statusTextMap = {
    ideal: '理想态',
    standard: '标准态',
    warning: '预警态',
    emergency: '应急态',
  };
  
  // 状态背景图片
  const getStatusResources = (status: string) => {
    const statusIndex = {
      ideal: 1,
      standard: 2,
      warning: 3,
      emergency: 4,
    }[status];
  
    return {
      statusBg: require(`@/assets/images/V-2504/cqi-clock-status-${statusIndex}.png`),
    };
  };
  
  const statusResources = getStatusResources(status);

  return (
    <div className={styles.container}>  
      <ModuleTitleWithTabs title="整体情况" />
      {/* 顶部部分：CQI分数、状态和变化趋势 */}
      <div className={styles.topSection}>
        {/* CQI分数 */}
        <div className={styles.scoreValue} style={{ color: statusColor }}>
          <CountUp 
            end={cqiScore} 
            decimals={2} 
            duration={1}
            preserveValue 
          />
        </div>
        
        {/* 状态标签 */}
        <div className={styles.statusWrapper}>
          <img src={statusResources.statusBg} className={styles.statusBg} alt="状态" />
        </div>
        
        {/* 变化状态 */}
        <div className={styles.changeWrapper}>
          <span className={styles.compareText}>较{compareHours}小时前</span>
          <img 
            src={cqiChange >= 0 
              ? require('@/assets/images/V-2504/cqi-clock-up.png') 
              : require('@/assets/images/V-2504/cqi-clock-down.png')} 
            className={styles.changeIcon} 
            alt={cqiChange >= 0 ? "上升" : "下降"} 
          />
          <span className={styles.changeValue}>{Math.abs(cqiChange).toFixed(2)}</span>
        </div>
      </div>
      
      {/* 底部部分：指标统计信息 */}
      <div className={styles.bottomSection}>
        <div className={styles.statItem}>
          <span className={styles.statLabel}>共</span>
          <span className={styles.statValue}>
            <CountUp 
              end={totalItems} 
              decimals={2} 
              duration={1}
              preserveValue 
            />
          </span> 
          <span className={styles.statLabel}>项指标，失分</span>
          <span className={styles.statValueHighlight}>
            <CountUp 
              end={lostItems} 
              decimals={2} 
              duration={1}
              preserveValue 
            />
          </span>
          <span className={styles.statLabel}>项</span>
        </div>
      </div>
    </div>
  );
};

export default OverallSituation; 