import React, { useEffect, useState } from 'react'
import { Button, Modal, Tooltip, Row, Col } from 'antd'
import { AMapSearch, getRegeo } from '@/components/AMap' 

const AMapSelector = React.forwardRef((props, ref) => {
  const [visible, updateVisible] = useState(false)
  const [lnglat, updateLngLat]  = useState()

  const handleSearch = (dt, evt) => {
    updateLngLat(dt)
  }
  const showModal = () => updateVisible(true)
  const hideModal = () => updateVisible(false)

  const handleOk = () => {
    getRegeo('14f05ce59c26364fd0674014dc0d8b1b', { location: lnglat }).then(res => {
      props.onChange(lnglat, res)
      hideModal()
    }).catch(err => {
      //
    })
  }

  useEffect(() => {
    updateLngLat(props.value)
  }, [props.value])

  const footer = (
    <div style={{ paddingRight: 64, textAlign: 'right' }}>
      <Button onClick={hideModal}>取消</Button>
      <Button type="primary" onClick={handleOk} disabled={!lnglat} style={{ marginLeft: 36 }}>确定</Button>
    </div>
  )

  return (
    <div ref={ref}>
      <Tooltip title="点我选择地址">      
        <Button onClick={showModal}>{props.value || '点我选择地址' }</Button>
      </Tooltip>
      <Modal visible={visible} centered title="请选择地点" onCancel={hideModal} footer={footer} width="calc(60vw + 50px)">
        <div style={{ width: '60vw', height: '60vh' }}>
          <AMapSearch value={lnglat} onChange={handleSearch} amapkey="f0d1d4f82432504003ebf46e5e36ff03" />
        </div>
      </Modal>
    </div>
  )
})

export default React.memo(AMapSelector)
