import type { Ref } from 'vue';

import type { StoreListItemDto } from '#/api/store';
import type {
  NewCustomerInviteRecordPager,
  NewCustomerPageForm,
  NewCustomerStatsViewModel,
} from '#/views/marketing/new-customer/types';

/**
 * 文件职责：新客有礼页面数据加载动作。
 * 1. 加载门店、详情与邀请记录分页。
 */
import { message } from 'ant-design-vue';

import {
  getMarketingNewCustomerDetailApi,
  getMarketingNewCustomerInviteRecordListApi,
} from '#/api/marketing';
import { getStoreListApi } from '#/api/store';

import {
  createDefaultNewCustomerInvitePager,
  createDefaultNewCustomerStats,
} from './constants';
import { mapSettingsToPageForm } from './helpers';

interface CreateDataActionsOptions {
  form: NewCustomerPageForm;
  invitePager: Ref<NewCustomerInviteRecordPager>;
  isDetailLoading: Ref<boolean>;
  isInviteLoading: Ref<boolean>;
  isStoreLoading: Ref<boolean>;
  selectedStoreId: Ref<string>;
  stats: Ref<NewCustomerStatsViewModel>;
  stores: Ref<StoreListItemDto[]>;
  updatedAt: Ref<string>;
}

export function createDataActions(options: CreateDataActionsOptions) {
  function applyForm(next: NewCustomerPageForm) {
    options.form.giftEnabled = next.giftEnabled;
    options.form.giftType = next.giftType;
    options.form.directReduceAmount = next.directReduceAmount;
    options.form.directMinimumSpend = next.directMinimumSpend;
    options.form.inviteEnabled = next.inviteEnabled;
    options.form.shareChannels = [...next.shareChannels];
    options.form.welcomeCoupons = [...next.welcomeCoupons];
    options.form.inviterCoupons = [...next.inviterCoupons];
    options.form.inviteeCoupons = [...next.inviteeCoupons];
  }

  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 = '';
        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 loadDetail(resetForm: boolean) {
    if (!options.selectedStoreId.value) {
      options.stats.value = createDefaultNewCustomerStats();
      options.invitePager.value = createDefaultNewCustomerInvitePager();
      options.updatedAt.value = '';
      return;
    }

    options.isDetailLoading.value = true;
    try {
      const detail = await getMarketingNewCustomerDetailApi({
        storeId: options.selectedStoreId.value,
        recordPage: options.invitePager.value.page,
        recordPageSize: options.invitePager.value.pageSize,
      });

      options.stats.value = detail.stats;
      options.updatedAt.value = detail.settings.updatedAt;

      if (resetForm) {
        applyForm(mapSettingsToPageForm(detail.settings));
      }

      options.invitePager.value = {
        items: detail.inviteRecords.items ?? [],
        page: detail.inviteRecords.page,
        pageSize: detail.inviteRecords.pageSize,
        totalCount: detail.inviteRecords.totalCount,
      };
    } catch (error) {
      console.error(error);
      options.stats.value = createDefaultNewCustomerStats();
      options.invitePager.value = createDefaultNewCustomerInvitePager();
      message.error('加载新客有礼失败');
    } finally {
      options.isDetailLoading.value = false;
    }
  }

  async function loadInviteRecords() {
    if (!options.selectedStoreId.value) {
      options.invitePager.value = createDefaultNewCustomerInvitePager();
      return;
    }

    options.isInviteLoading.value = true;
    try {
      const result = await getMarketingNewCustomerInviteRecordListApi({
        storeId: options.selectedStoreId.value,
        page: options.invitePager.value.page,
        pageSize: options.invitePager.value.pageSize,
      });

      options.invitePager.value = {
        items: result.items ?? [],
        page: result.page,
        pageSize: result.pageSize,
        totalCount: result.totalCount,
      };
    } catch (error) {
      console.error(error);
      options.invitePager.value = {
        ...options.invitePager.value,
        items: [],
        totalCount: 0,
      };
      message.error('加载邀请记录失败');
    } finally {
      options.isInviteLoading.value = false;
    }
  }

  return {
    loadDetail,
    loadInviteRecords,
    loadStores,
  };
}
