import { compact, cloneDeep, orderBy } from 'lodash';

export function computPlaceTreeHasUnknown(list, isNoDeep) {
  let treeData;
  list = orderBy(list, ['provinceId'], ['asc']);
  if (!isNoDeep) {
    treeData = cloneDeep(list);
  } else {
    treeData = list;
  }
  let treeMap = {};

  treeData.forEach((v) => {
    treeMap[v.areaCode] = v;
  });

  function getPcodesPlace(codes) {
    return compact(codes.map((v) => treeMap[v]));
  }

  let arr = [];
  treeData.forEach((item, index) => {
    let hasParent = false;
    if (item.level >= 5 && Array.isArray(item.pcodes)) {
      const pPlaces = getPcodesPlace(item.pcodes);
      const pLevels = pPlaces.map((v) => (v ? v.level : 0));
      const item2 = pPlaces[pLevels.indexOf(Math.max.apply(null, pLevels))];
      if (item2) {
        hasParent = true;
        !Array.isArray(item2.children) && (item2.children = []);
        item2.children.push(item);
      }
    }

    if (item.level < 5) {
      if (item.parentCode && treeMap[item.parentCode]) {
        hasParent = true;
        const item2 = treeMap[item.parentCode];
        !Array.isArray(item2.children) && (item2.children = []);
        item2.children.push(item);
      }
    }

    !hasParent && arr.push(index);
  });
  treeMap = null;

  return treeData.filter((v, index) => arr.includes(index));
}