/**
 * 文件职责：商品批量动作。
 * 1. 处理批量上架、下架、沽清、删除。
 * 2. 对批量动作做参数校验、确认与结果提示。
 */
import type { Ref } from 'vue';

import type { ProductBatchAction } from '#/views/product/list/types';

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

import { batchProductActionApi } from '#/api/product';

interface CreateBatchActionsOptions {
  clearSelection: () => void;
  reloadCurrentStoreData: () => Promise<void>;
  selectedProductIds: Ref<string[]>;
  selectedStoreId: Ref<string>;
}

export function createBatchActions(options: CreateBatchActionsOptions) {
  /** 执行批量操作。 */
  async function handleBatchAction(action: ProductBatchAction) {
    if (!options.selectedStoreId.value) return;
    if (options.selectedProductIds.value.length === 0) {
      message.warning('请先勾选商品');
      return;
    }

    if (action === 'batch_delete') {
      Modal.confirm({
        title: '确认批量删除吗？',
        content: `将删除 ${options.selectedProductIds.value.length} 个商品`,
        okText: '确认删除',
        cancelText: '取消',
        async onOk() {
          await submitBatchAction('batch_delete');
        },
      });
      return;
    }

    await submitBatchAction(action);
  }

  /** 提交批量动作并刷新页面。 */
  async function submitBatchAction(action: ProductBatchAction) {
    if (!options.selectedStoreId.value) return;
    const payload = {
      action,
      storeId: options.selectedStoreId.value,
      productIds: [...options.selectedProductIds.value],
      remainStock: 0,
      reason: '批量沽清',
      recoverAt: '',
      syncToPlatform: true,
      notifyManager: false,
    };

    try {
      const result = await batchProductActionApi(payload);
      message.success(`已处理 ${result.successCount}/${result.totalCount} 项`);
      options.clearSelection();
      await options.reloadCurrentStoreData();
    } catch (error) {
      console.error(error);
    }
  }

  return {
    handleBatchAction,
  };
}
