/**
 * 文件职责：交易流水详情与关联订单抽屉动作。
 */
import type { FinanceTransactionDetailDto } from '#/api/finance';
import type { OrderAllDetailDto } from '#/api/order';

import { getFinanceTransactionDetailApi } from '#/api/finance';
import { getOrderAllDetailApi } from '#/api/order';

interface DrawerActionOptions {
  isRelatedOrderDrawerOpen: { value: boolean };
  isRelatedOrderLoading: { value: boolean };
  isTransactionDetailLoading: { value: boolean };
  isTransactionDrawerOpen: { value: boolean };
  relatedOrderDetail: { value: null | OrderAllDetailDto };
  selectedStoreId: { value: string };
  transactionDetail: { value: FinanceTransactionDetailDto | null };
}

/** 创建抽屉动作。 */
export function createDrawerActions(options: DrawerActionOptions) {
  function setTransactionDrawerOpen(value: boolean) {
    options.isTransactionDrawerOpen.value = value;
    if (!value) {
      options.transactionDetail.value = null;
    }
  }

  function setRelatedOrderDrawerOpen(value: boolean) {
    options.isRelatedOrderDrawerOpen.value = value;
    if (!value) {
      options.relatedOrderDetail.value = null;
    }
  }

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

    options.isTransactionDrawerOpen.value = true;
    options.transactionDetail.value = null;
    options.isTransactionDetailLoading.value = true;
    try {
      options.transactionDetail.value = await getFinanceTransactionDetailApi({
        storeId: options.selectedStoreId.value,
        transactionId,
      });
    } finally {
      options.isTransactionDetailLoading.value = false;
    }
  }

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

    options.isRelatedOrderDrawerOpen.value = true;
    options.relatedOrderDetail.value = null;
    options.isRelatedOrderLoading.value = true;
    try {
      options.relatedOrderDetail.value = await getOrderAllDetailApi({
        storeId: options.selectedStoreId.value,
        orderNo,
      });
    } finally {
      options.isRelatedOrderLoading.value = false;
    }
  }

  return {
    openRelatedOrder,
    openTransactionDetail,
    setRelatedOrderDrawerOpen,
    setTransactionDrawerOpen,
  };
}
