import { FC, useEffect, useRef, useState } from 'react';
import { Select, Input, Modal } from 'antd';
import MapComponent from '~/components/select-map/map';
import { debounce } from 'lodash';

// 传参类型
interface propType {
  title?: string;
  open: boolean;
  closed: any;
  submit: any;
}

const SelectMapModal: FC<propType> = (props) => {
  SelectMapModal.defaultProps = {
    title: '选择地点',
  };
  //筛选值
  const [searchKey, setSearchKey] = useState<string>('');
  // 参数
  const { title, open, closed, submit } = props;
  // 子组件事件
  const childRef = useRef<{
    onSearch: (e: string) => void;
    addMarker: (e: { lat: number; lng: number }) => void;
    clearMarker: () => void;
  }>(null);
  // 位置信息
  const [position, setPosition] = useState<{
    lat: number;
    lon: number;
    address: string;
    adCode: number;
  }>();
  // 搜索地点
  const [addressList, setAddressList] =
    useState<{ label: string; value: number; data: any; searchKey: string }[]>();
  // 取消事件
  const handleCancel = () => {
    setPosition(undefined);
    setAddressList([]);
    closed();
  };
  // 确认事件
  const handleOk = () => {
    submit(position);
  };
  // 搜索地点
  const handleSearch = (e: string) => {
    setSearchKey(e || '');
    if (e) {
      childRef.current?.onSearch(e);
    } else {
      setAddressList([]);
    }
  };
  // 防抖
  const handleSearchDebounced = debounce(handleSearch, 500);
  // 选择了地址
  const handleSearchAddress = (e: number) => {
    if (!isNaN(e)) {
      // eslint-disable-next-line no-unsafe-optional-chaining
      const { lat, lng } = addressList?.[e].data.location;
      childRef.current?.addMarker({ lat, lng });
      setPosition({
        lat: lat,
        lon: lng,
        address: `${addressList?.[e].data.name}`,
        adCode: addressList?.[e].data.adcode,
      });
    } else {
      childRef.current?.clearMarker();
      setPosition(undefined);
    }
  };
  // componentDidMount
  useEffect(() => {
    if (!open) return;
    return () => {
      setPosition(undefined);
    };
  }, [open]);
  return (
    <Modal open={open} title={title} onCancel={handleCancel} onOk={handleOk} destroyOnClose>
      <div
        style={{
          display: 'flex',
          justifyContent: 'flex-start',
          alignItems: 'center',
          marginBottom: '10px',
        }}
      >
        <div style={{ width: '60px' }}>搜索地点：</div>
        <Select
          showSearch
          placeholder={'请输入地点'}
          optionFilterProp='children'
          style={{ width: '80%', marginRight: '20px' }}
          allowClear
          onSearch={handleSearchDebounced}
          filterOption={(input, option) =>
            (option?.searchKey ?? '').toLowerCase().includes(input.toLowerCase())
          }
          options={addressList}
          onChange={handleSearchAddress}
        />
      </div>
      <MapComponent
        // eslint-disable-next-line @typescript-eslint/ban-ts-comment
        // @ts-ignore
        ref={childRef}
        onSelectAddress={(e) => {
          setPosition({
            lat: e.lat,
            lon: e.lng,
            address: e.formattedAddress,
            adCode: Number(e.adcode),
          });
        }}
        onSearchAddress={(e) => {
          console.log('筛选e--->', e);
          setAddressList(e.map((i, j) => ({ label: i.name, value: j, data: i, searchKey })));
        }}
      ></MapComponent>
      <div
        style={{
          display: 'flex',
          justifyContent: 'flex-start',
          alignItems: 'center',
          marginTop: '10px',
          marginBottom: '20px',
        }}
      >
        <div style={{ width: '60px' }}>选择地点：</div>
        <Input
          value={position?.address}
          placeholder={'请选择地点'}
          maxLength={25}
          allowClear
          style={{ width: '80%', marginRight: '20px' }}
          disabled
        />
      </div>
    </Modal>
  );
};

export default SelectMapModal;
