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

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

import { exportMemberCsvApi } from '#/api/member';

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

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

/**
 * 文件职责：会员列表导出动作。
 */
export function createExportActions(options: ExportActionOptions) {
  async function handleExport() {
    if (!options.selectedStoreId.value) {
      return;
    }

    if (!options.canManage.value) {
      message.warning('暂无导出权限');
      return;
    }

    options.isExporting.value = true;
    try {
      const result = await exportMemberCsvApi(
        buildFilterPayload(options.selectedStoreId.value, options.filters),
      );

      if (!result.fileContentBase64) {
        message.info('当前筛选条件暂无可导出数据');
        return;
      }

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

  return {
    handleExport,
  };
}
