/**
 * @file TreeCalculation vendor
 * @author liangxiaojun(liangxiaojun@derbysoft.com)
 */

import Util from './Util';

const rootSymbol = Symbol('root');

function calDepth(data, path) {

    let list = data,
        depth = 0;

    if (!data || !path) {
        return depth = 0;
    }

    for (let item of path) {
        if (item.index in list) {
            list = list[item.index].children;
            depth++;
        } else {
            return depth;
        }
    }

    if (list && list.length > 0) {
        return depth + 1;
    }

    return depth;

}

function calPath(value, data, props) {

    if (!value || !data) {
        return;
    }

    data[rootSymbol] = true;

    return traverseData(data, value, props);

}

function traverseData(node, value, props, index = 0) {

    if (!node || node.length < 1 || !value) {
        return;
    }

    const {valueField, displayField} = props;

    // find in children
    if (node.children && node.children.length > 0) {

        for (let i = 0, len = node.children.length; i < len; i++) {

            // traverse child node
            const path = traverseData(node.children[i], value, props, i);

            // if finded in child node
            if (path) {

                if (node[rootSymbol]) {
                    return path;
                }

                path.unshift({
                    value: node,
                    index: index
                });
                return path;

            }

        }
    }

    if (Util.getValueByValueField(node, valueField, displayField)
        === Util.getValueByValueField(value, valueField, displayField)) {
        return [{
            value: node,
            index
        }];
    }

    return;

}

export default {
    calDepth,
    calPath
};
@@ -118,44 +118,8 @@
 ';%0A%0A
-const rootSymbol = Symbol('root');%0A%0A
 func
@@ -621,38 +621,8 @@
  %7D%0A%0A
-    data%5BrootSymbol%5D = true;%0A%0A
     
@@ -659,16 +659,22 @@
 e, props
+, null
 );%0A%0A%7D%0A%0Af
@@ -713,16 +713,24 @@
 , props,
+ parent,
  index =
@@ -1103,16 +1103,22 @@
 , props,
+ node,
  i);%0A%0A  
@@ -1203,24 +1203,15 @@
 if (
-node%5BrootSymbol%5D
+!parent
 ) %7B%0A

update TreeCalculation