import { defineStore } from 'pinia';
import { ref } from 'vue';
import { useFlowApi } from '@/api/flow/index';
import to from 'await-to-js';

const flowApi = useFlowApi();

export const useFlowStore = defineStore('flow', () => {
  // 审批实例节点列表
  const apprList = ref<any[]>([]);
  // 当前处于的节点
  const currentNode = ref<string>('');
  
  // 加载状态
  const fetchFlowLoading = ref<boolean>(false);

  /**
   * 获取审批实例详情列表
   * @param id 表单ID
   * @param businessCode 单据编码
   * @param defCode 流程编码
   * @param memberList 额外的成员匹配列表（比如为了取templateContent）
   */
  async function fetchFlowInstance(id: number, businessCode: string, defCode: string, memberList: any[] = []) {
    fetchFlowLoading.value = true;
    apprList.value = [];
    currentNode.value = '';

    const params = { id, businessCode, defCode };
    const [err, res] = await to(flowApi.getFlowInstance(params)) as [any, any];
    
    fetchFlowLoading.value = false;

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

    if (res && res.code === 200) {
      const arr = res.data?.nodes || [];
      // 匹配附加数据
      apprList.value = arr.map((item: any) => {
        const obj = memberList.find((i: any) => i.memberId === item.userId);
        return {
          ...item,
          templateContent: obj?.templateContent || null
        };
      });
      currentNode.value = res.data?.nodeId || '';
      return { success: true };
    }

    return { success: false };
  }

  return {
    apprList,
    currentNode,
    fetchFlowLoading,
    fetchFlowInstance
  };
});
