/* eslint-disable */
import React, { useEffect, useState } from 'react';

import { useRouter } from 'next/router';

import api from './api';
import icon from './assets/img.png';
import { Box } from './styled';

let MAP: any;
let Amap: any;

interface UserInfoType {
  lat: number;
  lon: number;
  pageNo?: number;
  pageSize?: number;
}

export default function MapComponent() {
  const router = useRouter();
  const [mapItem, setMapItem] = useState(0);
  const [userPositioning, setUserPositioning] = useState<UserInfoType>();
  const [markerCol, setMarkerCol] = useState<any>([]);
  // 初始化地图
  const init = async () => {
    try {
      const AMapLoader = await import(/* webpackChunkName: "amap" */ '@amap/amap-jsapi-loader');
      await AMapLoader.load({
        key: '87b424e68754efc3ba9d11ae07475091', // 申请好的Web端开发者Key，首次调用 load 时必填
        version: '2.0', // 指定要加载的 JSAPI 的版本，缺省时默认为 1.4.15
        plugins: [''], // 需要使用的的插件列表，如比例尺'AMap.Scale'等
      })
        .then(async (AMap) => {
          Amap = AMap;
          MAP = new AMap.Map('container', {
            // 设置地图容器id
            viewMode: '3D', // 是否为3D地图模式
            zoom: 9, // 初始化地图级别
            center: [113.93029, 22.53291], // 初始化地图中心点位置
          });
          // 用户定位
          AMap.plugin('AMap.Geolocation', function () {
            const geolocation = new AMap.Geolocation({
              enableHighAccuracy: true, // 是否使用高精度定位，默认:true
              timeout: 10000, // 超过10秒后停止定位，默认：5s
              position: 'RB', // 定位按钮的停靠位置
              offset: [10, 20], // 定位按钮与设置的停靠位置的偏移量，默认：[10, 20]
              zoomToAccuracy: true, // 定位成功后是否自动调整地图视野到定位点
            });
            MAP.addControl(geolocation);
            geolocation.getCurrentPosition(function (status: string, result: any) {
              if (status == 'complete') {
                onComplete(result);
              } else {
                onError(result);
              }
            });
          });
          // 解析定位结果
          async function onComplete(data: any) {
            console.log('定位成功');
            setUserPositioning(data.position);
            // return await mapEntiy(0,data.position);
          }
          // 解析定位错误信息
          async function onError(data: any) {
            // message.error(`定位失败
            // 失败原因排查信息：${data.message}
            // 浏览器返回信息：${data.originMessage}
            // `)
          }
          await mapEntiy(0);
        })
        .catch((e) => {
          console.log(e);
        });
    } catch (error) {
      console.log(error);
    }
  };
  const showPositioningInfo = async (index: number, data?: UserInfoType) => {
    const res = await api.listPositioningInfo({
      lon: userPositioning?.lon || data?.lon || 113.93029,
      lat: userPositioning?.lat || data?.lat || 22.53291,
      pageNo: 1,
      pageSize: 10,
    });
    const list = res.result?.list;
    const markerList: any = [];
    if (list?.length) {
      list?.map((item) => {
        const EntiyValue = addEntiy(item.lon, item.lat, item.name);
        markerList.push(EntiyValue);
      });
      if (markerList.length) MAP?.add(markerList);
      setMarkerCol([...markerList]);
    }
    // 自适应显示多个点位
    MAP?.setFitView();
  };
  const showFlyerBitmap = async (index: number, data?: UserInfoType, pageSize?: number) => {
    const res = await api.listFlyerBitmap({
      lon: userPositioning?.lon || data?.lon || 113.93029,
      lat: userPositioning?.lat || data?.lat || 22.53291,
      pageNo: 1,
      pageSize: pageSize || 40,
    });
    const list = res.result?.list;
    const markerList: any = [];
    if (list?.length) {
      list?.map((item) => {
        const EntiyValue = addEntiy(item.lon, item.lat, item.flyerName);
        markerList.push(EntiyValue);
      });
      if (markerList.length) MAP?.add(markerList);
      setMarkerCol(markerList);
    }
    // 自适应显示多个点位
    MAP?.setFitView();
  };
  const showUavBitmap = async (index: number, data?: UserInfoType) => {
    const res = await api.listUavBitmap({
      lon: userPositioning?.lon || data?.lon || 113.93029,
      lat: userPositioning?.lat || data?.lat || 22.53291,
      pageNo: 1,
      pageSize: 40,
    });
    const list = res.result?.list;
    const markerList: any = [];
    if (list?.length) {
      list?.map((item) => {
        const EntiyValue = addEntiy(item.lon, item.lat, item.uavName);
        markerList.push(EntiyValue);
      });
      if (markerList.length) MAP?.add(markerList);
      setMarkerCol(markerList);
    }
    // 自适应显示多个点位
    MAP?.setFitView();
  };
  // 添加点位
  const mapEntiy = async (index: number, data?: UserInfoType) => {
    MAP?.remove(markerCol);
    if (index === 0) {
      showPositioningInfo(index, data);
    } else if (index === 1) {
      showFlyerBitmap(index, data, 30);
    } else if (index === 2) {
      showUavBitmap(index, data);
    } else {
      router.push('/home/waterfallFlowBody/components/map/moreServicePoints');
    }
    setMapItem(index);
  };

  const addEntiy = (lon: any, lat: any, name: string) => {
    if (!Amap) return;
    const icons = new Amap.Icon({
      size: new Amap.Size(60, 60), // 图标尺寸
      image: icon.src, // Icon的图像
      imageSize: new Amap.Size(60, 60), // 根据所设置的大小拉伸或压缩图片
    });
    const marker = new Amap.Marker({
      position: new Amap.LngLat(lon, lat),
      offset: new Amap.Pixel(-10, -10),
      icon: icons, // 添加 Icon 实例
      title: name,
      zoom: 13,
    });
    return marker;
  };

  useEffect(() => {
    (async () => {
      await init();
    })();
    return MAP && MAP.destroy();
  }, []);

  return (
    <Box className='right-box-item'>
      <div id='container' className='map'></div>
      <div className='map-dosome'>
        <div className={`itemBox ${mapItem === 0 ? 'active' : ''}`} onClick={() => mapEntiy(0)}>
          服务网点
        </div>
        <div className={`itemBox ${mapItem === 1 ? 'active' : ''}`} onClick={() => mapEntiy(1)}>
          租赁网点
        </div>
        <div className={`itemBox ${mapItem === 2 ? 'active' : ''}`} onClick={() => mapEntiy(2)}>
          培训网点
        </div>
        <div className={`${mapItem === 3 ? 'active' : ''}`} onClick={() => mapEntiy(3)}>
          更多网点
        </div>
      </div>
    </Box>
  );
}
