import { DrawerForm } from '@ant-design/pro-components';
import React, { useEffect, useState } from 'react';

export interface ILatLngProps {
  lat: string;
  lng: string;
}

export interface IAddressProps {
  module: string;
  latlng: ILatLngProps;
  poiaddress: string;
  poiname: string;
  cityname: string;
}

export interface ITMapProps {
  onFinish: (address?: IAddressProps) => void;
  trigger?: JSX.Element;
}

const TMapModal: React.FC<ITMapProps> = ({ trigger, onFinish }) => {
  const [address, setAddress] = useState<IAddressProps>();

  useEffect(function () {
    window.addEventListener(
      'message',
      function (event) {
        // 接收位置信息，用户选择确认位置点后选点组件会触发该事件，回传用户的位置信息
        const loc = event.data as IAddressProps;
        if (loc && loc.module === 'locationPicker') {
          //防止其他应用也会向该页面post信息，需判断module是否为'locationPicker'
          console.log('location', loc);
          setAddress(loc);
        }
      },
      false,
    );
  }, []);

  return (
    <DrawerForm
      style={{
        height: '100%',
      }}
      title="选择地址"
      trigger={trigger}
      autoFocusFirstInput
      drawerProps={{
        destroyOnHidden: true,
      }}
      submitTimeout={2000}
      onFinish={async () => {
        onFinish(address);

        return true;
      }}
    >
      <iframe
        id="mapPage"
        width="100%"
        height="100%"
        frameBorder="0"
        src="https://apis.map.qq.com/tools/locpicker?search=1&type=1&key=JYTBZ-6GD3V-ZTZPJ-U35RX-EZMGQ-45BTF&referer=xunhong"
      ></iframe>
    </DrawerForm>
  );
};

export default TMapModal;
