import type { Ref } from 'vue';

/**
 * 文件职责：半径梯度编辑动作。
 * 1. 管理梯度抽屉开关与表单赋值。
 * 2. 处理梯度新增、编辑、删除。
 */
import type { RadiusTierDto } from '#/api/store-delivery';
import type {
  DeliveryDrawerMode,
  RadiusTierFormState,
} from '#/views/store/delivery/types';

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

interface CreateTierActionsOptions {
  createTierId: () => string;
  getTierColorByIndex: (index: number) => string;
  isTierDrawerOpen: Ref<boolean>;
  radiusTiers: Ref<RadiusTierDto[]>;
  sortRadiusTiers: (source: RadiusTierDto[]) => RadiusTierDto[];
  tierDrawerMode: Ref<DeliveryDrawerMode>;
  tierForm: RadiusTierFormState;
}

export function createTierActions(options: CreateTierActionsOptions) {
  /** 打开新增/编辑梯度抽屉，并填充表单。 */
  function openTierDrawer(mode: DeliveryDrawerMode, tier?: RadiusTierDto) {
    options.tierDrawerMode.value = mode;

    if (mode === 'edit' && tier) {
      options.tierForm.id = tier.id;
      options.tierForm.minDistance = tier.minDistance;
      options.tierForm.maxDistance = tier.maxDistance;
      options.tierForm.deliveryFee = tier.deliveryFee;
      options.tierForm.etaMinutes = tier.etaMinutes;
      options.tierForm.minOrderAmount = tier.minOrderAmount;
      options.tierForm.color = tier.color;
      options.isTierDrawerOpen.value = true;
      return;
    }

    const sorted = options.sortRadiusTiers(options.radiusTiers.value);
    const lastTier = sorted.at(-1);
    const nextMin = Number(lastTier?.maxDistance ?? 0);
    options.tierForm.id = '';
    options.tierForm.minDistance = nextMin;
    options.tierForm.maxDistance = nextMin + 1;
    options.tierForm.deliveryFee = Number(lastTier?.deliveryFee ?? 5);
    options.tierForm.etaMinutes = Number(lastTier?.etaMinutes ?? 30);
    options.tierForm.minOrderAmount = Number(lastTier?.minOrderAmount ?? 20);
    options.tierForm.color = options.getTierColorByIndex(
      options.radiusTiers.value.length,
    );
    options.isTierDrawerOpen.value = true;
  }

  /** 切换梯度抽屉可见性。 */
  function setTierDrawerOpen(value: boolean) {
    options.isTierDrawerOpen.value = value;
  }

  /** 更新梯度表单最小距离。 */
  function setTierMinDistance(value: number) {
    options.tierForm.minDistance = Math.max(0, Number(value || 0));
  }

  /** 更新梯度表单最大距离。 */
  function setTierMaxDistance(value: number) {
    options.tierForm.maxDistance = Math.max(0, Number(value || 0));
  }

  /** 更新梯度表单配送费。 */
  function setTierDeliveryFee(value: number) {
    options.tierForm.deliveryFee = Math.max(0, Number(value || 0));
  }

  /** 更新梯度表单预计送达时间。 */
  function setTierEtaMinutes(value: number) {
    options.tierForm.etaMinutes = Math.max(1, Number(value || 1));
  }

  /** 更新梯度表单起送金额。 */
  function setTierMinOrderAmount(value: number) {
    options.tierForm.minOrderAmount = Math.max(0, Number(value || 0));
  }

  /** 更新梯度表单颜色。 */
  function setTierColor(value: string) {
    options.tierForm.color = value || '#1677ff';
  }

  /** 提交梯度表单并更新列表。 */
  function handleTierSubmit() {
    // 1. 校验区间与字段合法性。
    if (options.tierForm.maxDistance <= options.tierForm.minDistance) {
      message.error('结束距离必须大于起始距离');
      return false;
    }

    if (
      options.tierForm.deliveryFee < 0 ||
      options.tierForm.minOrderAmount < 0
    ) {
      message.error('金额字段不能小于 0');
      return false;
    }

    // 2. 校验与现有梯度区间冲突。
    const hasOverlap = options.radiusTiers.value.some((item) => {
      if (item.id === options.tierForm.id) return false;
      const isDisjoint =
        options.tierForm.maxDistance <= item.minDistance ||
        options.tierForm.minDistance >= item.maxDistance;
      return !isDisjoint;
    });
    if (hasOverlap) {
      message.error('距离区间与已有梯度重叠，请调整后重试');
      return false;
    }

    // 3. 组装记录并写回列表。
    const record: RadiusTierDto = {
      id: options.tierForm.id || options.createTierId(),
      minDistance: options.tierForm.minDistance,
      maxDistance: options.tierForm.maxDistance,
      deliveryFee: options.tierForm.deliveryFee,
      etaMinutes: options.tierForm.etaMinutes,
      minOrderAmount: options.tierForm.minOrderAmount,
      color: options.tierForm.color,
    };

    options.radiusTiers.value =
      options.tierDrawerMode.value === 'edit' && options.tierForm.id
        ? options.sortRadiusTiers(
            options.radiusTiers.value.map((item) =>
              item.id === options.tierForm.id ? record : item,
            ),
          )
        : options.sortRadiusTiers([...options.radiusTiers.value, record]);

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

  /** 删除指定梯度。 */
  function handleDeleteTier(tierId: string) {
    if (options.radiusTiers.value.length <= 1) {
      message.warning('至少保留一个梯度');
      return false;
    }
    options.radiusTiers.value = options.radiusTiers.value.filter(
      (item) => item.id !== tierId,
    );
    message.success('梯度已删除');
    return true;
  }

  return {
    handleDeleteTier,
    handleTierSubmit,
    openTierDrawer,
    setTierColor,
    setTierDeliveryFee,
    setTierDrawerOpen,
    setTierEtaMinutes,
    setTierMaxDistance,
    setTierMinDistance,
    setTierMinOrderAmount,
  };
}
