import type {
  FinanceSettlementFilterState,
  FinanceSettlementPaginationState,
} from '../../types';

import type {
  FinanceSettlementAccountDto,
  FinanceSettlementListItemDto,
  FinanceSettlementStatsDto,
} from '#/api/finance';
import type { StoreListItemDto } from '#/api/store';

/**
 * 文件职责：到账查询页面数据加载动作。
 */
import {
  getFinanceSettlementAccountApi,
  getFinanceSettlementListApi,
  getFinanceSettlementStatsApi,
} from '#/api/finance';
import { getStoreListApi } from '#/api/store';

import { buildListQueryPayload } from './helpers';

interface DataActionOptions {
  account: { value: FinanceSettlementAccountDto | null };
  filters: FinanceSettlementFilterState;
  isAccountLoading: { value: boolean };
  isListLoading: { value: boolean };
  isStatsLoading: { value: boolean };
  isStoreLoading: { value: boolean };
  pagination: FinanceSettlementPaginationState;
  rows: { value: FinanceSettlementListItemDto[] };
  selectedStoreId: { value: string };
  stats: FinanceSettlementStatsDto;
  stores: { value: StoreListItemDto[] };
}

/** 创建数据相关动作。 */
export function createDataActions(options: DataActionOptions) {
  function resetStats() {
    options.stats.todayArrivedAmount = 0;
    options.stats.yesterdayArrivedAmount = 0;
    options.stats.currentMonthArrivedAmount = 0;
    options.stats.currentMonthTransactionCount = 0;
  }

  function clearPageData() {
    options.rows.value = [];
    options.pagination.total = 0;
    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 loadAccount() {
    options.isAccountLoading.value = true;
    try {
      options.account.value = await getFinanceSettlementAccountApi();
    } finally {
      options.isAccountLoading.value = false;
    }
  }

  async function loadPageData() {
    if (!options.selectedStoreId.value) {
      clearPageData();
      return;
    }

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

    options.isListLoading.value = true;
    options.isStatsLoading.value = true;
    try {
      const [listResult, statsResult] = await Promise.all([
        getFinanceSettlementListApi(listPayload),
        getFinanceSettlementStatsApi({ storeId }),
      ]);

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

      options.stats.todayArrivedAmount = statsResult.todayArrivedAmount;
      options.stats.yesterdayArrivedAmount = statsResult.yesterdayArrivedAmount;
      options.stats.currentMonthArrivedAmount =
        statsResult.currentMonthArrivedAmount;
      options.stats.currentMonthTransactionCount =
        statsResult.currentMonthTransactionCount;
    } finally {
      options.isListLoading.value = false;
      options.isStatsLoading.value = false;
    }
  }

  return {
    clearPageData,
    loadAccount,
    loadPageData,
    loadStores,
    resetStats,
  };
}
