import { defineStore } from 'pinia';

export interface nodeModelsMap {
  nodeMap: Map<string, Array<string>>;
}
export const useNodeByModelsStore = defineStore('nodeByModels', {
  // 状态
  state(): nodeModelsMap {
    return {
      nodeMap: new Map<string, Array<string>>()
    };
  },
  // 方法
  actions: {
    /**
     * 保存，更新  节点——组件的映射关系
     * @param nodeId 4遥节点id
     * @param modelId vue组件id
     */
    saveOrUpdate(nodeId: string, modelId: string) {
      //   console.log('nodeId：', nodeId);
      //   console.log('modelId：', modelId);
      if (this.nodeMap.has(nodeId)) {
        const modelIds = this.nodeMap.get(nodeId)!;
        if (!modelIds.includes(modelId)) {
          modelIds.push(modelId);
        }
      } else {
        this.nodeMap.set(nodeId, [modelId]);
      }
    },
    /**
     * 修改 节点——组件的映射关系
     * @param newNodeId 新节点id
     * @param oldNodeId 旧节点id
     * @param modelId vue组件id
     */
    change(newNodeId: string, oldNodeId: string, modelId: string) {
      this.delete(oldNodeId, modelId);
      this.saveOrUpdate(newNodeId, modelId);
    },
    /**
     * 删除 节点——组件的映射关系
     * @param nodeId 4遥节点id
     * @param modelId vue组件id
     */
    delete(nodeId: string, modelId: string) {
      if (!this.nodeMap.has(nodeId)) return;
      const modelIds = this.nodeMap.get(nodeId);
      if (modelIds.includes(modelId)) {
        modelIds.splice(modelIds.indexOf(modelId), 1);
      }
      if (modelIds.length === 0) {
        this.nodeMap.delete(nodeId);
      }
    }
  }
});
