import { useAPIClient, useRequest } from '@tachybase/client';
import { ArrayField, useField } from '@tachybase/schema';

export const useChinaRegionDataSource = (options) => {
  const field = useField<ArrayField>();
  const maxLevel = field.componentProps.maxLevel;
  return useRequest(
    {
      resource: 'chinaRegions',
      action: 'list',
      params: {
        sort: 'code',
        paginate: false,
        filter: { level: 1 },
      },
    },
    {
      ...options,
      onSuccess(data) {
        options?.onSuccess({
          data:
            data?.data?.map((item) => {
              if (maxLevel !== 1) {
                item.isLeaf = false;
              }
              return item;
            }) || [],
        });
      },
      manual: true,
    },
  );
};

export const useChinaRegionLoadData = () => {
  const api = useAPIClient();
  const field = useField<ArrayField>();
  const maxLevel = field.componentProps.maxLevel;
  return (selectedOptions, onSuccess?) => {
    const targetOption = selectedOptions[selectedOptions.length - 1];
    if (targetOption?.children?.length > 0) {
      return;
    }
    targetOption.loading = true;
    api
      .resource('chinaRegions')
      .list({
        sort: 'code',
        paginate: false,
        filter: {
          parentCode: targetOption.code,
        },
      })
      .then(({ data }) => {
        if (onSuccess) {
          onSuccess(data);
        } else {
          targetOption.loading = false;
          targetOption.children =
            data?.data?.map((item) => {
              if (maxLevel > item.level) {
                item.isLeaf = false;
              }
              return item;
            }) || [];
        }
        field.dataSource = [...field.dataSource];
      })
      .catch((err) => {
        console.error(err);
      });
  };
};
