import type {
  FinanceTransactionFilterState,
  FinanceTransactionPageSummaryState,
  FinanceTransactionPaginationState,
} from '../../types';

/**
 * 文件职责：交易流水页面数据加载动作。
 */
import type {
  FinanceTransactionListItemDto,
  FinanceTransactionStatsDto,
} from '#/api/finance';
import type { StoreListItemDto } from '#/api/store';

import {
  getFinanceTransactionListApi,
  getFinanceTransactionStatsApi,
} from '#/api/finance';
import { getStoreListApi } from '#/api/store';

import { buildFilterQueryPayload, buildListQueryPayload } from './helpers';

interface DataActionOptions {
  filters: FinanceTransactionFilterState;
  isListLoading: { value: boolean };
  isStatsLoading: { value: boolean };
  isStoreLoading: { value: boolean };
  pageSummary: FinanceTransactionPageSummaryState;
  pagination: FinanceTransactionPaginationState;
  rows: { value: FinanceTransactionListItemDto[] };
  selectedStoreId: { value: string };
  stats: FinanceTransactionStatsDto;
  stores: { value: StoreListItemDto[] };
}

/** 创建数据相关动作。 */
export function createDataActions(options: DataActionOptions) {
  function resetStats() {
    options.stats.totalIncome = 0;
    options.stats.totalRefund = 0;
    options.stats.totalCount = 0;
  }

  function resetPageSummary() {
    options.pageSummary.pageIncomeAmount = 0;
    options.pageSummary.pageRefundAmount = 0;
  }

  function clearPageData() {
    options.rows.value = [];
    options.pagination.total = 0;
    resetPageSummary();
    resetStats();
  }

  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 = '';
        clearPageData();
        return;
      }

      const matched = result.items.some(
        (item) => item.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) {
      clearPageData();
      return;
    }

    const listPayload = buildListQueryPayload(
      options.selectedStoreId.value,
      options.filters,
      options.pagination.page,
      options.pagination.pageSize,
    );
    const filterPayload = buildFilterQueryPayload(
      options.selectedStoreId.value,
      options.filters,
    );

    options.isListLoading.value = true;
    options.isStatsLoading.value = true;
    try {
      const [listResult, statsResult] = await Promise.all([
        getFinanceTransactionListApi(listPayload),
        getFinanceTransactionStatsApi(filterPayload),
      ]);

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

      options.stats.totalIncome = statsResult.totalIncome;
      options.stats.totalRefund = statsResult.totalRefund;
      options.stats.totalCount = statsResult.totalCount;
    } finally {
      options.isListLoading.value = false;
      options.isStatsLoading.value = false;
    }
  }

  return {
    clearPageData,
    loadPageData,
    loadStores,
  };
}
