import CooglMap from '@/components/CooglMap';
import { calculatePolygonCentroid } from '@/components/CooglMap/utils';
import services from '@/services';
import { useSetState } from 'ahooks';
import { Flex } from 'antd';
import classNames from 'classnames';
import React, { Fragment, useEffect, useMemo, useState } from 'react';
import styles from './index.less';
import RoadList from './RoadList';

const Map: React.FC = () => {
  const [activeTab, setActiveTab] = useState('1');

  const [dataSource, setDataSource] = useSetState<{
    num: { name: string; num: number }[];
    locationData: any;
  }>({
    num: [],
    locationData: [],
  });

  const [roadData, setRoadData] = useState([])

  const [selectedRoad, setSelectedRoad] = useState({})

  const tabItems = useMemo(
    () => [
      {
        key: '1',
        label: '市管功能照明监管网格分布',
      },
      {
        key: '2',
        label: '市管功能照明道路分布',
      },
    ],
    [],
  );

  useEffect(() => {
    services.DataBase.getSjdzInfoData({
      typeCode: 'hyzm-zm-dzs',
    }).then((res) => {
      if (res.code === 200) {
        const records = res.data.data.records;
        setDataSource({
          num: records,
        });
      }
    });

    services.DataBase.getWgjzInfoData({
      typeCode: 'wg-zm-wg1',
    }).then(res => {
      if (res) {
        if (res?.length > 0) {
          setDataSource({
            locationData: res,
          });
          const allRoadData = res?.map(item => item.childrenGeoJson.features)?.flat() || []
          console.log('allRoadData', allRoadData)
          setRoadData(allRoadData)
        }
      }
    })

    // services.DataBase.getWgjzInfoData({
    //   typeCode: 'wg-hdwg',
    //   data: {
    //     industryCode: '06',
    //     gridType: '05',
    //   },
    // }).then((res) => {
    //   if (res.code === 0) {
    //     const records = res.data.responsibilityGrid;
    //     setDataSource({
    //       locationData: records,
    //     });
    //   }
    // });
  }, []);
  /** @description 地图渲染需要的点位数据 */
  const mapData = useMemo(() => {
    if (dataSource.num?.length > 0 && dataSource.locationData?.length > 0) {
      const result = dataSource.locationData.map((v: any) => {
        // const points = JSON.parse(v.gridRange) as {
        //   coordinates: [number, number][][][];
        // };
        const points = v.geoJson.features[0]?.geometry

        const center = calculatePolygonCentroid(points?.coordinates[0][0]);

        const num = dataSource.num.find((item) => item.name === v.name)?.num;

        return {
          points: points.coordinates[0][0],
          center,
          num: num,
          name: v.name,
          childrenGeoJson: v.childrenGeoJson
        };
      });
      console.log(result)
      return result;
    }
    return undefined;
  }, [dataSource]);

  const mergeRoadData = async (item: any) => {
    const res = await services.DataBase.getGzInfoData({
      typeCode: 'gz-dl-dlgzd',
      params: {
        current: 1,
        size: 1000,
        roadName: item.roadName
      }
    })
    if (res.code === 200) {
      const { records } = res.data
      const result = records[0] || {}
      if (item.roadName === result.roadName) {
        item.luxObj = result
      }
    }
  }

  // 处理道路数据
  const handleMapRoad = async (list: any) => {
    console.log(list)
    // list.forEach((item: any) => {
    //   mergeRoadData(item)
    // })
  }

  return (
    <div className={styles.container}>
      <Flex gap={10} className={styles.tabContainer}>
        {tabItems.map((item, index) => {
          return (
            <div
              key={index}
              onClick={() => {
                setActiveTab(item.key);
                setSelectedRoad({})
              }}
              className={classNames(styles.tabItem, {
                [styles.active]: activeTab === item.key,
              })}
            >
              {item.label}
            </div>
          );
        })}
      </Flex>
      {
        //道路列表
        activeTab === '2' && (
          <RoadList
            setMapRoads={handleMapRoad}
            selectedRoad={selectedRoad}
            setSelectedRoad={(data) => setSelectedRoad(data)}
          />
        )
      }

      <CooglMap.MapView zoom={3} center={{ x: 103.96, y: 30.658842 }}>
        {mapData?.map((item: any) => {
          return (
            <Fragment key={item.name}>
              <CooglMap.Polygon
                points={item.points}
                fillColor="rgba(89, 238, 255, 0.3)"
                strokeWidth={2}
                strokeColor="#fff"
              ></CooglMap.Polygon>
              <CooglMap.CustomOverlay position={item.center}>
                <div className={styles.item}>
                  <div>
                    <div style={{ display: 'flex', alignItems: 'flex-end' }}>
                      <span className={styles.num}>{item.num}</span>
                      <span className={styles.unit}>盏</span>
                    </div>
                    <div className={styles.name}>{item.name}</div>
                  </div>
                </div>
              </CooglMap.CustomOverlay>
              {
                activeTab === '2' && (
                  <>
                    {
                      item?.childrenGeoJson?.features?.map((v: any) => {
                        return (
                          <CooglMap.Polyline
                            width={1}
                            key={v.id}
                            lineColor="#20D6AA"
                            points={v.geometry.coordinates[0][0]}
                          >
                          </CooglMap.Polyline>
                        )
                      })
                    }
                  </>
                )
              }
            </Fragment>
          );
        })}
      </CooglMap.MapView>
    </div>
  );
};

export default Map;
