import type { Ref } from 'vue';

import type {
  MarketingFlashSaleChannel,
  MarketingFlashSaleCycleType,
  MarketingFlashSaleRecurringDateMode,
} from '#/api/marketing';
import type { StoreListItemDto } from '#/api/store';
import type {
  FlashSaleEditorForm,
  FlashSaleEditorProductForm,
} from '#/views/marketing/flash-sale/types';

/**
 * 文件职责：限时折扣主编辑抽屉动作。
 */
import { ref } from 'vue';

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

import {
  getMarketingFlashSaleDetailApi,
  saveMarketingFlashSaleApi,
} from '#/api/marketing';

import { createDefaultFlashSaleEditorForm } from './constants';
import {
  buildSaveFlashSalePayload,
  cloneProductForm,
  mapDetailToEditorForm,
  resolveDiscountRateLabel,
} from './helpers';

interface CreateDrawerActionsOptions {
  form: FlashSaleEditorForm;
  isDrawerLoading: Ref<boolean>;
  isDrawerOpen: Ref<boolean>;
  isDrawerSubmitting: Ref<boolean>;
  loadActivities: () => Promise<void>;
  openPicker: (
    pickerOptions: {
      selectedProductIds: string[];
      selectedProducts: FlashSaleEditorProductForm[];
      storeId: string;
    },
    onConfirm: (products: FlashSaleEditorProductForm[]) => void,
  ) => Promise<void>;
  resolveOperationStoreId: (preferredStoreIds?: string[]) => string;
  selectedStoreId: Ref<string>;
  stores: Ref<StoreListItemDto[]>;
}

export function createDrawerActions(options: CreateDrawerActionsOptions) {
  const drawerMode = ref<'create' | 'edit'>('create');

  function setDrawerOpen(value: boolean) {
    options.isDrawerOpen.value = value;
  }

  function applyForm(next: FlashSaleEditorForm) {
    options.form.id = next.id;
    options.form.name = next.name;
    options.form.cycleType = next.cycleType;
    options.form.recurringDateMode = next.recurringDateMode;
    options.form.validDateRange = next.validDateRange;
    options.form.timeRange = next.timeRange;
    options.form.weekDays = [...next.weekDays];
    options.form.channels = [...next.channels];
    options.form.perUserLimit = next.perUserLimit;
    options.form.products = next.products.map((item) => cloneProductForm(item));
    options.form.metrics = { ...next.metrics };
    options.form.status = next.status;
    options.form.storeIds = [...next.storeIds];
  }

  function resetForm() {
    applyForm(createDefaultFlashSaleEditorForm());
  }

  function setFormName(value: string) {
    options.form.name = value;
  }

  function setFormCycleType(value: MarketingFlashSaleCycleType) {
    options.form.cycleType = value;
    if (value === 'once') {
      options.form.recurringDateMode = 'fixed';
      options.form.weekDays = [];
    } else if (options.form.weekDays.length === 0) {
      options.form.weekDays = [4];
    }
  }

  function setFormRecurringDateMode(
    value: MarketingFlashSaleRecurringDateMode,
  ) {
    options.form.recurringDateMode = value;
    if (value === 'long_term' && options.form.validDateRange) {
      // 长期模式允许保留日期范围；仅在用户清空时不强制校验。
    }
  }

  function setFormValidDateRange(value: FlashSaleEditorForm['validDateRange']) {
    options.form.validDateRange = value;
  }

  function setFormTimeRange(value: FlashSaleEditorForm['timeRange']) {
    options.form.timeRange = value;
  }

  function toggleWeekDay(day: number) {
    if (options.form.weekDays.includes(day)) {
      options.form.weekDays = options.form.weekDays.filter(
        (item) => item !== day,
      );
      return;
    }
    options.form.weekDays = [...options.form.weekDays, day].toSorted(
      (first, second) => first - second,
    );
  }

  function quickSelectWeekDays(mode: 'all' | 'weekday' | 'weekend') {
    if (mode === 'all') {
      options.form.weekDays = [1, 2, 3, 4, 5, 6, 7];
      return;
    }
    if (mode === 'weekday') {
      options.form.weekDays = [1, 2, 3, 4, 5];
      return;
    }
    options.form.weekDays = [6, 7];
  }

  function setFormChannels(value: MarketingFlashSaleChannel[]) {
    options.form.channels = [...new Set(value)];
  }

  function toggleChannel(channel: MarketingFlashSaleChannel) {
    if (options.form.channels.includes(channel)) {
      setFormChannels(options.form.channels.filter((item) => item !== channel));
      return;
    }
    setFormChannels([...options.form.channels, channel]);
  }

  function setFormPerUserLimit(value: null | number) {
    options.form.perUserLimit = normalizeNullableInteger(value);
  }

  function setProductDiscountPrice(index: number, value: null | number) {
    const row = options.form.products[index];
    if (!row) {
      return;
    }
    row.discountPrice = normalizeNullableNumber(value);
    options.form.products = [...options.form.products];
  }

  function setProductPerUserLimit(index: number, value: null | number) {
    const row = options.form.products[index];
    if (!row) {
      return;
    }
    row.perUserLimit = normalizeNullableInteger(value);
    options.form.products = [...options.form.products];
  }

  function removeProduct(index: number) {
    options.form.products = options.form.products.filter(
      (_, rowIndex) => rowIndex !== index,
    );
  }

  async function openProductPicker() {
    const operationStoreId = resolveScopeStoreId();
    if (!operationStoreId) {
      message.warning('请选择具体门店后再添加商品');
      return;
    }

    await options.openPicker(
      {
        storeId: operationStoreId,
        selectedProducts: options.form.products.map((item) =>
          cloneProductForm(item),
        ),
        selectedProductIds: options.form.products.map((item) => item.productId),
      },
      (products) => {
        const currentById = new Map(
          options.form.products.map((item) => [item.productId, item]),
        );
        const merged = products.map((item) => {
          const existing = currentById.get(item.productId);
          return existing ? cloneProductForm(existing) : cloneProductForm(item);
        });
        options.form.products = merged;
      },
    );
  }

  async function openCreateDrawer() {
    if (!options.selectedStoreId.value) {
      message.warning('请选择具体门店后再创建活动');
      return;
    }

    resetForm();
    options.form.storeIds = [options.selectedStoreId.value];
    drawerMode.value = 'create';
    options.isDrawerOpen.value = true;
  }

  async function openEditDrawer(
    activityId: string,
    preferredStoreIds: string[] = [],
  ) {
    const operationStoreId = options.resolveOperationStoreId(preferredStoreIds);
    if (!operationStoreId) {
      return;
    }

    options.isDrawerLoading.value = true;
    try {
      const detail = await getMarketingFlashSaleDetailApi({
        storeId: operationStoreId,
        activityId,
      });
      const mapped = mapDetailToEditorForm(detail);
      if (mapped.storeIds.length === 0) {
        mapped.storeIds = [operationStoreId];
      }
      applyForm(mapped);
      drawerMode.value = 'edit';
      options.isDrawerOpen.value = true;
    } catch (error) {
      console.error(error);
      message.error('加载活动详情失败');
    } finally {
      options.isDrawerLoading.value = false;
    }
  }

  async function submitDrawer() {
    const operationStoreId = options.resolveOperationStoreId(
      options.form.storeIds,
    );
    if (!operationStoreId) {
      message.warning('请选择可操作门店');
      return;
    }

    if (!validateBeforeSubmit(operationStoreId)) {
      return;
    }

    options.isDrawerSubmitting.value = true;
    try {
      await saveMarketingFlashSaleApi(
        buildSaveFlashSalePayload(options.form, operationStoreId),
      );
      message.success(
        drawerMode.value === 'create' ? '活动已创建' : '活动已更新',
      );
      options.isDrawerOpen.value = false;
      await options.loadActivities();
    } catch (error) {
      console.error(error);
    } finally {
      options.isDrawerSubmitting.value = false;
    }
  }

  function validateBeforeSubmit(operationStoreId: string) {
    const normalizedName = options.form.name.trim();
    if (!normalizedName) {
      message.warning('请输入活动名称');
      return false;
    }
    if (normalizedName.length > 64) {
      message.warning('活动名称长度不能超过 64 个字符');
      return false;
    }

    if (options.form.storeIds.length === 0) {
      message.warning('活动门店不能为空');
      return false;
    }
    if (!options.form.storeIds.includes(operationStoreId)) {
      message.warning('活动门店必须包含当前操作门店');
      return false;
    }

    if (options.form.cycleType === 'once' && !options.form.validDateRange) {
      message.warning('请选择活动时间');
      return false;
    }

    if (options.form.cycleType === 'recurring') {
      if (options.form.weekDays.length === 0) {
        message.warning('请选择循环日期');
        return false;
      }
      if (
        options.form.recurringDateMode === 'fixed' &&
        !options.form.validDateRange
      ) {
        message.warning('请选择周期活动日期区间');
        return false;
      }
    }

    if (options.form.channels.length === 0) {
      message.warning('请至少选择一个适用渠道');
      return false;
    }

    if (options.form.perUserLimit !== null && options.form.perUserLimit <= 0) {
      message.warning('每人限购必须大于 0');
      return false;
    }

    if (options.form.products.length === 0) {
      message.warning('请至少添加一个折扣商品');
      return false;
    }

    for (const row of options.form.products) {
      if (!row.productId) {
        message.warning('商品数据异常，请重新选择商品');
        return false;
      }
      if (!row.discountPrice || row.discountPrice <= 0) {
        message.warning(`商品「${row.name}」折扣价必须大于 0`);
        return false;
      }
      if (row.discountPrice > row.originalPrice) {
        message.warning(`商品「${row.name}」折扣价不能高于原价`);
        return false;
      }
      if (row.perUserLimit !== null && row.perUserLimit <= 0) {
        message.warning(`商品「${row.name}」限购必须大于 0`);
        return false;
      }
      if (
        options.form.perUserLimit &&
        row.perUserLimit &&
        row.perUserLimit > options.form.perUserLimit
      ) {
        message.warning(`商品「${row.name}」限购不能大于活动每人限购`);
        return false;
      }

      if (
        resolveDiscountRateLabel(row.originalPrice, row.discountPrice) === '-'
      ) {
        message.warning(`商品「${row.name}」折扣价配置不合法`);
        return false;
      }
    }

    return true;
  }

  function resolveScopeStoreId() {
    if (options.selectedStoreId.value) {
      return options.selectedStoreId.value;
    }

    if (options.form.storeIds.length > 0) {
      return options.form.storeIds[0] ?? '';
    }

    return options.stores.value[0]?.id ?? '';
  }

  return {
    drawerMode,
    openCreateDrawer,
    openEditDrawer,
    openProductPicker,
    quickSelectWeekDays,
    removeProduct,
    setDrawerOpen,
    setFormChannels,
    setFormCycleType,
    setFormName,
    setFormPerUserLimit,
    setFormRecurringDateMode,
    setFormTimeRange,
    setFormValidDateRange,
    setProductDiscountPrice,
    setProductPerUserLimit,
    submitDrawer,
    toggleChannel,
    toggleWeekDay,
  };
}

function normalizeNullableNumber(value: null | number) {
  if (value === null || value === undefined) {
    return null;
  }
  const numeric = Number(value);
  if (Number.isNaN(numeric)) {
    return null;
  }
  return Number(numeric.toFixed(2));
}

function normalizeNullableInteger(value: null | number) {
  if (value === null || value === undefined) {
    return null;
  }
  const numeric = Number(value);
  if (Number.isNaN(numeric)) {
    return null;
  }
  return Math.max(0, Math.floor(numeric));
}
