import type { FinanceBusinessReportPaginationState } from '../../types';

/**
 * 文件职责：经营报表页面数据加载动作。
 */
import type { FinanceBusinessReportListItemDto } from '#/api/finance';
import type { StoreListItemDto } from '#/api/store';

import { getFinanceBusinessReportListApi } from '#/api/finance';
import { getStoreListApi } from '#/api/store';

import { buildReportListQueryPayload } from './helpers';

interface DataActionOptions {
  isListLoading: { value: boolean };
  isStoreLoading: { value: boolean };
  pagination: FinanceBusinessReportPaginationState;
  periodType: { value: 'daily' | 'monthly' | 'weekly' };
  rows: { value: FinanceBusinessReportListItemDto[] };
  selectedStoreId: { value: string };
  stores: { value: StoreListItemDto[] };
}

/** 创建数据相关动作。 */
export function createDataActions(options: DataActionOptions) {
  function clearPageData() {
    options.rows.value = [];
    options.pagination.total = 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 = '';
        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 loadReportList() {
    if (!options.selectedStoreId.value) {
      clearPageData();
      return;
    }

    options.isListLoading.value = true;
    try {
      const payload = buildReportListQueryPayload(
        options.selectedStoreId.value,
        options.periodType.value,
        options.pagination.page,
        options.pagination.pageSize,
      );
      const result = await getFinanceBusinessReportListApi(payload);

      options.rows.value = result.items;
      options.pagination.total = result.total;
      options.pagination.page = result.page;
      options.pagination.pageSize = result.pageSize;
    } finally {
      options.isListLoading.value = false;
    }
  }

  return {
    clearPageData,
    loadReportList,
    loadStores,
  };
}
