import type { Ref } from 'vue';

import type { MarketingPunchCardStatsDto } from '#/api/marketing';
import type { StoreListItemDto } from '#/api/store';
import type {
  PunchCardListFilterForm,
  PunchCardTemplateCardViewModel,
  PunchCardTemplateOptionViewModel,
  PunchCardUsageFilterForm,
  PunchCardUsagePager,
  PunchCardUsageStatsViewModel,
} from '#/views/marketing/punch-card/types';

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

import {
  getMarketingPunchCardListApi,
  getMarketingPunchCardUsageRecordListApi,
} from '#/api/marketing';
import { getStoreListApi } from '#/api/store';

import { createDefaultPunchCardUsageStats } from './constants';
import { toUsageRecordViewModel } from './helpers';

interface CreateDataActionsOptions {
  isListLoading: Ref<boolean>;
  isRecordLoading: Ref<boolean>;
  isStoreLoading: Ref<boolean>;
  listFilterForm: PunchCardListFilterForm;
  listKeyword: Ref<string>;
  listPage: Ref<number>;
  listPageSize: Ref<number>;
  listRows: Ref<PunchCardTemplateCardViewModel[]>;
  listStats: Ref<MarketingPunchCardStatsDto>;
  listTotalCount: Ref<number>;
  recordFilterForm: PunchCardUsageFilterForm;
  recordKeyword: Ref<string>;
  selectedStoreId: Ref<string>;
  stores: Ref<StoreListItemDto[]>;
  templateOptions: Ref<PunchCardTemplateOptionViewModel[]>;
  usagePager: Ref<PunchCardUsagePager>;
  usageStats: Ref<PunchCardUsageStatsViewModel>;
}

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.listRows.value = [];
        options.listTotalCount.value = 0;
        options.usagePager.value = {
          ...options.usagePager.value,
          items: [],
          totalCount: 0,
        };
        options.templateOptions.value = [];
        options.listStats.value = {
          onSaleCount: 0,
          totalSoldCount: 0,
          totalRevenueAmount: 0,
          activeInUseCount: 0,
        };
        options.usageStats.value = createDefaultPunchCardUsageStats();
        return;
      }

      if (!options.selectedStoreId.value) {
        options.selectedStoreId.value = options.stores.value[0]?.id ?? '';
        return;
      }

      const exists = options.stores.value.some(
        (item) => item.id === options.selectedStoreId.value,
      );
      if (!exists) {
        options.selectedStoreId.value = options.stores.value[0]?.id ?? '';
      }
    } catch (error) {
      console.error(error);
      message.error('加载门店失败');
    } finally {
      options.isStoreLoading.value = false;
    }
  }

  async function loadPunchCardList() {
    if (!options.selectedStoreId.value) {
      options.listRows.value = [];
      options.listTotalCount.value = 0;
      return;
    }

    options.isListLoading.value = true;
    try {
      const result = await getMarketingPunchCardListApi({
        storeId: options.selectedStoreId.value,
        page: options.listPage.value,
        pageSize: options.listPageSize.value,
        status: options.listFilterForm.status,
        keyword: options.listKeyword.value.trim() || undefined,
      });

      options.listRows.value = result.items;
      options.listTotalCount.value = result.totalCount;
      options.listPage.value = result.page;
      options.listPageSize.value = result.pageSize;
      options.listStats.value = result.stats;
    } catch (error) {
      console.error(error);
      options.listRows.value = [];
      options.listTotalCount.value = 0;
      options.listStats.value = {
        onSaleCount: 0,
        totalSoldCount: 0,
        totalRevenueAmount: 0,
        activeInUseCount: 0,
      };
      message.error('加载次卡列表失败');
    } finally {
      options.isListLoading.value = false;
    }
  }

  async function loadUsageRecords() {
    if (!options.selectedStoreId.value) {
      options.usagePager.value = {
        ...options.usagePager.value,
        items: [],
        totalCount: 0,
      };
      options.templateOptions.value = [];
      options.usageStats.value = createDefaultPunchCardUsageStats();
      return;
    }

    options.isRecordLoading.value = true;
    try {
      const result = await getMarketingPunchCardUsageRecordListApi({
        storeId: options.selectedStoreId.value,
        page: options.usagePager.value.page,
        pageSize: options.usagePager.value.pageSize,
        punchCardId: options.recordFilterForm.templateId || undefined,
        status: options.recordFilterForm.status,
        keyword: options.recordKeyword.value.trim() || undefined,
      });

      options.usagePager.value = {
        items: result.items.map((item) => toUsageRecordViewModel(item)),
        page: result.page,
        pageSize: result.pageSize,
        totalCount: result.totalCount,
      };
      options.templateOptions.value = result.templateOptions;
      options.usageStats.value = result.stats;
    } catch (error) {
      console.error(error);
      options.usagePager.value = {
        ...options.usagePager.value,
        items: [],
        totalCount: 0,
      };
      options.templateOptions.value = [];
      options.usageStats.value = createDefaultPunchCardUsageStats();
      message.error('加载使用记录失败');
    } finally {
      options.isRecordLoading.value = false;
    }
  }

  return {
    loadPunchCardList,
    loadStores,
    loadUsageRecords,
  };
}
