import type { FlashSaleCardViewModel } from '#/views/marketing/flash-sale/types';

/**
 * 文件职责：限时折扣卡片行操作。
 */
import { message, Modal } from 'ant-design-vue';

import {
  changeMarketingFlashSaleStatusApi,
  deleteMarketingFlashSaleApi,
} from '#/api/marketing';

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

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

    const nextStatus = item.status === 'completed' ? 'active' : 'completed';
    const isEnabling = nextStatus === 'active';
    const feedbackKey = `flash-sale-status-${item.id}`;

    Modal.confirm({
      title: isEnabling
        ? `确认启用活动「${item.name}」吗？`
        : `确认停用活动「${item.name}」吗？`,
      content: isEnabling
        ? '启用后活动将恢复为进行中状态。'
        : '停用后活动将结束，可后续再次启用。',
      okText: isEnabling ? '确认启用' : '确认停用',
      cancelText: '取消',
      async onOk() {
        try {
          message.loading({
            key: feedbackKey,
            duration: 0,
            content: isEnabling ? '正在启用活动...' : '正在停用活动...',
          });
          await changeMarketingFlashSaleStatusApi({
            storeId: operationStoreId,
            activityId: item.id,
            status: nextStatus,
          });
          message.success({
            key: feedbackKey,
            content: isEnabling ? '活动已启用' : '活动已停用',
          });
          await options.loadActivities();
        } catch (error) {
          console.error(error);
          message.error({
            key: feedbackKey,
            content: isEnabling
              ? '启用失败，请稍后重试'
              : '停用失败，请稍后重试',
          });
        }
      },
    });
  }

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

    Modal.confirm({
      title: `确认删除活动「${item.name}」吗？`,
      okText: '确认删除',
      cancelText: '取消',
      async onOk() {
        try {
          await deleteMarketingFlashSaleApi({
            storeId: operationStoreId,
            activityId: item.id,
          });
          message.success('活动已删除');
          await options.loadActivities();
        } catch (error) {
          console.error(error);
          message.error('删除失败，请稍后重试');
        }
      },
    });
  }

  return {
    removeActivity,
    toggleActivityStatus,
  };
}
