import blueBg from '@/assets/images/SecurityServiceOverview/right/blueBg.png';
import orangeBg from '@/assets/images/SecurityServiceOverview/right/orangeBg.png';
import redBg from '@/assets/images/SecurityServiceOverview/right/redBg.png';
import yellowBg from '@/assets/images/SecurityServiceOverview/right/yellowBg.png';
import risk1 from '@/assets/images/urbanSituation/risk1.svg';
import risk2 from '@/assets/images/urbanSituation/risk2.svg';
import risk3 from '@/assets/images/urbanSituation/risk3.svg';
import risk4 from '@/assets/images/urbanSituation/risk4.svg';

import CooglMap from '@/components/CooglMap';
import Modal from '@/components/HncyModal';
import { useGlobalModalServices } from '@/pages/GlobalModalServices/provider';
import services from '@/services';
import { smoothScrollTo } from '@/utils';
import BMapService from '@/utils/mapService';
import { getColorByIndex } from '@/utils/ui';
import { useModel, useRequest } from '@umijs/max';
import { Flex, Image } from 'antd';
import dayjs from 'dayjs';
import React, { CSSProperties, useEffect, useRef, useState, useMemo } from 'react';

import BaseInfo from '@/pages/SecurityServiceOverview/components/BaseInfo';
import { joinPictureHttp } from '@/utils/comm';
import Apps from '../components/Apps';
import LeftTab from '../components/LeftTab';
import RiskIssue from '../RiskIssue';
import styles from './index.less';
import PopoverCard from './PopoverCard';
import { useDashboard } from '../../context';
export const colorConfig: Record<
  string,
  {
    color: CSSProperties['color'];
    bg: string;
    icon: string;
    bigIcon: string;
    tag: string;
  }
> = {
  红色预警: {
    //红色风险
    color: '#FFBCBC',
    bg: redBg,
    icon: risk1,
    bigIcon: 'redIcon',
    tag: require('@/assets/images/SecurityServiceOverview/dtyjtag1.png'),
  },
  橙色预警: {
    //橙色风险
    color: '#FDDFCE',
    bg: orangeBg,
    icon: risk2,
    bigIcon: 'orangeIcon',
    tag: require('@/assets/images/SecurityServiceOverview/dtyjtag2.png'),
  },
  黄色预警: {
    //黄色风险
    color: '#FFE892',
    bg: yellowBg,
    icon: risk3,
    bigIcon: 'yellowIcon',
    tag: require('@/assets/images/SecurityServiceOverview/dtyjtag3.png'),
  },
  一般预警: {
    //一般风险
    color: '#BFE4FF',
    bg: blueBg,
    icon: risk4,
    bigIcon: 'blueIcon',
    tag: require('@/assets/images/SecurityServiceOverview/dtyjtag4.png'),
  },
};
/** 地图 */
const DistrictMap: React.FC = () => {
  const { initialState } = useModel('@@initialState');
  const { areaId } = initialState;
  const { dispatch } = useGlobalModalServices();
  const [playingStatus, setPlayingStatus] = useState(true);
  //区域选择
  const [selected, setSelected] = useState<any>();

  const [checkedKeys, setCheckedKeys] = useState([
    // '安全风险',
    // '红色预警',
    // '橙色预警',
    // '黄色预警',
    // '一般预警',
    '城市问题',
    '其他问题',
    '突出问题',
  ]);
  const MapRef = useRef<any>();

  const eventHtmlRef = useRef<HTMLDivElement>(null);
  const { indexs } = useModel('regionalIndex', (store) => ({
    indexs: store.indexs,
  }));

  // 预警事件详情弹窗
  const [detailModalOpt, setDetailModalOpt] = useState<any>({
    open: false,
    title: '',
    eventId: '',
  });

  const [leftTabKey, setLeftTabKey] = useState('1');
  const [data, setData] = useState<any[]>([]);
  const [eventData, setEventData] = useState<any[]>([]);

  // Add this state to track the current zoom level
  const [currentZoom, setCurrentZoom] = useState(8);

  // Modify the fetchVisiblePolygons to store full data
  const [fullPolygonData, setFullPolygonData] = useState<any[]>([]);

  // Add a state to track if map is ready
  const [isMapReady, setIsMapReady] = useState(false);
  
  const { activePage } = useDashboard();
  const isHomePage = activePage === 'home';

  // 修改状态声明，使用useRef同步最新值
  const currentZoomRef = useRef(currentZoom);
  useEffect(() => {
    currentZoomRef.current = currentZoom;
  }, [currentZoom]);

  const fetchVisiblePolygons = (bounds: any) => {
    // console.log('fetchVisiblePolygons bounds', bounds);
    // Only fetch if we don't have data yet
    if (fullPolygonData.length === 0) {
      services.Physicalsign.getObjectPolygon({
        physicalSignType: 1,
        objectHierarchy: 1,
        bounds: bounds
      }).then((res) => {
        // console.log('fetchVisiblePolygons res', res);
        // Store the full dataset
        setFullPolygonData(res.data || []);
        // Also set the sampled data for initial render
        processDataForZoomLevel(res.data || [], currentZoom);
      });
    } else {
      // If we already have data, just process it for the current zoom
      processDataForZoomLevel(fullPolygonData, currentZoom);
    }
  };

  const getSamplingRate = (zoomLevel: number) => {
    let samplingRate;
    
    if (zoomLevel <= 7) {
      samplingRate = 20; // 1/20 sampling for very zoomed out
    } else if (zoomLevel <= 9) {
      samplingRate = 15; // 1/10 sampling for normal view
    } else if (zoomLevel <= 12) {
      samplingRate = 10; // 1/5 sampling for zoomed in
    } else if (zoomLevel <= 15) {
      samplingRate = 2; // 1/2 sampling for more detail
    } else {
      samplingRate = 1; // Full detail for maximum zoom
    }
    
    // if (zoomLevel <= 7) {
    //   samplingRate = 20; // 1/20 sampling for very zoomed out
    // } else if (zoomLevel <= 9) {
    //   samplingRate = 10; // 1/10 sampling for normal view
    // } else if (zoomLevel <= 12) {
    //   samplingRate = 5; // 1/5 sampling for zoomed in
    // } else if (zoomLevel <= 15) {
    //   samplingRate = 2; // 1/2 sampling for more detail
    // } else {
    //   samplingRate = 1; // Full detail for maximum zoom
    // }
    return samplingRate;
  }

  // Add a function to process data based on zoom level
  const processDataForZoomLevel = (sourceData: any[], zoomLevel: number) => {
    if (!sourceData || !Array.isArray(sourceData)) return;
    
    // Determine sampling rate based on zoom level
    // Higher zoom = lower sampling (more detail)
    let samplingRate = getSamplingRate(zoomLevel);
    
    console.log(`Processing data with sampling rate 1/${samplingRate} at zoom level ${zoomLevel}`);
    
    // Process and set the data
    setData(sourceData);
  };

  // Replace the camera events useEffect with a more reliable implementation
  useEffect(() => {
    // Skip if map isn't initialized yet
    if (!MapRef.current) return;
    
    let intervalId: NodeJS.Timeout | null = null;
    let isMounted = true;
    
    // Set up map ready event listener first
    const onMapReady = () => {
      console.log('Map is ready!');
      setIsMapReady(true);
      
      // After map is ready, start polling for camera position
      intervalId = setInterval(() => {
        // console.log('intervalId', intervalId);
        if (!isMounted || !MapRef.current) return;
        // console.log('MapRef.current', MapRef.current);
        
        try {
          // Get camera height from camera position
          const cameraHeight = MapRef.current.camera?.height;
          // const cameraHeight = MapRef.current.camera?.position?.z;
          // console.log('cameraHeight', cameraHeight, MapRef.current.camera, MapRef.current.camera._scene);
          if (typeof cameraHeight === 'number') {
            // Convert height to zoom level (inverse relationship)
            const newZoom = Math.max(1, Math.min(20, Math.round(20 - Math.log2(cameraHeight/500))));
            
            // 修改定时器中的判断逻辑
            if (Math.abs(newZoom - currentZoomRef.current) >= 2) {
              console.log(`Camera height: ${cameraHeight}, New zoom level: ${newZoom}`, newZoom, currentZoomRef.current);
              setCurrentZoom(newZoom);
              
              // Process polygon data for new zoom level
              if (fullPolygonData.length > 0) {
                processDataForZoomLevel(fullPolygonData, newZoom);
              }
            }
          }
        } catch (error) {
          console.error('Error monitoring camera position:', error);
        }
      }, 500); // Check every 500ms
    };

    // Listen for map ready event
    try {
      // Check if map is already ready (might have happened before this effect)
      if (MapRef.current.scene) {
        onMapReady();
      } else {
        // Wait for ready event
        MapRef.current.readyEvent?.addEventListener(onMapReady);
      }
    } catch (error) {
      console.error('Error setting up map ready listener:', error);
      // Fallback - try again in a bit
      setTimeout(() => {
        if (MapRef.current && isMounted) {
          onMapReady();
        }
      }, 1000);
    }
    
    return () => {
      isMounted = false;
      // Clear interval
      if (intervalId) {
        clearInterval(intervalId);
      }
      // Remove event listener if possible
      try {
        if (MapRef.current?.readyEvent) {
          MapRef.current.readyEvent.removeEventListener(onMapReady);
        }
      } catch (error) {
        console.error('Error cleaning up map event listener:', error);
      }
    };
  }, [MapRef.current]); // Only re-run if MapRef.current changes

  // Move the initial data loading to a separate effect that depends on isMapReady
  useEffect(() => {
    if (!isMapReady) return;
    
    console.log('Map is ready, loading initial data');
    const initialBounds = {
      southwest: { lng: 103.5, lat: 30.4 },
      northeast: { lng: 104.5, lat: 31.0 }
    };
    
    fetchVisiblePolygons(initialBounds);
  }, [isMapReady]);

  useEffect(() => {
    //最新事件
    services.CityProblemApi.getUpToDateEventOther({
      page: 1,
      count: 10,
    }).then((res: any) => {
      console.log('getUpToDateEvent', res);
      if (res.code === 200) {
        setEventData(res.data?.items);
      }
    });
  }, []);

  useEffect(() => {
    if (!eventHtmlRef.current || !playingStatus) return;
    
    const viewBoxH = eventHtmlRef.current.clientHeight;
    const scrollHandler = () => {
      if (!eventHtmlRef.current) return;
      
      if (eventHtmlRef.current.scrollHeight - viewBoxH <= eventHtmlRef.current.scrollTop) {
        eventHtmlRef.current.scrollTo({ top: 0, behavior: 'instant' });
        return;
      }
      
      eventHtmlRef.current.scrollTop += 1; // Smoother scrolling with less overhead
    };
    
    const intervalId = setInterval(scrollHandler, 50);
    return () => clearInterval(intervalId);
  }, [playingStatus]);

  const { data: signData } = useRequest(() =>
    services.districtController.getListIndexInstance({
      physicalSignType: '1',
      indexType: '1',
      indexId: '',
      objectId: areaId,
      indexHierarchy: '1',
      objectHierarchy: '1',
    }),
  );

  /** 标题渲染 */
  const titleRender = () => {
    return (
      <Flex align="center" className={styles.modalTitle}>
        <div className={styles.title}>{detailModalOpt?.riskdescription}</div>
        <img
          src={colorConfig[detailModalOpt?.riskLevelName!]?.tag}
          alt=""
          style={{ width: 136, height: 30, marginLeft: 36, marginRight: 13 }}
        />

        <span className={styles.type}>
          {detailModalOpt?.industry_name_dl}-{detailModalOpt?.name}
        </span>
      </Flex>
    );
  };


  
  // Modify the memoizedPolygons function to apply dynamic sampling
  const memoizedPolygons = useMemo(() => {
    if (!data) return null;
    
    let totalPoints = 0;
    
    // Determine sampling rate based on current zoom level
    let samplingRate = getSamplingRate(currentZoom);
    
    console.log(`Rendering polygons with sampling rate 1/${samplingRate} at zoom level ${currentZoom}`);
    
    return data.map((item, index) => {
      // Sample the points based on samplingRate
      const sampledPoints = item.multiPoints?.map((pointsArray: any[]) => {
        totalPoints += pointsArray.length;
        return pointsArray.filter((_, idx) => idx % samplingRate === 0);
      });
      
      // Return the sampled polygons
      return sampledPoints?.map((points: any, idx: number) => (
        <CooglMap.Polygon
          fillColor={getColorByIndex(Number(item.qualitySign))!}
          key={`${item.objectId}_${idx}`}
          strokeColor="#fff"
          points={points}
          strokeWidth={2}
          fillOpacity={0.2}
        />
      ));
    });
  }, [data, currentZoom]);

  // Force garbage collection opportunity when component unmounts or map changes
  useEffect(() => {
    return () => {
      setData([]); // Clear large data structures
      setEventData([]);
      setSelected(undefined);
      // Other cleanup
    };
  }, []);

  return (
    <div className={styles.container}>
      <CooglMap.MapView
        zoom={8}
        ref={MapRef}
        center={{ x: 103.96, y: 30.658842 }}
        changeSize={{ x1: 908, y1: 430, x2: 908, y2: 572 }}
      >
        {leftTabKey === '1' ? (
          <>
            {/**区域 */}
            {memoizedPolygons}
            {data?.map((item, index) => {
              const point = [Number(item.centerX), Number(item.centerY)];

              return (
                <CooglMap.CustomOverlay
                  key={index}
                  position={point}
                  onSet={() => {
                    const obj = signData?.find(
                      (signItem: any) => item.objectId === signItem?.objectId,
                    );
                    setSelected({
                      ...item,
                      eventCount: obj?.eventCount,
                      diffValue: obj?.diffValue,
                      desc: obj?.desc,
                    });
                  }}
                >
                  <div
                    data-event-key="set"
                    className={styles.indexMarker}
                    style={
                      BMapService.getMakerCSS(
                        Number(item.qualitySign),
                      ) as CSSProperties
                    }
                  >
                    {Number(item.qualitySign)}
                  </div>
                </CooglMap.CustomOverlay>
              );
            })}
            {selected && (
              <CooglMap.CustomOverlay
                position={[Number(selected.centerX), Number(selected.centerY)]}
                offset={{
                  top: -50,
                }}
                onClose={(e: any) => {
                  setSelected(undefined);
                }}
                onDetail={(e: any) => {
                  dispatch.push('districtIndex', {
                    title: selected?.objectName + '运行情况',
                    props: {
                      data: selected,
                      indexs: indexs,
                    },
                  });
                }}
              >
                <div className={styles.window1}>
                  <PopoverCard data={selected}></PopoverCard>
                </div>
              </CooglMap.CustomOverlay>
            )}
          </>
        ) : (
          <RiskIssue
            checkedKeys={checkedKeys}
            // setModalOpt={setModalOpt}
            setDetailModalOpt={setDetailModalOpt}
          />
        )}
      </CooglMap.MapView>

      {/* <div className={styles.statusBar}>
        <LeftTab
          leftTabKey={leftTabKey}
          checkedKeys={checkedKeys}
          setLeftTabKey={setLeftTabKey}
          setCheckedKeys={setCheckedKeys}
        />
        <Apps></Apps>
      </div> */}
      <div className={styles.leftWarp}>
        <div className={styles.menuBg}></div>

        <div className={styles.eventWarp}>
          <div className={styles.title}>{isHomePage ? '最新事件' : '餐饮油烟事件'}</div>
          <div
            className={styles.listWarp}
            ref={eventHtmlRef}
            onMouseMove={() => {
              setPlayingStatus(false);
            }}
            onMouseLeave={() => {
              setPlayingStatus(true);
            }}
          >
            {eventData?.map((item, index) => {
              return (
                <div
                  key={'event_' + item?.eventId}
                  className={styles.items}
                  onClick={() => {
                    dispatch.push('EventDetail', {
                      title: isHomePage ? '事件详情' : '餐饮油烟事件详情',
                      w: 'fit-content',
                      props: {
                        eventId: item?.eventId,
                      },
                    });
                  }}
                >
                  <Image
                    src={joinPictureHttp(item?.disposePicPath)}
                    alt=""
                    // {...imageOptions}
                    preview={false}
                    className={styles.img}
                  />
                  <div className={styles.bottomWarp}>{item?.mainTypeName}</div>
                  <div className={styles.time}>
                    {dayjs(item?.reportTime).format('YYYY-MM-DD')}
                  </div>
                  {/* <div className={styles.time}>{item?.reportTime}分钟前</div> */}
                </div>
              );
            })}
          </div>
          {/* <div className={styles.otherWarp}>
            <div className={styles.other}>更多</div>
          </div> */}
        </div>
      </div>
      {/* 风险事件详情 */}
      <Modal
        open={detailModalOpt?.open}
        titleRender={titleRender}
        onCancel={() => {
          setDetailModalOpt({
            open: false,
            title: '事件详情',
            eventId: '',
          });
        }}
        width={2650}
        height={900}
      >
        {detailModalOpt?.open && (
          <BaseInfo
            eventId={detailModalOpt?.eventId}
            detail={detailModalOpt}
            onChangeOpt={(val) => {
              setDetailModalOpt({
                ...detailModalOpt,
                position: val?.region_name,
                riskLevelName: val?.risklevel,
              });
            }}
          />
        )}
      </Modal>
    </div>
  );
};

export default DistrictMap;
