import {Injectable, OnInit} from "@angular/core";
@Injectable()
export class ToTree implements OnInit {

    constructor() {
        // 定义发射事件
    }

    ngOnInit() {

    }

    exists(list, parentId,myId){
        for(let i=0; i<list.length; i++){
            if(list[i][myId] == parentId){
                return true;
            }
        }
        return false;
    }

    listToTree(myId,pId,list){

        const  nodes = [];
        for(let i=0; i<list.length; i++){
            list[i].checked = false;
            const row = list[i];
            if ( !this.exists(list, row[pId],myId) ){
                nodes.push(row);
            }
        }

        const toDo = [];
        for(let i=0; i<nodes.length; i++){
            toDo.push(nodes[i]);
        }
        while(toDo.length){
            const node = toDo.shift(); // the parent node
            for(let i=0; i<list.length; i++){
                const row = list[i];
                if (row[pId] == node[myId]){
                    if (node.children){
                        node.children.push(row);
                    } else {
                        node.children = [row];
                    }
                    toDo.push(row);
                }
            }
        }
        return nodes;
    }

    toQuery(data){
        let str = '';
        for (let key in data) {
            if (data.hasOwnProperty(key)) {
                const value = data[key];
                str += key + '=' + value + '&';
            }
        }
        str = str.substring(0, str.length - 1);
        return str;
    }
}
