import React, { useEffect, useState } from 'react';

type MapModelProps = {
    lat: string | number;
    lng: string | number;
    getLoc: (values: object) => void;
};
const MapComponent: React.FC<MapModelProps> = ({ getLoc, lat, lng }) => {
    const [src, setSrc] = useState('');
    let isCurrent = true

    useEffect(() => {
        setSrc('https://apis.map.qq.com/tools/locpicker?search=1&type=1&key=' + '123' + '&referer=' + 'myapp');
        if (lat && lng) {
            setSrc('https://apis.map.qq.com/tools/locpicker?search=1&type=1&key=' + '123' + '&referer=' + 'myapp' + `&coord=${lat},${lng}`);
        }

        const handleMessage = (event: any) => {
            if (isCurrent && event.data && event.data.module === 'locationPicker') {
                getLoc(event.data)
            }
        };

        window.addEventListener('message', handleMessage);
        return () => {
            window.removeEventListener('message', handleMessage);
            isCurrent = false;
        };
    }, []);

    return (
        <>
            <div style={{ width: '100%', height: '100%' }}>
                <iframe id="mapPage" width="100%" height="800" frameborder={0} src={src}>
                </iframe>
            </div >
        </>
    );
};

export default MapComponent;