import React, { useState, useEffect, useCallback } from 'react';
import { useRequest } from 'ahooks';
import styles from './index.less';
import SubTitle from '../../../common/SubTitle';
import NumberBoard from '@/components/NumberBoard';
import DataItem from '@/components/DataItem';
import { EVENT_UPDATE_TOTAL_ISSUES } from '../LeftBottom';

// 导入资源
import titleBg from '@/assets/images/V-2504/running-title-bg.png';
import titleBgActive from '@/assets/images/V-2504/running-title-bg-active.png';
import titleText from '@/assets/images/V-2504/running-title.png';
import staffLogo from '@/assets/images/V-2504/running-logo-1.png';
import deviceLogo from '@/assets/images/V-2504/running-logo-2.png';
import services from '@/services';
import { useDashboard } from '../../../context';

// 默认数据，将被API数据覆盖
let defaultData = 9799;
let isDebug = false;
const consoleLog = isDebug ? console.log : () => {};

const testData = () => {
  const result = Math.floor(Math.random() * 50); // 测试用随机数字
  // const result = Math.floor(Math.random() * 999999); // 测试用随机数字
  defaultData = defaultData + result;
  return defaultData;
}
// 模拟API
const fetchRunningStatusData = async () => {
  // 模拟数据
  return {
    todayIssues: testData(), // 测试用随机数字
    staffData: {
      online: 95.25, // 城管人员在线
      unit: '万人在线'
    },
    deviceData: {
      online: 95.25, // 物联感知设备在线
      unit: '万个在线'
    }
  };
};

const LeftTopRunning: React.FC = () => {
  // 状态管理
  const [titleBarActive, setTitleBarActive] = useState(false);
  const [activeItem, setActiveItem] = useState<'staff' | 'device' | null>(null);
  
  // 人员在线数据
  const [staffOnlineData, setStaffOnlineData] = useState<number>(0);
  // 感知设备在线数据
  const [sensorCount, setSensorCount] = useState<number>(0);
  // 新增城市管理问题总数
  const [totalIssues, setTotalIssues] = useState<number>(0);
  // 城管24城市管理问题总数
  const [cityTotalData, setCityTotalData] = useState<number>(0);
  // 显示的最终总数（totalIssues + cityTotalData）
  const [displayTotal, setDisplayTotal] = useState<number>(0);
  
  // 获取运行态势数据
  // const { data, loading } = useRequest(fetchRunningStatusData, {
  //   pollingInterval: 30000, // 每30秒刷新一次
  // });
  const { activePage } = useDashboard();

  // 获取感知设备数据
  const fetchSensorData = useCallback(() => {
    let isHomePage = activePage === 'home';
    if (!isHomePage) {
      return;
    }
    services.DataBase.getGzInfoData({
      typeCode: 'gz-sbzs',
    }).then((res) => {
      if (res.code === 200) {
        // 将感知源数量转换为万个单位
        consoleLog(res.data?.sensorOnlineCount);
        const sensorCountInTenThousand =
          Math.floor(((res.data?.sensorOnlineCount || 0) / 10000) * 100) / 100;
        // console.log(sensorCountInTenThousand);
        setSensorCount(sensorCountInTenThousand);
      }
    }).catch(error => {
      console.error('获取感知设备数据出错:', error);
    });
  }, []);
  
  // 获取人员在线数据
  const fetchStaffOnlineData = useCallback(() => {
    
    let isHomePage = activePage === 'home';
    if (!isHomePage) {
      return;
    }
    services.AuthApi.getOnlineNumbersApi({}).then(res => {
      consoleLog('获取在线人数', res);  
      if (res.code === 200 && res.data) {
        setStaffOnlineData(res.data);
      }
    }).catch(error => {
      console.error('获取在线人数出错:', error);
    });
  }, []);
  
  // 获取城市管理问题总数（城管24）
  const fetchCityTotal = useCallback(() => {
    let isHomePage = activePage === 'home';
    if (!isHomePage) {
      return;
    }
    // 获取当前日期并格式化为 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);
    
    // 调用 API 获取城市管理问题总数
    services.CityProblemApi.getCityTotal({
      time: time
    }).then(res => {
      consoleLog('获取城市管理问题总数:', res);
      if (res.code === 200 && res.data) {
        const cityTotal = parseInt(res.data) || 0;
        setCityTotalData(cityTotal);
        
        // 更新显示的总数（当前告警总数 + 城管24问题总数）
        setDisplayTotal(totalIssues + cityTotal);
      }
    }).catch(error => {
      console.error('获取城市管理问题总数出错:', error);
    });
  }, [totalIssues]);

  // 监听城市管理问题总数更新事件
  useEffect(() => {
    const handleTotalIssuesUpdate = (event: any) => {
      const newTotal = event.detail;
      console.log('接收到城市管理问题总数更新:', newTotal);
      setTotalIssues(newTotal);
      
      // 更新显示的总数（当前告警总数 + 城管24问题总数）
      setDisplayTotal(newTotal + cityTotalData);
    };
    
    // 添加事件监听
    window.addEventListener(EVENT_UPDATE_TOTAL_ISSUES, handleTotalIssuesUpdate);
    
    // 组件卸载时移除事件监听
    return () => {
      window.removeEventListener(EVENT_UPDATE_TOTAL_ISSUES, handleTotalIssuesUpdate);
    };
  }, [cityTotalData]);
  
  // 初始加载人员在线数据、感知设备数据和城市管理问题总数
  useEffect(() => {
    fetchStaffOnlineData();
    fetchSensorData();
    fetchCityTotal();
    
    // 设置定时刷新，每30秒更新一次
    const staffIntervalId = setInterval(() => {
      fetchStaffOnlineData();
    }, 30000);
    
    const sensorIntervalId = setInterval(() => {
      fetchSensorData();
    }, 30000);
    
    const cityTotalIntervalId = setInterval(() => {
      fetchCityTotal();
    }, 30000);
    
    // 组件卸载时清除定时器
    return () => {
      clearInterval(staffIntervalId);
      clearInterval(sensorIntervalId);
      clearInterval(cityTotalIntervalId);
    };
  }, [fetchStaffOnlineData, fetchSensorData, fetchCityTotal]);
  
  // 处理标题栏点击
  const handleTitleBarClick = () => {
    // setTitleBarActive(!titleBarActive);
  };
  
  // 处理数据项点击
  const handleItemClick = (type: 'staff' | 'device') => {
    setActiveItem(activeItem === type ? null : type);
  };
  
  // 处理标题栏鼠标进入
  const handleTitleBarMouseEnter = () => {
    setTitleBarActive(true);
  };
  
  // 处理标题栏鼠标离开 
  const handleTitleBarMouseLeave = () => {
    setTitleBarActive(false);
  };
  
  // if (loading && !totalIssues && !staffOnlineData && !sensorCount) {
  //   return <div className={styles.loading}>加载中...</div>;
  // }

  return (
    <div className={styles.container}>
      <div className={styles.background}></div>      
      <SubTitle title="运行态势" />
      
      <div className={styles.content}>
        {/* 今日新增城市管理问题 */}
        <div 
          className={styles.titleBar} 
          onClick={handleTitleBarClick}
          onMouseEnter={handleTitleBarMouseEnter}
          onMouseLeave={handleTitleBarMouseLeave}
          style={{ 
            backgroundImage: `url(${titleBarActive ? titleBgActive : titleBg})` 
          }}
        >
          <img src={titleText} className={styles.titleText} alt="今日新增城市管理问题" />
        </div>
        
        {/* 数字展示板 - 使用API获取的总数 */}
        <div className={styles.numberBoardContainer}>
          <NumberBoard number={displayTotal || 0} totalDigits={6} />
          {/* <NumberBoard number={displayTotal || data?.todayIssues || 0} totalDigits={6} /> */}
        </div>
        
        {/* 城管人员和物联感知设备数据 */}
        <div className={styles.dataItemsContainer}>
          <DataItem 
            title="城管人员"
            value={staffOnlineData}
            unit='人'
            decimals={0}
            // unit={data.staffData.unit}
            logoSrc={staffLogo}
            active={activeItem === 'staff'}
            onClick={() => handleItemClick('staff')}
          />
          <DataItem 
            title="物联感知设备"
            value={sensorCount}
            unit='万个在线'
            decimals={2}
            logoSrc={deviceLogo}
            active={activeItem === 'device'}
            onClick={() => handleItemClick('device')}
          />
        </div>
      </div>
    </div>
  );
};

export default LeftTopRunning; 