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

import dayjs from 'dayjs';

import { getStoreOption } from '#/views/system/store/api';

import { SHADOW_PROVIDER_OPTIONS, SHADOW_SCENE_OPTIONS } from './constants';

/**
 * 影子流量对比搜索表单
 * 诊所用 ApiSelect（复用 getStoreOption），时间范围映射为 date_start/date_end 时间戳
 */
export const formOptions: VbenFormProps = {
  collapsed: false,
  schema: [
    {
      component: 'ApiSelect',
      componentProps: {
        allowClear: true,
        showSearch: true,
        filterOption: true,
        afterFetch: (data: { id: number; name: string }[]) => {
          return (data || []).map((item: any) => ({
            label: `${item.name}【${item.id}】`,
            value: item.id,
          }));
        },
        api: getStoreOption,
        placeholder: '请选择诊所',
      },
      defaultValue: undefined,
      fieldName: 'store_id',
      label: '诊所',
    },
    {
      component: 'VbenSelect',
      componentProps: {
        placeholder: '全部场景',
        allowClear: true,
        options: SHADOW_SCENE_OPTIONS,
      },
      defaultValue: undefined,
      fieldName: 'scene',
      label: '场景',
    },
    {
      component: 'VbenSelect',
      componentProps: {
        placeholder: '全部',
        allowClear: true,
        options: SHADOW_PROVIDER_OPTIONS,
      },
      defaultValue: undefined,
      fieldName: 'primary_provider',
      label: '主链路',
    },
    {
      component: 'VbenSelect',
      componentProps: {
        placeholder: '全部',
        allowClear: true,
        options: SHADOW_PROVIDER_OPTIONS,
      },
      defaultValue: undefined,
      fieldName: 'shadow_provider',
      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 → date_start/date_end（当天起止秒级时间戳）
 * 后端 AiShadowCompareService::listCompare 按 created_at 时间戳过滤
 */
export function normalizeShadowFilters(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.date_start = dayjs(range[0]).startOf('day').unix();
    params.date_end = 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;
}
