import type { Ref } from 'vue';

import type { ProductCategoryManageDto } from '#/api/product';
import type { StoreListItemDto } from '#/api/store';
import type { ProductPreviewItem } from '#/views/product/category/types';

/**
 * 文件职责：分类管理数据动作。
 * 1. 加载门店列表、分类列表与分类商品数据。
 * 2. 处理门店/分类切换时的数据一致性。
 */
import { message } from 'ant-design-vue';

import {
  getProductCategoryManageListApi,
  searchProductPickerApi,
} from '#/api/product';
import { getStoreListApi } from '#/api/store';
import { deriveMonthlySales } from '#/views/product/category/types';

import { normalizeCategoryChannels } from './constants';

interface CreateDataActionsOptions {
  categories: Ref<ProductCategoryManageDto[]>;
  categoryProducts: Ref<ProductPreviewItem[]>;
  isCategoryLoading: Ref<boolean>;
  isCategoryProductsLoading: Ref<boolean>;
  isStoreLoading: Ref<boolean>;
  selectedCategoryId: Ref<string>;
  selectedStoreId: Ref<string>;
  stores: Ref<StoreListItemDto[]>;
}

export function createDataActions(options: CreateDataActionsOptions) {
  async function loadStores() {
    options.isStoreLoading.value = true;
    try {
      const result = await getStoreListApi({
        page: 1,
        pageSize: 200,
      });
      options.stores.value = result.items ?? [];
      if (options.stores.value.length === 0) {
        options.selectedStoreId.value = '';
        return;
      }

      const hasSelected = options.stores.value.some(
        (item) => item.id === options.selectedStoreId.value,
      );

      if (!hasSelected) {
        options.selectedStoreId.value = options.stores.value[0]?.id ?? '';
      }
    } catch (error) {
      console.error(error);
      message.error('加载门店失败');
    } finally {
      options.isStoreLoading.value = false;
    }
  }

  async function loadCategoryProducts() {
    if (!options.selectedStoreId.value || !options.selectedCategoryId.value) {
      options.categoryProducts.value = [];
      return;
    }

    options.isCategoryProductsLoading.value = true;
    try {
      const list = await searchProductPickerApi({
        storeId: options.selectedStoreId.value,
        categoryId: options.selectedCategoryId.value,
        limit: 500,
      });
      options.categoryProducts.value = list.map((item) => ({
        ...item,
        monthlySales: deriveMonthlySales(item.id),
      }));
    } catch (error) {
      console.error(error);
      options.categoryProducts.value = [];
      message.error('加载分类商品失败');
    } finally {
      options.isCategoryProductsLoading.value = false;
    }
  }

  async function loadCategories(preferredCategoryId = '') {
    if (!options.selectedStoreId.value) {
      options.categories.value = [];
      options.selectedCategoryId.value = '';
      options.categoryProducts.value = [];
      return;
    }

    options.isCategoryLoading.value = true;
    const previousCategoryId = options.selectedCategoryId.value;
    try {
      const result = await getProductCategoryManageListApi({
        storeId: options.selectedStoreId.value,
      });

      options.categories.value = [...result]
        .map((item) => ({
          ...item,
          channels: normalizeCategoryChannels(item.channels),
        }))
        .toSorted((a, b) => a.sort - b.sort);

      const nextCategoryId =
        (preferredCategoryId &&
        options.categories.value.some((item) => item.id === preferredCategoryId)
          ? preferredCategoryId
          : '') ||
        (previousCategoryId &&
        options.categories.value.some((item) => item.id === previousCategoryId)
          ? previousCategoryId
          : '') ||
        options.categories.value[0]?.id ||
        '';

      options.selectedCategoryId.value = nextCategoryId;

      if (nextCategoryId && nextCategoryId === previousCategoryId) {
        await loadCategoryProducts();
      }
    } catch (error) {
      console.error(error);
      options.categories.value = [];
      options.selectedCategoryId.value = '';
      options.categoryProducts.value = [];
      message.error('加载分类失败');
    } finally {
      options.isCategoryLoading.value = false;
    }
  }

  return {
    loadCategories,
    loadCategoryProducts,
    loadStores,
  };
}
