import type {
  FinanceSettlementDetailStateMap,
  FinanceSettlementExpandAction,
} from '../../types';

/**
 * 文件职责：到账查询展开明细动作。
 */
import { getFinanceSettlementDetailApi } from '#/api/finance';

import { getSettlementRowKey } from './helpers';

interface DetailActionOptions {
  detailStates: FinanceSettlementDetailStateMap;
  expandedRowKeys: { value: string[] };
  selectedStoreId: { value: string };
}

/** 创建展开明细动作。 */
export function createDetailActions(options: DetailActionOptions) {
  function clearDetailStates() {
    options.expandedRowKeys.value = [];
    for (const key of Object.keys(options.detailStates)) {
      Reflect.deleteProperty(options.detailStates, key);
    }
  }

  async function handleExpand(action: FinanceSettlementExpandAction) {
    const key = getSettlementRowKey(action.row);

    if (!action.expanded) {
      options.expandedRowKeys.value = options.expandedRowKeys.value.filter(
        (item) => item !== key,
      );
      return;
    }

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

    if (!options.expandedRowKeys.value.includes(key)) {
      options.expandedRowKeys.value = [...options.expandedRowKeys.value, key];
    }

    const currentState = options.detailStates[key] ?? {
      loading: false,
      items: [],
    };

    if (currentState.loading || currentState.items.length > 0) {
      options.detailStates[key] = currentState;
      return;
    }

    currentState.loading = true;
    options.detailStates[key] = currentState;

    try {
      const result = await getFinanceSettlementDetailApi({
        storeId: options.selectedStoreId.value,
        arrivedDate: action.row.arrivedDate,
        channel: action.row.channel,
      });

      currentState.items = result.items;
    } finally {
      currentState.loading = false;
    }
  }

  return {
    clearDetailStates,
    handleExpand,
  };
}
