import type { Ref } from 'vue';

import type { StoreListItemDto } from '#/api/store';
/**
 * 文件职责：自提设置数据动作。
 * 1. 加载门店列表与门店自提配置。
 * 2. 保存基本设置、大时段、精细规则并维护快照。
 */
import type {
  PickupBasicSettingsDto,
  PickupFineRuleDto,
  PickupMode,
  PickupPreviewDayDto,
  PickupSlotDto,
} from '#/api/store-pickup';
import type { PickupSettingsSnapshot } from '#/views/store/pickup/types';

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

import { getStoreListApi } from '#/api/store';
import {
  getStorePickupSettingsApi,
  savePickupBasicSettingsApi,
  savePickupFineRuleApi,
  savePickupSlotsApi,
} from '#/api/store-pickup';

import {
  DEFAULT_FINE_RULE,
  DEFAULT_PICKUP_BASIC_SETTINGS,
  DEFAULT_PICKUP_MODE,
} from './constants';
import {
  cloneBasicSettings,
  cloneBigSlots,
  cloneFineRule,
  clonePreviewDays,
  createSettingsSnapshot,
  sortSlots,
} from './helpers';

interface CreateDataActionsOptions {
  basicSettings: PickupBasicSettingsDto;
  bigSlots: Ref<PickupSlotDto[]>;
  clearSettings: () => void;
  fineRule: PickupFineRuleDto;
  isConfigured: Ref<boolean>;
  isPageLoading: Ref<boolean>;
  isSavingBasic: Ref<boolean>;
  isSavingFineRule: Ref<boolean>;
  isSavingSlots: Ref<boolean>;
  isStoreLoading: Ref<boolean>;
  loadedStoreId: Ref<string>;
  mode: Ref<PickupMode>;
  previewDays: Ref<PickupPreviewDayDto[]>;
  selectedStoreId: Ref<string>;
  snapshot: Ref<null | PickupSettingsSnapshot>;
  stores: Ref<StoreListItemDto[]>;
}

export function createDataActions(options: CreateDataActionsOptions) {
  /** 同步基本设置，保持 reactive 引用不变。 */
  function syncBasicSettings(next: PickupBasicSettingsDto) {
    options.basicSettings.allowSameDayPickup = next.allowSameDayPickup;
    options.basicSettings.bookingDays = next.bookingDays;
    options.basicSettings.maxItemsPerOrder = next.maxItemsPerOrder;
  }

  /** 同步精细规则，保持 reactive 引用不变。 */
  function syncFineRule(next: PickupFineRuleDto) {
    options.fineRule.intervalMinutes = next.intervalMinutes;
    options.fineRule.slotCapacity = next.slotCapacity;
    options.fineRule.dayStartTime = next.dayStartTime;
    options.fineRule.dayEndTime = next.dayEndTime;
    options.fineRule.minAdvanceHours = next.minAdvanceHours;
    options.fineRule.dayOfWeeks = [...next.dayOfWeeks];
  }

  /** 创建当前页面快照，供重置回滚使用。 */
  function buildCurrentSnapshot() {
    return createSettingsSnapshot({
      mode: options.mode.value,
      basicSettings: options.basicSettings,
      bigSlots: options.bigSlots.value,
      fineRule: options.fineRule,
      previewDays: options.previewDays.value,
    });
  }

  /** 应用快照到当前页面状态。 */
  function applySnapshot(snapshot: PickupSettingsSnapshot) {
    options.mode.value = snapshot.mode;
    syncBasicSettings(snapshot.basicSettings);
    options.bigSlots.value = sortSlots(cloneBigSlots(snapshot.bigSlots));
    syncFineRule(snapshot.fineRule);
    options.previewDays.value = clonePreviewDays(snapshot.previewDays);
  }

  /** 加载指定门店自提设置。 */
  async function loadStoreSettings(storeId: string) {
    options.isPageLoading.value = true;
    try {
      const currentStoreId = storeId;
      const result = await getStorePickupSettingsApi(storeId);
      if (options.selectedStoreId.value !== currentStoreId) return;

      if (!result.isConfigured) {
        options.clearSettings();
        options.isConfigured.value = false;
        options.loadedStoreId.value = currentStoreId;
        options.snapshot.value = buildCurrentSnapshot();
        return;
      }

      options.mode.value = result.mode ?? DEFAULT_PICKUP_MODE;
      syncBasicSettings(
        result.basicSettings
          ? cloneBasicSettings(result.basicSettings)
          : cloneBasicSettings(DEFAULT_PICKUP_BASIC_SETTINGS),
      );
      options.bigSlots.value = sortSlots(
        result.bigSlots?.length ? result.bigSlots : [],
      );
      syncFineRule(
        result.fineRule
          ? cloneFineRule(result.fineRule)
          : cloneFineRule(DEFAULT_FINE_RULE),
      );
      options.previewDays.value =
        result.previewDays?.length > 0
          ? clonePreviewDays(result.previewDays)
          : [];

      options.isConfigured.value = true;
      options.loadedStoreId.value = currentStoreId;
      options.snapshot.value = buildCurrentSnapshot();
    } catch (error) {
      console.error(error);
      options.clearSettings();
      options.isConfigured.value = false;
      options.loadedStoreId.value = '';
      options.snapshot.value = null;
      message.error('加载自提设置失败，请稍后重试');
    } finally {
      options.isPageLoading.value = false;
    }
  }

  /** 加载门店列表并处理默认选中。 */
  async function loadStores() {
    options.isStoreLoading.value = true;
    try {
      const result = await getStoreListApi({
        keyword: undefined,
        businessStatus: undefined,
        auditStatus: undefined,
        serviceType: undefined,
        page: 1,
        pageSize: 200,
      });
      options.stores.value = result.items ?? [];

      if (options.stores.value.length === 0) {
        options.selectedStoreId.value = '';
        options.loadedStoreId.value = '';
        options.isConfigured.value = false;
        options.snapshot.value = null;
        options.clearSettings();
        return;
      }

      const hasSelected = options.stores.value.some(
        (item) => item.id === options.selectedStoreId.value,
      );
      if (!hasSelected) {
        const firstStore = options.stores.value[0];
        if (firstStore) options.selectedStoreId.value = firstStore.id;
        return;
      }
      if (options.selectedStoreId.value) {
        await loadStoreSettings(options.selectedStoreId.value);
      }
    } catch (error) {
      console.error(error);
      options.stores.value = [];
      options.selectedStoreId.value = '';
      options.loadedStoreId.value = '';
      options.isConfigured.value = false;
      options.snapshot.value = null;
      options.clearSettings();
      message.error('加载门店失败，请稍后重试');
    } finally {
      options.isStoreLoading.value = false;
    }
  }

  /** 保存基本设置并更新快照。 */
  async function saveBasicSettings() {
    if (!options.selectedStoreId.value) return;
    options.isSavingBasic.value = true;
    try {
      const currentStoreId = options.selectedStoreId.value;
      await savePickupBasicSettingsApi({
        storeId: currentStoreId,
        mode: options.mode.value,
        basicSettings: cloneBasicSettings(options.basicSettings),
      });
      await loadStoreSettings(currentStoreId);
      message.success('基本设置已保存');
    } catch (error) {
      console.error(error);
    } finally {
      options.isSavingBasic.value = false;
    }
  }

  /** 保存大时段并更新快照。 */
  async function saveBigSlots() {
    if (!options.selectedStoreId.value) return;
    options.isSavingSlots.value = true;
    try {
      const currentStoreId = options.selectedStoreId.value;
      await savePickupSlotsApi({
        storeId: currentStoreId,
        mode: options.mode.value,
        slots: cloneBigSlots(options.bigSlots.value),
      });
      await loadStoreSettings(currentStoreId);
      message.success('大时段配置已保存');
    } catch (error) {
      console.error(error);
    } finally {
      options.isSavingSlots.value = false;
    }
  }

  /** 保存精细规则并刷新预览。 */
  async function saveFineRule() {
    if (!options.selectedStoreId.value) return;
    options.isSavingFineRule.value = true;
    try {
      const currentStoreId = options.selectedStoreId.value;
      await savePickupFineRuleApi({
        storeId: currentStoreId,
        mode: options.mode.value,
        fineRule: cloneFineRule(options.fineRule),
      });
      await loadStoreSettings(currentStoreId);
      message.success('精细规则已保存');
    } catch (error) {
      console.error(error);
    } finally {
      options.isSavingFineRule.value = false;
    }
  }

  /** 重置到最近一次快照。 */
  function resetFromSnapshot() {
    if (!options.snapshot.value) {
      options.clearSettings();
      return;
    }
    applySnapshot(options.snapshot.value);
    message.success('已恢复到最近一次保存状态');
  }

  return {
    loadStoreSettings,
    loadStores,
    resetFromSnapshot,
    saveBasicSettings,
    saveBigSlots,
    saveFineRule,
  };
}
