var tool = {

    buildTree(data, pid) {
        let result = [];
        for (let item of data) {
            item.name = item.NAME;
            item.id = item.ID;
            if (item.PID === pid) {
                let children = this.buildTree(data, item.ID);
                if (children.length) {
                    item.children = children;
                }
                result.push(item);
            }
        }
        return result;
    },

    structureTree(data) {
        return data.map(i => {
            let newItem = {
                id: i.depInfo.departid,
                label: i.depInfo.departName,
                name: i.depInfo.departName,
                value: i.depInfo.departid,
                children: i.childDep,
                ...i.depInfo,
            };
            if (i.childDep && i.childDep.length > 0) {
                newItem.children = this.structureTree(i.childDep);
            }
            return newItem;
        });
    },

    objectToFormData(obj, form, namespace) {
        let fd = form || new FormData();
        let formKey;
        for (let property in obj) {
            if (obj.hasOwnProperty(property)) {
                if (namespace) {
                    formKey = namespace + '[' + property + ']';
                } else {
                    formKey = property;
                }
                if (!(obj[property] instanceof Array) && !(obj[property] instanceof File)) {
                    this.objectToFormData(obj[property], fd, formKey);
                } else {
                    fd.append(formKey, obj[property]);
                }
            }
        }

        return fd;
    }
}

export default tool;