import type { ComputedRef, Ref } from 'vue';

/**
 * 文件职责：费用设置复制动作。
 * 1. 管理复制弹窗状态与目标门店勾选。
 * 2. 提交复制请求并反馈结果。
 */
import type { StoreListItemDto } from '#/api/store';

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

import { copyStoreFeesSettingsApi } from '#/api/store-fees';

interface CreateCopyActionsOptions {
  copyCandidates: ComputedRef<StoreListItemDto[]>;
  copyTargetStoreIds: Ref<string[]>;
  isCopyModalOpen: Ref<boolean>;
  isCopySubmitting: Ref<boolean>;
  selectedStoreId: Ref<string>;
}

export function createCopyActions(options: CreateCopyActionsOptions) {
  /** 打开弹窗前清空目标勾选。 */
  function openCopyModal() {
    if (!options.selectedStoreId.value) return;
    options.copyTargetStoreIds.value = [];
    options.isCopyModalOpen.value = true;
  }

  /** 切换单个目标门店状态。 */
  function toggleCopyStore(storeId: string, checked: boolean) {
    options.copyTargetStoreIds.value = checked
      ? [...new Set([storeId, ...options.copyTargetStoreIds.value])]
      : options.copyTargetStoreIds.value.filter((id) => id !== storeId);
  }

  /** 全选/取消全选。 */
  function handleCopyCheckAll(checked: boolean) {
    options.copyTargetStoreIds.value = checked
      ? options.copyCandidates.value.map((store) => store.id)
      : [];
  }

  /** 提交复制请求。 */
  async function handleCopySubmit() {
    if (!options.selectedStoreId.value) return;
    if (options.copyTargetStoreIds.value.length === 0) {
      message.error('请至少选择一个目标门店');
      return;
    }

    options.isCopySubmitting.value = true;
    try {
      await copyStoreFeesSettingsApi({
        sourceStoreId: options.selectedStoreId.value,
        targetStoreIds: options.copyTargetStoreIds.value,
      });
      message.success(
        `已复制到 ${options.copyTargetStoreIds.value.length} 家门店`,
      );
      options.isCopyModalOpen.value = false;
      options.copyTargetStoreIds.value = [];
    } catch (error) {
      console.error(error);
      message.error('复制失败，请稍后重试');
    } finally {
      options.isCopySubmitting.value = false;
    }
  }

  return {
    handleCopyCheckAll,
    handleCopySubmit,
    openCopyModal,
    toggleCopyStore,
  };
}
