import type { Ref } from 'vue';

import type { MarketingCouponStatsDto } from '#/api/marketing';
import type { StoreListItemDto } from '#/api/store';
import type {
  CouponCardViewModel,
  CouponFilterForm,
} from '#/views/marketing/coupon/types';

/**
 * 文件职责：优惠券页面数据读取动作。
 * 1. 加载门店列表与优惠券分页列表。
 * 2. 维护分页、统计和加载态。
 */
import { message } from 'ant-design-vue';

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

interface CreateDataActionsOptions {
  filterForm: CouponFilterForm;
  isLoading: Ref<boolean>;
  isStoreLoading: Ref<boolean>;
  keyword: Ref<string>;
  page: Ref<number>;
  pageSize: Ref<number>;
  rows: Ref<CouponCardViewModel[]>;
  selectedStoreId: Ref<string>;
  stats: Ref<MarketingCouponStatsDto>;
  stores: Ref<StoreListItemDto[]>;
  total: Ref<number>;
}

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.rows.value = [];
        options.total.value = 0;
        return;
      }

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

  async function loadCoupons() {
    if (!options.selectedStoreId.value) {
      options.rows.value = [];
      options.total.value = 0;
      return;
    }

    options.isLoading.value = true;
    try {
      const result = await getMarketingCouponListApi({
        storeId: options.selectedStoreId.value,
        status: options.filterForm.status,
        couponType: options.filterForm.couponType,
        keyword: options.keyword.value.trim() || undefined,
        page: options.page.value,
        pageSize: options.pageSize.value,
      });

      options.rows.value = result.items ?? [];
      options.total.value = result.total;
      options.page.value = result.page;
      options.pageSize.value = result.pageSize;
      options.stats.value = result.stats;
    } catch (error) {
      console.error(error);
      options.rows.value = [];
      options.total.value = 0;
      options.stats.value = createEmptyStats();
      message.error('加载优惠券失败');
    } finally {
      options.isLoading.value = false;
    }
  }

  return {
    loadCoupons,
    loadStores,
  };
}

export function createEmptyStats(): MarketingCouponStatsDto {
  return {
    totalCount: 0,
    ongoingCount: 0,
    claimedCount: 0,
    redeemedCount: 0,
    redeemRate: 0,
  };
}
