import React, { useState, useEffect } from 'react';
import { Map, Marker } from 'react-amap';
import { Modal, Input } from 'antd';

const MAP_KEY = '82ae49bca6834ad0d5c9fb173e57f88a';

export default props => {
  const { visible, onSetPoint, onCancel, lngLat: propsLngLat, addrInfo } = props;
  let defaultLnglat = [116.404449, 39.914889];
  if (propsLngLat) {
    defaultLnglat = [propsLngLat.lng, propsLngLat.lat];
  }

  const [lnglat, setLnglat] = useState(defaultLnglat);
  const [lnglatText, setLnglatText] = useState(`${defaultLnglat[0]},${defaultLnglat[1]}`);

  const handleOk = () => {
    onSetPoint(lnglatText);
    onCancel(true);
  };

  const onGetPoint = e => {
    setLnglat([e.lnglat.lng, e.lnglat.lat]);
    setLnglatText(`${e.lnglat.lng},${e.lnglat.lat}`);
  };

  const getPoint = () => {
    if (!window.AMap) {
      return;
    }

    window.AMap.plugin(['AMap.Geocoder'], () => {
      const city = addrInfo.provice || '北京市';
      const geocoder = new window.AMap.Geocoder({
        city,
      });
      geocoder.getLocation(addrInfo.address, (status, result) => {
        if (status === 'complete' && result.geocodes.length) {
          const { lng, lat } = result.geocodes[0].location;
          setLnglat([lng, lat]);
          setLnglatText(`${lng},${lat}`);
        } else {
          console.error('根据地址查询位置失败');
          // setLnglat([116.397561,39.909063])
        }
      });
    });
  };

  useEffect(() => {
    if (visible) getPoint();
  }, [visible]);

  return (
    <Modal
      title="门店信息"
      visible={visible}
      width="800px"
      onOk={() => handleOk()}
      onCancel={() => onCancel(true)}
    >
      <div style={{ marginBottom: '20px' }}>
        <Input value={lnglatText} placeholder="点击地图选择经纬度" />
      </div>
      <div style={{ width: '100%', height: '360px' }}>
        <Map
          plugins={['ToolBar']}
          center={lnglat}
          amapkey={MAP_KEY}
          events={{
            created: getPoint,
            click: onGetPoint,
          }}
          zoom={14}
        >
          <Marker position={lnglat}></Marker>
        </Map>
      </div>
    </Modal>
  );
};
