/**
 * 文件职责：商品列表数据加载动作。
 * 1. 加载门店、分类、列表数据。
 * 2. 管理列表与分类的 loading 状态。
 */
import type { Ref } from 'vue';

import type { ProductCategoryDto, ProductListItemDto } from '#/api/product';
import type { StoreListItemDto } from '#/api/store';
import type { ProductFilterState } from '#/views/product/list/types';

import { getProductCategoryListApi, getProductListApi } from '#/api/product';
import { getStoreListApi } from '#/api/store';

interface CreateDataActionsOptions {
  categories: Ref<ProductCategoryDto[]>;
  filters: ProductFilterState;
  isCategoryLoading: Ref<boolean>;
  isListLoading: Ref<boolean>;
  isStoreLoading: Ref<boolean>;
  products: Ref<ProductListItemDto[]>;
  selectedStoreId: Ref<string>;
  stores: Ref<StoreListItemDto[]>;
  total: Ref<number>;
}

export function createDataActions(options: CreateDataActionsOptions) {
  /** 加载门店列表并设置默认门店。 */
  async function loadStores() {
    options.isStoreLoading.value = true;
    try {
      const result = await getStoreListApi({
        keyword: undefined,
        businessStatus: undefined,
        auditStatus: undefined,
        serviceType: undefined,
        page: 1,
        pageSize: 200,
      });
      options.stores.value = result.items ?? [];

      if (options.stores.value.length === 0) {
        options.selectedStoreId.value = '';
        options.categories.value = [];
        options.products.value = [];
        options.total.value = 0;
        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);
    } finally {
      options.isStoreLoading.value = false;
    }
  }

  /** 加载商品分类（全量口径，不受筛选影响）。 */
  async function loadCategories() {
    if (!options.selectedStoreId.value) {
      options.categories.value = [];
      return;
    }

    options.isCategoryLoading.value = true;
    try {
      options.categories.value = await getProductCategoryListApi(
        options.selectedStoreId.value,
      );
    } catch (error) {
      console.error(error);
      options.categories.value = [];
    } finally {
      options.isCategoryLoading.value = false;
    }
  }

  /** 加载商品列表。 */
  async function loadProducts() {
    if (!options.selectedStoreId.value) {
      options.products.value = [];
      options.total.value = 0;
      return;
    }

    options.isListLoading.value = true;
    try {
      const result = await getProductListApi({
        storeId: options.selectedStoreId.value,
        categoryId: options.filters.categoryId || undefined,
        keyword: options.filters.keyword.trim() || undefined,
        status: options.filters.status || undefined,
        kind: options.filters.kind || undefined,
        page: options.filters.page,
        pageSize: options.filters.pageSize,
      });

      options.products.value = result.items ?? [];
      options.total.value = result.total ?? 0;
    } catch (error) {
      console.error(error);
      options.products.value = [];
      options.total.value = 0;
    } finally {
      options.isListLoading.value = false;
    }
  }

  /** 同步刷新当前门店分类与列表。 */
  async function reloadCurrentStoreData() {
    await Promise.all([loadCategories(), loadProducts()]);
  }

  return {
    loadCategories,
    loadProducts,
    loadStores,
    reloadCurrentStoreData,
  };
}
