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

/**
 * 文件职责：员工排班复制动作。
 * 1. 管理复制弹窗选择状态。
 * 2. 提交“模板+排班”复制请求。
 */
import type { StoreListItemDto } from '#/api/store';

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

import { copyStoreStaffScheduleApi } from '#/api/store-staff';

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((item) => item.id)
      : [];
  }

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

    options.isCopySubmitting.value = true;
    try {
      await copyStoreStaffScheduleApi({
        sourceStoreId: options.selectedStoreId.value,
        targetStoreIds: options.copyTargetStoreIds.value,
        copyScope: 'template_and_schedule',
      });

      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,
  };
}
