import { Map, fromJS, List } from "immutable";
export function treeSearchParam(
  state = Map(
    fromJS({
      entity: {
        roleId: "",
      },
    })
  ),
  action
) {
  switch (action.type) {
    case "update_search_param":
      state = state.mergeIn(["entity"], action.data);
      return state;
    default:
      return state;
  }
}
export function treeData(state = List(), action) {
  let temp;
  switch (action.type) {
    case "update":
      return List(fromJS(action.data));
    case "updateChildren":
      temp = updateChildren(state.toJS(), action.data);
      return List(fromJS(temp));
    case "addChildren":
      return addChildren(state, action.data);
    default:
      return state;
  }
}
function updateChildren(
  list,
  { functioinId, children, subNodeFlag, ...orther }
) {
  return list.map((item) => {
    if (item.functioinId === functioinId) {
      item = Object.assign(item, orther);
      if (children !== undefined) item.children = children;
      if (subNodeFlag !== undefined) item.subNodeFlag = subNodeFlag;
      return item;
    } else {
      if (item && item.children) {
        let temp = item;
        temp.children = updateChildren(item.children, {
          functioinId,
          children,
          subNodeFlag,
          ...orther,
        });
        return temp;
      } else {
        return item;
      }
    }
  });
}

function addChildren(state, { parentId, ...orther }) {
  return state.map((value, key) => {
    let temp;
    if (value.gf(["functioinId"]) === parentId) {
      if (value.has("children")) {
        temp = value.update("children", (children) =>
          children.push({ parentId, ...orther })
        );
      } else {
        temp = value.set("children", fromJS([{ parentId, ...orther }]));
      }
      temp = temp.set("subNodeFlag", "1");
      return temp;
    } else {
      if (value.has("children")) {
        temp = value.update("children", (children) => {
          return addChildren(children, { parentId, ...orther });
        });
      } else {
        temp = value;
      }
    }
    return temp;
  });
}
