import type { Ref } from 'vue';

import type { StoredCardPlanCardViewModel } from '#/views/member/stored-card/types';

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

import {
  changeMemberStoredCardPlanStatusApi,
  deleteMemberStoredCardPlanApi,
} from '#/api/member/stored-card';

interface CreatePlanActionsOptions {
  canManage: Ref<boolean>;
  loadPlanList: () => Promise<void>;
  loadRecordList: () => Promise<void>;
  selectedStoreId: Ref<string>;
}

export function createPlanActions(options: CreatePlanActionsOptions) {
  async function toggleStatus(row: StoredCardPlanCardViewModel) {
    if (!options.canManage.value) {
      return;
    }

    if (!options.selectedStoreId.value) {
      message.warning('请先选择门店');
      return;
    }

    const targetStatus = row.status === 'enabled' ? 'disabled' : 'enabled';
    try {
      await changeMemberStoredCardPlanStatusApi({
        storeId: options.selectedStoreId.value,
        planId: row.planId,
        status: targetStatus,
      });
      message.success(targetStatus === 'enabled' ? '已启用方案' : '已停用方案');
      await options.loadPlanList();
    } catch (error) {
      console.error(error);
      message.error('状态更新失败');
    }
  }

  function removePlan(row: StoredCardPlanCardViewModel) {
    if (!options.canManage.value) {
      return;
    }

    if (!options.selectedStoreId.value) {
      message.warning('请先选择门店');
      return;
    }

    Modal.confirm({
      title: '删除充值方案',
      content: '删除后不可恢复，确认继续吗？',
      okText: '删除',
      okType: 'danger',
      cancelText: '取消',
      async onOk() {
        try {
          await deleteMemberStoredCardPlanApi({
            storeId: options.selectedStoreId.value,
            planId: row.planId,
          });
          message.success('删除成功');
          await Promise.all([options.loadPlanList(), options.loadRecordList()]);
        } catch (error) {
          console.error(error);
          message.error('删除失败');
        }
      },
    });
  }

  return {
    removePlan,
    toggleStatus,
  };
}
