import type { Ref } from 'vue';

import type { StoreListItemDto } from '#/api/store';
import type {
  MarketingCalendarMonthCursor,
  MarketingCalendarOverviewViewModel,
} from '#/views/marketing/calendar/types';

/**
 * 文件职责：营销日历页面数据拉取动作。
 */
import { message } from 'ant-design-vue';

import { getMarketingCalendarOverviewApi } from '#/api/marketing';
import { getStoreListApi } from '#/api/store';

import { createEmptyOverview } from './constants';

interface CreateDataActionsOptions {
  cursor: Ref<MarketingCalendarMonthCursor>;
  isOverviewLoading: Ref<boolean>;
  isStoreLoading: Ref<boolean>;
  overview: Ref<MarketingCalendarOverviewViewModel>;
  selectedStoreId: Ref<string>;
  stores: Ref<StoreListItemDto[]>;
}

export function createDataActions(options: CreateDataActionsOptions) {
  async function loadStores() {
    options.isStoreLoading.value = true;
    try {
      const result = await getStoreListApi({
        page: 1,
        pageSize: 200,
      });

      options.stores.value = result.items ?? [];
      if (options.stores.value.length === 0) {
        options.selectedStoreId.value = '';
        options.overview.value = createEmptyOverview(
          options.cursor.value.month,
          options.cursor.value.year,
        );
        return;
      }

      if (options.selectedStoreId.value === '') {
        options.selectedStoreId.value = options.stores.value[0]?.id ?? '';
      } else {
        const exists = options.stores.value.some(
          (item) => item.id === options.selectedStoreId.value,
        );
        if (exists) {
          return;
        }

        options.selectedStoreId.value = options.stores.value[0]?.id ?? '';
      }
    } catch (error) {
      console.error(error);
      message.error('加载门店失败');
    } finally {
      options.isStoreLoading.value = false;
    }
  }

  async function loadOverview() {
    if (!options.selectedStoreId.value) {
      options.overview.value = createEmptyOverview(
        options.cursor.value.month,
        options.cursor.value.year,
      );
      return;
    }

    options.isOverviewLoading.value = true;
    try {
      const result = await getMarketingCalendarOverviewApi({
        storeId: options.selectedStoreId.value,
        year: options.cursor.value.year,
        month: options.cursor.value.month,
      });

      options.overview.value = result;
    } catch (error) {
      console.error(error);
      options.overview.value = createEmptyOverview(
        options.cursor.value.month,
        options.cursor.value.year,
      );
      message.error('加载营销日历失败');
    } finally {
      options.isOverviewLoading.value = false;
    }
  }

  return {
    loadOverview,
    loadStores,
  };
}
