import type { FullReductionCardViewModel } from '#/views/marketing/full-reduction/types';

/**
 * 文件职责：满减活动卡片行操作。
 * 1. 封装停用（完成）与删除动作。
 * 2. 统一确认弹窗与反馈提示。
 */
import { message, Modal } from 'ant-design-vue';

import {
  changeMarketingFullReductionStatusApi,
  deleteMarketingFullReductionApi,
} from '#/api/marketing';

interface CreateCardActionsOptions {
  loadActivities: () => Promise<void>;
  resolveOperationStoreId: (preferredStoreIds?: string[]) => string;
}

export function createCardActions(options: CreateCardActionsOptions) {
  function disableActivity(item: FullReductionCardViewModel) {
    const operationStoreId = options.resolveOperationStoreId(item.storeIds);
    if (!operationStoreId) return;

    Modal.confirm({
      title: `确认停用活动「${item.name}」吗？`,
      content: '停用后活动将直接结束，且不可恢复。',
      okText: '确认停用',
      cancelText: '取消',
      async onOk() {
        const feedbackKey = `full-reduction-status-${item.id}`;
        try {
          message.loading({
            key: feedbackKey,
            duration: 0,
            content: '正在停用活动...',
          });
          await changeMarketingFullReductionStatusApi({
            storeId: operationStoreId,
            activityId: item.id,
            status: 'completed',
          });
          message.success({
            key: feedbackKey,
            content: '活动已停用',
          });
          await options.loadActivities();
        } catch (error) {
          console.error(error);
          message.error({
            key: feedbackKey,
            content: '停用失败，请稍后重试',
          });
        }
      },
    });
  }

  function removeActivity(item: FullReductionCardViewModel) {
    const operationStoreId = options.resolveOperationStoreId(item.storeIds);
    if (!operationStoreId) return;

    Modal.confirm({
      title: `确认删除活动「${item.name}」吗？`,
      okText: '确认删除',
      cancelText: '取消',
      async onOk() {
        await deleteMarketingFullReductionApi({
          storeId: operationStoreId,
          activityId: item.id,
        });
        message.success('活动已删除');
        await options.loadActivities();
      },
    });
  }

  return {
    disableActivity,
    removeActivity,
  };
}
