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 EventDetail from '@/pages/Common/Event/EventDetail';
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 { IMG_URL } from '@/utils/variables';
import { useModel, useRequest } from '@umijs/max';
import { ConfigProvider, Flex, Tree } from 'antd';
import dayjs from 'dayjs';
import React, { CSSProperties, useEffect, useRef, useState } from 'react';
import BaseInfo from '../../BaseInfo';
import styles from './index.less';
import PopoverCard from './PopoverCard';
import PopoverCardKnotty from './PopoverCardKnotty';
import PopoverCardWarn from './PopoverCardWarn';

/** 地图 */
const DistrictMap: React.FC = () => {
  const { initialState } = useModel('@@initialState');
  const { areaId } = initialState;

  const [playingStatus, setPlayingStatus] = useState(true);
  //区域选择
  const [selected, setSelected] = useState<any>();
  //风险
  const [fxSelectd, setFxSelectd] = useState<any>();
  //问题
  const [kontSelectd, setKontSelectd] = useState<any>();
  const colorConfig: Record<
    string,
    {
      color: CSSProperties['color'];
      bg: string;
      icon: string;
      bigIcon: string;
    }
  > = {
    红色风险: {
      //红色风险
      color: '#FFBCBC',
      bg: redBg,
      icon: risk1,
      bigIcon: 'redIcon',
    },
    橙色风险: {
      //橙色风险
      color: '#FDDFCE',
      bg: orangeBg,
      icon: risk2,
      bigIcon: 'orangeIcon',
    },
    黄色风险: {
      //黄色风险
      color: '#FFE892',
      bg: yellowBg,
      icon: risk3,
      bigIcon: 'yellowIcon',
    },
    一般风险: {
      //一般风险
      color: '#BFE4FF',
      bg: blueBg,
      icon: risk4,
      bigIcon: 'blueIcon',
    },
  };
  /** @description store */

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

  const eventHtmlRef = useRef<HTMLDivElement>(null);
  const { selectDistrict, areaListDto, getIndexs, indexs } = useModel(
    'regionalIndex',
    (store) => ({
      areaListDto: store.areaListDto,
      selectDistrict: store.selectDistrict!,
      getIndexs: store.getIndexs,
      indexs: store.indexs,
    }),
  );
  // 事件详情弹窗
  const [modalOpt, setModalOpt] = useState({
    open: false,
    title: '',
    eventId: '',
  });
  // 预警事件详情弹窗
  const [detailModalOpt, setDetailModalOpt] = useState<any>({
    open: false,
    title: '',
    eventId: '',
  });

  const [leftTabKey, setLeftTabKey] = useState('1');
  const [data, setData] = useState<any[]>([]);
  const [eventData, setEventData] = useState<any[]>([]);
  const { dispatch } = useGlobalModalServices();
  const [searchParams, setSearchParams] = useState({
    parentTypeCode: 'dlql',
    lat: 30.680193,
    lon: 104.075555,
    distance: 1000,
    page: 1,
    count: 100,
  });

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

    //最新事件
    services.CityProblemApi.getUpToDateEvent({
      page: 1,
      count: 10,
      // protrudeFlag: '1',
    }).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?.clientWidth;
    const childrenMaxH = (eventHtmlRef.current?.firstChild as HTMLImageElement)
      ?.clientHeight;

    // 进度条速度
    const speed = 40;
    if (playingStatus) {
      // 开始计时任务
      intervalId = setInterval(() => {
        if (
          (eventHtmlRef.current as HTMLDivElement).scrollTop + viewBoxH >=
          childrenMaxH * 10
        ) {
          eventHtmlRef.current?.scrollTo({ top: 0, behavior: 'instant' });
          return;
        }
        smoothScrollTo(eventHtmlRef.current as HTMLDivElement, 500, speed);
      }, 500);
    } else {
      // 清除定时器
      clearInterval(intervalId);
    }
    // 在组件卸载时清除定时器
    return () => {
      clearInterval(intervalId);
    };
  }, [playingStatus]);

  //safetyRiskEventMap
  const { data: warnMark } = useRequest(
    () => services.CityRiskApi.safetyRiskEventMap(searchParams),
    {
      refreshDeps: [searchParams],
    },
  );

  const pList = [
    {
      l: [103.87453593938976, 30.746739203687397],
      type: 1,
      name: '突出问题',
      icon: require('@/assets/images/tuchuIc.png'),
    },
    {
      l: [103.9541617397942, 30.735316951515046],
      type: 2,
      name: '突出问题',
      icon: require('@/assets/images/tuchuIc.png'),
    },
    {
      l: [103.87424848162657, 30.72240319350852],
      type: 3,
      name: '突出问题',
      icon: require('@/assets/images/tuchuIc.png'),
    },
    {
      l: [103.92455359018533, 30.71569728382409],
      type: 4,
      name: '未结案',
      icon: require('@/assets/images/wtIc.png'),
    },
    {
      l: [103.87453593938976, 30.71569728382409],
      type: 5,
      name: '未结案',
      icon: require('@/assets/images/wtIc.png'),
    },
  ];

  //safetyRiskEventMap
  const { data: signData } = useRequest(() =>
    services.districtController.getListIndexInstance({
      physicalSignType: '1',
      indexType: '1',
      indexId: '',
      objectId: areaId,
      indexHierarchy: '1',
      objectHierarchy: '1',
    }),
  );
  const { data: eventList } = useRequest(() =>
    services.CityRiskApi.getEventPage({ page: 1, count: 2 }),
  );

  /** 标题渲染 */
  const titleRender = () => {
    return (
      <Flex align="center" className={styles.modalTitle}>
        <div className={styles.title}>{detailModalOpt?.eventType}</div>
        <span
          className={styles.tag}
          style={{
            backgroundImage: `url(${
              colorConfig[detailModalOpt?.riskLevelName]?.bg
            })`,
            color: colorConfig[detailModalOpt?.riskLevelName]?.color,
          }}
        >
          {detailModalOpt?.riskLevelName}
        </span>
        <span className={styles.type}>{detailModalOpt?.position}</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 (
                <CooglMap.Polygon
                  fillColor={getColorByIndex(Number(item.qualitySign))!}
                  key={index}
                  strokeColor="#fff"
                  points={item.points}
                  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.window}>
                  <PopoverCard data={selected}></PopoverCard>
                </div>
              </CooglMap.CustomOverlay>
            )}
          </>
        ) : (
          <>
            {warnMark?.items
              ?.filter((item: any) => checkedKeys?.includes(item?.riskLevel))
              ?.map((item: any, index: number) => {
                const point = [Number(item?.x_pos), Number(item?.y_pos)];

                return (
                  <CooglMap.CustomOverlay
                    key={index}
                    position={point}
                    onSet={async () => {
                      const res = await services.CityRiskApi.getInfo({
                        // riskId: '24555845',
                        riskId: item?.riskId,
                      });

                      setFxSelectd({ ...res?.data, riskId: item?.riskId });
                    }}
                  >
                    <img
                      data-event-key="set"
                      src={colorConfig[item?.riskLevel]?.icon}
                      alt=""
                      style={{ width: 46, height: 46, zIndex: 999 }}
                    />
                  </CooglMap.CustomOverlay>
                );
              })}
            {eventData
              ?.filter((item) =>
                checkedKeys?.includes(
                  item?.protrudeFlag == '2' ? '突出问题' : '其他问题',
                ),
              )
              ?.map((item, index) => {
                const point = [Number(item?.lon), Number(item?.lat)];
                return (
                  <CooglMap.Marker
                    key={index}
                    onClick={() => {
                      setKontSelectd(item);
                    }}
                    position={point}
                    icon={
                      item?.protrudeFlag == '2'
                        ? require('@/assets/images/tuchuIc.png')
                        : require('@/assets/images/wtIc.png')
                    }
                  ></CooglMap.Marker>
                );
              })}
            {/**预警popover */}
            {fxSelectd && (
              <CooglMap.CustomOverlay
                position={[Number(fxSelectd.x_pos), Number(fxSelectd.y_pos)]}
                offset={{
                  top: -50,
                }}
                onDetail={(e) => {
                  setDetailModalOpt({
                    open: true,
                    eventId: fxSelectd?.riskId,
                    ...fxSelectd,
                  });
                }}
                onClose={(e) => {
                  setFxSelectd(undefined);
                }}
              >
                <div className={styles.window}>
                  <PopoverCardWarn data={fxSelectd}></PopoverCardWarn>
                </div>
              </CooglMap.CustomOverlay>
            )}
            {/**问题popover */}
            {kontSelectd && (
              <CooglMap.CustomOverlay
                position={[Number(kontSelectd?.lon), Number(kontSelectd?.lat)]}
                offset={{
                  top: -50,
                }}
                onDetail={(e) => {
                  // e?.stopPropagation();
                  // e?.nativeEvent?.stopImmediatePropagation();
                  setModalOpt({
                    open: true,
                    title: '事件详情',
                    ...kontSelectd,
                  });
                }}
                onClose={(e) => {
                  // e?.stopPropagation();
                  // e?.nativeEvent?.stopImmediatePropagation();

                  setKontSelectd(undefined);
                }}
              >
                <div className={styles.window}>
                  <PopoverCardKnotty data={kontSelectd}></PopoverCardKnotty>
                </div>
              </CooglMap.CustomOverlay>
            )}
          </>
        )}
      </CooglMap.MapView>

      {selectDistrict && (
        <div className={styles.districtName}>{selectDistrict.objectName}</div>
      )}
      <div className={styles.statusBar}>
        <div className={styles.title}>图层图例</div>
        <div
          className={styles.leftTab}
          style={{ background: leftTabKey == '1' ? 'rgb(19, 146, 224)' : '' }}
          onClick={() => setLeftTabKey('1')}
        >
          CQI
        </div>
        <div className={styles.itemWarp}>
          <div className={styles.mark} style={{ backgroundColor: '#F24F4F' }} />
          <div>
            应急态
            {/* &lt;60 */}
          </div>
        </div>
        <div className={styles.itemWarp}>
          <div className={styles.mark} style={{ backgroundColor: '#FFA81A' }} />
          <div>预警态 &lt;85</div>
        </div>
        <div className={styles.itemWarp}>
          <div className={styles.mark} style={{ backgroundColor: '#00B9FF' }} />
          <div>标准态 85-95</div>
        </div>
        <div className={styles.itemWarp}>
          <div className={styles.mark} style={{ backgroundColor: '#57EF58' }} />
          <div>理想态 &gt;95</div>
        </div>
        <div
          className={styles.leftTab}
          style={{ background: leftTabKey == '2' ? 'rgb(19, 146, 224)' : '' }}
          onClick={() => setLeftTabKey('2')}
        >
          风险预警与问题分布
        </div>
        {leftTabKey == '2' && (
          <ConfigProvider
            theme={{
              token: {},
              components: {
                Tree: {
                  directoryNodeSelectedBg: '#133c6d',
                },
              },
            }}
          >
            <Tree
              checkable
              defaultExpandAll
              onCheck={(e: any) => {
                setCheckedKeys(e);
              }}
              checkedKeys={checkedKeys}
              treeData={[
                {
                  title: '安全风险',
                  key: '安全风险',
                  disabled: true,
                  children: [
                    {
                      title: (
                        <div className={styles.treeTitle}>
                          <img src={risk1}></img>红色风险
                        </div>
                      ),
                      key: '红色风险',
                      disabled: true,
                    },
                    {
                      title: (
                        <div className={styles.treeTitle}>
                          <img src={risk2}></img>橙色风险
                        </div>
                      ),
                      disabled: true,
                      key: '橙色风险',
                    },
                    {
                      title: (
                        <div className={styles.treeTitle}>
                          <img src={risk3}></img>黄色风险
                        </div>
                      ),
                      disabled: true,
                      key: '黄色风险',
                    },
                    {
                      title: (
                        <div className={styles.treeTitle}>
                          <img src={risk4}></img>一般风险
                        </div>
                      ),
                      disabled: true,
                      key: '一般风险',
                    },
                  ],
                },
                {
                  title: '城市问题',
                  key: '城市问题',
                  children: [
                    {
                      title: (
                        <div className={styles.treeTitle}>
                          <img src={require('@/assets/images/wtIc.png')}></img>
                          其他问题
                        </div>
                      ),
                      key: '其他问题',
                    },
                    {
                      title: (
                        <div className={styles.treeTitle}>
                          <img
                            src={require('@/assets/images/tuchuIc.png')}
                          ></img>
                          突出问题
                        </div>
                      ),
                      key: '突出问题',
                    },
                  ],
                },
              ]}
            />
          </ConfigProvider>
        )}
      </div>
      <div className={styles.leftWarp}>
        <div className={styles.eventWarp}>
          <div className={styles.title}>最新事件</div>
          <div className={styles.listWarp} ref={eventHtmlRef}>
            {eventData?.map((item, index) => {
              return (
                <div
                  key={'event_' + item?.eventId}
                  className={styles.items}
                  onMouseMove={() => {
                    setPlayingStatus(false);
                  }}
                  onMouseLeave={() => {
                    setPlayingStatus(true);
                  }}
                  onClick={() => {
                    setModalOpt({ open: true, title: '事件详情', ...item });
                  }}
                >
                  <img
                    src={IMG_URL + item?.disposePicPath}
                    alt=""
                    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) => {
              console.log(val);

              setDetailModalOpt({
                ...detailModalOpt,
                position: val?.position,
                eventType: val?.event_type,
                riskLevelName: val?.risklevel,
              });
            }}
          />
        )}
      </Modal>
      {/**事件详情 */}
      <Modal
        open={modalOpt?.open}
        title={modalOpt?.title}
        onCancel={() => setModalOpt({ open: false, title: '', eventId: '' })}
        width={'fit-content'}
        height={950}
      >
        <EventDetail eventId={modalOpt?.eventId} />
      </Modal>
    </div>
  );
};

export default DistrictMap;
