import React, { Component, Dispatch, SetStateAction, useEffect, useState } from 'react';
import { message } from 'antd';
import { Box } from './styled';
import { useRouter } from 'next/router';
let MAP: any;
let Amap: any;

interface UserInfoType {
  lat: number;
  lon: number;
  pageNo?: number;
  pageSize?: number;
}
interface BoxProps {
  setAddressContent: Dispatch<SetStateAction<any>>;
  setIsAddressMapShow: Dispatch<SetStateAction<boolean>>;
}

export default function MapComponent(props: BoxProps) {
  const { setAddressContent, setIsAddressMapShow } = props;
  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 mapEntiy = async (index: number, data?: UserInfoType) => {
    MAP.on('click', mapGet);
    setMapItem(index);
  };
  const mapGet = (e: any) => {
    console.log(e);
    // 在这里获取点位信息
    const lnglat = e.lnglat;
    console.log(lnglat);

    const geocoder = new Amap.Geocoder({
      radius: 1000,
      extensions: 'all',
    });
    geocoder.getAddress(lnglat, function (status: any, result: any) {
      if (status === 'complete' && result.regeocode) {
        const address = result.regeocode.addressComponent;
        const addressDteail =
          address.province +
          address.city +
          address.district +
          address.township +
          address.street +
          address.streetNumber;
        setAddressContent({
          province: address.province,
          city: address.city,
          lon: lnglat.lng,
          lat: lnglat.lat,
          addressDteail,
        });
        setIsAddressMapShow(false);
        // console.log(
        //   address.province +
        //     address.city +
        //     address.district +
        //     address.township +
        //     address.street +
        //     address.streetNumber
        // ) // 打印省市区信息
      }
    });
    // MAP.off('click', mapGet); // 移除click事件
  };

  const addEntiy = (lon: any, lat: any, name: string) => {
    if (!Amap) return;
    const icons = new Amap.Icon({
      size: new Amap.Size(60, 60), // 图标尺寸
      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>
    </Box>
  );
}
