import type { Ref } from 'vue';

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

import { getCustomerAnalysisOverviewApi } from '#/api/customer';
import { getStoreListApi } from '#/api/store';

import { EMPTY_OVERVIEW } from './constants';

interface DataActionOptions {
  isOverviewLoading: Ref<boolean>;
  isStoreLoading: Ref<boolean>;
  overview: Ref<CustomerAnalysisOverviewDto>;
  period: Ref<'7d' | '30d' | '90d' | '365d'>;
  selectedStoreId: Ref<string>;
  stores: Ref<StoreListItemDto[]>;
}

/**
 * 文件职责：客户分析页的数据加载动作。
 */
export function createDataActions(options: DataActionOptions) {
  function resolvePeriodDays(period: '7d' | '30d' | '90d' | '365d'): number {
    switch (period) {
      case '7d': {
        return 7;
      }
      case '90d': {
        return 90;
      }
      case '365d': {
        return 365;
      }
      default: {
        return 30;
      }
    }
  }

  function resetOverview() {
    options.overview.value = {
      ...EMPTY_OVERVIEW,
      periodCode: options.period.value,
      periodDays: resolvePeriodDays(options.period.value),
    };
  }

  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 = '';
        resetOverview();
        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 loadOverview() {
    if (!options.selectedStoreId.value) {
      resetOverview();
      return;
    }

    options.isOverviewLoading.value = true;
    try {
      options.overview.value = await getCustomerAnalysisOverviewApi({
        storeId: options.selectedStoreId.value,
        period: options.period.value,
      });
    } finally {
      options.isOverviewLoading.value = false;
    }
  }

  return {
    loadOverview,
    loadStores,
    resetOverview,
  };
}
