import { message } from 'antd';
import { useEffect, useState } from 'react';
import Layout from '~/components/layout';
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 MoreServicePoints() {
  const [mapItem, setMapItem] = useState(0);
  const [userPositioning, setUserPositioning] = useState<UserInfoType>();
  const [markerCol, setMarkerCol] = useState<any>([]);
  const [servicePoints, setServicePoints] = 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) {
              console.log(result);

              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);
      });
      setServicePoints(list);
      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);
      });
      setServicePoints(list);
      if (markerList.length) MAP?.add(markerList);
      setMarkerCol(markerList);
    }
    //自适应显示多个点位
    MAP?.setFitView();
  };
  const showMaintainBitmap = async (index: number, data?: UserInfoType, pageSize?: number) => {
    const res = await api.listMaintainBitmap({
      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.name);
        markerList.push(EntiyValue);
      });
      setServicePoints(list);
      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);
      });
      setServicePoints(list);
      if (markerList.length) MAP?.add(markerList);
      setMarkerCol(markerList);
    }
    //自适应显示多个点位
    MAP?.setFitView();
  };
  //添加点位
  const mapEntiy = async (index: number, data?: UserInfoType) => {
    MAP?.remove(markerCol);
    if (userPositioning) {
      MAP?.setCenter([userPositioning.lon, userPositioning.lat]);
    }
    if (index === 0) {
      showPositioningInfo(index, data);
    } else if (index === 1) {
      showFlyerBitmap(index, data, 30);
    } else if (index === 2) {
      showUavBitmap(index, data);
    } else {
      showMaintainBitmap(index, data, 30);
    }
    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;
  };

  const moveTo = (item: any, index: number) => {
    const p = markerCol[index].getPosition();
    var infoWindow = new Amap.InfoWindow({
      position: p,
      offset: new Amap.Pixel(20, -10),
      content: item.dizhi || item.flyerName || item.uavName || item.name,
    });
    infoWindow.open(MAP);
    if (item.dizhi) {
      return MAP?.setCenter([item.jd, item.wd]);
    } else if (item.flyerName || item.uavName || item.name) {
      return MAP?.setCenter([item.lon, item.lat]);
    }
    return message.warning('暂无位置信息');
  };

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

  return (
    <Layout>
      <Box>
        <div className='title'>
          <div onClick={() => mapEntiy(0)} className={`item ${mapItem === 0 ? 'active' : ''}`}>
            服务网点
          </div>
          <div onClick={() => mapEntiy(1)} className={`item ${mapItem === 1 ? 'active' : ''}`}>
            培训网点
          </div>
          <div onClick={() => mapEntiy(2)} className={`item ${mapItem === 2 ? 'active' : ''}`}>
            租赁网点
          </div>
          <div onClick={() => mapEntiy(3)} className={`item ${mapItem === 3 ? 'active' : ''}`}>
            维修网点
          </div>
        </div>
        <div className='content'>
          <div className='left'>
            {mapItem === 0 && <div className='left-title'>服务网点</div>}
            {mapItem === 1 && <div className='left-title'>培训网点</div>}
            {mapItem === 2 && <div className='left-title'>租赁网点</div>}
            {mapItem === 3 && <div className='left-title'>维修网点</div>}
            <div className='left-content'>
              {servicePoints.map((item: any, index: number) => (
                <div
                  key={item.id}
                  onClick={() => moveTo(item, index)}
                  className='left-content-item'
                  title={item.dizhi || item.flyerName || item.uavName || item.name}
                >
                  {item.dizhi || item.flyerName || item.uavName || item.name}
                </div>
              ))}
            </div>
          </div>
          <div className='right'>
            <div id='container'></div>
          </div>
        </div>
      </Box>
    </Layout>
  );
}
