import type { Ref } from 'vue';

import type { StoreListItemDto } from '#/api/store';
import type {
  StoredCardPlanCardViewModel,
  StoredCardPlanStatsViewModel,
  StoredCardRecordFilterForm,
  StoredCardRecordPager,
} from '#/views/member/stored-card/types';

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

import {
  getMemberStoredCardPlanListApi,
  getMemberStoredCardRechargeRecordListApi,
} from '#/api/member/stored-card';
import { getStoreListApi } from '#/api/store';

import { mapRecordFilterToQuery } from './helpers';

interface CreateDataActionsOptions {
  isPlanLoading: Ref<boolean>;
  isRecordLoading: Ref<boolean>;
  isStoreLoading: Ref<boolean>;
  planRows: Ref<StoredCardPlanCardViewModel[]>;
  planStats: Ref<StoredCardPlanStatsViewModel>;
  recordFilterForm: StoredCardRecordFilterForm;
  recordPager: Ref<StoredCardRecordPager>;
  selectedStoreId: Ref<string>;
  stores: Ref<StoreListItemDto[]>;
}

export function createDataActions(options: CreateDataActionsOptions) {
  function resetPlanData() {
    options.planRows.value = [];
    options.planStats.value = {
      totalRechargeAmount: 0,
      totalGiftAmount: 0,
      currentMonthRechargeAmount: 0,
      rechargeMemberCount: 0,
    };
  }

  function resetRecordData() {
    options.recordPager.value = {
      ...options.recordPager.value,
      items: [],
      totalCount: 0,
    };
  }

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

    options.isPlanLoading.value = true;
    try {
      const result = await getMemberStoredCardPlanListApi({
        storeId: options.selectedStoreId.value,
      });

      options.planRows.value = result.items ?? [];
      options.planStats.value = result.stats ?? {
        totalRechargeAmount: 0,
        totalGiftAmount: 0,
        currentMonthRechargeAmount: 0,
        rechargeMemberCount: 0,
      };
    } catch (error) {
      console.error(error);
      resetPlanData();
      message.error('加载充值方案失败');
    } finally {
      options.isPlanLoading.value = false;
    }
  }

  async function loadRecordList() {
    if (!options.selectedStoreId.value) {
      resetRecordData();
      return;
    }

    options.isRecordLoading.value = true;
    try {
      const query = mapRecordFilterToQuery(options.recordFilterForm);
      const result = await getMemberStoredCardRechargeRecordListApi({
        storeId: options.selectedStoreId.value,
        page: options.recordPager.value.page,
        pageSize: options.recordPager.value.pageSize,
        ...query,
      });

      options.recordPager.value = {
        items: result.items ?? [],
        page: result.page,
        pageSize: result.pageSize,
        totalCount: result.totalCount,
      };
    } catch (error) {
      console.error(error);
      resetRecordData();
      message.error('加载充值记录失败');
    } finally {
      options.isRecordLoading.value = false;
    }
  }

  return {
    loadPlanList,
    loadRecordList,
    loadStores,
  };
}
