import type { FormSchema } from '@/components/core/schema-form/';

import Api from '@/api';
import { debounce } from 'lodash-es';
export const exportSchemas: FormSchema<API.MaterialsInventoryExportParams>[] = [
  {
    label: '时间',
    field: 'time',
    component: 'MonthPicker',
    required: true,
    colProps: {
      span: 12,
    },
  },
  {
    field: 'projectId',
    component: 'Select',
    label: '项目',
    colProps: {
      span: 12,
    },
    helpMessage: '如果不选项目，则导出所选月份所有项目，每个项目一个wooksheet',
    componentProps: ({ formInstance, schema, formModel }) => ({
      showSearch: true,
      filterOption: false,
      fieldNames: {
        label: 'label',
        value: 'value',
      },
      getPopupContainer: () => document.body,
      defaultActiveFirstOption: true,
      onClear: async () => {
        const newSchema = {
          field: schema.field,
          componentProps: {
            options: [] as LabelValueOptions,
          },
        };
        const options = await getProjectOptions().finally(() => (schema.loading = false));
        newSchema.componentProps.options = options;
        formInstance?.updateSchema([newSchema]);
      },
      request: () => {
        return getProjectOptions();
      },
      onSearch: debounce(async (keyword) => {
        schema.loading = true;
        const newSchema = {
          field: schema.field,
          componentProps: {
            options: [] as LabelValueOptions,
          },
        };
        formInstance?.updateSchema([newSchema]);
        const options = await getProjectOptions(keyword).finally(() => (schema.loading = false));
        newSchema.componentProps.options = options;
        formInstance?.updateSchema([newSchema]);
      }, 500),
    }),
  },
];

const getProjectOptions = async (keyword?: string): Promise<LabelValueOptions> => {
  const { items: result } = await Api.project.projectList({ pageSize: 100, name: keyword });
  return (
    result?.map((item) => ({
      label: `${item.name}`,
      value: item.id,
    })) || []
  );
};
