import type { Ref } from 'vue';

import type { BatchCategoryOption, BatchProductOption } from '../../types';

import type { ProductPickerItemDto } from '#/api/product';
import type { StoreListItemDto } from '#/api/store';

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

import {
  getProductCategoryManageListApi,
  searchProductPickerApi,
} from '#/api/product';
import { getStoreListApi } from '#/api/store';

import { toBatchCategoryOptions, toBatchProductOptions } from '../../types';

interface CreateBatchDataActionsOptions {
  categoryOptions: Ref<BatchCategoryOption[]>;
  isCategoryLoading: Ref<boolean>;
  isProductLoading: Ref<boolean>;
  isStoreLoading: Ref<boolean>;
  productOptions: Ref<BatchProductOption[]>;
  selectedStoreId: Ref<string>;
  stores: Ref<StoreListItemDto[]>;
}

/**
 * 文件职责：批量工具页数据加载。
 * 1. 加载门店列表。
 * 2. 基于门店加载分类和商品选择器数据。
 */
export function createBatchDataActions(options: CreateBatchDataActionsOptions) {
  async function loadStores() {
    options.isStoreLoading.value = true;
    try {
      const result = await getStoreListApi({
        page: 1,
        pageSize: 200,
      });
      const rows = result.items ?? [];
      options.stores.value = rows;
      if (rows.length === 0) {
        options.selectedStoreId.value = '';
        return;
      }

      const hasCurrent = rows.some(
        (item) => item.id === options.selectedStoreId.value,
      );
      if (!hasCurrent) {
        options.selectedStoreId.value = rows[0]?.id ?? '';
      }
    } catch (error) {
      console.error(error);
      message.error('加载门店失败');
    } finally {
      options.isStoreLoading.value = false;
    }
  }

  async function loadStoreScopedData() {
    if (!options.selectedStoreId.value) {
      options.categoryOptions.value = [];
      options.productOptions.value = [];
      return;
    }

    options.isCategoryLoading.value = true;
    options.isProductLoading.value = true;
    try {
      const [categories, products] = await Promise.all([
        getProductCategoryManageListApi({
          storeId: options.selectedStoreId.value,
        }),
        searchProductPickerApi({
          storeId: options.selectedStoreId.value,
          limit: 500,
        }),
      ]);

      options.categoryOptions.value = toBatchCategoryOptions(categories);
      options.productOptions.value = toBatchProductOptions(
        products as ProductPickerItemDto[],
      );
    } catch (error) {
      console.error(error);
      options.categoryOptions.value = [];
      options.productOptions.value = [];
      message.error('加载批量工具数据失败');
    } finally {
      options.isCategoryLoading.value = false;
      options.isProductLoading.value = false;
    }
  }

  return {
    loadStoreScopedData,
    loadStores,
  };
}
