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 { cqiDisplay, getColorByIndex, getCqiStatusStyle } from '@/utils/ui';
import { DownCircleFilled, UpCircleFilled } from '@ant-design/icons';
import { useModel } from '@umijs/max';
import { useRequest } from 'ahooks';
import { ConfigProvider, Flex, Space, Tree } from 'antd';
import React, { CSSProperties, useEffect, useRef, useState } from 'react';
import BaseInfo from '../../BaseInfo';
import PopoverCardKnotty from '../DistrictMap/PopoverCardKnotty';
import PopoverCardWarn from '../DistrictMap/PopoverCardWarn';
import styles from './index.less';
import PopoverCardArea from './PopoverCardArea';
const EmphasisAreaMap: React.FC = () => {
  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',
    },
  };
  // 事件详情弹窗
  const [modalOpt, setModalOpt] = useState({
    open: false,
    title: '',
    eventId: '',
  });
  const { initialState } = useModel('@@initialState');
  const { areaId } = initialState;
  const [center, setCenter] = useState();
  //风险
  const [fxSelectd, setFxSelectd] = useState<any>();
  //区域
  const [areaSelectd, setAreaSelectd] = useState<any>();
  //问题
  const [kontSelectd, setKontSelectd] = useState<any>();
  const [expand, setExpand] = useState<number>();
  const ref = useRef(0);
  const { dispatch } = useGlobalModalServices();
  /** 是否启用百度地图 */
  const [isBmap, setIsBmap] = useState(false);
  const MapRef = useRef<any>();
  const [leftTabKey, setLeftTabKey] = useState('1');
  const [checkedKeys, setCheckedKeys] = useState([
    // '安全风险',
    // '红色风险',
    // '橙色风险',
    // '黄色风险',
    // '一般风险',
    '城市问题',
    '其他问题',
    '突出问题',
  ]);
  // 事件详情弹窗
  const [detailModalOpt, setDetailModalOpt] = useState<any>({
    open: false,
    title: '',
    eventId: '',
  });
  const [areaList, setAreaList] = useState<any>([]);
  const [allAreaMapData, setAllAreaMapData] = useState<any>([]);
  const [searchParams, setSearchParams] = useState({
    parentTypeCode: 'dlql',
    lat: 30.680193,
    lon: 104.075555,
    distance: 1000,
    page: 1,
    count: 100,
  });

  const p1 = [103.74243115816007, 30.79721665183887];

  const p2 = [104.48437948789275, 30.807638945537175];

  /**
   * @description 设置地图视野
   */
  const setViewport = () => {
    // const map = MapRef.current?.map as BMapGL.Map;
    // if (map) {
    //   map.setViewport([p1, p2]);
    // }
  };
  const { data: newEvent } = useRequest(
    services.CityProblemApi.getUpToDateEvent,
    {
      defaultParams: [
        {
          page: 1,
          count: 10,
        },
      ],
    },
  );

  /** @description 移动视角到能显示全部覆盖物 */
  useEffect(() => {
    setViewport();
  }, [MapRef.current]);
  const { data: warnMark } = useRequest(
    () => services.CityRiskApi.safetyRiskEventMap(searchParams),
    {
      refreshDeps: [searchParams],
    },
  );

  // 重点区域列表
  const getImportantAreaList = async () => {
    const params = {
      physicalSignType: 1,
      objectHierarchy: 19,
    };
    const res = await services.Physicalsign.getGroupObjectPhysicalSignIndex(
      params,
    );

    if (res.code === 200) {
      setAreaList(res.data);
    }
  };

  useEffect(() => {
    getImportantAreaList();
  }, []);

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

  const getObjectPolygon = async () => {
    const params = {
      physicalSignType: 1,
      objectHierarchy: 19,
    };
    const res = await services.Physicalsign.getObjectPolygon(params);
    if (res.code === 200) {
      if (res.data?.length) {
        setAllAreaMapData(res.data);
      }
    }
  };

  useEffect(() => {
    getObjectPolygon();
  }, []);
  console.log(center);

  /** 标题渲染 */
  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}>
      {isBmap ? (
        <></>
      ) : (
        <CooglMap.MapView
          zoom={8}
          ref={MapRef}
          center={{ x: 103.96, y: 30.658842 }}
        >
          {leftTabKey === '1' ? (
            <>
              {allAreaMapData?.map((item: any) => (
                <CooglMap.CustomOverlay
                  position={[item?.centerX, item?.centerY]}
                  onClick={async () => {
                    try {
                      const params = {
                        physicalSignType: '1', // 1实况指数  3周期指数
                        indexType: '1', // 指数体系类型 0:内评价 1:外评价
                        indexHierarchy: '1,2', // 指数层级，从1开始，多个用,逗号隔开
                        objectId: item?.objectId, // 区域网格id
                        indexId: '', // 指数id
                      };
                      const res =
                        await services.Physicalsign.getComparisonIndexInstance(
                          params,
                        );

                      const res1 =
                        await services.Physicalsign.getTotalCountForKeyAreas({
                          keyAreaId: item?.objectId,
                          eventStatus: '处置中',
                        });

                      setAreaSelectd({
                        ...res?.data,
                        centerX: item?.centerX,
                        centerY: item?.centerY,
                        objectName: item?.objectName,
                        issueCount: res1?.data,
                      });
                    } catch (error) {
                      console.log(error);
                    }
                  }}
                  key={item.objectId}
                >
                  <div className={styles.indexMarker}>
                    <div className={styles.markerContent}>
                      {item?.objectName}
                      <span
                        style={{ color: getColorByIndex(item?.qualitySign) }}
                      >
                        {cqiDisplay(item?.qualitySign)}
                      </span>
                    </div>
                    <div
                      className={styles.markerIcon}
                      style={{
                        borderColor: getColorByIndex(item?.qualitySign),
                      }}
                    ></div>
                  </div>
                </CooglMap.CustomOverlay>
              ))}
              {areaSelectd && (
                <CooglMap.CustomOverlay
                  position={[
                    Number(areaSelectd.centerX),
                    Number(areaSelectd.centerY),
                  ]}
                  offset={{
                    top: -50,
                  }}
                  onDetail={(e) => {
                    dispatch.push('KeyAreaDetail', {
                      title: areaSelectd.objectName,
                      props: {
                        objectId: areaSelectd?.objectId,
                        cqi: areaSelectd?.qualitySign,
                      },
                    });
                  }}
                  onClose={(e) => {
                    setAreaSelectd(undefined);
                    // console.log('close', e);
                  }}
                >
                  <div className={styles.window} style={{ width: 555 }}>
                    <PopoverCardArea data={areaSelectd}></PopoverCardArea>
                  </div>
                </CooglMap.CustomOverlay>
              )}
              {center && (
                <CooglMap.Polygon
                  fillColor={getColorByIndex(Number(center?.qualitySign))!}
                  strokeColor="#fff"
                  points={center?.points}
                  strokeWidth={2}
                  fillOpacity={0.2}
                ></CooglMap.Polygon>
              )}
            </>
          ) : (
            <>
              {warnMark?.data?.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>
                  );
                })}
              {newEvent?.data?.items
                ?.filter((item: any) =>
                  checkedKeys?.includes(
                    item?.protrudeFlag == '2' ? '突出问题' : '其他问题',
                  ),
                )
                .map((item: any, index: number) => {
                  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>
                  );
                })}
              {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>
      )}

      <div className={styles.leftList}>
        <div className={styles.listTitle}>重点区域列表</div>
        <div>
          {areaList?.map((item: any, index: number) => {
            return (
              <div key={index}>
                <Flex
                  className={styles.listItem}
                  align="center"
                  justify="space-between"
                  onClick={() => {
                    if (expand === index) {
                      setExpand(undefined);
                      return;
                    }
                    ref.current = index;

                    setExpand(index);
                  }}
                >
                  <div>{item?.objGroup}</div>
                  <Space>
                    <div>{item?.objects?.length}</div>
                    <div>个</div>
                    {index === expand ? (
                      <UpCircleFilled style={{ color: '#1CC0FF' }} />
                    ) : (
                      <DownCircleFilled style={{ color: '#1CC0FF' }} />
                    )}
                  </Space>
                </Flex>
                {expand === index && (
                  <div className={styles.childWrap}>
                    {item?.objects.map((child: any, child_index: any) => {
                      return (
                        <Flex
                          key={child_index}
                          align="center"
                          className={styles.childItem}
                          justify="space-between"
                          onClick={() => {
                            const data = allAreaMapData?.find(
                              (it) => it.objectId === child?.objectId,
                            );
                            console.log(data);

                            MapRef?.current?.flyTo({
                              destination: {
                                x: Number(data?.centerX),
                                y: Number(data?.centerY),
                                z: 23961,
                              },

                              // orientation: {
                              //   heading: 6.283185307179586,
                              //   pitch: -1.568627330287271,
                              //   roll: 0,
                              // },
                            });

                            setCenter(data);

                            //   destination: {
                            //     x: -82.50000000000001,
                            //     y: 35.1631173323302,
                            //     z: 23961170.015054718,
                            //   },
                            //   orientation: {
                            //     heading: 6.283185307179586,
                            //     pitch: -1.568627330287271,
                            //     roll: 0,
                            //   },
                            // });
                          }}
                        >
                          <div>{child.objectName}</div>
                          <div
                            style={{
                              color: getCqiStatusStyle(child.cqi)?.color,
                            }}
                          >
                            {cqiDisplay(child.cqi)}
                          </div>
                        </Flex>
                      );
                    })}
                  </div>
                )}
              </div>
            );
          })}
        </div>
      </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: '#1b4761',
                },
              },
            }}
          >
            <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>
                      ),
                      key: '橙色风险',
                      disabled: true,
                    },
                    {
                      title: (
                        <div className={styles.treeTitle}>
                          <img src={risk3}></img>黄色风险
                        </div>
                      ),
                      key: '黄色风险',
                      disabled: true,
                    },
                    {
                      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>
      {/* 事件详情 */}
      <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 EmphasisAreaMap;
