import type { OrderAllFilterState } from '../../types';

import { message } from 'ant-design-vue';

import { exportOrderAllCsvApi } from '#/api/order';

import { downloadBase64File, isDateRangeInvalid } from './helpers';

interface ExportActionOptions {
  filters: OrderAllFilterState;
  isExporting: { value: boolean };
  selectedStoreId: { value: string };
}

/**
 * 文件职责：全部订单导出动作。
 */
export function createExportActions(options: ExportActionOptions) {
  async function handleExport() {
    if (!options.selectedStoreId.value) {
      return;
    }

    if (isDateRangeInvalid(options.filters)) {
      message.warning('开始日期不能晚于结束日期');
      return;
    }

    options.isExporting.value = true;
    try {
      const result = await exportOrderAllCsvApi({
        storeId: options.selectedStoreId.value,
        startDate: options.filters.startDate || undefined,
        endDate: options.filters.endDate || undefined,
        status:
          options.filters.status === 'all' ? undefined : options.filters.status,
        channel:
          options.filters.channel === 'all'
            ? undefined
            : options.filters.channel,
        paymentMethod:
          options.filters.paymentMethod === 'all'
            ? undefined
            : options.filters.paymentMethod,
        keyword: options.filters.keyword.trim() || undefined,
      });

      downloadBase64File(result.fileName, result.fileContentBase64);
      message.success(`导出成功，共 ${result.totalCount} 条记录`);
    } finally {
      options.isExporting.value = false;
    }
  }

  return {
    handleExport,
  };
}
