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

import dayjs from 'dayjs';

import {
  QUEUE_JOB_DELAY_TYPE_OPTIONS,
  QUEUE_JOB_STATUS_OPTIONS,
} from './constants';

/**
 * 队列任务搜索表单
 * 业务队列额外提供「普通/延迟」筛选
 */
export function createFormOptions(options?: {
  showDelayFilter?: boolean;
}): VbenFormProps {
  const schema: VbenFormProps['schema'] = [
    {
      component: 'VbenInput',
      componentProps: {
        placeholder: '标题 / 简介 / 错误 / 任务类',
        allowClear: true,
      },
      fieldName: 'keyword',
      label: '关键词',
    },
    {
      component: 'Select',
      componentProps: {
        allowClear: true,
        options: [...QUEUE_JOB_STATUS_OPTIONS],
        placeholder: '全部',
      },
      fieldName: 'status',
      label: '状态',
    },
    {
      component: 'Select',
      componentProps: {
        allowClear: true,
        options: [],
        placeholder: '全部',
        showSearch: true,
        optionFilterProp: 'label',
      },
      fieldName: 'job_name',
      label: '任务类型',
    },
  ];
  // 业务队列：普通 / 延迟 筛选
  if (options?.showDelayFilter) {
    schema.push({
      component: 'Select',
      componentProps: {
        allowClear: true,
        options: [...QUEUE_JOB_DELAY_TYPE_OPTIONS],
        placeholder: '全部',
      },
      fieldName: 'delay_type',
      label: '队列类型',
    });
  }
  schema.push({
    component: 'RangePicker',
    componentProps: {
      format: 'YYYY-MM-DD',
      valueFormat: 'YYYY-MM-DD',
    },
    // 默认近 7 天
    defaultValue: [
      dayjs().subtract(6, 'day').format('YYYY-MM-DD'),
      dayjs().format('YYYY-MM-DD'),
    ],
    fieldName: 'search_time',
    label: '时间范围',
  });
  return {
    collapsed: false,
    schema,
    showCollapseButton: true,
    submitButtonOptions: {
      content: '查询',
    },
    submitOnChange: false,
    submitOnEnter: true,
  };
}

/**
 * search_time → start_time/end_time 时间戳
 */
export function normalizeQueueJobFilters(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;
}
