import bridge1Icon from '@/assets/images/brdige/bridge1.png';
import bridge2Icon from '@/assets/images/brdige/bridge2.png';
import bridge3Icon from '@/assets/images/brdige/bridge3.png';
import bridge4Icon from '@/assets/images/brdige/bridge4.png';
import bridge5Icon from '@/assets/images/brdige/bridge5.png';
import locationIcon from '@/assets/images/location.png';
import CooglMap from '@/components/CooglMap';
import services from '@/services';
import { convertUnits } from '@/utils/ui';
import { RightOutlined } from '@ant-design/icons';
import { useRequest, useSetState } from 'ahooks';
import { Flex, List, Spin } from 'antd';
import React, { Fragment, useEffect, useMemo, useRef, useState } from 'react';
import type { ViewType } from '../../context';
import { useBridgeManage } from '../../context';
import styles from './index.less';

import InfiniteScroll from 'react-infinite-scroll-component';
import PopoverCard from './PopoverCard';
import useRoadBridgeData from './useRoadBridgeData';

interface MapBaseProps {
  type?: ViewType;
}
const risklevel = {
  红色预警: bridge5Icon,
  橙色预警: bridge4Icon,
  黄色预警: bridge3Icon,
};
const MapBase: React.FC<MapBaseProps> = () => {
  const { viewType, setViewType, isUsingValue } = useBridgeManage();
  const {
    bridgeTotal,
    roadTotal,
    newCityRoadTotal,
    coreRoadTotal,
    suburbRoadTotal,
    newCityBridgeTotal,
    centerBridgeTotal,
    suburbBridgeTotal,
  } = useRoadBridgeData();
  const mapRef = useRef<any>();
  const [bridgeSelectd, setBridgeSelectd] = useState<any>(undefined);
  //桥梁列表分页阐述
  const [fetchParams, setFetchParams] = useState<any>({
    pageNo: 0,
    pageSize: 10,
  });
  //桥梁列表
  const [listData, setListData] = useState<any>({
    items: [],
    loading: true,

    hasNext: false,
  });
  const [isListCollapsed, setIsListCollapsed] = useState(false);
  const [dataSource, setDataSource] = useSetState<{
    /** 区划列表 */
    areaList: any[];
    /** 桥梁数据列表 */
    bridgeDistributionList: {
      regionName: string;
      num: number;
    }[];
    roadDistributionList: any;
  }>({
    areaList: [],
    bridgeDistributionList: [],
    roadDistributionList: [],
  });

  const tabs = [
    { key: 'bridge' as ViewType, label: '桥梁分布' },
    { key: 'road' as ViewType, label: '道路分布' },
    { key: 'location' as ViewType, label: '桥梁位置分布' },
  ];

  /** 获取行政区划 */
  const getAreaList = () => {
    services.Physicalsign.getObjectPolygon({
      physicalSignType: 1,
      objectHierarchy: 1,
    }).then((res) => {
      setDataSource({
        areaList: res.data,
      });
    });
  };

  /** 获取桥梁分布数据 */
  const getBridgeList = () => {
    services.DataBase.getSjdzInfoData({
      typeCode: 'zzcc-dq-qyfztj',
    }).then((res) => {
      if (res.code === 200) {
        const record = res.data?.data?.records;
        setDataSource({
          bridgeDistributionList: record,
        });
      }
    });
  };

  /** 获取道路分布数据 */
  const getRoadList = () => {
    services.DataBase.getSjdzInfoData({
      typeCode: 'zzcc-dq-dlqyfztjdlsl ',
    }).then((res) => {
      if (res.code === 200) {
        const record = res.data?.data?.records;
        setDataSource({
          roadDistributionList: record,
        });
      }
    });
  };

  //桥梁位置分布底部总数
  const { data: bridgeBotmTotal } = useRequest(() =>
    services.DataBase.getSjdzInfoData({
      typeCode: 'zzcc-aq-qldlsl',
    }).then((res) => {
      if (res.code === 200) {
        return res?.data?.data?.records?.[0]?.ql;
      }
      throw new Error('获取数据失败');
    }),
  );
  //桥梁位置分布底部数据
  const { data: bridgeEarlyData } = useRequest(() =>
    services.DataBase.getSjdzInfoData({
      typeCode: 'zzcc-dq-yjfdjtjql ',
      params: {
        type: '桥梁',
        sshyXlCode: '0401',
      },
    }).then((res) => {
      if (res.code === 200) {
        console.log(res);

        return res?.data?.data?.records?.[0]?.stat;
      }
      throw new Error('获取数据失败');
    }),
  );

  //桥梁列表请求
 const{data:bridgeMarkData}= useRequest(
    () =>
      services.DataBase.getSjdzInfoData({
        typeCode: 'zzcc-dq-qllbx',
        params: {
          // ...fetchParams,
          pageNo:0,
          pageSize: 100,
        },
      }).then((res) => {
        if (res.code === 200) {
          console.log(res);

          return res?.data?.data?.records?.[0];
        }
        throw new Error('获取数据失败');
      }),
    {
      refreshDeps: [fetchParams],
      onSuccess: (res) => {
        const list = [...listData?.items, ...res?.list];
        setListData({
          hasNext: list?.length < res?.page?.total,
          items: list,
        });
      },
    },
  );

  // 根据viewType显示不同的信息
  const mapInfo = {
    bridge: {
      cityNew: newCityBridgeTotal + '座',
      centerCity: centerBridgeTotal + '座',
      suburbs: suburbBridgeTotal + '座',
      total: bridgeTotal?.num + '座',
      area: convertUnits(Number(bridgeTotal?.mj))?.num + '万m2',
    },
    road: {
      cityNew: convertUnits(Number(newCityRoadTotal))?.num + '万m2',
      centerCity: convertUnits(Number(coreRoadTotal))?.num + '万m2',
      countyNew: convertUnits(Number(suburbRoadTotal))?.num + '万m2',
      area: convertUnits(Number(roadTotal?.mj))?.num + '万m2',
      length: (roadTotal?.cd / 1000).toFixed(2) + 'KM',
      count: roadTotal?.num + '条',
    },
    location: {
      centerCity: isUsingValue ? '1242座' : '--',
      suburbs: isUsingValue ? '801座' : '--',
      total: isUsingValue ? '2043座' : '--',
      area: isUsingValue ? '747万m2' : '--',
    },
  }[viewType];

  // 监测统计数据
  const monitorStats = useMemo(() => {
    return [
      {
        name: '已接入监测',
        count: bridgeBotmTotal,
        unit: '座',
        icon: bridge1Icon,
      },
      {
        name: '正常',
        count:
          bridgeBotmTotal -
          bridgeEarlyData?.reduce((acc, curr) => {
            return acc + curr.num;
          }, 0),
        unit: '',
        icon: bridge2Icon,
      },
      {
        name: '黄色预警',
        count: bridgeEarlyData?.find((item) => item.risklevel === '黄色预警')
          ?.num,

        unit: '',
        icon: bridge3Icon,
      },
      {
        name: '橙色预警',
        count: bridgeEarlyData?.find((item) => item.risklevel === '橙色预警')
          ?.num,

        unit: '',
        icon: bridge4Icon,
      },
      {
        name: '红色预警',
        count: bridgeEarlyData?.find((item) => item.risklevel === '红色预警')
          ?.num,

        unit: '',
        icon: bridge5Icon,
      },
    ];
  }, [bridgeEarlyData, bridgeBotmTotal]);

  const getDetails = async (item: any) => {
    try {
      console.log(item);
      
      setBridgeSelectd({ ...item });

      mapRef?.current?.flyTo({
        destination: {
          x: Number(item?.longitude),
          y: Number(item?.latitude) + 0.005,
          z: 2396,
        },
      });
    } catch (error) {
      console.log(error);
    }
  };
  useEffect(() => {
    getAreaList();
    getBridgeList();
    getRoadList();
  }, []);

  return (
    <div className={styles.container}>
      <div className={styles.tabBar}>
        <Flex gap={10}>
          {tabs.map((tab) => (
            <div
              key={tab.key}
              className={`${styles.tabBtn} ${
                viewType === tab.key ? styles.active : ''
              }`}
              onClick={() => setViewType(tab.key)}
            >
              {tab.label}
            </div>
          ))}
        </Flex>
      </div>

      {viewType !== 'location' && (
        <div
          className={`${styles.mapInfo} ${
            viewType === 'bridge' ? styles.mapInfo : styles.mapInfoRoad
          }`}
        >
          <Flex vertical gap={8}>
            {viewType === 'bridge' ? (
              <>
                <Flex align="start" className={styles.infoItem}>
                  <span className={styles.label}>城市新区：</span>
                  <span className={styles.value}>{mapInfo.cityNew}</span>
                </Flex>
                <Flex align="start" className={styles.infoItem}>
                  <span className={styles.label}>中心城区：</span>
                  <span className={styles.value}>{mapInfo.centerCity}</span>
                </Flex>
                <Flex align="start" className={styles.infoItem}>
                  <span className={styles.label}>县市新城：</span>
                  <span className={styles.value}>{mapInfo.suburbs}</span>
                </Flex>
                <Flex align="start" className={styles.infoItem}>
                  <span className={styles.label}>合计：</span>
                  <span className={styles.value}>{mapInfo.total}</span>
                </Flex>
                <Flex align="start" className={styles.infoItem}>
                  <span className={styles.label}>面积：</span>
                  <span className={styles.value}>{mapInfo.area}</span>
                </Flex>
              </>
            ) : (
              <>
                <Flex align="start" className={styles.infoItem}>
                  <span className={styles.label}>城市新区：</span>
                  <span className={styles.value}>{mapInfo.cityNew}</span>
                </Flex>
                <Flex align="start" className={styles.infoItem}>
                  <span className={styles.label}>中心城区：</span>
                  <span className={styles.value}>{mapInfo.centerCity}</span>
                </Flex>
                <Flex align="start" className={styles.infoItem}>
                  <span className={styles.label}>县市新城：</span>
                  <span className={styles.value}>{mapInfo.countyNew}</span>
                </Flex>
                <Flex align="start" className={styles.infoItem}>
                  <span className={styles.label}>面积：</span>
                  <span className={styles.value}>{mapInfo.area}</span>
                </Flex>
                <Flex align="start" className={styles.infoItem}>
                  <span className={styles.label}>长度：</span>
                  <span className={styles.value}>{mapInfo.length}</span>
                </Flex>
                <Flex align="start" className={styles.infoItem}>
                  <span className={styles.label}>数量：</span>
                  <span className={styles.value}>{mapInfo.count}</span>
                </Flex>
              </>
            )}
          </Flex>
        </div>
      )}

      <CooglMap.MapView
        ref={mapRef}
        zoom={8}
        center={{ x: 103.96, y: 30.658842 }}
        mode="3D"
      >
        {viewType === 'bridge' || viewType === 'road' ? (
          dataSource.areaList?.map((item, index) => {
            const points = item?.multiPoints;
            // 根据不同类型渲染不同Overlay
            let info!: {
              name: string;
              val: number;
              unit: any;
            };

            if (viewType === 'bridge') {
              const newData = dataSource.bridgeDistributionList?.find(
                (bridge) => bridge.regionName === item.objectName,
              );
              if (newData) {
                info = {
                  name: newData.regionName,
                  val: Number(newData.num),
                  unit: '座',
                };
              }
            }

            if (viewType === 'road') {
              const newData = dataSource.roadDistributionList?.find(
                (road: any) => road.regionName === item.objectName,
              );

              if (newData) {
                info = {
                  name: newData.regionName,
                  val: convertUnits(Number(newData.num))?.num,
                  unit: (
                    <span>
                      万m<sup>2</sup>
                    </span>
                  ),
                };
              }
            }

            return (
              <Fragment>
                <CooglMap.Polygon
                  fillColor="rgba(89, 238, 255, 0.3)"
                  strokeWidth={2}
                  key={index + '_area'}
                  strokeColor="#fff"
                  points={points[0]}
                  fillOpacity={0.2}
                ></CooglMap.Polygon>
                <CooglMap.CustomOverlay
                  position={[Number(item.centerX), Number(item.centerY)]}
                >
                  <div className={styles.item}>
                    <div>
                      <div style={{ display: 'flex', alignItems: 'flex-end' }}>
                        <span className={styles.num}>{info?.val}</span>
                        <span className={styles.unit}>{info?.unit}</span>
                      </div>
                      <div className={styles.name}>{info?.name}</div>
                    </div>
                  </div>
                </CooglMap.CustomOverlay>
              </Fragment>
            );
          })
        ) : (
          <div>
            {bridgeMarkData?.list?.map((item, index) => {
              return (
                <CooglMap.CustomOverlay
                  key={index}
                  position={[Number(item?.longitude), Number(item?.latitude)]}
                  onClick={async () => {
                    getDetails(item);
                  }}
                >
                  <div className={styles.markWrap}>
                    <div className={styles.name} title={item?.name}>
                      {item?.name}
                    </div>
                    <div className={styles.iconWrap}>
                      <img
                        src={risklevel[item?.risklevel] ?? bridge2Icon}
                        alt=""
                      />
                    </div>
                  </div>
                </CooglMap.CustomOverlay>
              );
            })}
            {bridgeSelectd && (
              <CooglMap.CustomOverlay
                position={[
                  Number(bridgeSelectd.longitude),
                  Number(bridgeSelectd.latitude),
                ]}
                offset={{
                  top: -50,
                }}
                onClose={() => {
                  setBridgeSelectd(undefined);
                }}
              >
                <div className={styles.window} style={{ width: 382 }}>
                  <PopoverCard data={bridgeSelectd}></PopoverCard>
                </div>
              </CooglMap.CustomOverlay>
            )}
          </div>
        )}
      </CooglMap.MapView>

      {/* 桥梁位置分布特有的底部监测统计 */}
      {viewType === 'location' && (
        <div className={styles.monitorStats}>
          <Flex align="center" justify="center">
            {monitorStats.map((stat, index) => (
              <Flex key={index} align="center" className={styles.statGroup}>
                <div
                  className={`${styles.icon} ${
                    index === 0 ? styles.largeIcon : ''
                  }`}
                >
                  <img src={stat.icon} alt={stat.name} />
                </div>
                <span className={styles.name}>{stat.name}</span>
                <Flex align="center" className={styles.valueWrapper}>
                  <span
                    className={`${styles.count} ${styles[`count${index}`]}`}
                  >
                    {stat.count}
                  </span>
                  {stat.unit && (
                    <span className={styles.unit}>{stat.unit}</span>
                  )}
                </Flex>
              </Flex>
            ))}
          </Flex>
        </div>
      )}

      {/* 桥梁位置分布特有的右侧列表 */}
      {viewType === 'location' && (
        <>
          {/* 收起按钮独立放置 */}
          <div
            className={`${styles.collapseBtn} ${
              isListCollapsed ? styles.collapsed : ''
            }`}
            onClick={() => setIsListCollapsed(!isListCollapsed)}
          >
            {!isListCollapsed && (
              <div className={styles.btnText}>
                <span>收</span>
                <span>起</span>
              </div>
            )}
            <RightOutlined className={styles.collapseIcon} />
          </div>

          {/* 列表内容 */}
          <div
            className={`${styles.bridgeList} ${
              isListCollapsed ? styles.collapsed : ''
            }`}
          >
            <div className={styles.listHeader}>
              <span>桥梁列表</span>
            </div>
            <div className={styles.listContent}>
              <div id={'scrollableDiv1'}>
                {/* <InfiniteScroll
                  style={{
                    height: 410,
                    overflow: 'auto',
                  }}
                  height={410}
                  dataLength={listData.items?.length ?? 0}
                  hasMore={listData?.hasNext}
                  scrollableTarget={'scrollableDiv1'}
                  loader={
                    <div style={{ textAlign: 'center' }}>
                      <Spin />
                    </div>
                  }
                  next={() => {
                    fetchParams.pageNo++;
                    setFetchParams({ ...fetchParams });
                  }}
                >
                  <List
                    grid={{ column: 1, gutter: 20 }}
                    dataSource={listData.items}
                    loading={false}
                    renderItem={(item: any, index) => (
                      <List.Item key={index}>
                        <div
                          onClick={() => {
                            getDetails(item);
                            // setBridgeSelectd(item)
                            // console.log(item);

                            // mapRef?.current?.flyTo({
                            //   destination: {
                            //     x: Number(item?.longitude),
                            //     y: Number(item?.latitude),
                            //     z: 23961,
                            //   },
                            // });
                          }}
                          className={styles.bridgeItem}
                          title={item?.name}
                        >
                          <span className={styles.bridgeName}>
                            {item?.name}
                          </span>
                          <div className={styles.locationIcon}>
                            <img
                              src={locationIcon}
                              alt="location icon"
                              style={{ width: '10px', height: '11px' }}
                            />
                          </div>
                        </div>
                      </List.Item>
                    )}
                  />
                </InfiniteScroll> */}
              </div>
              {bridgeMarkData?.list?.map((bridge, index) => (
                <div
                  key={index}
                  className={styles.bridgeItem}
                  onClick={() => {
                    getDetails(bridge);
                  }}
                  style={{ cursor: 'pointer' }}
                >
                  <span className={styles.bridgeName}>{bridge.name}</span>
                  <div className={styles.locationIcon}>
                    <img
                      src={locationIcon}
                      alt="location icon"
                      style={{ width: '10px', height: '11px' }}
                    />
                  </div>
                </div>
              ))}
            </div>
          </div>
        </>
      )}
    </div>
  );
};

export default MapBase;
