import type { VbenFormProps } from '#/adapter/form';

import dayjs from 'dayjs';

import { CHANGE_TYPE_OPTIONS, USER_TYPE_OPTIONS } from './constants';

/**
 * 仓库修改记录搜索表单
 */
export const formOptions: VbenFormProps = {
  collapsed: false,
  schema: [
    {
      component: 'VbenInput',
      componentProps: {
        placeholder: '药名 / 编码 / 操作人 / 批次号',
        allowClear: true,
      },
      fieldName: 'keyword',
      label: '关键词',
    },
    {
      component: 'Select',
      componentProps: {
        allowClear: true,
        options: [...CHANGE_TYPE_OPTIONS],
        placeholder: '全部',
      },
      fieldName: 'change_type',
      label: '变更类型',
    },
    {
      component: 'Select',
      componentProps: {
        allowClear: true,
        options: [...USER_TYPE_OPTIONS],
        placeholder: '全部',
      },
      fieldName: 'user_type',
      label: '用户类型',
    },
    {
      component: 'RangePicker',
      componentProps: {
        format: 'YYYY-MM-DD',
        valueFormat: 'YYYY-MM-DD',
      },
      fieldName: 'search_time',
      label: '时间范围',
    },
  ],
  showCollapseButton: true,
  submitButtonOptions: {
    content: '查询',
  },
  submitOnChange: false,
  submitOnEnter: true,
};

/**
 * search_time → start_time/end_time 时间戳
 */
export function normalizeChangeLogFilters(formValues: Record<string, any> = {}) {
  const params: Record<string, any> = { ...formValues };
  const range = params.search_time;
  delete params.search_time;
  if (Array.isArray(range) && range.length === 2 && range[0] && range[1]) {
    params.start_time = dayjs(range[0]).startOf('day').unix();
    params.end_time = dayjs(range[1]).endOf('day').unix();
  }
  Object.keys(params).forEach((k) => {
    if (params[k] === '' || params[k] === undefined || params[k] === null) {
      delete params[k];
    }
  });
  return params;
}
