import type { StoreListItemDto } from '#/api/store';
/**
 * 文件职责：自提设置页面主编排。
 * 1. 维护页面级状态（门店、模式、设置、抽屉、复制弹窗）。
 * 2. 组合数据加载、复制、大时段与精细规则动作。
 * 3. 对外暴露视图层可直接消费的状态与方法。
 */
import type {
  PickupBasicSettingsDto,
  PickupPreviewDayDto,
  PickupSlotDto,
} from '#/api/store-pickup';
import type {
  PickupDrawerMode,
  PickupSettingsSnapshot,
  PickupSlotFormState,
} from '#/views/store/pickup/types';

import { computed, onActivated, onMounted, reactive, ref, watch } from 'vue';

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

import { savePickupModeApi } from '#/api/store-pickup';

import {
  ALL_WEEK_DAYS,
  DEFAULT_FINE_RULE,
  DEFAULT_PICKUP_BASIC_SETTINGS,
  DEFAULT_PICKUP_MODE,
  FINE_INTERVAL_OPTIONS,
  PICKUP_MODE_OPTIONS,
  WEEKDAY_OPTIONS,
} from './pickup-page/constants';
import { createCopyActions } from './pickup-page/copy-actions';
import { createDataActions } from './pickup-page/data-actions';
import { createFineRuleActions } from './pickup-page/fine-rule-actions';
import {
  calcReservedPercent,
  cloneBasicSettings,
  cloneFineRule,
  clonePreviewDays,
  createSettingsSnapshot,
  createSlotId,
  formatDayOfWeeksText,
} from './pickup-page/helpers';
import { createSlotActions } from './pickup-page/slot-actions';

export function useStorePickupPage() {
  // 1. 页面 loading / submitting 状态。
  const isStoreLoading = ref(false);
  const isPageLoading = ref(false);
  const isSavingBasic = ref(false);
  const isSavingSlots = ref(false);
  const isSavingFineRule = ref(false);
  const isModeSwitching = ref(false);
  const isCopySubmitting = ref(false);
  const isConfigured = ref(false);
  const loadedStoreId = ref('');

  // 2. 页面核心业务数据。
  const stores = ref<StoreListItemDto[]>([]);
  const selectedStoreId = ref('');
  const pickupMode = ref(DEFAULT_PICKUP_MODE);
  const basicSettings = reactive<PickupBasicSettingsDto>(
    cloneBasicSettings(DEFAULT_PICKUP_BASIC_SETTINGS),
  );
  const bigSlots = ref<PickupSlotDto[]>([]);
  const fineRule = reactive(cloneFineRule(DEFAULT_FINE_RULE));
  const previewDays = ref<PickupPreviewDayDto[]>([]);
  const selectedPreviewDate = ref(previewDays.value[0]?.date ?? '');
  const snapshot = ref<null | PickupSettingsSnapshot>(null);

  // 3. 复制弹窗状态。
  const isCopyModalOpen = ref(false);
  const copyTargetStoreIds = ref<string[]>([]);

  // 4. 大时段抽屉状态。
  const isSlotDrawerOpen = ref(false);
  const slotDrawerMode = ref<PickupDrawerMode>('create');
  const slotForm = reactive<PickupSlotFormState>({
    id: '',
    name: '',
    startTime: '09:00',
    endTime: '17:00',
    cutoffMinutes: 30,
    capacity: 20,
    dayOfWeeks: [...ALL_WEEK_DAYS],
    enabled: true,
  });

  // 5. 页面衍生视图数据。
  const storeOptions = computed(() =>
    stores.value.map((store) => ({ label: store.name, value: store.id })),
  );

  const selectedStoreName = computed(
    () =>
      stores.value.find((store) => store.id === selectedStoreId.value)?.name ??
      '',
  );

  const copyCandidates = computed(() =>
    stores.value.filter((store) => store.id !== selectedStoreId.value),
  );

  const isCopyAllChecked = computed(
    () =>
      copyCandidates.value.length > 0 &&
      copyTargetStoreIds.value.length === copyCandidates.value.length,
  );

  const isCopyIndeterminate = computed(
    () =>
      copyTargetStoreIds.value.length > 0 &&
      copyTargetStoreIds.value.length < copyCandidates.value.length,
  );

  const selectedPreviewDay = computed(
    () =>
      previewDays.value.find(
        (item) => item.date === selectedPreviewDate.value,
      ) ?? previewDays.value[0],
  );

  const slotDrawerTitle = computed(() =>
    slotDrawerMode.value === 'edit'
      ? `编辑时段 - ${slotForm.name}`
      : '添加时段',
  );
  const hasSelectedStore = computed(() => Boolean(selectedStoreId.value));
  const hasLoadedStoreSettings = computed(
    () =>
      loadedStoreId.value === selectedStoreId.value && snapshot.value !== null,
  );
  const canOperate = computed(
    () =>
      hasSelectedStore.value &&
      loadedStoreId.value === selectedStoreId.value &&
      !isStoreLoading.value &&
      !isPageLoading.value &&
      !isSavingBasic.value &&
      !isSavingSlots.value &&
      !isSavingFineRule.value &&
      !isModeSwitching.value,
  );

  function clearSettings() {
    pickupMode.value = DEFAULT_PICKUP_MODE;
    basicSettings.allowSameDayPickup =
      DEFAULT_PICKUP_BASIC_SETTINGS.allowSameDayPickup;
    basicSettings.bookingDays = DEFAULT_PICKUP_BASIC_SETTINGS.bookingDays;
    basicSettings.maxItemsPerOrder =
      DEFAULT_PICKUP_BASIC_SETTINGS.maxItemsPerOrder;
    bigSlots.value = [];
    Object.assign(fineRule, cloneFineRule(DEFAULT_FINE_RULE));
    previewDays.value = [];
    selectedPreviewDate.value = '';
  }

  // 6. 数据域动作装配。
  const {
    loadStoreSettings,
    loadStores,
    resetFromSnapshot,
    saveBasicSettings,
    saveBigSlots,
    saveFineRule,
  } = createDataActions({
    basicSettings,
    bigSlots,
    clearSettings,
    fineRule,
    isConfigured,
    isPageLoading,
    isSavingBasic,
    isSavingFineRule,
    isSavingSlots,
    isStoreLoading,
    loadedStoreId,
    mode: pickupMode,
    previewDays,
    selectedStoreId,
    snapshot,
    stores,
  });

  const {
    handleCopyCheckAll,
    handleCopySubmit,
    openCopyModal,
    toggleCopyStore,
  } = createCopyActions({
    copyCandidates,
    copyTargetStoreIds,
    isCopyModalOpen,
    isCopySubmitting,
    selectedStoreId,
  });

  const {
    handleDeleteSlot,
    handleSubmitSlot,
    handleToggleSlotEnabled,
    isSlotDaySelected,
    openSlotDrawer,
    quickSelectSlotDays,
    setSlotCapacity,
    setSlotCutoffMinutes,
    setSlotDrawerOpen,
    setSlotEnabled,
    setSlotEndTime,
    setSlotName,
    setSlotStartTime,
    toggleSlotDay,
  } = createSlotActions({
    bigSlots,
    createSlotId,
    isSlotDrawerOpen,
    saveBigSlots,
    slotDrawerMode,
    slotForm,
  });

  const {
    handleSaveFineRule,
    isFineDaySelected,
    quickSelectFineDays,
    setFineDayEndTime,
    setFineDayStartTime,
    setFineIntervalMinutes,
    setFineMinAdvanceHours,
    setFineSlotCapacity,
    setSelectedPreviewDate,
    toggleFineDay,
  } = createFineRuleActions({
    fineRule,
    saveFineRule,
    selectedPreviewDate,
  });

  // 7. 页面字段更新方法。
  function setSelectedStoreId(value: string) {
    selectedStoreId.value = value;
  }

  function getPickupModeConfirmContent(value: 'big' | 'fine') {
    if (value === 'big') {
      return '切换后将按大时段统一预约，精细时段规则与预览将暂不生效。';
    }
    return '切换后将按精细时段预约，大时段配置将暂不生效。';
  }

  function setPickupMode(value: 'big' | 'fine') {
    if (!canOperate.value) return;
    if (value === pickupMode.value) return;
    if (!selectedStoreId.value) return;

    const currentStoreId = selectedStoreId.value;
    const previousMode = pickupMode.value;

    Modal.confirm({
      title: '确认切换自提预约模式？',
      content: getPickupModeConfirmContent(value),
      okText: '确认切换',
      cancelText: '取消',
      async onOk() {
        if (isModeSwitching.value) return;
        isModeSwitching.value = true;
        pickupMode.value = value;

        try {
          await savePickupModeApi({
            storeId: currentStoreId,
            mode: value,
          });

          if (selectedStoreId.value === currentStoreId) {
            isConfigured.value = true;
            loadedStoreId.value = currentStoreId;
            snapshot.value = snapshot.value
              ? {
                  ...snapshot.value,
                  mode: value,
                }
              : createSettingsSnapshot({
                  mode: value,
                  basicSettings,
                  bigSlots: bigSlots.value,
                  fineRule,
                  previewDays: previewDays.value,
                });
            message.success('自提预约模式已切换');
          }
        } catch (error) {
          console.error(error);
          if (selectedStoreId.value === currentStoreId) {
            pickupMode.value = previousMode;
          }
          message.error('自提预约模式切换失败，请稍后重试');
        } finally {
          isModeSwitching.value = false;
        }
      },
    });
  }

  function setAllowSameDayPickup(value: boolean) {
    basicSettings.allowSameDayPickup = Boolean(value);
  }

  function setBookingDays(value: number) {
    basicSettings.bookingDays = Math.max(1, Math.floor(Number(value || 1)));
  }

  function setMaxItemsPerOrder(value: null | number) {
    if (value === null || value === undefined) {
      basicSettings.maxItemsPerOrder = null;
      return;
    }
    basicSettings.maxItemsPerOrder = Math.max(
      0,
      Math.floor(Number(value || 0)),
    );
  }

  /** 仅重置基本设置区域，避免影响其他配置。 */
  function resetBasicSettings() {
    const source =
      snapshot.value?.basicSettings ??
      cloneBasicSettings(DEFAULT_PICKUP_BASIC_SETTINGS);
    basicSettings.allowSameDayPickup = source.allowSameDayPickup;
    basicSettings.bookingDays = source.bookingDays;
    basicSettings.maxItemsPerOrder = source.maxItemsPerOrder;
  }

  /** 仅重置精细规则区域，并同步预览。 */
  function resetFineRule() {
    const source = snapshot.value?.fineRule ?? cloneFineRule(DEFAULT_FINE_RULE);
    fineRule.intervalMinutes = source.intervalMinutes;
    fineRule.slotCapacity = source.slotCapacity;
    fineRule.dayStartTime = source.dayStartTime;
    fineRule.dayEndTime = source.dayEndTime;
    fineRule.minAdvanceHours = source.minAdvanceHours;
    fineRule.dayOfWeeks = [...source.dayOfWeeks];
    previewDays.value =
      snapshot.value?.previewDays && snapshot.value.previewDays.length > 0
        ? clonePreviewDays(snapshot.value.previewDays)
        : [];
    selectedPreviewDate.value = previewDays.value[0]?.date ?? '';
  }

  // 8. 门店切换时自动刷新配置。
  watch(selectedStoreId, async (storeId) => {
    if (!storeId) {
      isModeSwitching.value = false;
      loadedStoreId.value = '';
      isConfigured.value = false;
      clearSettings();
      snapshot.value = null;
      return;
    }
    isModeSwitching.value = false;
    loadedStoreId.value = '';
    isConfigured.value = false;
    snapshot.value = null;
    clearSettings();
    await loadStoreSettings(storeId);
    selectedPreviewDate.value = previewDays.value[0]?.date ?? '';
  });

  watch(previewDays, (days) => {
    if (days.length === 0) {
      selectedPreviewDate.value = '';
      return;
    }

    const hasCurrent = days.some(
      (item) => item.date === selectedPreviewDate.value,
    );
    if (!hasCurrent) {
      selectedPreviewDate.value = days[0]?.date ?? '';
    }
  });

  // 9. 页面首屏初始化。
  onMounted(loadStores);
  // 10. 路由回到当前页时刷新门店列表，避免使用旧缓存。
  onActivated(loadStores);

  return {
    FINE_INTERVAL_OPTIONS,
    PICKUP_MODE_OPTIONS,
    WEEKDAY_OPTIONS,
    basicSettings,
    bigSlots,
    canOperate,
    calcReservedPercent,
    copyCandidates,
    copyTargetStoreIds,
    fineRule,
    formatDayOfWeeksText,
    handleCopyCheckAll,
    handleCopySubmit,
    handleDeleteSlot,
    handleSaveFineRule,
    handleSubmitSlot,
    handleToggleSlotEnabled,
    isCopyAllChecked,
    isCopyIndeterminate,
    isCopyModalOpen,
    isCopySubmitting,
    isConfigured,
    hasLoadedStoreSettings,
    hasSelectedStore,
    isFineDaySelected,
    isPageLoading,
    isSavingBasic,
    isSavingFineRule,
    isModeSwitching,
    isSavingSlots,
    isSlotDaySelected,
    isSlotDrawerOpen,
    isStoreLoading,
    openCopyModal,
    openSlotDrawer,
    loadedStoreId,
    pickupMode,
    previewDays,
    quickSelectFineDays,
    quickSelectSlotDays,
    resetBasicSettings,
    resetFineRule,
    resetFromSnapshot,
    saveBasicSettings,
    selectedPreviewDate,
    selectedPreviewDay,
    selectedStoreId,
    selectedStoreName,
    setAllowSameDayPickup,
    setBookingDays,
    setFineDayEndTime,
    setFineDayStartTime,
    setFineIntervalMinutes,
    setFineMinAdvanceHours,
    setFineSlotCapacity,
    setMaxItemsPerOrder,
    setPickupMode,
    setSelectedPreviewDate,
    setSelectedStoreId,
    setSlotCapacity,
    setSlotCutoffMinutes,
    setSlotDrawerOpen,
    setSlotEnabled,
    setSlotEndTime,
    setSlotName,
    setSlotStartTime,
    slotDrawerTitle,
    slotForm,
    storeOptions,
    toggleCopyStore,
    toggleFineDay,
    toggleSlotDay,
  };
}
