import type { Ref } from 'vue';

import type { StoreListItemDto } from '#/api/store';
/**
 * 文件职责：配送设置数据动作。
 * 1. 加载门店列表与当前门店配送设置。
 * 2. 保存与重置页面配置。
 */
import type {
  DeliveryGeneralSettingsDto,
  DeliveryMode,
  PolygonZoneDto,
  RadiusTierDto,
} from '#/api/store-delivery';
import type { DeliverySettingsSnapshot } from '#/views/store/delivery/types';

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

import { getStoreListApi } from '#/api/store';
import {
  getStoreDeliverySettingsApi,
  saveStoreDeliverySettingsApi,
} from '#/api/store-delivery';

import {
  DEFAULT_DELIVERY_MODE,
  DEFAULT_GENERAL_SETTINGS,
  DEFAULT_POLYGON_ZONES,
  DEFAULT_RADIUS_TIERS,
} from './constants';
import {
  cloneGeneralSettings,
  clonePolygonZones,
  cloneRadiusTiers,
  createSettingsSnapshot,
  sortPolygonZones,
  sortRadiusTiers,
} from './helpers';

interface CreateDataActionsOptions {
  clearSettings: () => void;
  editingMode: Ref<DeliveryMode>;
  generalSettings: DeliveryGeneralSettingsDto;
  isConfigured: Ref<boolean>;
  isSaving: Ref<boolean>;
  isSettingsLoading: Ref<boolean>;
  isStoreLoading: Ref<boolean>;
  loadedStoreId: Ref<string>;
  mode: Ref<DeliveryMode>;
  radiusCenterLatitude: Ref<null | number>;
  radiusCenterLongitude: Ref<null | number>;
  polygonZones: Ref<PolygonZoneDto[]>;
  radiusTiers: Ref<RadiusTierDto[]>;
  selectedStoreId: Ref<string>;
  snapshot: Ref<DeliverySettingsSnapshot | null>;
  stores: Ref<StoreListItemDto[]>;
}

export function createDataActions(options: CreateDataActionsOptions) {
  /** 同步通用设置对象，保留 reactive 引用。 */
  function syncGeneralSettings(next: DeliveryGeneralSettingsDto) {
    options.generalSettings.freeDeliveryThreshold = next.freeDeliveryThreshold;
    options.generalSettings.maxDeliveryDistance = next.maxDeliveryDistance;
    options.generalSettings.hourlyCapacityLimit = next.hourlyCapacityLimit;
    options.generalSettings.etaAdjustmentMinutes = next.etaAdjustmentMinutes;
  }

  /** 将快照应用到页面状态。 */
  function applySnapshot(snapshot: DeliverySettingsSnapshot) {
    options.mode.value = snapshot.mode;
    options.editingMode.value = snapshot.mode;
    options.radiusCenterLatitude.value = snapshot.radiusCenterLatitude;
    options.radiusCenterLongitude.value = snapshot.radiusCenterLongitude;
    options.radiusTiers.value = sortRadiusTiers(snapshot.radiusTiers);
    options.polygonZones.value = sortPolygonZones(snapshot.polygonZones);
    syncGeneralSettings(snapshot.generalSettings);
  }

  /** 读取当前页面状态并生成快照。 */
  function buildCurrentSnapshot() {
    return createSettingsSnapshot({
      mode: options.mode.value,
      radiusCenterLatitude: options.radiusCenterLatitude.value,
      radiusCenterLongitude: options.radiusCenterLongitude.value,
      radiusTiers: options.radiusTiers.value,
      polygonZones: options.polygonZones.value,
      generalSettings: options.generalSettings,
    });
  }

  /** 加载指定门店的配送设置。 */
  async function loadStoreSettings(storeId: string) {
    options.isSettingsLoading.value = true;
    try {
      const currentStoreId = storeId;
      const result = await getStoreDeliverySettingsApi(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_DELIVERY_MODE;
      options.editingMode.value = options.mode.value;
      options.radiusCenterLatitude.value = result.radiusCenterLatitude ?? null;
      options.radiusCenterLongitude.value =
        result.radiusCenterLongitude ?? null;
      options.radiusTiers.value = sortRadiusTiers(
        result.radiusTiers ?? DEFAULT_RADIUS_TIERS,
      );
      options.polygonZones.value = sortPolygonZones(
        result.polygonZones ?? clonePolygonZones(DEFAULT_POLYGON_ZONES),
      );

      syncGeneralSettings(
        result.generalSettings
          ? cloneGeneralSettings(result.generalSettings)
          : cloneGeneralSettings(DEFAULT_GENERAL_SETTINGS),
      );
      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.isSettingsLoading.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(
        (store) => store.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 saveCurrentSettings() {
    if (!options.selectedStoreId.value) return false;
    options.isSaving.value = true;

    try {
      await saveStoreDeliverySettingsApi({
        storeId: options.selectedStoreId.value,
        mode: options.mode.value,
        radiusCenterLatitude: options.radiusCenterLatitude.value,
        radiusCenterLongitude: options.radiusCenterLongitude.value,
        radiusTiers: cloneRadiusTiers(options.radiusTiers.value),
        polygonZones: clonePolygonZones(options.polygonZones.value),
        generalSettings: cloneGeneralSettings(options.generalSettings),
      });
      options.snapshot.value = buildCurrentSnapshot();
      message.success('配送设置已保存');
      return true;
    } catch (error) {
      console.error(error);
      message.error('配送设置保存失败，请稍后重试');
      return false;
    } finally {
      options.isSaving.value = false;
    }
  }

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

  return {
    loadStoreSettings,
    loadStores,
    resetFromSnapshot,
    saveCurrentSettings,
  };
}
