import type { Ref } from 'vue';

import type { CustomerDetailDto, CustomerProfileDto } from '#/api/customer';

import {
  getCustomerAnalysisDetailApi,
  getCustomerAnalysisProfileApi,
} from '#/api/customer';

interface DrawerActionOptions {
  detail: Ref<CustomerDetailDto | null>;
  isDetailDrawerOpen: Ref<boolean>;
  isDetailLoading: Ref<boolean>;
  isProfileDrawerOpen: Ref<boolean>;
  isProfileLoading: Ref<boolean>;
  profile: Ref<CustomerProfileDto | null>;
  selectedStoreId: Ref<string>;
}

/**
 * 文件职责：客户分析页客户详情与画像抽屉动作。
 */
export function createDrawerActions(options: DrawerActionOptions) {
  function setDetailDrawerOpen(value: boolean) {
    options.isDetailDrawerOpen.value = value;
    if (!value) {
      options.detail.value = null;
      options.isProfileDrawerOpen.value = false;
      options.profile.value = null;
    }
  }

  function setProfileDrawerOpen(value: boolean) {
    options.isProfileDrawerOpen.value = value;
    if (!value) {
      options.profile.value = null;
    }
  }

  async function openDetail(customerKey: string) {
    if (!options.selectedStoreId.value || !customerKey) {
      return;
    }

    options.isDetailDrawerOpen.value = true;
    options.detail.value = null;
    options.isProfileDrawerOpen.value = false;
    options.profile.value = null;
    options.isDetailLoading.value = true;
    try {
      options.detail.value = await getCustomerAnalysisDetailApi({
        storeId: options.selectedStoreId.value,
        customerKey,
      });
    } finally {
      options.isDetailLoading.value = false;
    }
  }

  async function openProfile(customerKey: string) {
    if (!options.selectedStoreId.value || !customerKey) {
      return;
    }

    options.isProfileDrawerOpen.value = true;
    options.profile.value = null;
    options.isProfileLoading.value = true;
    try {
      options.profile.value = await getCustomerAnalysisProfileApi({
        storeId: options.selectedStoreId.value,
        customerKey,
      });
    } finally {
      options.isProfileLoading.value = false;
    }
  }

  return {
    openDetail,
    openProfile,
    setDetailDrawerOpen,
    setProfileDrawerOpen,
  };
}
