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

/**
 * 文件职责：经营报表批量导出弹窗与导出动作。
 */
import type { FinanceBusinessReportPeriodType } from '#/api/finance';

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

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

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

interface ExportActionOptions {
  canExport: { value: boolean };
  isBatchExportModalOpen: { value: boolean };
  isBatchExporting: { value: boolean };
  pagination: FinanceBusinessReportPaginationState;
  periodType: { value: FinanceBusinessReportPeriodType };
  selectedStoreId: { value: string };
}

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

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

    options.isBatchExportModalOpen.value = true;
  }

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

    options.isBatchExporting.value = true;
    try {
      const payload = buildReportBatchExportQueryPayload(
        options.selectedStoreId.value,
        options.periodType.value,
        options.pagination.page,
        options.pagination.pageSize,
      );
      const result = await exportFinanceBusinessReportBatchApi(payload);
      downloadBase64File(
        result.fileName,
        result.fileContentBase64,
        'application/zip',
      );
      message.success(`批量导出成功，共 ${result.totalCount} 份报表`);
      setBatchExportModalOpen(false);
    } finally {
      options.isBatchExporting.value = false;
    }
  }

  return {
    handleConfirmBatchExport,
    openBatchExportModal,
    setBatchExportModalOpen,
  };
}
