import { productcontrollerGetattributelist } from '@/servers/api/product';
import { ProFormSelect } from '@ant-design/pro-components';
import { useState } from 'react';

interface AttributeFormItemProps {
  dictName: string;
  name: string;
  label: string;
  isTag?: boolean;
}

const fetchDictOptions = async (dictName: string, keyword?: string) => {
  const { data } = await productcontrollerGetattributelist({
    dictName,
    name: keyword,
  });
  return (data?.items || []).map((item: any) => ({
    label: item.name,
    value: item.name,
    id: item.id,
    item,
  }));
};

const AttributeFormItem: React.FC<AttributeFormItemProps> = ({
  dictName,
  name,
  label,
  isTag = false,
}) => {
  const [options, setOptions] = useState<{ label: string; value: string }[]>(
    [],
  );

  if (isTag) {
    return (
      <ProFormSelect
        name={name}
        width="lg"
        label={label}
        placeholder={`请输入或选择${label}`}
        fieldProps={{
          mode: 'tags',
          showSearch: true,
          filterOption: false,
          onSearch: async (val) => {
            const opts = await fetchDictOptions(dictName, val);
            setOptions(opts);
          },
        }}
        request={async () => {
          const opts = await fetchDictOptions(dictName);
          setOptions(opts);
          return opts;
        }}
        options={options}
      />
    );
  }

  return (
    <ProFormSelect
      name={name}
      width="lg"
      label={label}
      placeholder={`请选择${label}`}
      request={() => fetchDictOptions(dictName)}
    />
  );
};

export default AttributeFormItem;
