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 } 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';
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[]>([]);

  useEffect(() => {
    services.Physicalsign.getObjectPolygon({
      physicalSignType: 1,
      objectHierarchy: 1,
      // objectId: '510107',
    }).then((res) => {
      setData(res.data);
    });

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

  useEffect(() => {
    let intervalId!: NodeJS.Timeout;
    if (!eventHtmlRef.current) {
      return;
    }
    const viewBoxH = eventHtmlRef.current?.clientHeight;

    const childrenMaxH = (eventHtmlRef.current?.firstChild as HTMLImageElement)
      ?.clientHeight;

    // 进度条速度
    const speed = 15;
    if (playingStatus) {
      // 开始计时任务
      intervalId = setInterval(() => {
        if (!eventHtmlRef.current) {
          clearInterval(intervalId);
        }

        if (
          (eventHtmlRef.current as HTMLDivElement)?.scrollHeight - viewBoxH <=
          (eventHtmlRef.current as HTMLDivElement)?.scrollTop
        ) {
          eventHtmlRef.current?.scrollTo({ top: 0, behavior: 'instant' });
          return;
        }

        smoothScrollTo(eventHtmlRef.current as HTMLDivElement, 300, speed);
      }, 300);
    } else {
      // 清除定时器
      clearInterval(intervalId);
    }
    // 在组件卸载时清除定时器
    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>
    );
  };

  return (
    <div className={styles.container}>
      <CooglMap.MapView
        zoom={8}
        ref={MapRef}
        center={{ x: 103.96, y: 30.658842 }}
      >
        {leftTabKey === '1' ? (
          <>
            {/**区域 */}
            {data?.map((item, index) => {
              return item?.multiPoints?.map((it: any, idx: number) => {
                return (
                  <CooglMap.Polygon
                    fillColor={getColorByIndex(Number(item.qualitySign))!}
                    key={idx}
                    strokeColor="#fff"
                    points={it}
                    strokeWidth={2}
                    fillOpacity={0.2}
                  ></CooglMap.Polygon>
                );
              });
            })}
            {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) => {
                  setSelected(undefined);
                }}
                onDetail={(e) => {
                  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}>最新事件</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: '事件详情',
                      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;
