import type { Ref } from 'vue';

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

import { exportCustomerAnalysisCsvApi } from '#/api/customer';

import { downloadBase64File } from './helpers';

interface ExportActionOptions {
  canExport: Ref<boolean>;
  isExporting: Ref<boolean>;
  period: Ref<'7d' | '30d' | '90d' | '365d'>;
  selectedStoreId: Ref<string>;
}

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

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

    options.isExporting.value = true;
    try {
      const result = await exportCustomerAnalysisCsvApi({
        storeId: options.selectedStoreId.value,
        period: options.period.value,
      });
      downloadBase64File(result.fileName, result.fileContentBase64);
      message.success('客户分析报表导出成功');
    } finally {
      options.isExporting.value = false;
    }
  }

  return {
    handleExport,
  };
}
