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

/**
 * 文件职责：配送设置复制动作。
 * 1. 维护复制弹窗开关与目标门店选择。
 * 2. 提交复制请求并反馈结果。
 */
import type { StoreListItemDto } from '#/api/store';

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

import { copyStoreDeliverySettingsApi } from '#/api/store-delivery';

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) {
    if (checked) {
      options.copyTargetStoreIds.value = options.copyCandidates.value.map(
        (item) => item.id,
      );
      return;
    }
    options.copyTargetStoreIds.value = [];
  }

  /** 提交复制请求。 */
  async function handleCopySubmit() {
    if (!options.selectedStoreId.value) return;

    if (options.copyTargetStoreIds.value.length === 0) {
      message.error('请至少选择一个目标门店');
      return;
    }

    options.isCopySubmitting.value = true;
    try {
      await copyStoreDeliverySettingsApi({
        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);
    } finally {
      options.isCopySubmitting.value = false;
    }
  }

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