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

/**
 * 文件职责：交易流水导出弹窗与导出动作。
 */
import { message } from 'ant-design-vue';

import { exportFinanceTransactionCsvApi } from '#/api/finance';

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

interface ExportActionOptions {
  canExport: { value: boolean };
  filters: FinanceTransactionFilterState;
  isExportModalOpen: { value: boolean };
  isExporting: { value: boolean };
  selectedStoreId: { value: string };
}

/** 创建导出动作。 */
export function createExportActions(options: ExportActionOptions) {
  function setExportModalOpen(value: boolean) {
    options.isExportModalOpen.value = value;
  }

  function openExportModal() {
    if (!options.canExport.value || !options.selectedStoreId.value) {
      return;
    }
    options.isExportModalOpen.value = true;
  }

  async function handleConfirmExport() {
    if (!options.canExport.value || !options.selectedStoreId.value) {
      return;
    }

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

    options.isExporting.value = true;
    try {
      const payload = buildFilterQueryPayload(
        options.selectedStoreId.value,
        options.filters,
      );
      const result = await exportFinanceTransactionCsvApi(payload);
      downloadBase64File(result.fileName, result.fileContentBase64);
      message.success(`导出成功，共 ${result.totalCount} 条记录`);
      setExportModalOpen(false);
    } finally {
      options.isExporting.value = false;
    }
  }

  return {
    handleConfirmExport,
    openExportModal,
    setExportModalOpen,
  };
}
