import {Select as SelectOri} from 'antd';
import css from './index.module.css';
import {FC} from 'react';
import {DictionaryParamsType} from '@models';
import {useDictionaryKeyOptions, useSelectFilterOptions} from '@hooks';

type Props = {
  label: string;
  value: string;
  name: string;
  selectKey: DictionaryParamsType;
  onChange?: (value: string) => void;
  placeholder?: string;
};

const DictionarySelect: FC<Props> = function ({
  label,
  value,
  onChange,
  placeholder,
  name,
  selectKey,
}) {
  const {options, isFetching} = useDictionaryKeyOptions(
    selectKey,
    function ({code, tldId, name}) {
      if (
        selectKey === '供应商/客户' ||
        selectKey === '公司' ||
        selectKey === '部门字典'
      )
        return code;
      if (selectKey === '物料类型') return name;

      return tldId;
    },
  );
  const [filterOptions, {onSelectSearch, clearSearch}] =
    useSelectFilterOptions(options);

  return (
    <div className={css.field}>
      <label htmlFor={`filter_${name}`} className={css.fieldLabel}>
        {label}
      </label>
      <div className={css.fieldWrapper}>
        <SelectOri
          showSearch
          allowClear
          onClear={() => {
            onChange?.('');
            clearSearch();
          }}
          loading={isFetching}
          filterOption={false}
          className='width-full'
          id={`filter_${name}`}
          data-testid={`filter_${name}`}
          placeholder={placeholder ?? '请输入'}
          value={value?.length ? value : void 0}
          options={filterOptions}
          onChange={onChange}
          getPopupContainer={(node: HTMLElement) =>
            node.parentNode as HTMLElement
          }
          onSearch={onSelectSearch}
        />
      </div>
    </div>
  );
};

export default DictionarySelect;
