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

import dayjs from 'dayjs';

import { AI_GENERATION_SCENE_OPTIONS, AI_GENERATION_STATUS_OPTIONS } from './constants';

/**
 * AI 生成记录搜索表单
 * 平台/模型用下拉（options 在页面 onMounted 注入），时间范围映射为 start_time/end_time
 */
export const formOptions: VbenFormProps = {
  collapsed: false,
  schema: [
    {
      component: 'VbenInput',
      componentProps: {
        placeholder: '名称 / 错误摘要',
        allowClear: true,
      },
      defaultValue: '',
      fieldName: 'keyword',
      label: '关键词',
    },
    {
      component: 'VbenSelect',
      componentProps: {
        placeholder: '状态',
        allowClear: true,
        options: AI_GENERATION_STATUS_OPTIONS,
      },
      defaultValue: undefined,
      fieldName: 'status',
      label: '状态',
    },
    {
      component: 'VbenSelect',
      componentProps: {
        placeholder: '场景',
        allowClear: true,
        options: AI_GENERATION_SCENE_OPTIONS,
      },
      defaultValue: undefined,
      fieldName: 'scene',
      label: '场景',
    },
    {
      component: 'Select',
      componentProps: {
        placeholder: '全部平台',
        allowClear: true,
        showSearch: true,
        optionFilterProp: 'label',
        options: [],
      },
      defaultValue: undefined,
      fieldName: 'platform_id',
      label: '平台',
    },
    {
      component: 'Select',
      componentProps: {
        placeholder: '全部模型',
        allowClear: true,
        showSearch: true,
        optionFilterProp: 'label',
        options: [],
      },
      defaultValue: undefined,
      fieldName: 'model',
      label: '模型',
    },
    {
      component: 'RangePicker',
      componentProps: {
        format: 'YYYY-MM-DD',
        valueFormat: 'YYYY-MM-DD',
      },
      defaultValue: undefined,
      fieldName: 'search_time',
      label: '时间范围',
    },
  ],
  showCollapseButton: true,
  submitButtonOptions: {
    content: '查询',
  },
  submitOnChange: true,
  submitOnEnter: false,
};

/**
 * 将表单值转为接口参数：search_time → start_time/end_time（当天起止秒级时间戳）
 */
export function normalizeAiGenerationFilters(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;
}
