import { defineStore } from 'pinia';
import { ref } from 'vue';
import { useExecutionApi } from '@/api/execution';
import to from 'await-to-js';

const executionApi = useExecutionApi();

export const useApprovalFlowStore = defineStore('approvalFlow', () => {
  // 审批记录列表（Execution.GetParticipantByProcInstID 返回的数据）
  const apprList = ref<any[]>([]);
  // 当前处于的节点（用于高亮）
  const currentNode = ref<string>('');

  // 加载状态
  const fetchLoading = ref<boolean>(false);

  /**
   * 根据流程实例ID获取审批记录
   * @param id 流程实例ID（procInstId）
   */
  async function fetchByProcInstId(id: number) {
    fetchLoading.value = true;
    apprList.value = [];
    currentNode.value = '';

    const [err, res] = await to(executionApi.getParticipantByProcInstID({ id })) as [any, any];

    fetchLoading.value = false;

    if (err) {
      console.error('获取审批记录失败:', err);
      return { success: false };
    }

    if (res && res.code === 200) {
      const arr = res.data || [];
      apprList.value = arr;

      // 简单规则：第一个审批中或尚未审批的节点作为当前节点
      const current = arr.find((item: any) => item.type !== 'start' && !item.approveResult);
      currentNode.value = current?.nodeId || '';

      return { success: true };
    }

    return { success: false };
  }

  return {
    apprList,
    currentNode,
    fetchLoading,
    fetchByProcInstId
  };
});

