import { defineStore } from 'pinia';
import { getBusinessFlowList } from '/@/api/flow/flow';

// 定义流程ID映射类型
export interface FlowMap {
  [key: string]: string; // key是VITE_FLOWID_X形式，值是实际的flowId
}

export const useGlobalFlowStore = defineStore('globalFlow', {
  state: () => ({
    flowMap: {} as FlowMap,
    loaded: false,
    loading: false, // 添加loading状态，防止重复请求
  }),
  
  actions: {
    /**
     * 从后端获取流程ID映射关系
     */
    async loadFlowList() {
      // 防止重复请求
      if (this.loading) {
        // 如果正在加载中，等待一段时间后再次检查
        await new Promise(resolve => setTimeout(resolve, 100));
        await this.loadFlowList();
        return
      }
      
      if (this.loaded) {
        return;
      }
      
      this.loading = true;
      try {
        const { data } = await getBusinessFlowList();
        const map: FlowMap = {};
        
        // 将返回的数据转换为键值对映射
        data.forEach(item => {
          map[`VITE_FLOWID_${item.id}`] = item.flowId;
        });
        
        this.flowMap = map;
        this.loaded = true;
      } catch (error) {
        console.error('获取业务流程ID列表失败:', error);
      } finally {
        this.loading = false;
      }
    },
    
    /**
     * 根据环境变量名获取实际的flowId
     * @param envVar 环境变量名，如 VITE_FLOWID_1
     */
    getFlowId(envVar: string): string | undefined {
      // 如果已经从接口加载了数据，则使用接口数据
      if (this.loaded && this.flowMap[envVar]) {
        return this.flowMap[envVar];
      }
      
      // 否则降级使用环境变量中的值
      return import.meta.env[envVar];
    }
  }
});