import { useEffect, useState } from 'react';
import { Select, Spin } from 'antd';
import { fetchJSON } from '@/utils/request';
import { HT_HOST } from '@/config';
import { useTranslation } from 'react-i18next';
import { groupBy } from '@/utils/commons';

// 产品列表
export const fetchAgencyProductsList = async (params) => {
  const map = { title: 'label', id: 'value' };
  const { errcode, result } = await fetchJSON(`${HT_HOST}/Service_BaseInfoWeb/travel_agency_products`, params);
  const byTypes = errcode !== 0 ? {} : (groupBy(result.products, (row) => row.info.product_type_name));
  // console.log(byTypes)
  return Object.keys(byTypes).map((type_name) => ({ lable: type_name, title: type_name, key: type_name, options: byTypes[type_name].map(row => ({...row, label: `${row.info.code} : ${row.info.title}`, value: row.info.id})) }));
};

const ProductsSelector = ({ params, ...props }) => {
  const { t } = useTranslation();
  const [fetching, setFetching] = useState(false);
  const [options, setOptions] = useState([]);

  const fetchAction = async () => {
    setOptions([]);
    setFetching(true);
    const data = await fetchAgencyProductsList(params);
    // console.log(data)
    setOptions(data);
    setFetching(false);
    return data;
  };
  useEffect(() => {
    fetchAction();

    return () => {};
  }, []);

  return (
    <>
      <Select
        placeholder={t('products:ProductName')}
        labelInValue
        // filterOption={false}
        showSearch
        allowClear
        maxTagCount={0}
        dropdownStyle={{ width: '20rem' }}
        {...props}
        // onSearch={debounceFetcher}
        notFoundContent={fetching ? <Spin size='small' /> : null}
        optionFilterProp='label'
        options={options}>
      </Select>
    </>
  );
};
export default ProductsSelector;
