import type { Ref } from 'vue';

import type { PackagingFeeTierDto } from '#/api/store-fees';
import type {
  FeesTierDrawerMode,
  PackagingFeeTierFormState,
  StoreFeesFormState,
} from '#/views/store/fees/types';

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

import {
  cloneTiers,
  createTierId,
  normalizeMoney,
  sortTiers,
  validateTierList,
} from './helpers';

interface CreatePackagingActionsOptions {
  form: StoreFeesFormState;
  isTierDrawerOpen: Ref<boolean>;
  tierDrawerMode: Ref<FeesTierDrawerMode>;
  tierForm: PackagingFeeTierFormState;
}

export function createPackagingActions(options: CreatePackagingActionsOptions) {
  /** 打开阶梯抽屉。 */
  function openTierDrawer(
    mode: FeesTierDrawerMode,
    tier?: PackagingFeeTierDto,
  ) {
    options.tierDrawerMode.value = mode;
    if (mode === 'edit' && tier) {
      options.tierForm.id = tier.id;
      options.tierForm.minAmount = tier.minAmount;
      options.tierForm.maxAmount = tier.maxAmount;
      options.tierForm.fee = tier.fee;
      options.isTierDrawerOpen.value = true;
      return;
    }

    const sorted = sortTiers(options.form.packagingFeeTiers);
    const lastTier = sorted[sorted.length - 1];
    const defaultMin =
      lastTier?.maxAmount === null
        ? normalizeMoney(lastTier.minAmount + 10, 0)
        : normalizeMoney(lastTier?.maxAmount ?? 0, 0);

    options.tierForm.id = '';
    options.tierForm.minAmount = defaultMin;
    options.tierForm.maxAmount = null;
    options.tierForm.fee = normalizeMoney(lastTier?.fee ?? 0, 0);
    options.isTierDrawerOpen.value = true;
  }

  /** 更新抽屉开关。 */
  function setTierDrawerOpen(value: boolean) {
    options.isTierDrawerOpen.value = value;
  }

  /** 更新阶梯起始金额。 */
  function setTierMinAmount(value: number) {
    options.tierForm.minAmount = normalizeMoney(
      value,
      options.tierForm.minAmount,
    );
  }

  /** 更新阶梯结束金额（空值表示无上限）。 */
  function setTierMaxAmount(value: null | number) {
    if (value === null || value === undefined) {
      options.tierForm.maxAmount = null;
      return;
    }
    options.tierForm.maxAmount = normalizeMoney(
      value,
      options.tierForm.minAmount,
    );
  }

  /** 更新阶梯包装费。 */
  function setTierFee(value: number) {
    options.tierForm.fee = normalizeMoney(value, options.tierForm.fee);
  }

  /** 切换包装费模式。 */
  function setPackagingFeeMode(value: StoreFeesFormState['packagingFeeMode']) {
    options.form.packagingFeeMode = value;
    if (value === 'item') {
      options.form.orderPackagingFeeMode = 'fixed';
    }
  }

  /** 切换是否启用阶梯包装费。 */
  function toggleTiered(checked: boolean) {
    options.form.orderPackagingFeeMode = checked ? 'tiered' : 'fixed';
  }

  /** 删除阶梯。 */
  function handleDeleteTier(tier: PackagingFeeTierDto) {
    options.form.packagingFeeTiers = options.form.packagingFeeTiers.filter(
      (item) => item.id !== tier.id,
    );
    message.success('阶梯已删除');
  }

  /** 校验抽屉表单。 */
  function validateTierForm() {
    if (options.tierForm.minAmount < 0) {
      message.error('起始金额不能小于 0');
      return false;
    }
    if (
      options.tierForm.maxAmount !== null &&
      options.tierForm.maxAmount <= options.tierForm.minAmount
    ) {
      message.error('结束金额必须大于起始金额');
      return false;
    }
    if (options.tierForm.fee < 0) {
      message.error('包装费不能小于 0');
      return false;
    }
    return true;
  }

  /** 提交阶梯表单（仅更新本地表单态）。 */
  function handleSubmitTier() {
    if (!validateTierForm()) return false;

    const tier: PackagingFeeTierDto = {
      id: options.tierForm.id || createTierId(),
      minAmount: normalizeMoney(options.tierForm.minAmount, 0),
      maxAmount:
        options.tierForm.maxAmount === null
          ? null
          : normalizeMoney(
              options.tierForm.maxAmount,
              options.tierForm.minAmount,
            ),
      fee: normalizeMoney(options.tierForm.fee, 0),
      sort: 0,
    };

    const nextList = cloneTiers(options.form.packagingFeeTiers);
    if (options.tierDrawerMode.value === 'edit') {
      const index = nextList.findIndex((item) => item.id === tier.id);
      if (index === -1) nextList.push(tier);
      else nextList[index] = tier;
    } else {
      nextList.push(tier);
    }

    const sorted = sortTiers(nextList).map((item, index) => ({
      ...item,
      sort: index + 1,
    }));
    const validationError = validateTierList(sorted);
    if (validationError) {
      message.error(validationError);
      return false;
    }

    options.form.packagingFeeTiers = sorted;
    options.isTierDrawerOpen.value = false;
    message.success(
      options.tierDrawerMode.value === 'edit' ? '阶梯已更新' : '阶梯已添加',
    );
    return true;
  }

  /** 校验当前包装费配置（保存前调用）。 */
  function validateCurrentPackaging() {
    if (options.form.packagingFeeMode === 'item') return true;

    if (options.form.fixedPackagingFee < 0) {
      message.error('固定包装费不能小于 0');
      return false;
    }

    if (options.form.orderPackagingFeeMode !== 'tiered') return true;

    const validationError = validateTierList(options.form.packagingFeeTiers);
    if (validationError) {
      message.error(validationError);
      return false;
    }
    return true;
  }

  return {
    handleDeleteTier,
    handleSubmitTier,
    openTierDrawer,
    setPackagingFeeMode,
    setTierDrawerOpen,
    setTierFee,
    setTierMaxAmount,
    setTierMinAmount,
    toggleTiered,
    validateCurrentPackaging,
  };
}
