/**
 * 文件职责：经营报表页面状态与动作编排。
 */
import type {
  FinanceBusinessReportDetailDto,
  FinanceBusinessReportListItemDto,
  FinanceBusinessReportPeriodType,
} from '#/api/finance';
import type { StoreListItemDto } from '#/api/store';

import { computed, onActivated, onMounted, reactive, ref, watch } from 'vue';

import { useAccessStore } from '@vben/stores';

import {
  DEFAULT_PAGINATION,
  DEFAULT_PERIOD_TYPE,
  FINANCE_REPORT_EXPORT_PERMISSION,
  FINANCE_REPORT_VIEW_PERMISSION,
} from './report-page/constants';
import { createDataActions } from './report-page/data-actions';
import { createDetailActions } from './report-page/detail-actions';
import { createExportActions } from './report-page/export-actions';
import { createFilterActions } from './report-page/filter-actions';

/** 创建经营报表页面组合状态。 */
export function useFinanceReportPage() {
  const accessStore = useAccessStore();

  const stores = ref<StoreListItemDto[]>([]);
  const selectedStoreId = ref('');
  const isStoreLoading = ref(false);

  const periodType = ref<FinanceBusinessReportPeriodType>(DEFAULT_PERIOD_TYPE);
  const rows = ref<FinanceBusinessReportListItemDto[]>([]);
  const pagination = reactive({ ...DEFAULT_PAGINATION });
  const isListLoading = ref(false);

  const previewDetail = ref<FinanceBusinessReportDetailDto | null>(null);
  const currentPreviewReportId = ref('');
  const isPreviewDrawerOpen = ref(false);
  const isPreviewLoading = ref(false);
  const isDownloadingPdf = ref(false);
  const isDownloadingExcel = ref(false);

  const isBatchExportModalOpen = ref(false);
  const isBatchExporting = ref(false);

  const storeOptions = computed(() =>
    stores.value.map((item) => ({
      label: item.name,
      value: item.id,
    })),
  );

  const selectedStoreName = computed(
    () =>
      storeOptions.value.find((item) => item.value === selectedStoreId.value)
        ?.label ?? '--',
  );

  const accessCodeSet = computed(
    () => new Set((accessStore.accessCodes ?? []).map(String)),
  );

  const canView = computed(() =>
    accessCodeSet.value.has(FINANCE_REPORT_VIEW_PERMISSION),
  );

  const canExport = computed(() =>
    accessCodeSet.value.has(FINANCE_REPORT_EXPORT_PERMISSION),
  );

  const { clearPageData, loadReportList, loadStores } = createDataActions({
    stores,
    selectedStoreId,
    periodType,
    rows,
    pagination,
    isStoreLoading,
    isListLoading,
  });

  const { handlePageChange, setPeriodType } = createFilterActions({
    periodType,
    pagination,
    loadReportList,
  });

  const { downloadExcel, downloadPdf, openPreview, setPreviewDrawerOpen } =
    createDetailActions({
      canExport,
      selectedStoreId,
      previewDetail,
      currentPreviewReportId,
      isPreviewDrawerOpen,
      isPreviewLoading,
      isDownloadingPdf,
      isDownloadingExcel,
    });

  const {
    handleConfirmBatchExport,
    openBatchExportModal,
    setBatchExportModalOpen,
  } = createExportActions({
    canExport,
    selectedStoreId,
    periodType,
    pagination,
    isBatchExportModalOpen,
    isBatchExporting,
  });

  function setSelectedStoreId(value: string) {
    selectedStoreId.value = value;
  }

  function clearByPermission() {
    stores.value = [];
    selectedStoreId.value = '';
    clearPageData();
    setPreviewDrawerOpen(false);
    setBatchExportModalOpen(false);
  }

  watch(selectedStoreId, async (storeId) => {
    setPreviewDrawerOpen(false);
    setBatchExportModalOpen(false);

    if (!storeId) {
      clearPageData();
      return;
    }

    pagination.page = 1;
    await loadReportList();
  });

  watch(periodType, async (value, oldValue) => {
    if (value === oldValue) {
      return;
    }

    setPreviewDrawerOpen(false);
    setBatchExportModalOpen(false);

    if (!selectedStoreId.value) {
      clearPageData();
      return;
    }

    pagination.page = 1;
    await loadReportList();
  });

  watch(canView, async (value, oldValue) => {
    if (value === oldValue) {
      return;
    }

    if (!value) {
      clearByPermission();
      return;
    }

    await loadStores();
  });

  onMounted(async () => {
    if (!canView.value) {
      clearByPermission();
      return;
    }

    await loadStores();
  });

  onActivated(() => {
    if (!canView.value) {
      return;
    }

    if (stores.value.length === 0 || !selectedStoreId.value) {
      void loadStores();
    }
  });

  return {
    canExport,
    canView,
    currentPreviewReportId,
    downloadPreviewExcel: downloadExcel,
    downloadPreviewPdf: downloadPdf,
    handleConfirmBatchExport,
    handlePageChange,
    isBatchExportModalOpen,
    isBatchExporting,
    isDownloadingExcel,
    isDownloadingPdf,
    isListLoading,
    isPreviewDrawerOpen,
    isPreviewLoading,
    isStoreLoading,
    openBatchExportModal,
    openPreview,
    pagination,
    periodType,
    previewDetail,
    rows,
    selectedStoreId,
    selectedStoreName,
    setBatchExportModalOpen,
    setPeriodType,
    setPreviewDrawerOpen,
    setSelectedStoreId,
    storeOptions,
  };
}
