import type { Ref } from 'vue';

import type { ProductScheduleCardViewModel } from '#/views/product/schedule/types';

/**
 * 文件职责：时段规则卡片动作。
 */
import { message, Modal } from 'ant-design-vue';

import {
  changeProductScheduleStatusApi,
  deleteProductScheduleApi,
} from '#/api/product';

interface CreateRuleActionsOptions {
  loadSchedules: () => Promise<void>;
  selectedStoreId: Ref<string>;
}

export function createRuleActions(options: CreateRuleActionsOptions) {
  async function setRuleStatus(
    item: ProductScheduleCardViewModel,
    status: ProductScheduleCardViewModel['status'],
  ) {
    if (!options.selectedStoreId.value) return;

    try {
      const result = await changeProductScheduleStatusApi({
        storeId: options.selectedStoreId.value,
        scheduleId: item.id,
        status,
      });
      item.status = result.status;
      item.updatedAt = result.updatedAt;
      message.success(status === 'enabled' ? '已启用规则' : '已停用规则');
    } catch (error) {
      console.error(error);
    }
  }

  async function toggleRuleStatus(item: ProductScheduleCardViewModel) {
    const nextStatus = item.status === 'enabled' ? 'disabled' : 'enabled';
    await setRuleStatus(item, nextStatus);
  }

  function removeRule(item: ProductScheduleCardViewModel) {
    if (!options.selectedStoreId.value) return;

    Modal.confirm({
      title: `确认删除规则「${item.name}」吗？`,
      okText: '删除',
      okButtonProps: { danger: true },
      cancelText: '取消',
      async onOk() {
        await deleteProductScheduleApi({
          storeId: options.selectedStoreId.value,
          scheduleId: item.id,
        });
        message.success('时段规则已删除');
        await options.loadSchedules();
      },
    });
  }

  return {
    removeRule,
    toggleRuleStatus,
  };
}
