import React, { useState, useEffect, useCallback, useRef } from 'react';
import StatusCard, { DataRow } from '@/components/StatusCard';
import styles from './index.less';
import { useDashboard } from '@/pages/Home_v_2504/components/context';
import services from '@/services';
import dayjs from 'dayjs';

// 导入图标 - 暂时都使用bike图标
import bikeIcon from '@/assets/images/V-2504/main-bike.png';
import restaurantIcon from '@/assets/images/V-2504/main-restaurant.png';
import drainageIcon from '@/assets/images/V-2504/main-drainage.png';
import toiletIcon from '@/assets/images/V-2504/main-toilet.png';
import lightingIcon from '@/assets/images/V-2504/main-lighting.png';
import manholeIcon from '@/assets/images/V-2504/main-manhole.png';
import patrolIcon from '@/assets/images/V-2504/main-patrol.png';
import onlineIcon from '@/assets/images/V-2504/main-online.png';
import complaintIcon from '@/assets/images/V-2504/main-complaint.png';

// 导出更新城市管理问题总数的事件
export const EVENT_UPDATE_TOTAL_ISSUES = 'updateTotalIssues';

// 定义卡片数据键类型
interface DataKey {
  online: string;
  alert: string;
}

interface CardConfig {
  id: string;
  title: string;
  iconSrc: string;
  iconStyle?: React.CSSProperties;
  dataRows: DataRow[];
  pageKey?: string;
  dataKey?: DataKey;
}

// 餐饮油烟特殊数据类型
interface RestaurantData {
  zx: number; // 在线数量
  lx: number; // 离线数量
  gj: number; // 告警次数
  zs: number; // 总数
  qy: number; // 区域数量
}

let isDebug = false;
const consoleLog = isDebug ? console.log : () => {};

const LeftBottom: React.FC = () => {
  const [activeCardId, setActiveCardId] = useState<string>(); // 'toilet'
  const { setActivePage, setIsTransitioning, activePage } = useDashboard();
  
  // 添加API数据状态
  const [onlineData, setOnlineData] = useState<any>(null);
  const [alertData, setAlertData] = useState<any>(null);
  const [totalAlerts, setTotalAlerts] = useState<number>(0);
  
  // 新增数据状态
  const [complaintData, setComplaintData] = useState<number>(0);
  const [patrolData, setPatrolData] = useState<{
    smartReport: number;
    manualReport: number;
  }>({ smartReport: 0, manualReport: 0 });
  const [onlinePublicData, setOnlinePublicData] = useState<number>(0);
  
  // 新增餐饮油烟特定数据
  const [restaurantData, setRestaurantData] = useState<RestaurantData>({
    zx: 0,
    lx: 0,
    gj: 0,
    zs: 0,
    qy: 0
  });
  
  // 使用 refs 跟踪最新状态值，避免在 useCallback 中引入依赖
  const alertDataRef = useRef(alertData);
  const totalAlertsRef = useRef(totalAlerts);
  const complaintDataRef = useRef(complaintData);
  const patrolDataRef = useRef(patrolData);
  const onlinePublicDataRef = useRef(onlinePublicData);
  const restaurantDataRef = useRef(restaurantData);
  
  // 更新 refs 以跟踪最新状态
  useEffect(() => {
    alertDataRef.current = alertData;
    totalAlertsRef.current = totalAlerts;
    complaintDataRef.current = complaintData;
    patrolDataRef.current = patrolData;
    onlinePublicDataRef.current = onlinePublicData;
    restaurantDataRef.current = restaurantData;
  }, [alertData, totalAlerts, complaintData, patrolData, onlinePublicData, restaurantData]);

  // 卡片数据配置 - 根据UI图精确配置
  const cardConfigs: CardConfig[] = [
    {
      id: 'bike',
      title: '共享单车',
      iconSrc: bikeIcon,
      iconStyle: { width: '68px', height: '63.5px' },
      dataRows: [
        {
          label: '在线',
          value: onlineData?.sensorOnlineBike || 0,
          unit: '万辆',
          decimals: 2
        },
        {
          label: '今日告警',
          value: alertData?.eventSumBike || 0,
          unit: '次',
          status: 'error',
          decimals: 0
        },
      ],
      dataKey: {
        online: 'sensorOnlineBike',
        alert: 'eventSumBike'
      }
    },
    {
      id: 'restaurant',
      title: '餐饮油烟',
      iconSrc: restaurantIcon,
      iconStyle: { width: '43.5px', height: '51.5px' },
      dataRows: [
        {
          label: '在线',
          value: restaurantData.zx || 0,
          unit: '个',
          decimals: 0
        },
        {
          label: '今日告警',
          value: restaurantData.gj || 0,
          unit: '次',
          status: 'error',
          decimals: 0
        },
      ],
      pageKey: 'restaurantOil',
    },
    {
      id: 'drainage',
      title: '智慧管廊',
      iconSrc: drainageIcon,
      iconStyle: { width: '60px', height: '55.5px' },
      dataRows: [
        {
          label: '在线',
          value: onlineData?.sensorOnlineTunnel || 0,
          unit: '个',
          decimals: 0
        },
        {
          label: '今日告警',
          value: alertData?.eventSumTunnel || 0,
          unit: '次',
          status: 'error',
          decimals: 0
        },
      ],
      dataKey: {
        online: 'sensorOnlineTunnel',
        alert: 'eventSumTunnel'
      }
    },
    {
      id: 'toilet',
      title: '智慧公厕',
      iconSrc: toiletIcon,
      iconStyle: { width: '54px', height: '61px' },
      dataRows: [
        {
          label: '在线',
          value: onlineData?.sensorOnlineWC || 0,
          unit: '个',
          decimals: 0
        },
        {
          label: '今日告警',
          value: alertData?.eventSumWC || 0,
          unit: '次',
          status: 'error',
          decimals: 0
        },
      ],
      dataKey: {
        online: 'sensorOnlineWC',
        alert: 'eventSumWC'
      }
    },
    {
      id: 'lighting',
      title: '智慧照明',
      iconSrc: lightingIcon,
      iconStyle: { width: '60px', height: '64px' },
      dataRows: [
        {
          label: '在线',
          value: onlineData?.sensorOnlineLight || 0,
          unit: '个',
          decimals: 0
        },
        {
          label: '今日告警',
          value: alertData?.eventSumLight || 0,
          unit: '次',
          status: 'error',
          decimals: 0
        },
      ],
      dataKey: {
        online: 'sensorOnlineLight',
        alert: 'eventSumLight'
      }
    },
    {
      id: 'manhole',
      title: '智慧井盖',
      iconSrc: manholeIcon,
      iconStyle: { width: '54.5px', height: '54.5px' },
      dataRows: [
        {
          label: '在线',
          value: onlineData?.sensorOnlineCover || 0,
          unit: '个',
          decimals: 0
        },
        {
          label: '今日告警',
          value: alertData?.eventSumCover || 0,
          unit: '次',
          status: 'error',
          decimals: 0
        },
      ],
      dataKey: {
        online: 'sensorOnlineCover',
        alert: 'eventSumCover'
      }
    },
    {
      id: 'patrol',
      title: '数字巡查',
      iconSrc: patrolIcon,
      iconStyle: { width: '59px', height: '59px' },
      dataRows: [
        {
          label: '智能上报',
          value: patrolData.smartReport,
          unit: '件',
          decimals: 0
        },
        {
          label: '人工上报',
          value: patrolData.manualReport,
          unit: '件',
          decimals: 0
        },
      ]
    },
    {
      id: 'online',
      title: '网络舆情',
      iconSrc: onlineIcon,
      iconStyle: { width: '68.5px', height: '54px' },
      dataRows: [
        {
          label: '今日发现',
          value: onlinePublicData,
          unit: '件',
          decimals: 0
        },
      ]
    },
    {
      id: 'complaint',
      title: '百姓投诉',
      iconSrc: complaintIcon,
      iconStyle: { width: '57px', height: '60px' },
      dataRows: [
        {
          label: '今日投诉',
          value: complaintData,
          unit: '次',
          decimals: 0
        },
      ]
    },
  ];

  // 获取设备在线数据
  const fetchOnlineData = useCallback(async () => {
    try {
      const response = await services.DataBase.getGzInfoData({
        typeCode: 'gz-yjlbzxs',
      });
      
      consoleLog('设备在线数据:', response);
      
      if (response.code === 200 && response.data) {
        setOnlineData(response.data);
      }
    } catch (error) {
      console.error('获取设备在线数据失败:', error);
    }
  }, []);

  // 获取预警数据
  const fetchAlertData = useCallback(async () => {
    try {
      const response = await services.DataBase.getGzInfoData({
        typeCode: 'gz-yjlbtj',
      });
      
      consoleLog('预警数据:', response);
      
      if (response.code === 200 && response.data) {
        setAlertData(response.data);
        
        // 计算所有预警(告警)数的总和 - 但排除餐饮油烟，因为它使用单独的API
        const alertFields = [
          'eventSumBike', 
          'eventSumTunnel', 
          'eventSumWC', 
          'eventSumLight', 
          'eventSumCover'
        ];
        
        const totalAlertsSum = alertFields.reduce((sum, key) => {
          return sum + (parseInt(response.data[key]) || 0);
        }, 0);
        
        // 添加餐饮油烟告警数
        const totalWithRestaurant = totalAlertsSum + restaurantDataRef.current.gj;
        
        consoleLog('预警总数:', totalWithRestaurant);
        setTotalAlerts(totalWithRestaurant);
      }
    } catch (error) {
      console.error('获取预警数据失败:', error);
    }
  }, []);

  // 获取餐饮油烟数据，使用新的API
  const fetchRestaurantData = useCallback(async () => {
    try {
      // 获取当前日期，并格式化为API需要的格式
      const today = new Date();
      const formattedDate = dayjs(today).format('YYYY-MM-DD');
      
      // 构建API参数
      const params = {
        startTime: `${formattedDate} 00:00:00`,
        endTime: `${formattedDate} 23:59:59`,
      };
      
      // 调用新API
      const response = await services.DataBase.getSjdzInfoData({
        typeCode: 'dp-yyyzt-yytj',
        params,
      });
      
      consoleLog('餐饮油烟数据:', response);
      
      if (response.code === 200 && response.data) {
        // 提取正确路径下的数据
        const record = response.data.data?.records?.[0] || {};
        
        const restaurantStats = {
          gj: parseInt(record.gj) || 0,
          zs: parseInt(record.zs) || 0,
          lx: parseInt(record.lx) || 0,
          zx: parseInt(record.zx) || 0,
          qy: parseInt(record.qy) || 0
        };
        
        // 更新状态
        setRestaurantData(restaurantStats);
        
        // 如果已经获取了其他告警数据，更新总告警数
        if (alertDataRef.current) {
          // 计算所有预警(告警)数的总和，但排除餐饮油烟
          const alertFields = [
            'eventSumBike', 
            'eventSumTunnel', 
            'eventSumWC', 
            'eventSumLight', 
            'eventSumCover'
          ];
          
          const totalAlertsSum = alertFields.reduce((sum, key) => {
            return sum + (parseInt(alertDataRef.current[key]) || 0);
          }, 0);
          
          // 添加餐饮油烟告警数
          const totalWithRestaurant = totalAlertsSum + restaurantStats.gj;
          
          consoleLog('更新后的预警总数:', totalWithRestaurant);
          setTotalAlerts(totalWithRestaurant);
        }
      }
    } catch (error) {
      console.error('获取餐饮油烟数据失败:', error);
    }
  }, []);
  
  // 获取百姓投诉数据
  const fetchComplaintData = useCallback(async () => {
    try {
      // 获取当前日期
      const today = new Date();
      const formatDate = (date: Date) => {
        return `${date.getFullYear()}-${String(date.getMonth() + 1).padStart(2, '0')}-${String(date.getDate()).padStart(2, '0')}`;
      };
      
      const startTime = formatDate(today);
      const endTime = formatDate(today);
      
      // 调用API
      const response = await services.DataBase.getMzhsData({
        params: {
          startTime,
          endTime
        }
      });
      
      consoleLog('百姓投诉数据:', response);
      
      if (response.code === 200 && response.data) {
        // 获取百姓投诉数据 slNumDay
        const complaintCount = parseInt(response.data.slNumDay) || 0;
        setComplaintData(complaintCount);
      }
    } catch (error) {
      console.error('获取百姓投诉数据失败:', error);
    }
  }, []);
  
  // 获取数字巡查数据
  const fetchPatrolData = useCallback(async () => {
    try {
      // 获取当前日期并格式化为 YYYY-MM-DD
      const today = new Date();
      const formatDate = (date: Date) => {
        return `${date.getFullYear()}-${String(date.getMonth() + 1).padStart(2, '0')}-${String(date.getDate()).padStart(2, '0')}`;
      };
      const time = formatDate(today);
      
      const response = await services.CityProblemApi.getSourceTotal({
        time: time
      });
      
      consoleLog('数字巡查数据:', response);
      
      if (response.code === 200 && response.data) {
        let smartReport = 0;
        let manualReport = 0;
        
        // 解析数据
        if (Array.isArray(response.data)) {
          response.data.forEach((item: any) => {
            if (item.name === '智能上报') {
              smartReport = parseInt(item.value) || 0;
            } else if (item.name === '人工上报') {
              manualReport = parseInt(item.value) || 0;
            }
          });
        }
        
        setPatrolData({
          smartReport,
          manualReport
        });
      }
    } catch (error) {
      console.error('获取数字巡查数据失败:', error);
    }
  }, []);
  
  // 统一获取所有数据并计算总和
  const fetchAllData = useCallback(async () => {    
    let isHomePage = activePage === 'home';
    if (!isHomePage) {
      return;
    }
    try {
      // 并行获取所有数据，现在包括餐饮油烟数据
      await Promise.all([
        fetchOnlineData(),
        fetchAlertData(),
        fetchComplaintData(),
        fetchPatrolData(),
        fetchRestaurantData(), // 新增餐饮油烟数据获取
      ]);
      
      // 从 refs 中获取最新状态值，而不是依赖闭包中的值
      // 这样可以避免将状态添加到依赖数组中
      const currentAlertTotal = totalAlertsRef.current;
      const currentComplaintData = complaintDataRef.current;
      const currentPatrolData = patrolDataRef.current;
      const currentOnlinePublicData = onlinePublicDataRef.current;
      
      // 计算总数
      const calculatedTotal = 
        currentAlertTotal + 
        currentComplaintData + 
        currentPatrolData.smartReport + 
        currentPatrolData.manualReport + 
        currentOnlinePublicData; 
      
      consoleLog('计算总数: fetchAllData ', calculatedTotal, {
        totalAlerts: currentAlertTotal,
        complaintData: currentComplaintData,
        smartReport: currentPatrolData.smartReport,
        manualReport: currentPatrolData.manualReport,
        onlinePublicData: currentOnlinePublicData
      });
      
      // 使用自定义事件通知LeftTopRunning组件
      const event = new CustomEvent(EVENT_UPDATE_TOTAL_ISSUES, { 
        detail: calculatedTotal 
      });
      window.dispatchEvent(event);
    } catch (error) {
      consoleLog('获取数据失败:', error);
    }
  }, [
    // 只保留函数依赖和 activePage，移除状态依赖以防止循环更新
    fetchOnlineData, 
    fetchAlertData, 
    fetchComplaintData, 
    fetchPatrolData,
    fetchRestaurantData, // 新增依赖
    activePage
  ]);
  
  // 初始获取数据并设置定时刷新
  useEffect(() => {
    // 首次加载时获取数据
    fetchAllData();
    
    // 设置15秒定时刷新
    const intervalId = setInterval(() => {
      fetchAllData();
    }, 15000);
    
    // 组件卸载时清除定时器
    return () => {
      clearInterval(intervalId);
    };
  }, [fetchAllData]);

  const handleCardClick = (id: string, pageKey?: string) => {
    setActiveCardId(id);
    
    // 如果有对应的页面key，则跳转到对应的子页面
    if (pageKey) {
      setIsTransitioning(true);
      setTimeout(() => {
        setActivePage(pageKey);
        setIsTransitioning(false);
      }, 500); // 500ms的过渡动画时间
    }
  };

  // 动态生成最新的卡片数据
  const getUpdatedCardConfigs = useCallback(() => {
    return cardConfigs.map(card => {
      // 深度克隆
      const updatedCard = JSON.parse(JSON.stringify(card));
      
      // 特殊处理餐饮油烟卡片
      if (card.id === 'restaurant') {
        updatedCard.dataRows[0].value = restaurantData.zx || 0;
        updatedCard.dataRows[1].value = restaurantData.gj || 0;
      }
      // 其他卡片处理
      else if (card.dataKey) {
        updatedCard.dataRows = updatedCard.dataRows.map((row: DataRow, index: number) => {
          // 首行处理在线数据
          if (index === 0 && card.dataKey?.online && onlineData?.[card.dataKey.online]) {
            // 为单车特殊处理万辆单位
            if (card.id === 'bike') {
              row.value = Math.floor((parseInt(onlineData[card.dataKey.online]) || 0) / 10000 * 100) / 100;
            } else {
              row.value = parseInt(onlineData[card.dataKey.online]) || 0;
            }
          } 
          // 第二行处理告警数据
          else if (index === 1 && card.dataKey?.alert && alertData?.[card.dataKey.alert]) {
            row.value = parseInt(alertData[card.dataKey.alert]) || 0;
          }
          
          return row;
        });
      } 
      // 特殊处理几个没有dataKey的卡片
      else if (card.id === 'patrol') {
        updatedCard.dataRows[0].value = patrolData.smartReport;
        updatedCard.dataRows[1].value = patrolData.manualReport;
      } else if (card.id === 'online') {
        updatedCard.dataRows[0].value = onlinePublicData; // 始终为0
      } else if (card.id === 'complaint') {
        updatedCard.dataRows[0].value = complaintData;
      }
      
      return updatedCard;
    });
  }, [cardConfigs, onlineData, alertData, patrolData, onlinePublicData, complaintData, restaurantData]);

  return (
    <div className={styles.container}>
      <div className={styles.cardsContainer}>
        {getUpdatedCardConfigs().map((card) => (
          <StatusCard
            key={card.id}
            title={card.title}
            iconSrc={card.iconSrc}
            dataRows={card.dataRows}
            isActive={activeCardId === card.id}
            onClick={() => handleCardClick(card.id, card.pageKey)}
            iconStyle={card.iconStyle}
          />
        ))}
      </div>
    </div>
  );
};

export default LeftBottom; 