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

import dayjs from 'dayjs';

import { SCHEDULE_ACTION_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: [...SCHEDULE_ACTION_OPTIONS],
        placeholder: '全部',
      },
      fieldName: 'action',
      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 normalizeScheduleLogFilters(
  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;
}
