index.js 2.3 KB
import React, { useState, useEffect, useCallback } from 'react'
import { Input, message, Popover } from 'antd'
import { searchAdress } from '../../../../apis/process'
import { debounce, lngmkt, isObject } from '../../../../utils/index'

const SearchLocation = (props) => {

  const areaName = window?.globalConfig?.mapsettings?.areasettings?.areaName || ''
  const { value, onChange, schema, addons } = props
  const { disabled, placeholder, presetValue, coordSync } = schema
  const [options, setOptions] = useState([])

  const getAdress = async (value) => {
    const { code, data } = await searchAdress({ keywords: `${areaName}${value}`, region: areaName })
    if (code === '0') {
      setOptions(data?.pois)
    } else {
      message.error('请求错误!')
    }
  }

  const doSomeThing = useCallback(debounce(getAdress), [])

  const onSearch = async (e) => {
    doSomeThing(e.target.value)
    onChange(e.target.value)
  }

  const selectChange = (item) => {
    if (item.location) {
      let array = item.location.split(',')
      let coord = lngmkt({ lng: array[0], lat: array[1] })
      if (coordSync) {
        let paths = Object.keys(addons.formData)
        let targetPath = null
        if (Array.isArray(paths)) {
          paths.forEach(v => {
            let values = addons.getValue(v)
            if (isObject(values)) {
              for (let key in values) {
                if (key === coordSync) {
                  targetPath = `${v}.${key}`
                }
              }
            }
          })
        }
        if (targetPath) {
          addons.setValue(targetPath, `${coord.x},${coord.y}`)
        }
      }
    }
    onChange(item.name)
  }

  useEffect(() => {
    if (addons) {
      addons.setValue(addons.dataPath, presetValue || '')
    }
  }, [presetValue])

  const content = (
    <div>
      {
        (options || []).map((v, i) => <p key={i} onClick={() => selectChange(v)}><a>{v.name}</a></p>)
      }
    </div>
  )

  return (
    <div>
      <Popover content={content} title="地名选择" trigger="hover" placement="topLeft">
        <Input
          disabled={disabled}
          placeholder={disabled ? (placeholder || '') : (placeholder || '请输入地址')}
          value={value}
          onChange={onSearch}
        />
      </Popover>
    </div>
  )
}

export default SearchLocation