/**
 * 文件职责：成本管理页面数据加载与保存动作。
 */
import type {
  FinanceCostAnalysisState,
  FinanceCostCategoryViewModel,
  FinanceCostEntryState,
  FinanceCostFilterState,
} from '../../types';

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

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

import {
  getFinanceCostAnalysisApi,
  getFinanceCostEntryApi,
  saveFinanceCostEntryApi,
} from '#/api/finance/cost';
import { getStoreListApi } from '#/api/store';

import { DEFAULT_ANALYSIS_STATE, DEFAULT_ENTRY_STATE } from './constants';
import {
  buildSaveCategoryPayload,
  buildScopeQueryPayload,
  mapCategoriesToViewModel,
} from './helpers';

interface DataActionOptions {
  analysis: FinanceCostAnalysisState;
  entry: FinanceCostEntryState;
  filters: FinanceCostFilterState;
  isAnalysisLoading: { value: boolean };
  isEntryLoading: { value: boolean };
  isSaving: { value: boolean };
  isStoreLoading: { value: boolean };
  stores: { value: StoreListItemDto[] };
}

/** 创建数据动作集合。 */
export function createDataActions(options: DataActionOptions) {
  async function loadStores() {
    options.isStoreLoading.value = true;
    try {
      const result = await getStoreListApi({ page: 1, pageSize: 200 });
      options.stores.value = result.items ?? [];
    } finally {
      options.isStoreLoading.value = false;
    }
  }

  function clearEntry() {
    options.entry.monthRevenue = DEFAULT_ENTRY_STATE.monthRevenue;
    options.entry.totalCost = DEFAULT_ENTRY_STATE.totalCost;
    options.entry.costRate = DEFAULT_ENTRY_STATE.costRate;
    options.entry.categories = [];
  }

  function clearAnalysis() {
    options.analysis.stats = { ...DEFAULT_ANALYSIS_STATE.stats };
    options.analysis.trend = [];
    options.analysis.composition = [];
    options.analysis.detailRows = [];
  }

  function clearAllData() {
    clearEntry();
    clearAnalysis();
  }

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

    options.isEntryLoading.value = true;
    try {
      const expandedMap = new Map(
        (options.entry.categories ?? []).map((item) => [
          item.category,
          Boolean(item.expanded),
        ]),
      );

      const result = await getFinanceCostEntryApi(
        buildScopeQueryPayload(options.filters),
      );

      options.entry.monthRevenue = result.monthRevenue;
      options.entry.totalCost = result.totalCost;
      options.entry.costRate = result.costRate;
      options.entry.categories = mapCategoriesToViewModel(
        result.categories ?? [],
        expandedMap,
      );
    } finally {
      options.isEntryLoading.value = false;
    }
  }

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

    options.isAnalysisLoading.value = true;
    try {
      const result = await getFinanceCostAnalysisApi({
        ...buildScopeQueryPayload(options.filters),
        trendMonthCount: 6,
      });

      options.analysis.stats = { ...result.stats };
      options.analysis.trend = [...(result.trend ?? [])];
      options.analysis.composition = [...(result.composition ?? [])];
      options.analysis.detailRows = [...(result.detailRows ?? [])];
    } finally {
      options.isAnalysisLoading.value = false;
    }
  }

  async function saveEntryData() {
    if (options.filters.dimension === 'store' && !options.filters.storeId) {
      message.warning('请先选择门店');
      return;
    }

    options.isSaving.value = true;
    try {
      const result = await saveFinanceCostEntryApi({
        ...buildScopeQueryPayload(options.filters),
        categories: buildSaveCategoryPayload(
          options.entry.categories as FinanceCostCategoryViewModel[],
        ),
      });

      const expandedMap = new Map(
        (options.entry.categories ?? []).map((item) => [
          item.category,
          Boolean(item.expanded),
        ]),
      );

      options.entry.monthRevenue = result.monthRevenue;
      options.entry.totalCost = result.totalCost;
      options.entry.costRate = result.costRate;
      options.entry.categories = mapCategoriesToViewModel(
        result.categories ?? [],
        expandedMap,
      );

      message.success('成本数据保存成功');
    } finally {
      options.isSaving.value = false;
    }
  }

  return {
    clearAllData,
    clearAnalysis,
    clearEntry,
    loadAnalysisData,
    loadEntryData,
    loadStores,
    saveEntryData,
  };
}
