/**
 * 复制到其他门店动作：
 * - 选择目标门店
 * - 全选/单选联动
 * - 提交复制请求
 */
import type { ComputedRef, Ref } from 'vue';

import type { StoreListItemDto } from '#/api/store';

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

import { copyStoreHoursApi } from '#/api/store-hours';

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

export function createCopyActions(options: CreateCopyActionsOptions) {
  // 1. 弹窗与选中状态维护。
  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 toggleCopyAll(checked: boolean) {
    if (checked) {
      options.copyTargetStoreIds.value = options.copyCandidates.value.map(
        (store) => store.id,
      );
      return;
    }
    options.copyTargetStoreIds.value = [];
  }

  function handleCopyCheckAll(checked: boolean) {
    toggleCopyAll(Boolean(checked));
  }

  function handleCopyStoreChange(storeId: string, checked: boolean) {
    toggleCopyStore(storeId, Boolean(checked));
  }

  // 2. 调用复制接口并处理结果提示。
  async function handleCopySubmit() {
    if (!options.selectedStoreId.value) return;

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

    options.isCopySubmitting.value = true;
    try {
      await copyStoreHoursApi({
        sourceStoreId: options.selectedStoreId.value,
        targetStoreIds: options.copyTargetStoreIds.value,
        includeWeeklyHours: true,
        includeHolidays: true,
      });
      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,
    handleCopyStoreChange,
    handleCopySubmit,
    openCopyModal,
    toggleCopyStore,
  };
}
