import type { Ref } from 'vue';

import type { StoreListItemDto } from '#/api/store';
/**
 * 文件职责：费用设置数据动作。
 * 1. 加载门店列表与门店费用配置。
 * 2. 保存费用配置并维护快照。
 */
import type {
  SaveStoreFeesSettingsParams,
  StoreFeesSettingsDto,
} from '#/api/store-fees';
import type {
  StoreFeesFormState,
  StoreFeesSettingsSnapshot,
} from '#/views/store/fees/types';

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

import { getStoreListApi } from '#/api/store';
import {
  getStoreFeesSettingsApi,
  saveStoreFeesSettingsApi,
} from '#/api/store-fees';

import {
  cloneOtherFees,
  cloneTiers,
  createSettingsSnapshot,
  normalizeMoney,
  sortTiers,
} from './helpers';

interface CreateDataActionsOptions {
  clearSettings: () => void;
  form: StoreFeesFormState;
  isConfigured: Ref<boolean>;
  isPageLoading: Ref<boolean>;
  isStoreLoading: Ref<boolean>;
  loadedStoreId: Ref<string>;
  selectedStoreId: Ref<string>;
  snapshot: Ref<null | StoreFeesSettingsSnapshot>;
  stores: Ref<StoreListItemDto[]>;
}

const EMPTY_OTHER_FEES = {
  cutlery: {
    enabled: false,
    amount: 0,
  },
  rush: {
    enabled: false,
    amount: 0,
  },
};

export function createDataActions(options: CreateDataActionsOptions) {
  /** 同步页面表单，保持 reactive 引用不变。 */
  function syncForm(next: StoreFeesFormState) {
    options.form.minimumOrderAmount = normalizeMoney(
      next.minimumOrderAmount,
      0,
    );
    options.form.baseDeliveryFee = normalizeMoney(next.baseDeliveryFee, 0);
    options.form.platformServiceRate = normalizeMoney(
      next.platformServiceRate,
      0,
    );
    options.form.freeDeliveryThreshold =
      next.freeDeliveryThreshold === null
        ? null
        : normalizeMoney(next.freeDeliveryThreshold, 0);
    options.form.packagingFeeMode = next.packagingFeeMode;
    options.form.orderPackagingFeeMode = next.orderPackagingFeeMode;
    options.form.fixedPackagingFee = normalizeMoney(next.fixedPackagingFee, 0);
    options.form.packagingFeeTiers = sortTiers(
      cloneTiers(next.packagingFeeTiers),
    );
    options.form.otherFees = cloneOtherFees(next.otherFees);
  }

  /** 构建当前表单快照。 */
  function buildCurrentSnapshot() {
    return createSettingsSnapshot(options.form);
  }

  /** 将接口返回值转为页面表单态。 */
  function normalizeSettings(
    source: null | Partial<StoreFeesSettingsDto> | undefined,
  ): StoreFeesFormState {
    const packagingFeeMode =
      source?.packagingFeeMode === 'item' ||
      source?.packagingFeeMode === 'order'
        ? source.packagingFeeMode
        : 'order';
    const orderPackagingFeeMode =
      source?.orderPackagingFeeMode === 'fixed' ||
      source?.orderPackagingFeeMode === 'tiered'
        ? source.orderPackagingFeeMode
        : 'fixed';

    const otherFees = cloneOtherFees({
      cutlery: {
        enabled: Boolean(source?.otherFees?.cutlery?.enabled),
        amount: normalizeMoney(source?.otherFees?.cutlery?.amount ?? 0, 0),
      },
      rush: {
        enabled: Boolean(source?.otherFees?.rush?.enabled),
        amount: normalizeMoney(source?.otherFees?.rush?.amount ?? 0, 0),
      },
    });

    return {
      minimumOrderAmount: normalizeMoney(source?.minimumOrderAmount ?? 0, 0),
      baseDeliveryFee: normalizeMoney(source?.baseDeliveryFee ?? 0, 0),
      platformServiceRate: normalizeMoney(source?.platformServiceRate ?? 0, 0),
      freeDeliveryThreshold:
        source?.freeDeliveryThreshold === null ||
        source?.freeDeliveryThreshold === undefined
          ? null
          : normalizeMoney(source.freeDeliveryThreshold, 0),
      packagingFeeMode,
      orderPackagingFeeMode,
      fixedPackagingFee: normalizeMoney(source?.fixedPackagingFee ?? 0, 0),
      packagingFeeTiers: sortTiers(cloneTiers(source?.packagingFeeTiers ?? [])),
      otherFees: source?.otherFees
        ? otherFees
        : cloneOtherFees(EMPTY_OTHER_FEES),
    };
  }

  /** 按当前门店构建保存参数。 */
  function buildSavePayload(storeId: string): SaveStoreFeesSettingsParams {
    return {
      storeId,
      minimumOrderAmount: options.form.minimumOrderAmount,
      baseDeliveryFee: options.form.baseDeliveryFee,
      platformServiceRate: options.form.platformServiceRate,
      freeDeliveryThreshold: options.form.freeDeliveryThreshold,
      packagingFeeMode: options.form.packagingFeeMode,
      orderPackagingFeeMode: options.form.orderPackagingFeeMode,
      fixedPackagingFee: options.form.fixedPackagingFee,
      packagingFeeTiers: cloneTiers(options.form.packagingFeeTiers),
      otherFees: cloneOtherFees(options.form.otherFees),
    };
  }

  /** 加载指定门店费用配置。 */
  async function loadStoreSettings(storeId: string) {
    options.isPageLoading.value = true;
    try {
      const currentStoreId = storeId;
      const result = await getStoreFeesSettingsApi(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;
      }

      syncForm(normalizeSettings(result));
      options.isConfigured.value = true;
      options.loadedStoreId.value = currentStoreId;
      options.snapshot.value = buildCurrentSnapshot();
    } catch (error) {
      console.error(error);
      options.isConfigured.value = false;
      options.loadedStoreId.value = '';
      options.snapshot.value = null;
      options.clearSettings();
      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.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);
      message.error('加载门店失败，请稍后重试');
      options.stores.value = [];
      options.selectedStoreId.value = '';
      options.isConfigured.value = false;
      options.snapshot.value = null;
      options.clearSettings();
    } finally {
      options.isStoreLoading.value = false;
    }
  }

  /** 保存当前配置（按调用方文案提示）。 */
  async function saveCurrentSettings(successText: string) {
    if (!options.selectedStoreId.value) return false;
    try {
      const payload = buildSavePayload(options.selectedStoreId.value);
      const result = await saveStoreFeesSettingsApi(payload);
      syncForm(normalizeSettings(result ?? payload));
      options.isConfigured.value = true;
      options.snapshot.value = buildCurrentSnapshot();
      message.success(successText);
      return true;
    } catch (error) {
      console.error(error);
      message.error('保存失败，请稍后重试');
      return false;
    }
  }

  /** 重置到最近一次快照。 */
  function resetFromSnapshot() {
    if (!options.snapshot.value) {
      message.warning('暂无可恢复的已保存配置');
      return;
    }
    syncForm(options.snapshot.value);
  }

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