/* eslint-disable no-undef */
import $ from 'jquery';
import React, { useEffect, useRef } from 'react';
import { customStyle } from './mapStyle';

interface MapPoint {
    id: string;
    name: string;
    lng: string | number;
    lat: string | number;
    url: string;
    width?: number;
    height?: number;
    offset?: { width?: number; height?: number };
}

interface VmMapProps {
    mapCenter?: [number, number];
    mapPoints?: MapPoint[];
}

type addPointFunc = (points?: MapPoint[]) => void;

export default function VmMap({ mapCenter, mapPoints }: VmMapProps) {
    const mapRef = useRef<any>();
    const markers = useRef<any>([]);

    useEffect(() => {
        initMap();
    }, []);

    useEffect(() => {
        mapRef.current && addPoints(mapPoints);
    }, [mapPoints]);

    const initMap = () => {
        $.getScript(
            `//api.map.baidu.com/getscript?type=webgl&v=1.0&ak=1XjLLEhZhQNUzd93EjU5nOGQ`,
            () => {
                const center = mapCenter || [119.603701, 30.636529];
                mapRef.current = new window.BMapGL.Map('modalMap', {
                    style: { styleJson: customStyle },
                });
                let point = new window.BMapGL.Point(center[0], center[1]);
                // 设置中心点和层级
                mapRef.current.centerAndZoom(point, 15);
            },
        );
    };

    // 地图添加点位
    const addPoints: addPointFunc = (points = []) => {
        removePoints();
        if (!points?.length) return;
        // 添加点位
        const positions: { lng: number; lat: number }[] = [];
        points.forEach((item: any) => {
            const position = new window.BMapGL.Point(item.lng, item.lat);
            positions.push(position);
            const icon = new window.BMapGL.Icon(
                item.url,
                new window.BMapGL.Size(item.width || 32, item.height || 45),
            );
            const marker = new window.BMapGL.Marker(position, {
                icon,
                offset: new window.BMapGL.Size(
                    item.offset?.width || -10,
                    item.offset?.height || -16,
                ),
                title: item.name || '',
            });
            markers.current.push(marker);
            mapRef.current.addOverlay(marker);
        });
        mapRef.current.setViewport(positions);
    };

    // 清除地图点位
    const removePoints = () => {
        markers.current.forEach((marker: any) => {
            mapRef.current.addOverlay(marker);
        });
        markers.current = [];
    };
    return <div id="modalMap" style={{ width: '100%', height: '100%' }} />;
}
