/**
 * 文件职责：交易流水页面状态与动作编排。
 */
import type {
  FinanceTransactionDetailDto,
  FinanceTransactionListItemDto,
  FinanceTransactionStatsDto,
} from '#/api/finance';
import type { OrderAllDetailDto } from '#/api/order';
import type { StoreListItemDto } from '#/api/store';

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

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

import {
  createDefaultFilters,
  DEFAULT_PAGE_SUMMARY,
  DEFAULT_STATS,
  FINANCE_TRANSACTION_EXPORT_PERMISSION,
  FINANCE_TRANSACTION_VIEW_PERMISSION,
} from './transaction-page/constants';
import { createDataActions } from './transaction-page/data-actions';
import { createDrawerActions } from './transaction-page/drawer-actions';
import { createExportActions } from './transaction-page/export-actions';
import { createFilterActions } from './transaction-page/filter-actions';

/** 创建交易流水页面组合状态。 */
export function useFinanceTransactionPage() {
  const accessStore = useAccessStore();

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

  const filters = reactive(createDefaultFilters());
  const rows = ref<FinanceTransactionListItemDto[]>([]);
  const pagination = reactive({
    page: 1,
    pageSize: 20,
    total: 0,
  });
  const pageSummary = reactive({ ...DEFAULT_PAGE_SUMMARY });

  const stats = reactive<FinanceTransactionStatsDto>({ ...DEFAULT_STATS });
  const isListLoading = ref(false);
  const isStatsLoading = ref(false);

  const transactionDetail = ref<FinanceTransactionDetailDto | null>(null);
  const isTransactionDrawerOpen = ref(false);
  const isTransactionDetailLoading = ref(false);

  const relatedOrderDetail = ref<null | OrderAllDetailDto>(null);
  const isRelatedOrderDrawerOpen = ref(false);
  const isRelatedOrderLoading = ref(false);

  const isExportModalOpen = ref(false);
  const isExporting = 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_TRANSACTION_VIEW_PERMISSION),
  );

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

  const { clearPageData, loadPageData, loadStores } = createDataActions({
    stores,
    selectedStoreId,
    filters,
    rows,
    pagination,
    pageSummary,
    stats,
    isStoreLoading,
    isListLoading,
    isStatsLoading,
  });

  const {
    handlePageChange,
    handleSearch,
    setChannel,
    setEndDate,
    setKeyword,
    setPaymentMethod,
    setQuickRange,
    setStartDate,
    setType,
  } = createFilterActions({
    filters,
    pagination,
    loadPageData,
  });

  const {
    openRelatedOrder,
    openTransactionDetail,
    setRelatedOrderDrawerOpen,
    setTransactionDrawerOpen,
  } = createDrawerActions({
    selectedStoreId,
    transactionDetail,
    isTransactionDrawerOpen,
    isTransactionDetailLoading,
    relatedOrderDetail,
    isRelatedOrderDrawerOpen,
    isRelatedOrderLoading,
  });

  const { handleConfirmExport, openExportModal, setExportModalOpen } =
    createExportActions({
      canExport,
      selectedStoreId,
      filters,
      isExportModalOpen,
      isExporting,
    });

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

  function clearByPermission() {
    stores.value = [];
    selectedStoreId.value = '';
    clearPageData();
    setTransactionDrawerOpen(false);
    setRelatedOrderDrawerOpen(false);
    setExportModalOpen(false);
  }

  watch(selectedStoreId, async (storeId) => {
    setTransactionDrawerOpen(false);
    setRelatedOrderDrawerOpen(false);

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

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

  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,
    filters,
    handleConfirmExport,
    handlePageChange,
    handleSearch,
    isExportModalOpen,
    isExporting,
    isListLoading,
    isRelatedOrderDrawerOpen,
    isRelatedOrderLoading,
    isStatsLoading,
    isStoreLoading,
    isTransactionDetailLoading,
    isTransactionDrawerOpen,
    openExportModal,
    openRelatedOrder,
    openTransactionDetail,
    pageSummary,
    pagination,
    relatedOrderDetail,
    rows,
    selectedStoreId,
    selectedStoreName,
    setChannel,
    setEndDate,
    setExportModalOpen,
    setKeyword,
    setPaymentMethod,
    setQuickRange,
    setRelatedOrderDrawerOpen,
    setSelectedStoreId,
    setStartDate,
    setTransactionDrawerOpen,
    setType,
    stats,
    storeOptions,
    transactionDetail,
  };
}
