/**
 * 文件职责：财务概览页面数据动作。
 */
import type { Ref } from 'vue';

import type {
  FinanceOverviewDashboardState,
  FinanceOverviewFilterState,
} from '../../types';

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

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

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

import { createDefaultFinanceOverviewDashboard } from './constants';
import { buildDashboardQuery } from './helpers';

interface CreateDataActionsOptions {
  dashboard: FinanceOverviewDashboardState;
  filters: FinanceOverviewFilterState;
  isDashboardLoading: Ref<boolean>;
  isStoreLoading: Ref<boolean>;
  stores: Ref<StoreListItemDto[]>;
}

/** 创建页面数据动作。 */
export function createDataActions(options: CreateDataActionsOptions) {
  function syncDashboard(source: FinanceOverviewDashboardState) {
    options.dashboard.dimension = source.dimension;
    options.dashboard.storeId = source.storeId;
    options.dashboard.todayRevenue = { ...source.todayRevenue };
    options.dashboard.actualReceived = { ...source.actualReceived };
    options.dashboard.refundAmount = { ...source.refundAmount };
    options.dashboard.netIncome = { ...source.netIncome };
    options.dashboard.withdrawableBalance = { ...source.withdrawableBalance };
    options.dashboard.incomeTrend = {
      last7Days: [...source.incomeTrend.last7Days],
      last30Days: [...source.incomeTrend.last30Days],
    };
    options.dashboard.profitTrend = {
      last7Days: [...source.profitTrend.last7Days],
      last30Days: [...source.profitTrend.last30Days],
    };
    options.dashboard.incomeComposition = {
      totalAmount: source.incomeComposition.totalAmount,
      items: [...source.incomeComposition.items],
    };
    options.dashboard.costComposition = {
      totalAmount: source.costComposition.totalAmount,
      items: [...source.costComposition.items],
    };
    options.dashboard.topProducts = {
      periodDays: source.topProducts.periodDays,
      items: [...source.topProducts.items],
    };
  }

  function clearDashboard() {
    syncDashboard(createDefaultFinanceOverviewDashboard());
  }

  async function loadStores() {
    options.isStoreLoading.value = true;
    try {
      const result = await getStoreListApi({
        page: 1,
        pageSize: 200,
      });
      options.stores.value = result.items ?? [];
    } catch (error) {
      console.error(error);
      options.stores.value = [];
      message.error('加载门店列表失败，请稍后重试');
    } finally {
      options.isStoreLoading.value = false;
    }
  }

  async function loadDashboard() {
    if (options.filters.dimension === 'store' && !options.filters.storeId) {
      clearDashboard();
      return;
    }

    options.isDashboardLoading.value = true;
    try {
      const result = await getFinanceOverviewDashboardApi(
        buildDashboardQuery(options.filters),
      );
      syncDashboard(result);
    } catch (error) {
      console.error(error);
      clearDashboard();
      message.error('加载财务概览失败，请稍后重试');
    } finally {
      options.isDashboardLoading.value = false;
    }
  }

  return {
    clearDashboard,
    loadDashboard,
    loadStores,
    syncDashboard,
  };
}
