import React, { FC, useState, useEffect } from 'react';
import { uniqueId } from 'lodash';
import { Input, AutoComplete } from 'antd';
import { ExpansionProps, Position } from '../types';
import { lngRegexp, latRegexp } from '@/utils/regexp';
import styles from './index.less';

interface SearchAddressProps extends ExpansionProps {
  onChange?: (position: Position) => void;
  setPosition?: (position: Position) => void;
}

let autocomplete: any = null;

const SearchAddress: FC<SearchAddressProps> = props => {
  const { __map__, onChange, setPosition } = props;
  const map = __map__;
  const [options, setOptions] = useState([]);

  useEffect(() => {
    map.plugin(['AMap.Autocomplete'], function() {
      try {
        autocomplete = new window.AMap.Autocomplete();
      } catch (e) {
        console.log(e);
      }
    });
  }, []);

  const handleSelect = (value: string, options: any) => {
    const location = options.location;
    if (!location) return;
    map?.setCenter([location.lng, location.lat]);
    map?.setZoom(15);
    onChange?.({
      longitude: location.lng,
      latitude: location.lat,
    });
  };

  const handleSearch = (value: string) => {
    const splitValue = value.split(',');
    if (
      splitValue?.length === 2 &&
      splitValue[1] &&
      lngRegexp.test(splitValue[0]) &&
      latRegexp.test(splitValue[1]) &&
      setPosition
    ) {
      setPosition?.([splitValue[0], splitValue[1]]);
      onChange?.([splitValue[0], splitValue[1]]);
      return;
    }
    if (!autocomplete) return;

    autocomplete.search(value, (status: string, results: any) => {
      if (status === 'complete') {
        const tips = results.tips
          .filter((item: any) => item.id)
          .map(renderItem);
        setOptions(tips);
      }
    });
  };

  const renderItem = (item: any) => {
    return {
      ...item,
      value: item.name,
      key: uniqueId('address_'),
      label: (
        <div>
          {item.name}
          <span style={{ paddingLeft: 4, color: 'rgba(0, 0, 0, 0.45)' }}>
            {item.district}
          </span>
        </div>
      ),
    };
  };

  return (
    <span className={styles.searchAddress}>
      <AutoComplete
        onSelect={handleSelect}
        onSearch={handleSearch}
        style={{ width: 200 }}
        options={options}
      >
        <Input.Search placeholder="请输入地址或经纬度" />
      </AutoComplete>
    </span>
  );
};

export default SearchAddress;
