import React, { useState, useEffect, useRef } from 'react';
import { useRequest } from 'ahooks';
import { useModel } from '@umijs/max';
import CQIGauge from '@/components/CQIGauge';
import DimensionCard from '@/components/DimensionCard';
import { getStatusByScore, STATUS_COLORS, STATUS_COLORS_OPACITY } from '@/components/DimensionCard';
import { useGlobalModalServices } from '@/pages/GlobalModalServices/provider';
import services from '@/services';
import { message } from '@/layouts/messageStore';
import styles from './index.less';

// 导入维度图标
import safetyIcon from '@/assets/images/V-2504/cqi-dimension-1.png';
import cleanIcon from '@/assets/images/V-2504/cqi-dimension-2.png';
import orderIcon from '@/assets/images/V-2504/cqi-dimension-3.png';
import convenienceIcon from '@/assets/images/V-2504/cqi-dimension-4.png';
import beautyIcon from '@/assets/images/V-2504/cqi-dimension-5.png';
import SubTitle from '../../../common/SubTitle';
import { useDashboard } from '@/pages/Home_v_2504/components/context';

const randomNumber = (min: number, max: number) => {
  return parseFloat((Math.random() * (max - min) + min).toFixed(2));
};

// 定义模拟数据生成函数
const generateMockData = () => {
  return {
    total: randomNumber(0, 99.99), // 总分
    change: randomNumber(-1, 1), // 变化值
    compareHours: 2, // 比较的小时数
    dimensions: {
      safety: randomNumber(0, 99.99), // 安全
      clean: randomNumber(0, 99.99), // 整洁
      order: randomNumber(0, 99.99), // 有序
      convenience: randomNumber(0, 99.99), // 便民
      beauty: randomNumber(0, 99.99), // 美观（暂不可用，但是保留数据）
    }
  };
};

// 模拟API
const fetchMockCQIData = async () => {
  return generateMockData();
};

// 定义维度类型
type DimensionType = 'safety' | 'clean' | 'order' | 'convenience' | 'beauty';

// 维度ID映射
const dimensionIdMap = {
  safety: '1',
  clean: '2',
  order: '3',
  convenience: '4',
  beauty: '5',
};

// 维度名称映射
const dimensionNameMap = {
  safety: '安全',
  clean: '整洁',
  order: '有序',
  convenience: '便民',
  beauty: '美观',
};

const LeftTopCQI: React.FC = () => {
  const { initialState } = useModel('@@initialState');
  const { areaId } = initialState;
  // const areaId = initialState?.areaId || '510100000000';
  const { dispatch } = useGlobalModalServices();
  
  // 状态管理
  const [useMockData, setUseMockData] = useState<boolean>(false);
  const [clickCount, setClickCount] = useState<number>(0);
  const [lastClickTime, setLastClickTime] = useState<number>(0);
  const [activeDimension, setActiveDimension] = useState<DimensionType | null>(null);
  const [realData, setRealData] = useState<any>(null);
  const { navigateTo } = useDashboard();
  
  // 图标样式配置
  const iconStyles = {
    safety: { width: '23px', height: '30px' },
    clean: { width: '36px', height: '35px' },
    order: { width: '32px', height: '30px' },
    convenience: { width: '27px', height: '22px' },
    beauty: { width: '25px', height: '29px' },
  };

  // 获取模拟CQI数据
  const { data: mockData, loading: mockLoading, run: refreshMockData } = useRequest(fetchMockCQIData, {
    pollingInterval: useMockData ? 5000 : undefined, // 只在使用模拟数据时轮询
  });
  
  // 获取真实CQI数据
  const fetchRealCQIData = 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) {
        let processedData = res.data;
        
        // 处理数据格式，适配模拟数据结构
        if (res.data.currentIndex?.indexs) {
          const indexs = res.data.currentIndex.indexs
            .map((item: any) =>
              item.name === '美观'
                ? {
                  ...item,
                  value: '--',
                  color: '#57EF58',
                  background: 'rgba(39, 211, 134, 0.2)',
                }
                : { ...item },
            )
            .sort((a: any, b: any) => Number(a.id) - Number(b.id));
            
          processedData = {
            ...res.data,
            currentIndex: { ...res.data.currentIndex, indexs },
          };
        }
        
        setRealData(processedData);
        return processedData;
      }
      return null;
    } catch (error) {
      console.error('Failed to fetch real CQI data:', error);
      return null;
    }
  };
  
  // 获取真实数据的请求
  const { loading: realLoading, run: refreshRealData } = useRequest(fetchRealCQIData, {
    manual: true,
    pollingInterval: !useMockData ? 60000 * 60 * 2 : undefined, // 只在使用真实数据时轮询  2小时
  });

  // 根据数据源切换刷新数据
  useEffect(() => {
    if (useMockData) {
      refreshMockData();
    } else {
      refreshRealData();
    }
  }, [useMockData]);

  // 处理标题点击，实现模式切换
  const handleTitleClick = () => {
    const now = Date.now();
    
    // 如果与上次点击时间间隔小于3秒，计数器+1
    if (now - lastClickTime < 3000) {
      const newCount = clickCount + 1;
      setClickCount(newCount);
      
      // 达到10次点击，切换数据源
      if (newCount >= 10) {
        setUseMockData(!useMockData);
        setClickCount(0);
        message.success(`已切换到${useMockData ? '实际' : '模拟'}数据源`);
      }
    } else {
      // 超过3秒重置计数器
      setClickCount(1);
    }
    
    setLastClickTime(now);
  };

  // 处理维度卡片点击
  const handleDimensionClick = (dimension: DimensionType) => {
    setActiveDimension(activeDimension === dimension ? null : dimension);
    
    // 如果是美观维度，显示提示
    if (dimension === 'beauty') {
      message.warning('指标正在构建中');
      return;
    }
    
    // 打开Category模态框
    dispatch.push('Category', {
      title: dimensionNameMap[dimension],
      props: {
        item: {
          id: dimensionIdMap[dimension],
          value: useMockData 
            ? mockData?.dimensions[dimension] 
            : getRealDimensionValue(dimension),
          name: dimensionNameMap[dimension],
          objectId: areaId,
        },
      },
    });
  };
  
  // 处理总分点击
  const handleTotalClick = () => {
    dispatch.push('Category', {
      title: 'CQI',
      props: {
        item: {
          id: useMockData 
            ? '0' 
            : realData?.currentIndex?.indexId,
          value: useMockData 
            ? mockData?.total 
            : realData?.currentIndex?.cqi,
          name: 'CQI',
          objectId: areaId,
        },
      },
    });
  };
  
  // 从实际数据中获取维度值
  const getRealDimensionValue = (dimension: DimensionType) => {    
    // 美观指标暂不可用，使用>100的数字，会处理成'--'
    if (dimension === 'beauty') return 1230;
    if (!realData?.currentIndex?.indexs) return 0;
    
    const dimensionItem = realData.currentIndex.indexs.find(
      (item: any) => item.name === dimensionNameMap[dimension]
    );
    
    return dimensionItem?.value || 0;
  };

  // 获取当前使用的数据
  const getCurrentData = () => {
    if (useMockData) {
      return mockData;
    } else {
      if (!realData) {
        // 返回默认数据，使用>100的数字，会处理成'--'
        return {
          total: 100,
          change: 0,
          // change: '--',
          compareHours: 2,
          dimensions: {
            safety: 101,
            clean: 101,
            order: 101,
            convenience: 101,
            beauty: 101,
          }
        };
      }

      // console.log('realData', realData);
      
      // 使用实际数据
      return {
        total: realData.currentIndex.cqi,
        change: realData.currentIndex.change || 0,
        compareHours: 2,
        dimensions: {
          safety: getRealDimensionValue('safety'),
          clean: getRealDimensionValue('clean'),
          order: getRealDimensionValue('order'),
          convenience: getRealDimensionValue('convenience'),
          // beauty: Number('123'),
          beauty: getRealDimensionValue('beauty'),
        }
      };
    }
  };
  
  const currentData = getCurrentData();
  const loading = useMockData ? mockLoading : realLoading;

  // 计算状态和背景色
  const status = currentData ? getStatusByScore(currentData.total) : 'ideal';
  const backgroundOpacity = { backgroundColor: STATUS_COLORS_OPACITY[status] };

  // 如果loading为true，显示加载中，要展示默认页面，就不能加loading
  // if (loading || !currentData) {
  if (!currentData) {
    return <div className={styles.loading}>加载中...</div>;
  }

  return (
    <div className={styles.container} onClick={() => navigateTo('overallSituation')}>
      <div className={styles.background} style={backgroundOpacity}></div>
      <div className={styles.titleArea} onClick={handleTitleClick}>
        <SubTitle title="实时体征" />
      </div>
      
      <div className={styles.content}>
        {/* 左侧总分时钟 */}
        <div className={styles.leftSection} onClick={handleTotalClick}>
          <CQIGauge 
            score={currentData.total}
            change={currentData.change}
            compareHours={Number(currentData.compareHours)}
          />
        </div>
        
        {/* 右侧维度卡片 */}
        <div className={styles.rightSection}>
          <div className={styles.cardRow}>
            <DimensionCard 
              title="安全"
              score={currentData.dimensions.safety}
              iconSrc={safetyIcon}
              iconStyle={iconStyles.safety}
              active={activeDimension === 'safety'}
              onClick={() => handleDimensionClick('safety')}
            />
            <DimensionCard 
              title="整洁"
              score={currentData.dimensions.clean}
              iconSrc={cleanIcon}
              iconStyle={iconStyles.clean}
              active={activeDimension === 'clean'}
              onClick={() => handleDimensionClick('clean')}
            />
          </div>
          <div className={styles.cardRow}>
            <DimensionCard 
              title="有序"
              score={currentData.dimensions.order}
              iconSrc={orderIcon}
              iconStyle={iconStyles.order}
              active={activeDimension === 'order'}
              onClick={() => handleDimensionClick('order')}
            />
            <DimensionCard 
              title="便民"
              score={currentData.dimensions.convenience}
              iconSrc={convenienceIcon}
              iconStyle={iconStyles.convenience}
              active={activeDimension === 'convenience'}
              onClick={() => handleDimensionClick('convenience')}
            />
          </div>
          <div className={styles.cardRow}>
            <DimensionCard 
              title="美观"
              score={currentData.dimensions.beauty}
              iconSrc={beautyIcon}
              iconStyle={iconStyles.beauty}
              active={activeDimension === 'beauty'}
              onClick={() => handleDimensionClick('beauty')}
            />
          </div>
        </div>
      </div>
    </div>
  );
};

export default LeftTopCQI; 