import type { OrderAllFilterState, OrderAllPaginationState } from '../../types';

import type { OrderAllListItemDto, OrderAllStatsDto } from '#/api/order';
import type { StoreListItemDto } from '#/api/store';

import { getOrderAllListApi, getOrderAllStatsApi } from '#/api/order';
import { getStoreListApi } from '#/api/store';

import { buildQueryPayload } from './helpers';

interface DataActionOptions {
  filters: OrderAllFilterState;
  isListLoading: { value: boolean };
  isStatsLoading: { value: boolean };
  isStoreLoading: { value: boolean };
  pagination: OrderAllPaginationState;
  rows: { value: OrderAllListItemDto[] };
  selectedStoreId: { value: string };
  stats: OrderAllStatsDto;
  stores: { value: StoreListItemDto[] };
}

/**
 * 文件职责：全部订单数据加载动作。
 */
export function createDataActions(options: DataActionOptions) {
  function resetStats() {
    options.stats.totalOrders = 0;
    options.stats.totalAmount = 0;
    options.stats.averageAmount = 0;
    options.stats.refundCount = 0;
  }

  async function loadStores() {
    options.isStoreLoading.value = true;
    try {
      const result = await getStoreListApi({ page: 1, pageSize: 200 });
      options.stores.value = result.items;

      if (result.items.length === 0) {
        options.selectedStoreId.value = '';
        options.rows.value = [];
        options.pagination.total = 0;
        resetStats();
        return;
      }

      const matched = result.items.some(
        (store) => store.id === options.selectedStoreId.value,
      );
      if (!matched) {
        options.selectedStoreId.value = result.items[0]?.id ?? '';
      }
    } finally {
      options.isStoreLoading.value = false;
    }
  }

  async function loadPageData() {
    if (!options.selectedStoreId.value) {
      options.rows.value = [];
      options.pagination.total = 0;
      resetStats();
      return;
    }

    const queryPayload = buildQueryPayload(
      options.selectedStoreId.value,
      options.filters,
      options.pagination.page,
      options.pagination.pageSize,
    );
    const { page: _page, pageSize: _pageSize, ...filterPayload } = queryPayload;

    options.isListLoading.value = true;
    options.isStatsLoading.value = true;
    try {
      const [listResult, statsResult] = await Promise.all([
        getOrderAllListApi(queryPayload),
        getOrderAllStatsApi(filterPayload),
      ]);

      options.rows.value = listResult.items;
      options.pagination.total = listResult.total;
      options.pagination.page = listResult.page;
      options.pagination.pageSize = listResult.pageSize;

      options.stats.totalOrders = statsResult.totalOrders;
      options.stats.totalAmount = statsResult.totalAmount;
      options.stats.averageAmount = statsResult.averageAmount;
      options.stats.refundCount = statsResult.refundCount;
    } finally {
      options.isListLoading.value = false;
      options.isStatsLoading.value = false;
    }
  }

  return {
    loadPageData,
    loadStores,
  };
}
