const state = {
  nodeMap: new Map(),
  isEdit: null,
  selectedNode: {},
  selectFormItem: null,
  design: {
    templateId: null,
    templateKey: '',
    templateVersion: 1,
    templateName: '',
    groupId: null,
    formItems: [],
    process: {},
    settings: {
      sign: false
    },
    remark: ''
  },
  runningTask: [],
  noTakeList: [],
  endList: [],
  diagramMode: 'design'
};

const mutations = {
  INIT_NODE_MAP(state) {
    state.nodeMap = new Map();
  },

  // 增量写入单个节点（保证返回新引用以触发响应式）
  UPSERT_NODE(state, node) {
    if (!node || !node.id) return;
    const next = new Map(state.nodeMap);
    next.set(node.id, node);
    state.nodeMap = next;
  },

  // 增量写入多个节点
  UPSERT_NODES(state, nodes = []) {
    const next = new Map(state.nodeMap);
    (Array.isArray(nodes) ? nodes : [nodes]).forEach(n => {
      if (n && n.id) next.set(n.id, n);
    });
    state.nodeMap = next;
  },

  REMOVE_NODE(state, id) {
    const next = new Map(state.nodeMap);
    next.delete(id);
    state.nodeMap = next;
  },
  SET_NODE_MAP(state,value) {
    // 允许传 Map / 节点对象 / 节点数组，统一合并
    const next = new Map(state.nodeMap);
    if (value instanceof Map) {
      for (const [k, v] of value) next.set(k, v);
    } else if (Array.isArray(value)) {
      value.forEach(n => n && n.id && next.set(n.id, n));
    } else if (value && value.id) {
      next.set(value.id, value);
    }
    state.nodeMap = next;
  },
  LOAD_FORM(state, payload) {
    state.design = payload;
  },
  SET_SELECTED_NODE(state, node) {
    state.selectedNode = node;
  },
  UPDATE_SELECT_FORM_ITEM(state, item) {
    state.selectFormItem = item;
  },
  SET_NODE_ASSIGNEE_LIST(state, list) {
    if (state.selectedNode) {
      state.selectedNode.nodeAssigneeList = list;
    }
  }
};

const actions = {
  loadForm({ commit }, value) {
    commit('LOAD_FORM', value);
  },
  updateSelectFormItem({ commit }, item) {
    commit('UPDATE_SELECT_FORM_ITEM', item);
  }
};

const getters = {
  // 你可以根据需要添加 getter
};

export default {
  namespaced: true,
  state,
  mutations,
  actions,
  getters
};
