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

/**
 * 文件职责：到账查询导出动作。
 */
import { message } from 'ant-design-vue';

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

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

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

/** 创建导出动作。 */
export function createExportActions(options: ExportActionOptions) {
  async function handleExport() {
    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 exportFinanceSettlementCsvApi(payload);
      downloadBase64File(result.fileName, result.fileContentBase64);
      message.success(`导出成功，共 ${result.totalCount} 条记录`);
    } finally {
      options.isExporting.value = false;
    }
  }

  return {
    handleExport,
  };
}
