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

import Api from '@/api';
import { debounce } from 'lodash-es';
import { MaterialsInOutEnum } from '@/enums/materialsInventoryEnum';
export const formSchemas = (isEdit?: boolean): FormSchema<API.MaterialsInOutEntity>[] => [
  {
    field: 'inOrOut',
    component: 'Select',
    label: '出入库',
    rules: [{ required: true, type: 'number' }],
    defaultValue: MaterialsInOutEnum.In,
    colProps: {
      span: 8,
    },
    componentProps: {
      allowClear: false,
      disabled: isEdit,
      options: [
        { label: '出库', value: MaterialsInOutEnum.Out },
        { label: '入库', value: MaterialsInOutEnum.In },
      ],
    },
  },
  {
    field: 'inventoryNumber',
    component: 'Select',
    label: '库存编号',
    vIf: ({ formModel }) => formModel.inOrOut === MaterialsInOutEnum.Out,
    colProps: {
      span: 16,
    },
    helpMessage: '出库必须选择入库时的编号',
    componentProps: ({ formInstance, schema, formModel }) => ({
      showSearch: true,
      filterOption: false,
      disabled: isEdit,
      fieldNames: {
        label: 'label',
        value: 'value',
      },
      options: [],
      getPopupContainer: () => document.body,
      defaultActiveFirstOption: true,
      onClear: async () => {
        const newSchema = {
          field: schema.field,
          componentProps: {
            options: [] as LabelValueOptions,
          },
        };
        const options = await getInventoryNumberOptions().finally(() => (schema.loading = false));
        newSchema.componentProps.options = options;
        formInstance?.updateSchema([newSchema]);
      },
      request: {
        watchFields: ['inOrOut'],
        options: {
          immediate: true,
        },
        callback: async ({ formModel }) => {
          if (formModel.inOrOut === MaterialsInOutEnum.Out) {
            return getInventoryNumberOptions();
          } else {
            return Promise.resolve([] as LabelValueOptions);
          }
        },
      },
      onSearch: debounce(async (keyword) => {
        schema.loading = true;
        const newSchema = {
          field: schema.field,
          componentProps: {
            options: [] as LabelValueOptions,
          },
        };
        formInstance?.updateSchema([newSchema]);
        const options = await getInventoryNumberOptions(keyword).finally(
          () => (schema.loading = false),
        );
        newSchema.componentProps.options = options;
        formInstance?.updateSchema([newSchema]);
      }, 500),
    }),
  },

  {
    field: 'productId',
    component: 'Select',
    vIf: ({ formModel }) => formModel.inOrOut === MaterialsInOutEnum.In || isEdit,
    label: '产品',
    colProps: {
      span: 16,
    },
    helpMessage: '如未找到对应产品,请先去产品管理添加产品。',
    rules: [{ required: true, type: 'number' }],
    componentProps: ({ formInstance, schema, formModel }) => ({
      showSearch: true,
      filterOption: false,
      disabled: isEdit,
      fieldNames: {
        label: 'label',
        value: 'value',
      },
      options: [],
      getPopupContainer: () => document.body,
      defaultActiveFirstOption: true,
      onClear: async () => {
        const newSchema = {
          field: schema.field,
          componentProps: {
            options: [] as LabelValueOptions,
          },
        };
        const options = await getProductOptions().finally(() => (schema.loading = false));
        newSchema.componentProps.options = options;
        formInstance?.updateSchema([newSchema]);
      },
      request: () => {
        return getProductOptions();
      },
      onSearch: debounce(async (keyword) => {
        schema.loading = true;
        const newSchema = {
          field: schema.field,
          componentProps: {
            options: [] as LabelValueOptions,
          },
        };
        formInstance?.updateSchema([newSchema]);
        const options = await getProductOptions(keyword).finally(() => (schema.loading = false));
        newSchema.componentProps.options = options;
        formInstance?.updateSchema([newSchema]);
      }, 500),
    }),
  },
  {
    field: 'projectId',
    component: 'Select',
    label: '项目',
    colProps: {
      span: 12,
    },
    helpMessage: '如未找到对应项目,请先去项目管理添加项目。',
    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),
    }),
  },
  {
    label: '时间',
    field: 'time',
    component: 'DatePicker',
    colProps: {
      span: 12,
    },
  },
  {
    label: '数量',
    field: 'quantity',
    component: 'InputNumber',
    colProps: {
      span: 12,
    },
  },
  {
    label: '单价',
    field: 'unitPrice',
    component: 'InputNumber',
    colProps: {
      span: 12,
    },
  },
  {
    label: '金额',
    field: 'amount',
    component: 'InputNumber',
    colProps: {
      span: 12,
    },
  },
  {
    label: '经办人',
    field: 'agent',
    component: 'Input',
    colProps: {
      span: 12,
    },
  },
  {
    label: '领料单号',
    field: 'issuanceNumber',
    component: 'Input',
    vIf:isEdit,
    colProps: {
      span: 12,
    },
  },

  {
    label: '备注',
    field: 'remark',
    component: 'InputTextArea',
  },
];

export 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,
    })) || []
  );
};

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

const getInventoryNumberOptions = async (inventoryNumber?: string): Promise<LabelValueOptions> => {
  const { items: result } = await Api.materialsInOut.materialsInOutList({
    inventoryNumber,
    isCreateOut: true,
    pageSize: 100,
  });
  return (
    result?.map((item) => ({
      label: item.inventoryNumber,
      value: item.inventoryNumber,
    })) || []
  );
};