import type { Ref } from 'vue';

import type {
  CustomerAnalysisSegmentCode,
  CustomerAnalysisSegmentListResultDto,
} from '#/api/customer';

import { getCustomerAnalysisSegmentListApi } from '#/api/customer';

interface SegmentPagination {
  page: number;
  pageSize: number;
  total: number;
}

interface SegmentActionOptions {
  currentSegmentCode: Ref<CustomerAnalysisSegmentCode>;
  isSegmentDrawerOpen: Ref<boolean>;
  isSegmentLoading: Ref<boolean>;
  keyword: Ref<string>;
  pagination: SegmentPagination;
  period: Ref<'7d' | '30d' | '90d' | '365d'>;
  result: Ref<CustomerAnalysisSegmentListResultDto | null>;
  selectedStoreId: Ref<string>;
}

/**
 * 文件职责：客户分析页客群明细抽屉动作。
 */
export function createSegmentActions(options: SegmentActionOptions) {
  function setSegmentDrawerOpen(value: boolean) {
    options.isSegmentDrawerOpen.value = value;
    if (!value) {
      options.result.value = null;
      options.keyword.value = '';
      options.pagination.page = 1;
      options.pagination.total = 0;
    }
  }

  function setSegmentKeyword(value: string) {
    options.keyword.value = value;
  }

  async function loadSegmentData() {
    if (!options.selectedStoreId.value) {
      options.result.value = null;
      options.pagination.total = 0;
      return;
    }

    options.isSegmentLoading.value = true;
    try {
      const result = await getCustomerAnalysisSegmentListApi({
        storeId: options.selectedStoreId.value,
        period: options.period.value,
        segmentCode: options.currentSegmentCode.value,
        keyword: options.keyword.value.trim() || undefined,
        page: options.pagination.page,
        pageSize: options.pagination.pageSize,
      });

      options.result.value = result;
      options.pagination.page = result.page;
      options.pagination.pageSize = result.pageSize;
      options.pagination.total = result.totalCount;
    } finally {
      options.isSegmentLoading.value = false;
    }
  }

  async function openSegment(segmentCode: CustomerAnalysisSegmentCode) {
    options.currentSegmentCode.value = segmentCode;
    options.keyword.value = '';
    options.pagination.page = 1;
    options.isSegmentDrawerOpen.value = true;
    await loadSegmentData();
  }

  async function handleSegmentSearch() {
    options.pagination.page = 1;
    await loadSegmentData();
  }

  async function handleSegmentPageChange(page: number, pageSize: number) {
    options.pagination.page = page;
    options.pagination.pageSize = pageSize;
    await loadSegmentData();
  }

  return {
    handleSegmentPageChange,
    handleSegmentSearch,
    loadSegmentData,
    openSegment,
    setSegmentDrawerOpen,
    setSegmentKeyword,
  };
}
