/**
 * 文件职责：商品抽屉与单项动作。
 * 1. 维护添加/编辑、快速编辑、沽清抽屉打开与提交流程。
 * 2. 处理单商品删除与状态切换动作。
 */
import type { Ref } from 'vue';

import type { ProductListItemDto, ProductStatus } from '#/api/product';
import type {
  ProductEditorDrawerMode,
  ProductEditorFormState,
  ProductQuickEditFormState,
  ProductSoldoutFormState,
} from '#/views/product/list/types';

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

import {
  changeProductStatusApi,
  deleteProductApi,
  getProductDetailApi,
  saveProductApi,
  soldoutProductApi,
} from '#/api/product';

import {
  formatDateTime,
  mapDetailToEditorForm,
  mapListItemToEditorForm,
  mapListItemToQuickEditForm,
  mapListItemToSoldoutForm,
  toSavePayload,
} from './helpers';

interface CreateDrawerActionsOptions {
  clearSelection: () => void;
  currentQuickEditProduct: Ref<null | ProductListItemDto>;
  currentSoldoutProduct: Ref<null | ProductListItemDto>;
  editorDrawerMode: Ref<ProductEditorDrawerMode>;
  editorForm: ProductEditorFormState;
  isEditorDrawerOpen: Ref<boolean>;
  isEditorSubmitting: Ref<boolean>;
  isQuickEditDrawerOpen: Ref<boolean>;
  isQuickEditSubmitting: Ref<boolean>;
  isSoldoutDrawerOpen: Ref<boolean>;
  isSoldoutSubmitting: Ref<boolean>;
  quickEditForm: ProductQuickEditFormState;
  reloadCurrentStoreData: () => Promise<void>;
  selectedStoreId: Ref<string>;
  soldoutForm: ProductSoldoutFormState;
}

export function createDrawerActions(options: CreateDrawerActionsOptions) {
  /** 打开添加商品抽屉。 */
  function openCreateDrawer(defaultCategoryId: string) {
    options.editorDrawerMode.value = 'create';
    options.editorForm.id = '';
    options.editorForm.name = '';
    options.editorForm.subtitle = '';
    options.editorForm.description = '';
    options.editorForm.comboGroups = [];
    options.editorForm.imageUrls = [];
    options.editorForm.categoryId = defaultCategoryId;
    options.editorForm.kind = 'single';
    options.editorForm.price = 0;
    options.editorForm.originalPrice = null;
    options.editorForm.stock = 0;
    options.editorForm.tagsText = '';
    options.editorForm.status = 'off_shelf';
    options.editorForm.shelfMode = 'draft';
    options.editorForm.timedOnShelfAt = '';
    options.isEditorDrawerOpen.value = true;
  }

  /** 打开编辑商品抽屉并尽量补全详情。 */
  async function openEditDrawer(item: ProductListItemDto) {
    options.editorDrawerMode.value = 'edit';
    Object.assign(options.editorForm, mapListItemToEditorForm(item));
    options.isEditorDrawerOpen.value = true;

    if (!options.selectedStoreId.value) return;
    try {
      const detail = await getProductDetailApi({
        storeId: options.selectedStoreId.value,
        productId: item.id,
      });
      Object.assign(options.editorForm, mapDetailToEditorForm(detail));
    } catch (error) {
      console.error(error);
    }
  }

  /** 提交添加/编辑商品。 */
  async function submitEditor() {
    if (!options.selectedStoreId.value) return;

    if (!options.editorForm.name.trim()) {
      message.warning('请输入商品名称');
      return;
    }
    if (!options.editorForm.categoryId) {
      message.warning('请选择商品分类');
      return;
    }
    if (
      options.editorForm.shelfMode === 'scheduled' &&
      !options.editorForm.timedOnShelfAt
    ) {
      message.warning('请选择定时上架时间');
      return;
    }
    if (options.editorForm.kind === 'combo') {
      if (options.editorForm.comboGroups.length === 0) {
        message.warning('套餐至少需要一个分组');
        return;
      }

      for (const group of options.editorForm.comboGroups) {
        if (!group.name.trim()) {
          message.warning('请填写套餐分组名称');
          return;
        }
        if (group.minSelect <= 0 || group.maxSelect <= 0) {
          message.warning(`分组「${group.name}」的最小/最大选择数必须大于 0`);
          return;
        }
        if (group.maxSelect < group.minSelect) {
          message.warning(
            `分组「${group.name}」的最大选择数不能小于最小选择数`,
          );
          return;
        }
        if (group.items.length === 0) {
          message.warning(`分组「${group.name}」至少需要一个商品`);
          return;
        }
        if (group.items.some((item) => item.quantity <= 0)) {
          message.warning(`分组「${group.name}」的商品数量必须大于 0`);
          return;
        }
      }
    }

    options.isEditorSubmitting.value = true;
    try {
      await saveProductApi(
        toSavePayload(options.editorForm, options.selectedStoreId.value),
      );
      message.success(
        options.editorDrawerMode.value === 'edit' ? '商品已保存' : '商品已添加',
      );
      options.isEditorDrawerOpen.value = false;
      options.clearSelection();
      await options.reloadCurrentStoreData();
    } catch (error) {
      console.error(error);
    } finally {
      options.isEditorSubmitting.value = false;
    }
  }

  /** 打开快速编辑抽屉。 */
  function openQuickEditDrawer(item: ProductListItemDto) {
    options.currentQuickEditProduct.value = item;
    Object.assign(options.quickEditForm, mapListItemToQuickEditForm(item));
    options.isQuickEditDrawerOpen.value = true;
  }

  /** 提交快速编辑。 */
  async function submitQuickEdit() {
    if (!options.selectedStoreId.value) return;
    if (!options.currentQuickEditProduct.value) return;

    const current = options.currentQuickEditProduct.value;
    options.isQuickEditSubmitting.value = true;
    try {
      const detail = await getProductDetailApi({
        storeId: options.selectedStoreId.value,
        productId: current.id,
      });

      await saveProductApi({
        id: current.id,
        storeId: options.selectedStoreId.value,
        categoryId: detail.categoryId,
        kind: detail.kind,
        name: detail.name,
        subtitle: detail.subtitle,
        description: detail.description,
        price: Number(options.quickEditForm.price || 0),
        originalPrice:
          Number(options.quickEditForm.originalPrice || 0) > 0
            ? Number(options.quickEditForm.originalPrice)
            : null,
        stock: Math.max(
          0,
          Math.floor(Number(options.quickEditForm.stock || 0)),
        ),
        tags: [...detail.tags],
        comboGroups: (detail.comboGroups ?? []).map((group) => ({
          name: group.name,
          minSelect: group.minSelect,
          maxSelect: group.maxSelect,
          sortOrder: group.sortOrder,
          items: group.items.map((item) => ({
            productId: item.productId,
            quantity: item.quantity,
            sortOrder: item.sortOrder,
          })),
        })),
        imageUrls: detail.imageUrls ?? [],
        status: options.quickEditForm.isOnSale ? 'on_sale' : 'off_shelf',
        shelfMode: options.quickEditForm.isOnSale ? 'now' : 'draft',
        spuCode: detail.spuCode,
      });
      message.success('商品已更新');
      options.isQuickEditDrawerOpen.value = false;
      options.clearSelection();
      await options.reloadCurrentStoreData();
    } catch (error) {
      console.error(error);
    } finally {
      options.isQuickEditSubmitting.value = false;
    }
  }

  /** 打开沽清抽屉。 */
  function openSoldoutDrawer(item: ProductListItemDto) {
    options.currentSoldoutProduct.value = item;
    Object.assign(options.soldoutForm, mapListItemToSoldoutForm(item));
    options.isSoldoutDrawerOpen.value = true;
  }

  /** 提交沽清设置。 */
  async function submitSoldout() {
    if (!options.selectedStoreId.value) return;
    if (!options.currentSoldoutProduct.value) return;

    if (
      options.soldoutForm.mode === 'timed' &&
      !options.soldoutForm.recoverAt
    ) {
      message.warning('请选择恢复时间');
      return;
    }

    options.isSoldoutSubmitting.value = true;
    try {
      await soldoutProductApi({
        storeId: options.selectedStoreId.value,
        productId: options.currentSoldoutProduct.value.id,
        mode: options.soldoutForm.mode,
        remainStock: Math.max(0, Math.floor(options.soldoutForm.remainStock)),
        reason: options.soldoutForm.reason.trim(),
        recoverAt:
          options.soldoutForm.mode === 'timed' && options.soldoutForm.recoverAt
            ? formatDateTime(options.soldoutForm.recoverAt)
            : undefined,
        syncToPlatform: options.soldoutForm.syncToPlatform,
        notifyManager: options.soldoutForm.notifyManager,
      });
      message.success('商品已沽清');
      options.isSoldoutDrawerOpen.value = false;
      options.clearSelection();
      await options.reloadCurrentStoreData();
    } catch (error) {
      console.error(error);
    } finally {
      options.isSoldoutSubmitting.value = false;
    }
  }

  /** 删除单个商品。 */
  async function deleteProduct(item: ProductListItemDto) {
    if (!options.selectedStoreId.value) return;
    try {
      await deleteProductApi({
        storeId: options.selectedStoreId.value,
        productId: item.id,
      });
      message.success('商品已删除');
      options.clearSelection();
      await options.reloadCurrentStoreData();
    } catch (error) {
      console.error(error);
    }
  }

  /** 切换单个商品状态。 */
  async function changeProductStatus(
    item: ProductListItemDto,
    status: ProductStatus,
  ) {
    if (!options.selectedStoreId.value) return;
    try {
      await changeProductStatusApi({
        storeId: options.selectedStoreId.value,
        productId: item.id,
        status,
      });
      message.success(status === 'on_sale' ? '商品已上架' : '商品已下架');
      options.clearSelection();
      await options.reloadCurrentStoreData();
    } catch (error) {
      console.error(error);
    }
  }

  /** 切换添加/编辑抽屉显隐。 */
  function setEditorDrawerOpen(value: boolean) {
    options.isEditorDrawerOpen.value = value;
  }

  /** 切换快速编辑抽屉显隐。 */
  function setQuickEditDrawerOpen(value: boolean) {
    options.isQuickEditDrawerOpen.value = value;
  }

  /** 切换沽清抽屉显隐。 */
  function setSoldoutDrawerOpen(value: boolean) {
    options.isSoldoutDrawerOpen.value = value;
  }

  return {
    changeProductStatus,
    deleteProduct,
    openCreateDrawer,
    openEditDrawer,
    openQuickEditDrawer,
    openSoldoutDrawer,
    setEditorDrawerOpen,
    setQuickEditDrawerOpen,
    setSoldoutDrawerOpen,
    submitEditor,
    submitQuickEdit,
    submitSoldout,
  };
}
