import CooglMap from '@/components/CooglMap';
import Modal from '@/components/HncyModal';
import { useGlobalModalServices } from '@/pages/GlobalModalServices/provider';
import services from '@/services';
import { cqiDisplay, getColorByIndex, getCqiStatusStyle } from '@/utils/ui';
import { Flex, Space } from 'antd';
import React, { useEffect, useRef, useState } from 'react';

import Apps from '../components/Apps';
import LeftTab from '../components/LeftTab';
import { colorConfig } from '../DistrictMap';
import RiskIssue from '../RiskIssue';
import styles from './index.less';
import PopoverCardArea from './PopoverCardArea';
import BaseInfo from '@/pages/SecurityServiceOverview/components/BaseInfo';
const EmphasisAreaMap: React.FC = () => {
  const [checkedKeys, setCheckedKeys] = useState([
    '城市问题',
    '其他问题',
    '突出问题',
  ]);

  //区域切换
  const [center, setCenter] = useState<any>();

  //区域
  const [areaSelectd, setAreaSelectd] = useState<any>();

  const [expand, setExpand] = useState<number>();
  const ref = useRef(0);
  const { dispatch } = useGlobalModalServices();

  const MapRef = useRef<any>();
  const [leftTabKey, setLeftTabKey] = useState('1');

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

  /**
   * @description 设置地图视野
   */
  const setViewport = () => {
    // const map = MapRef.current?.map as BMapGL.Map;
    // if (map) {
    //   map.setViewport([p1, p2]);
    // }
  };

  // /** @description 移动视角到能显示全部覆盖物 */
  // useEffect(() => {
  //   setViewport();
  // }, [MapRef.current]);

  // 重点区域列表
  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 getObjectPolygon = async () => {
    const params = {
      physicalSignType: 1,
      objectHierarchy: 19,
    };
    const res = await services.Physicalsign.getObjectPolygon(params);
    if (res.code === 200 && res.data?.length) {
      setAllAreaMapData(res.data);
    }
  };

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

  /** 标题渲染 */
  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' ? (
          <>
            {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) => {
                  console.log('areaSelectd', areaSelectd);
                  dispatch.push('KeyAreaDetail', {
                    title: areaSelectd.objectName,
                    props: {
                      objectId: areaSelectd?.currentIndex?.objectId,
                      cqi: areaSelectd?.currentIndex?.cqi,
                    },
                  });
                }}
                onClose={(e) => {
                  setAreaSelectd(undefined);
                  // console.log('close', e);
                }}
              >
                <div className={styles.window} style={{ width: 555 }}>
                  <PopoverCardArea data={areaSelectd}></PopoverCardArea>
                </div>
              </CooglMap.CustomOverlay>
            )}
            {allAreaMapData && (
              <>
                {center?.multiPoints?.map((item: any, index: number) => {
                  return (
                    <CooglMap.Polygon
                      key={index}
                      fillColor={getColorByIndex(Number(center?.qualitySign))!}
                      strokeColor="#fff"
                      points={item}
                      strokeWidth={2}
                      fillOpacity={0.2}
                    ></CooglMap.Polygon>
                  );
                })}
              </>
            )}
          </>
        ) : (
          <RiskIssue
            checkedKeys={checkedKeys}
            // setModalOpt={setModalOpt}
            setDetailModalOpt={setDetailModalOpt}
          />
        )}
      </CooglMap.MapView>
      <div className={styles.leftList}>
        <div className={styles.bg}></div>
        <div className={styles.listContent}>
          <div className={styles.listTitle}>重点区域列表</div>
          <div style={{ height: 520, overflow: 'auto' }}>
            {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 ? (
                        <img
                          src={require('@/assets/images/down.png')}
                          alt=""
                          style={{
                            width: 22,
                            height: 22,
                            transform: 'rotate(180deg)',
                          }}
                        />
                      ) : (
                        <img
                          src={require('@/assets/images/down.png')}
                          alt=""
                          style={{ width: 22, height: 22 }}
                        />
                      )}
                    </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,
                              );
                      

                              MapRef?.current?.flyTo({
                                destination: {
                                  x: Number(data?.centerX),
                                  y: Number(data?.centerY),
                                  z: 739,
                                },
                              });
                              setLeftTabKey('1');
                              setCenter(data);
                            }}
                          >
                            <div>{child.objectName}</div>
                            <div
                              style={{
                                color: getCqiStatusStyle(child.cqi)?.color,
                              }}
                            >
                              {cqiDisplay(child.cqi)}
                            </div>
                          </Flex>
                        );
                      })}
                    </div>
                  )}
                </div>
              );
            })}
          </div>
        </div>
      </div>

      <div className={styles.statusBar}>
        <LeftTab
          leftTabKey={leftTabKey}
          checkedKeys={checkedKeys}
          setLeftTabKey={setLeftTabKey}
          setCheckedKeys={setCheckedKeys}
        />
        <Apps></Apps>
      </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?.position,
                eventType: val?.event_type,
                riskLevelName: val?.risklevel,
              });
            }}
          />
        )}
      </Modal>
    </div>
  );
};

export default EmphasisAreaMap;
