import { debounce } from 'lodash';
import { memo, useEffect, useState } from 'react';
import { fetchDepartName } from '../server';
import { Select } from 'antd';
import type { SelectProps } from 'antd';
import { useIntl, useRequest } from 'umi';
import _ from 'lodash';
type valueProps = {
  value: number;
  label: string;
};
type AnyKeyObject<T> = {
  [key: string]: T;
};
interface TypeDepartSelect extends SelectProps {
  value?: valueProps[] | number[];
  onChange?: (value: valueProps[] | number[]) => void;
  /**
   * @description 可以选择单选还是多选，multiple是多选。
   */
  mode?: 'multiple' | 'tags' | undefined;
  placeholder?: string;
}
const DepartSelect = ({
  placeholder,
  mode = 'multiple',
  onChange,
  value,
  ...others
}: TypeDepartSelect) => {
  const { formatMessage } = useIntl();
  const [selectUserMap, setSelectUserMap] = useState<AnyKeyObject<valueProps>>({});
  const { run } = useRequest(
    (ids) => ({
      url: '/goapi/depart/getByIds',
      method: 'POST',
      data: {
        ids,
      },
    }),
    {
      manual: true,
    },
  );
  const debounceDepart = debounce(async (val) => {
    if (!val) {
      return;
    }
    const res = await fetchDepartName(val);
    const newUserMap = {};
    res?.data?.map((item) => {
      newUserMap[item.id] = {
        value: item?.id,
        label: item?.departPath?.reverse().join('-'),
      };
      return newUserMap[item.id];
    });
    setSelectUserMap((values) => ({ ...values, ...newUserMap }));
  }, 500);
  useEffect(() => {
    let isHaveName = true;
    value?.forEach((item) => {
      if (!selectUserMap?.[item]) {
        isHaveName = false;
      }
    });
    if (!isHaveName) {
      run(value?.map((item) => item - 0)).then((d) => {
        const newmap = {};
        d?.forEach((item) => {
          newmap[item.id] = {
            value: item?.id,
            label: item?.departPath?.reverse().join('-'),
          };
        });
        setSelectUserMap((values) => ({ ...values, ...newmap }));
      });
    }
  }, []);
  return (
    <Select
      mode={mode}
      filterOption={false}
      showSearch={true}
      style={{ width: '100%', minWidth: 300 }}
      options={_.values(selectUserMap)}
      placeholder={placeholder || formatMessage({ id: 'component.UserSelect.placeholder' })}
      allowClear={true}
      onSearch={(val) => debounceDepart(val.trim())}
      value={mode ? value?.map((item) => item?.value - 0 || item - 0) : value}
      onChange={(val) => onChange?.(val)}
      {...others}
    />
  );
};
export default memo(DepartSelect);
