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 risk4 from '@/assets/images/SecurityServiceOverview/risk/blue.png';
import risk2 from '@/assets/images/SecurityServiceOverview/risk/orange.png';
import risk1 from '@/assets/images/SecurityServiceOverview/risk/red.png';
import risk3 from '@/assets/images/SecurityServiceOverview/risk/yellow.png';
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 BMapService from '@/utils/mapService';
import { getColorByIndex } from '@/utils/ui';
import { IMG_URL } from '@/utils/variables';
import { useModel, useRequest } from '@umijs/max';
import { ConfigProvider, Flex, Space, Tree } from 'antd';
import classNames from 'classnames';
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 [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;
    }
  > = {
    红色风险: {
      //红色风险
      color: '#FFBCBC',
      bg: redBg,
      icon: 'redIcon',
    },
    橙色风险: {
      //橙色风险
      color: '#FDDFCE',
      bg: orangeBg,
      icon: 'orangeIcon',
    },
    黄色风险: {
      //黄色风险
      color: '#FFE892',
      bg: yellowBg,
      icon: 'yellowIcon',
    },
    一般风险: {
      //一般风险
      color: '#BFE4FF',
      bg: blueBg,
      icon: 'blueIcon',
    },
  };
  /** @description store */

  const [checkedKeys, setCheckedKeys] = useState([
    '安全风险',
    '红色风险',
    '橙色风险',
    '黄色风险',
    '一般风险',
    '城市问题',
    '其他问题',
    '突出问题',
  ]);
  const MapRef = useRef<any>();
  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) => {
      console.log('getUpToDateEvent', res);
      if (res.code === 200) {
        setEventData(res.data?.items);
      }
    });
  }, []);

  //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={13}
        ref={MapRef}
        center={{ x: 104.066349, 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) => 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) => 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={require(`@/assets/images/SecurityServiceOverview/right/${
                        colorConfig[item?.riskLevel]?.icon
                      }.png`)}
                      alt=""
                      style={{ width: 82, height: 82, 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) => {
                  e?.stopPropagation();
                  e?.nativeEvent?.stopImmediatePropagation();
                  setDetailModalOpt({
                    open: true,
                    eventId: fxSelectd?.riskId,
                    ...fxSelectd,
                  });
                }}
                onClose={(e) => {
                  e?.stopPropagation();
                  e?.nativeEvent?.stopImmediatePropagation();

                  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) => {
                setCheckedKeys(e);
              }}
              checkedKeys={checkedKeys}
              treeData={[
                {
                  title: '安全风险',
                  key: '安全风险',
                  children: [
                    {
                      title: (
                        <div className={styles.treeTitle}>
                          <img src={risk1}></img>红色风险
                        </div>
                      ),
                      key: '红色风险',
                    },
                    {
                      title: (
                        <div className={styles.treeTitle}>
                          <img src={risk2}></img>橙色风险
                        </div>
                      ),
                      key: '橙色风险',
                    },
                    {
                      title: (
                        <div className={styles.treeTitle}>
                          <img src={risk3}></img>黄色风险
                        </div>
                      ),
                      key: '黄色风险',
                    },
                    {
                      title: (
                        <div className={styles.treeTitle}>
                          <img src={risk4}></img>一般风险
                        </div>
                      ),

                      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.warnWarp}>
          {eventList?.items?.map((it) => {
            return (
              <Flex
                className={styles.warnItem}
                justify="center"
                vertical
                style={
                  {
                    '--color': colorConfig[it?.riskLevelName]?.color,
                    background: `url(${colorConfig[it?.riskLevelName]?.bg})`,
                    backgroundSize: '100% 100%',
                  } as CSSProperties
                }
                onClick={() => {
                  setDetailModalOpt({
                    open: true,
                    eventId: it?.asriskId,
                    ...it,
                  });
                }}
              >
                {colorConfig[it?.riskLevelName]?.icon && (
                  <img
                    src={require(`@/assets/images/SecurityServiceOverview/right/${
                      colorConfig[it?.riskLevelName]?.icon
                    }.png`)}
                    className={styles.icon}
                  />
                )}
                <div className={classNames(styles.title, 'textellipsis')}>
                  {it?.eventType}
                </div>
                <Space align="start">
                  <span className={classNames(styles.address, 'textellipsis')}>
                    {it?.position}
                  </span>
                  <div
                    className={styles.time}
                    title={dayjs().diff(it?.warningTime, 'm') + '分钟前'}
                  >
                    {dayjs().diff(it?.warningTime, 'm')}分钟前
                  </div>
                </Space>
              </Flex>
            );
          })}
        </div>
        <div className={styles.eventWarp}>
          <div className={styles.title}>最新事件</div>
          <div className={styles.listWarp}>
            {eventData?.map((item, index) => {
              return (
                <div
                  key={'event_' + item?.eventId}
                  className={styles.items}
                  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;
