import type { StoreListItemDto } from '#/api/store';
/**
 * 文件职责：费用设置页面主编排。
 * 1. 维护页面级状态（门店、费用配置、抽屉、复制弹窗）。
 * 2. 组合数据加载、复制、包装费阶梯动作。
 * 3. 对外暴露视图层可直接消费的状态与方法。
 */
import type { PackagingFeeMode, PackagingFeeTierDto } from '#/api/store-fees';
import type {
  FeesTierDrawerMode,
  PackagingFeeTierFormState,
  StoreFeesFormState,
  StoreFeesSettingsSnapshot,
} from '#/views/store/fees/types';

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

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

import { saveStoreFeesModeApi } from '#/api/store-fees';

import { PACKAGING_MODE_OPTIONS } from './fees-page/constants';
import { createCopyActions } from './fees-page/copy-actions';
import { createDataActions } from './fees-page/data-actions';
import {
  cloneFeesForm,
  cloneOtherFees,
  cloneTiers,
  createSettingsSnapshot,
  formatCurrency,
  formatTierRange,
  normalizeMoney,
} from './fees-page/helpers';
import { createPackagingActions } from './fees-page/packaging-actions';

const EMPTY_FEES_SETTINGS: StoreFeesFormState = {
  minimumOrderAmount: 0,
  baseDeliveryFee: 0,
  platformServiceRate: 0,
  freeDeliveryThreshold: null,
  packagingFeeMode: 'order',
  orderPackagingFeeMode: 'fixed',
  fixedPackagingFee: 0,
  packagingFeeTiers: [],
  otherFees: {
    cutlery: {
      enabled: false,
      amount: 0,
    },
    rush: {
      enabled: false,
      amount: 0,
    },
  },
};

export function useStoreFeesPage() {
  // 1. 页面 loading / submitting 状态。
  const isStoreLoading = ref(false);
  const isPageLoading = ref(false);
  const isSavingDelivery = ref(false);
  const isSavingPackaging = ref(false);
  const isSavingOther = ref(false);
  const isSwitchingPackagingMode = ref(false);
  const isCopySubmitting = ref(false);
  const isConfigured = ref(false);

  // 2. 页面核心业务数据。
  const stores = ref<StoreListItemDto[]>([]);
  const selectedStoreId = ref('');
  const loadedStoreId = ref('');
  const form = reactive<StoreFeesFormState>(cloneFeesForm(EMPTY_FEES_SETTINGS));
  const snapshot = ref<null | StoreFeesSettingsSnapshot>(null);

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

  // 4. 阶梯抽屉状态。
  const isTierDrawerOpen = ref(false);
  const tierDrawerMode = ref<FeesTierDrawerMode>('create');
  const tierForm = reactive<PackagingFeeTierFormState>({
    id: '',
    minAmount: 0,
    maxAmount: null,
    fee: 0,
  });

  // 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 hasSelectedStore = computed(() => Boolean(selectedStoreId.value));
  const hasLoadedStoreSettings = computed(() => snapshot.value !== null);
  const canOperate = computed(
    () =>
      hasSelectedStore.value &&
      loadedStoreId.value === selectedStoreId.value &&
      hasLoadedStoreSettings.value &&
      !isStoreLoading.value &&
      !isPageLoading.value &&
      !isSavingDelivery.value &&
      !isSavingPackaging.value &&
      !isSavingOther.value &&
      !isSwitchingPackagingMode.value,
  );

  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 tierDrawerTitle = computed(() =>
    tierDrawerMode.value === 'edit' ? '编辑阶梯包装费' : '添加阶梯包装费',
  );

  const isOrderMode = computed(() => form.packagingFeeMode === 'order');

  function getPackagingModeConfirmContent(value: PackagingFeeMode) {
    if (value === 'order') {
      return '切换后将按订单收取包装费，固定/阶梯包装费立即生效；商品维度包装费将暂不生效。';
    }
    return '切换后将按商品收取包装费，商品配置的包装费立即生效；本页固定/阶梯包装费将暂不生效。';
  }

  function clearSettings() {
    loadedStoreId.value = '';
    Object.assign(form, cloneFeesForm(EMPTY_FEES_SETTINGS));
    isTierDrawerOpen.value = false;
  }

  // 6. 动作装配。
  const {
    loadStoreSettings,
    loadStores,
    resetFromSnapshot,
    saveCurrentSettings,
  } = createDataActions({
    clearSettings,
    form,
    isConfigured,
    isPageLoading,
    isStoreLoading,
    loadedStoreId,
    selectedStoreId,
    snapshot,
    stores,
  });

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

  const {
    handleDeleteTier,
    handleSubmitTier,
    openTierDrawer,
    setPackagingFeeMode,
    setTierDrawerOpen,
    setTierFee,
    setTierMaxAmount,
    setTierMinAmount,
    toggleTiered,
    validateCurrentPackaging,
  } = createPackagingActions({
    form,
    isTierDrawerOpen,
    tierDrawerMode,
    tierForm,
  });

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

  function setMinimumOrderAmount(value: number) {
    form.minimumOrderAmount = normalizeMoney(value, form.minimumOrderAmount);
  }

  function setBaseDeliveryFee(value: number) {
    form.baseDeliveryFee = normalizeMoney(value, form.baseDeliveryFee);
  }

  function setPlatformServiceRate(value: number) {
    form.platformServiceRate = normalizeMoney(value, form.platformServiceRate);
  }

  function setFreeDeliveryThreshold(value: null | number) {
    if (value === null || value === undefined) {
      form.freeDeliveryThreshold = null;
      return;
    }
    form.freeDeliveryThreshold = normalizeMoney(value, 0);
  }

  function setFixedPackagingFee(value: number) {
    form.fixedPackagingFee = normalizeMoney(value, form.fixedPackagingFee);
  }

  function setPackagingMode(value: PackagingFeeMode) {
    if (!canOperate.value) return;
    if (value === form.packagingFeeMode) return;
    if (!selectedStoreId.value) return;

    const currentStoreId = selectedStoreId.value;
    const previousMode = form.packagingFeeMode;
    const previousOrderMode = form.orderPackagingFeeMode;

    Modal.confirm({
      title: '确认切换包装费收取方式？',
      content: getPackagingModeConfirmContent(value),
      okText: '确认切换',
      cancelText: '取消',
      async onOk() {
        if (isSwitchingPackagingMode.value) return;
        isSwitchingPackagingMode.value = true;
        setPackagingFeeMode(value);

        try {
          await saveStoreFeesModeApi({
            storeId: currentStoreId,
            packagingFeeMode: value,
          });

          if (selectedStoreId.value === currentStoreId) {
            isConfigured.value = true;
            loadedStoreId.value = currentStoreId;
            snapshot.value = snapshot.value
              ? {
                  ...snapshot.value,
                  packagingFeeMode: form.packagingFeeMode,
                  orderPackagingFeeMode: form.orderPackagingFeeMode,
                }
              : createSettingsSnapshot(form);
            message.success('包装费收取方式已切换');
          }
        } catch (error) {
          console.error(error);
          if (selectedStoreId.value === currentStoreId) {
            form.packagingFeeMode = previousMode;
            form.orderPackagingFeeMode = previousOrderMode;
          }
          message.error('包装费收取方式切换失败，请稍后重试');
        } finally {
          isSwitchingPackagingMode.value = false;
        }
      },
    });
  }

  function setCutleryEnabled(value: boolean) {
    form.otherFees.cutlery.enabled = Boolean(value);
  }

  function setCutleryAmount(value: number) {
    form.otherFees.cutlery.amount = normalizeMoney(
      value,
      form.otherFees.cutlery.amount,
    );
  }

  function setRushEnabled(value: boolean) {
    form.otherFees.rush.enabled = Boolean(value);
  }

  function setRushAmount(value: number) {
    form.otherFees.rush.amount = normalizeMoney(
      value,
      form.otherFees.rush.amount,
    );
  }

  /** 重置“起送与配送费”分区。 */
  function resetDeliverySection() {
    if (!snapshot.value) {
      message.warning('暂无可恢复的已保存配置');
      return;
    }
    const source = snapshot.value;
    form.minimumOrderAmount = source.minimumOrderAmount;
    form.baseDeliveryFee = source.baseDeliveryFee;
    form.platformServiceRate = source.platformServiceRate;
    form.freeDeliveryThreshold = source.freeDeliveryThreshold;
    message.success('已重置起送与配送费');
  }

  /** 重置“包装费设置”分区。 */
  function resetPackagingSection() {
    if (!snapshot.value) {
      message.warning('暂无可恢复的已保存配置');
      return;
    }
    const source = snapshot.value;
    form.packagingFeeMode = source.packagingFeeMode;
    form.orderPackagingFeeMode = source.orderPackagingFeeMode;
    form.fixedPackagingFee = source.fixedPackagingFee;
    form.packagingFeeTiers = cloneTiers(source.packagingFeeTiers);
    message.success('已重置包装费设置');
  }

  /** 重置“其他费用”分区。 */
  function resetOtherSection() {
    if (!snapshot.value) {
      message.warning('暂无可恢复的已保存配置');
      return;
    }
    const source = snapshot.value;
    form.otherFees = cloneOtherFees(source.otherFees);
    message.success('已重置其他费用');
  }

  /** 保存“起送与配送费”分区。 */
  async function saveDeliverySection() {
    if (!canOperate.value) return;
    isSavingDelivery.value = true;
    try {
      await saveCurrentSettings('起送与配送费已保存');
    } finally {
      isSavingDelivery.value = false;
    }
  }

  /** 保存“包装费设置”分区。 */
  async function savePackagingSection() {
    if (!canOperate.value) return;
    if (!validateCurrentPackaging()) return;
    isSavingPackaging.value = true;
    try {
      await saveCurrentSettings('包装费设置已保存');
    } finally {
      isSavingPackaging.value = false;
    }
  }

  /** 保存“其他费用”分区。 */
  async function saveOtherSection() {
    if (!canOperate.value) return;
    isSavingOther.value = true;
    try {
      await saveCurrentSettings('其他费用已保存');
    } finally {
      isSavingOther.value = false;
    }
  }

  /** 处理阶梯删除并保持包装模式合法。 */
  function onDeleteTier(tier: PackagingFeeTierDto) {
    handleDeleteTier(tier);
    if (
      form.packagingFeeMode === 'order' &&
      form.orderPackagingFeeMode === 'tiered' &&
      form.packagingFeeTiers.length === 0
    ) {
      message.warning('阶梯模式下至少需要一档，请添加后再保存');
    }
  }

  /** 设置是否启用阶梯包装费。 */
  function setTieredEnabled(value: boolean) {
    toggleTiered(value);
  }

  /** 切换门店时同步拉取配置。 */
  watch(selectedStoreId, async (storeId) => {
    isSwitchingPackagingMode.value = false;
    if (!storeId) {
      clearSettings();
      isConfigured.value = false;
      snapshot.value = null;
      return;
    }
    loadedStoreId.value = '';
    isConfigured.value = false;
    isTierDrawerOpen.value = false;
    await loadStoreSettings(storeId);
  });

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

  return {
    PACKAGING_MODE_OPTIONS,
    copyCandidates,
    copyTargetStoreIds,
    canOperate,
    form,
    formatCurrency,
    formatTierRange,
    handleCopyCheckAll,
    handleCopySubmit,
    handleSubmitTier,
    isCopyAllChecked,
    isCopyIndeterminate,
    isCopyModalOpen,
    isCopySubmitting,
    isConfigured,
    isOrderMode,
    isPageLoading,
    isSavingDelivery,
    isSavingOther,
    isSavingPackaging,
    isSwitchingPackagingMode,
    isStoreLoading,
    isTierDrawerOpen,
    loadedStoreId,
    onDeleteTier,
    openCopyModal,
    openTierDrawer,
    resetDeliverySection,
    resetFromSnapshot,
    resetOtherSection,
    resetPackagingSection,
    saveDeliverySection,
    saveOtherSection,
    savePackagingSection,
    hasLoadedStoreSettings,
    hasSelectedStore,
    selectedStoreId,
    selectedStoreName,
    setBaseDeliveryFee,
    setCopyModalOpen: (value: boolean) => {
      isCopyModalOpen.value = value;
    },
    setCutleryAmount,
    setCutleryEnabled,
    setFixedPackagingFee,
    setFreeDeliveryThreshold,
    setMinimumOrderAmount,
    setPlatformServiceRate,
    setPackagingMode,
    setRushAmount,
    setRushEnabled,
    setSelectedStoreId,
    setTierDrawerOpen,
    setTierFee,
    setTierMaxAmount,
    setTierMinAmount,
    setTieredEnabled,
    storeOptions,
    tierDrawerMode,
    tierDrawerTitle,
    tierForm,
    toggleCopyStore,
  };
}
