/**
 * 项目管理相关js
 *
 * @author CaiAoLin
 * @date 2017/8/22
 * @version
 */
let Tree = null;
let movetoZTree = null;
let copytoZTree = null;
let engineering = [];
let feeRateData = [];
let isSaving = false;
let projectProperty = [];
let projectType = {
    folder: 'Folder',
    tender: 'Tender',
    project: 'Project',
    engineering: 'Engineering'
};
let ProjTreeSetting = {
    tree: {
        id: 'ID',
        pid: 'ParentID',
        nid: 'NextSiblingID',
        btnColumn: 1,
        nullId: -1
    },
    columns: [
        {
            head: '',
            data: '',
            width: '40',
            event: {}
        },
        {
            head: '工程列表',
            data: 'name',
            width: '78%',
            event: {
                getText: function (html, node, text) {
                    let className = '';
                    let aClassName = '';
                    switch (node.data.projType) {
                        case projectType.folder:
                            className = "fa fa-folder-open-o";
                            break;
                        case projectType.tender:
                            className = "fa fa-sticky-note-o";
                            break;
                        case projectType.project:
                            className = "fa fa-cubes";
                            aClassName = "open-sidebar";
                            break;
                        case projectType.engineering:
                            className = "fa fa-cube";
                            aClassName = "open-sidebar";
                            break;
                    }
                    let icon = '<i class ="tree-icon '+ className +'"></i>';
                    html.push((node && node.data && node.data.projType === projectType.folder) ? '&nbsp;' : '');
                    html.push('<a ');
                    if (aClassName !== '') {
                        html.push('class="'+ aClassName +'" ');
                    }
                    if (node && node.data) {
                        //html.push('href="/main?project=', node.id(), '"');
                        html.push('href="javacript:void(0);"');
                    }
                    html.push('>', icon, '&nbsp;', text, '<a>');
                },
                getIcon: function (html, node) {
                    if (node.data.projType === projectType.tender) {
                        html.push('<span class="poj-icon">└</span>');
                    }
                },
                tdBindEvent: function (td, node) {
                    if (node.data.projType === projectType.tender) {
                        $('a:eq(1)', td).bind('click', function () {
                            BeforeOpenProject(node.id(), {'fullFolder': GetFullFolder(node.parent)}, function () {
                                window.location.href = '/main?project=' + node.id();
                            });
                            return false;
                        });
                    }
                }
            }
        },
        {
            head: '最近使用',
            data: 'lastDateTime',
            width: '10%',
            event: {
                getText: function (html, node, text) {
                    if (node.data.projType === projectType.tender) {
                        html.push(text ? new Date(text).Format('yyyy-MM-dd') : '');
                    }
                }
            }
        },
        {
            head: '创建日期',
            data: 'createDateTime',
            width: '10%',
            event: {
                getText: function (html, node, text) {
                    if (node.data.projType === projectType.tender) {
                        html.push(text ? new Date(text).Format('yyyy-MM-dd') : '');
                    }
                }
            }
        }
    ],
    viewEvent: {
        beforeSelect: function (node) {
            if (node && node.row) {
                $('td:eq(0)', node.row).children().remove();
            }
        },
        onSelectNode: function (node) {
            $(".tools-btn > a").not(".disabled").addClass("disabled");
            switch(node.data.projType) {
                case projectType.project:
                    $("#add-engineering-btn").removeClass("disabled");
                    $("#add-project-btn").removeClass("disabled");
                    break;
                case projectType.folder:
                    $("#add-folder-btn").removeClass("disabled");
                    $("#add-project-btn").removeClass("disabled");
                    break;
                case projectType.engineering:
                    $("#add-tender-btn").removeClass("disabled");
                    $("#add-engineering-btn").removeClass("disabled");
                    break;
                case projectType.tender:
                    $("#add-tender-btn").removeClass("disabled");
                    $("#move-to-btn").removeClass("disabled");
                    $("#copy-to-btn").removeClass("disabled");
                    $("#share-btn").removeClass("disabled");
                    $("#cooperate-btn").removeClass("disabled");
                    break;
            }
            $("#del-btn").removeClass("disabled");
            $("#rename-btn").removeClass("disabled");
            $('td:eq(0)', node.row).append($('<i class="fa fa-sort" data-toggle="tooltip" data-placement="top" title="长安拖动"></i>'));
        }
    }
};

$(document).ready(function() {
    init();

    // 侧滑数据
    $(".poj-list").on('click', ".open-sidebar", function() {
        setDataToSideBar();
        $(".slide-sidebar").animate({width:"800"}).addClass("open");
    });

    // 新增建设项目点击
    $('#add-project-btn').click(function () {
        let selectedItem = Tree.selected();
        try {
            let selectedType = selectedItem !== null && selectedItem.data !== undefined ?
                selectedItem.data.projType : projectType.folder;
            if (selectedType !== projectType.folder && selectedType !== projectType.project) {
                throw '建设项目只能添加到最外层或文件夹中';
            }
            $('#add-project-dialog').modal('show');
        } catch (error) {
            alert(error);
        }
    });

    // 新增建设项目操作
    $('#addProjOk').click(function () {
        AddProject();
    });

    // 选择计价方式
    $("input[name='valuation_type']").click(function() {
        let type = $(this).val();
        let targetData = type === 'bill' ? JSON.parse(billValuation) : JSON.parse(rationValuation);
        let html = '<option value="">请选择计价规则</option>';

        for(let valuation of targetData) {
            if (valuation === null) {
                continue;
            }
            html += '<option value="'+ valuation._id +'">'+ valuation.name +'</option>';
        }
        $("#valuation").html(html);
    });

    // 新增单项项目点击
    $("#add-engineering-btn").click(function() {
        let selectedItem = Tree.selected();
        try {
            if (selectedItem === null) {
                throw '请选择要添加到的项目工程';
            }
            let selectedType = selectedItem.data !== undefined ? selectedItem.data.projType : '';
            if (selectedType !== projectType.project && selectedType !== projectType.engineering) {
                throw '单项项目只能添加到建设项目中';
            }
            $("#add-engineering-dialog").modal("show");
        } catch (error) {
            alert(error);
        }
    });

    // 新增单项工程操作
    $("#add-engineering-confirm").click(function() {
        AddEngineering();
    });

    // 新增单位工程点击
    $("#add-tender-btn").click(function() {
        let selectedItem = Tree.selected();
        try {
            if (selectedItem === null) {
                throw '请选择要添加到的单项工程';
            }
            let selectedType = selectedItem.data !== undefined ? selectedItem.data.projType : '';
            if (selectedType !== projectType.engineering && selectedType !== projectType.tender) {
                throw '单项项目只能添加到单项工程中';
            }
            $("#add-tender-dialog").modal("show");
        } catch (error) {
            alert(error);
        }
    });

    // 新增单位工程弹层改变
    $('#add-tender-dialog').on('show.bs.modal', function() {
        // 当前选中的建设项目
        let selectedItem = Tree.selected();
        let projectInfo = null;
        if (selectedItem.data.projType === projectType.tender) {
            projectInfo = selectedItem !== null && selectedItem.parent !== undefined && selectedItem.parent.parent !== undefined ?
                selectedItem.parent.parent : null;
        } else {
            projectInfo = selectedItem !== null && selectedItem.parent !== undefined ? selectedItem.parent : null;
        }
        if (projectInfo !== null) {
            let parentID = projectInfo.data.ID;
            // 获取当前的数据属性
            getProperty(projectInfo.data);
        }

        // 获取单价文件数据
        getUnitFile(projectInfo.data.ID);
        // 获取费率文件数据
        getFeeRateFile(projectInfo.data.ID);
    });

    // 新增单位工程
    $("#add-tender-confirm").click(function() {
        AddTender();
    });

    // 新增文件夹按钮点击
    $("#add-folder-btn").click(function() {
        let selectedItem = Tree.selected();
        try {
            let selectedType = selectedItem !== null && selectedItem.data !== undefined ?
                    selectedItem.data.projType : projectType.folder;
            if (selectedType !== projectType.folder) {
                throw '文件夹只能添加在最外层或者添加在文件夹中';
            }
            $("#add-folder-dialog").modal("show");
        } catch (error) {
            alert(error);
        }
    });

    // 新增文件夹操作
    $("#add-folder-confirm").click(function() {
        AddFolder();
    });

    // 删除按钮点击
    $('#del-btn').click(function() {
        if (Tree && Tree.selected()) {
            $('#del').modal('show');
        }
    });

    // 删除时文字替换
    $('#del').on('show.bs.modal', function() {
        let hasTenderChild = function (children) {
            for (let i = 0; i < children.length; i++) {
                if (children[i].children.length === 0) {
                    if (children[i].data.projType === 'Tender') {
                        return true;
                    }
                } else if (hasTenderChild(children[i].children)) {
                    return true;
                }
            }
            return false;
        };
        // 显示内容
        let tenderHintElement = $('#tenderHint');
        let folderHintElement = $('#folderHint');
        if (Tree.selected().children.length === 0) {
            tenderHintElement.show();
            tenderHintElement.text('删除 "' + Tree.selected().data.name +'" ？');
            folderHintElement.hide();
        } else {
            tenderHintElement.hide();
            folderHintElement.show();
            folderHintElement.text('删除 "'+ Tree.selected().data.name +'" 以及它包含的子项？');
        }
        // 显示是否可以找回
        if (hasTenderChild([Tree.selected()])) {
            $('#restoreHint').show();
        } else {
            $('#restoreHint').hide();
        }
    });

    // 删除操作
    $('#delete-confirm').click(function () {
        let updateData = null;
        let dialog = $('#del');
        if (Tree) {
            updateData = GetDeleteUpdateData(Tree.selected());
            UpdateProjectData(updateData, function () {
                dialog.modal('hide');
                Tree.removeNode(Tree.selected());
            });
        }
    });

    // 重命名按钮点击
    $('#rename-btn').click(function() {
        if (!Tree) {
            return false;
        }
        if (!Tree.selected()) {
            alert('请选择需要重命名的数据');
            return false;
        }
        $('#rename-dialog').modal('show');
    });

    // 重命名操作
    $("#rename-confirm").click(function() {
        let select = Tree.selected();
        let newName = $('#rename-name').val();
        let dialog = $('#rename-dialog');
        if (newName === '') {
            alert('请输入重命名的名称');
            return false;
        }

        if (newName === select.data.name) {
            dialog.modal('hide');
            return false;
        }
        RenameProject(select.id(), newName, select.data.ParentID, function () {
            dialog.modal('hide');
            select.data.name = newName;
            Tree.refreshNodesDom([select]);
        });
    });

    // 移动到按钮点击
    $('#move-to-btn').click(function () {
        if (Tree && Tree.selected()) {
            $('#move-to-dialog').modal('show');
        }
    });

    // 移动到窗口内容重组
    $('#move-to-dialog').on('show.bs.modal', function () {
        movetoZTree = ConvertTreeToZtree(Tree, $('#treeDemo'), Tree.selected());
    });

    // 移动到操作
    $('#move-to-confirm').click(function () {
        console.log(111);
        let updateData = null;
        let dialog = $('#move-to-dialog');
        let target = GetTargetTreeNode($.fn.zTree.getZTreeObj('treeDemo'));
        let cur = Tree.selected();

        if (!target) {
            dialog.modal('hide');
            return false;
        }
        if (target.data.projType !== projectType.engineering) {
            alert("请移动到单项工程中!");
            return false;
        }
        // 判断同级是否有同名
        if (target.children.length > 0) {
            for (let tmp in target.children) {
                if (tmp === 0) {
                    continue;
                }
                if (target.children[tmp].data.name === cur.data.name) {
                    alert("对应单项工程中存在同名数据!");
                    return false;
                }
            }
        }

        let parent = target;
        let next = target.firstChild();
        if (parent !== cur.parent || (next !== cur && next !== cur.nextSibling)){
            let typeInfo = {
                updateType: 'update',
                projectType: null
            };
            updateData = GetUpdateData(parent, next, '', null, Tree.selected().id(), typeInfo);
            UpdateProjectData(updateData, function (data) {
                dialog.modal('hide');
                Tree.move(Tree.selected(), parent, next);
            });
        } else {
            dialog.modal('hide');
        }
    });

    // 复制到按钮点击
    $('#copy-to-btn').click(function () {
        let selectedItem = Tree.selected();
        try {
            let selectedType = selectedItem !== null && selectedItem.data !== undefined ?
                selectedItem.data.projType : '';
            if (selectedType !== projectType.tender) {
                throw '请选择单位工程进行复制';
            }
        } catch (error) {
            alert(error);
            return false;
        }
        $('#copy-to-dialog').modal('show');
    });
    // 复制到弹层替换
    $('#copy-to-dialog').on('show.bs.modal', function () {
        copytoZTree = ConvertTreeToZtree(Tree, $('#treeDemo2'), null);
    });

    // 复制到操作
    $("#copy-to-confirm").click(function() {
        let dialog = $('#copy-to-dialog');
        let target = GetTargetTreeNode($.fn.zTree.getZTreeObj('treeDemo2'));
        let parent = null;
        let next = null;
        let pre = null;
        let cur = Tree.selected();
        if (!target) {
            return false;
        }
        if (target.data.projType !== projectType.engineering) {
            alert("请移动到单项工程中!");
            return false;
        }
        if (target.data.projType !== projectType.tender && target.children.length !== 0 &&
            target.firstChild().data.projType !== projectType.tender) {
            dialog.modal('hide');
        }

        // 判断同级是否有同名
        if (target.children.length > 0) {
            for (let tmp in target.children) {
                if (tmp === 0) {
                    continue;
                }
                if (target.children[tmp].data.name === cur.data.name) {
                    alert("对应单项工程中存在同名数据!");
                    return false;
                }
            }
        }

        if (target.data.projType === projectType.tender) {
            parent = target.parent;
            next = target.nextSibling;
        } else {
            parent = target;
            next = target.firstChild();
        }

        if (parent !== cur.parent || (next !== cur && next !== cur.nextSibling)){
            CommonAjax.post('/pm/api/getNewProjectID', {count: 1, user_id: userID}, function (IDs) {
                let typeInfo = {
                    updateType: 'copy',
                    projType: cur.data.projectType
                };
                let updateData = GetUpdateData(parent, next, cur.data.name, cur.data.property, IDs.lowID, typeInfo);
                updateData.forEach(function (data) {
                    if (data.updateType === 'copy') {
                        data['srcProjectId'] = cur.id();
                    }
                });
                pre = GetNeedUpdatePreNode(parent, next);
                if (pre) {
                    updateData = {};
                    updateData['updateType'] = 'update';
                    updateData['updateData'] = {};
                    updateData['updateData'][Tree.setting.tree.id] = pre.id();
                    updateData['updateData'][Tree.setting.tree.nid] = node.tree.maxNodeId() + 1;
                }
                Tree.maxNodeId(IDs.lowID - 1);
                CommonAjax.post('/pm/api/copyProjects', {updateData: updateData, user_id: userID}, function (data) {
                    dialog.modal('hide');
                    data.forEach(function (nodeData) {
                        if (nodeData.updateType === 'copy') {
                            Tree.addNodeData(nodeData.updateData, parent, next);
                        }
                    });
                }, function () {
                    dialog.modal('hide');
                });
            });
        }
    });

    // 选择工程专业后动态更改费率文件等数据
    $("#tender-engineering").change(function() {
        if (projectProperty.engineeringList === undefined || projectProperty.engineeringList.length <= 0) {
            return false;
        }
        let selectedEngineering = $(this).val();
        selectedEngineering = parseInt(selectedEngineering);
        let currentLib = {};
        for(let engineering of projectProperty.engineeringList) {
            if (engineering.engineering === selectedEngineering) {
                currentLib = engineering.lib;
            }
        }

        if (Object.keys(currentLib).length <= 0) {
            return false;
        }
        // 输出数据到页面
        if (currentLib.fee_lib !== undefined && currentLib.fee_lib.length > 0) {
            $("#tender-fee-rate").children("option").first().val("newFeeRate-"+currentLib.fee_lib[0].id);
        }
        $(this).parent().siblings('.hidden-area').slideDown('fast');
    });
});

/**
 * 初始化数据
 *
 * @return {void}
 */
function init() {
    billValuation = billValuation.replace(/\n/g, '\\n');
    rationValuation = rationValuation.replace(/\n/g, '\\n');

    let table = $('#ProjTree');
    $('thead', table).remove();
    $('tbody', table).remove();
    GetAllProjectData(function (data) {
        Tree = $.fn.treeTable.init(table, ProjTreeSetting, data);
    });

    // 显示默认两个可选菜单
    $(".tools-btn > a").not(".disabled").addClass("disabled");
    $("#add-folder-btn").removeClass("disabled");
    $("#add-project-btn").removeClass("disabled");

    engineering = engineeringList !== null && engineeringList !== undefined ? JSON.parse(engineeringList) : [];
}

/**
 * 新增建设项目
 *
 * @return {boolean}
 */
function AddProject() {
    let name = $('#project-name').val();
    if (name === '') {
        alert('请填写工程');
        return false;
    }
    let valuation = $("#valuation").val();
    if (valuation === '') {
        alert("请选择计价规则");
        return false;
    }
    let valuationName = $("#valuation").children("option:selected").text();
    let valuationType = $("input[name='valuation_type']:checked").val();
    let engineeringList = [];

    let valuationData = valuationType === 'bill' ? JSON.parse(billValuation) : JSON.parse(rationValuation);
    for(let tmp of valuationData) {
        if (tmp._id === valuation) {
            engineeringList = tmp.engineering_list;
            break;
        }
    }
    let projectInfo = {
        valuation: valuation,
        valuationType: valuationType,
        valuationName: valuationName,
        engineeringList: engineeringList
    };

    let callback = function() {
        $("#add-project-dialog").modal("hide");
        $("#project-name").val('');
        $("input[name='valuation_type']").removeAttr('checked');
        $("#valuation").children("option").not(":eq(0)").remove();
    };
    let selectedItem = Tree.selected();

    // 如果选择的是建设项目则新增同级数据
    if (selectedItem !== null && selectedItem.data.projType === projectType.project) {
        AddSiblingsItem(name, projectInfo, projectType.project, callback);
    } else {
        AddChildrenItem(name, projectInfo, projectType.project, callback);
    }
}

/**
 * 新增子元素
 *
 * @param {String} name
 * @param {String} type
 * @param {function} callback
 * @return {void}
 */
function AddChildrenItem(name, property, type, callback) {
    let parent = Tree.selected() ? Tree.selected() : Tree._root;
    let next = Tree.selected() ? Tree.selected().firstChild() : Tree.firstNode();
    GetNewProjectId(function(IDs) {
        let typeInfo = {
            updateType: 'new',
            projectType: type
        };
        let updateData = GetUpdateData(parent, next, name, property, IDs.lowID, typeInfo);
        Tree.maxNodeId(IDs.lowID - 1);
        UpdateProjectData(updateData, function(datas){
            datas.forEach(function (data) {
                if (data.updateType === 'new') {
                    Tree.addNodeData(data.updateData, parent, next);
                }
            });
            callback();
        });
    });
}

/**
 * 新增同级元素
 *
 * @param {String} name
 * @param {String} type
 * @param {function} callback
 * @return {void}
 */
function AddSiblingsItem(name, property, type, callback) {
    let selected = Tree.selected();
    let parent = selected ? selected.parent : Tree._root;
    let next = selected ? selected.nextSibling : Tree.firstNode();
    GetNewProjectId(function(IDs) {
        let typeInfo = {
            updateType: 'new',
            projectType: type
        };
        let updateData = GetUpdateData(parent, next, name, property, IDs.lowID, typeInfo);
        Tree.maxNodeId(IDs.lowID - 1);
        UpdateProjectData(updateData, function(datas){
            datas.forEach(function (data) {
                if (data.updateType === 'new') {
                    Tree.addNodeData(data.updateData, parent, next);
                }
            });
            callback();
        });
    });
}

/**
 * 新增单项工程
 *
 * @return {boolean}
 */
function AddEngineering() {
    let name = $('#engineering-name').val();
    if (name === '') {
        alert('请填写单项工程名称');
        return false;
    }
    let callback = function() {
        $("#add-engineering-dialog").modal("hide");
        $("#engineering-name").val('');
    };
    let selectedItem = Tree.selected();
    // 如果选择的是单项工程则新增同级数据
    if (selectedItem !== null && selectedItem.data.projType === projectType.engineering) {
        AddSiblingsItem(name, null, projectType.engineering, callback);
    } else {
        AddChildrenItem(name, null, projectType.engineering, callback);
    }
}

/**
 * 新增单位工程
 *
 * @return {boolean}
 */
function AddTender() {
    try {
        let name = $('#tender-name').val();
        if (name === '') {
            throw '请填写单位工程名称';
        }

        let engineering = $("#tender-engineering").val();
        if (engineering === '') {
            throw '请选择工程专业';
        }

        let unitPriceFile = $("#unit-price").val();
        let unitPriceName = unitPriceFile !== '' ? $("#unit-price").children("option:selected").text() : name;

        let feeFile = $("#tender-fee-rate").val();
        if (feeFile === '') {
            throw '请选择费率文件';
        }
        let feeFileName = $("#tender-fee-rate").children("option:selected").text();

        let valuation = $("#tender-valuation").val();
        let valuationName = $("#tender-valuation").children("option:selected").text();
        let valuationType = $("input[name='tender_valuation_type']:checked").val();

        let engineering_id = undefined;
        let valuationData = valuationType === 'bill' ? JSON.parse(billValuation) : JSON.parse(rationValuation);
        let engineeringList = [];
        for(let tmp of valuationData) {
            if (tmp._id === valuation) {
                engineeringList = tmp.engineering_list;
                break;
            }
        }
        for(let tmp of engineeringList) {
            if (tmp.engineering == engineering) {
                engineering_id = tmp.engineering_id;
                break;
            }
        }
        let engineeringName = $('#tender-engineering').children("option:selected").text();

        let callback = function() {
            $("#add-tender-dialog").modal("hide");
            $('#tender-name').val('');
            $("#tender-fee-rate").children("option").removeAttr("selected");
            $("#tender-engineering").children("option").removeAttr("selected");
            $(".hidden-area").hide();
        };
        let selectedItem = Tree.selected();
        let tenderInfo = {
            valuation: valuation,
            valuationType: valuationType,
            valuationName: valuationName,
            engineering: engineering,
            engineering_id: engineering_id,
            engineeringName: engineeringName,
            unitPriceFile: {name: unitPriceName, id: unitPriceFile},
            feeFile: {name: feeFileName, id: feeFile}
        };
        // 如果选择的是单项工程则新增同级数据
        if (selectedItem !== null && selectedItem.data.projType === projectType.tender) {
            AddSiblingsItem(name, tenderInfo, projectType.tender, callback);
        } else {
            AddChildrenItem(name, tenderInfo, projectType.tender, callback);
        }

    } catch (error) {
        alert(error);
    }

}

/**
 * 新增文件夹
 *
 * @return {boolean}
 */
function AddFolder() {
    let name = $('#folder-name').val();
    if (name === '') {
        alert('请填写文件夹名称');
        return false;
    }

    let selectedItem = Tree.selected();
    let callback = function() {
        $("#add-folder-dialog").modal("hide");
        $("#folder-name").val('');
    };
    if (selectedItem !== null) {
        // 判断是否超过3层
        if (selectedItem.parent !== null && selectedItem.parent.parent !== null &&
            selectedItem.parent.parent.parent !== null) {
            alert("文件夹不能超过3层");
            return false;
        }
        AddChildrenItem(name, null, projectType.folder, callback);
    } else {
        AddSiblingsItem(name, null, projectType.folder, callback);
    }
}

/**
 * 组织更新数据
 *
 * @param {Object} parent
 * @param {Object} next
 * @param {String} name
 * @param {Object} type
 * @return {Object}
 */
function GetUpdateData(parent, next, name, property, newId, type) {
    let data = [];
    let updateData = {};

    let rootProjectID = -1;
    if(type.projectType === projectType.tender){
        let rootProject = parent ? parent.parent : Tree._root;
        rootProjectID = rootProject ? rootProject.id() : -1;
        if(property){
            property.rootProjectID=rootProjectID;
        }
    }

    updateData['updateType'] = type.updateType === undefined ? 'new' : type.updateType;
    updateData['updateData'] = {};
    if (newId !== '') {
        updateData['updateData'][Tree.setting.tree.id] = newId;
    }
    updateData['updateData'][Tree.setting.tree.pid] = parent ? parent.id() : -1;
    updateData['updateData'][Tree.setting.tree.nid] = next ? next.id() : -1;
    if (name !== '') {
        updateData['updateData']['name'] = name;
    }
    if (property !== null && property !== undefined) {
        updateData['updateData']['property'] = property;
    }
    if (type !== null && type.projectType !== null) {
        updateData['updateData']['projType'] = type.projectType !== undefined ? type.projectType : 'Tender';
    }

    data.push(updateData);
    return data;
}

/**
 * 获取删除数据
 *
 * @return {Object} node
 * @return {Object}
 */
function GetDeleteUpdateData(node) {
    let datas = [], updateData,
        pre = node.preSibling(),
        deleteNodeData = function (node) {
            var data = {};
            data['updateType'] = 'delete';
            data['updateData'] = {};
            data['updateData'][Tree.setting.tree.id] = node.id();
            if (node.data.projType === 'Tender') {
                data['updateData']['FullFolder'] = GetFullFolder(node.parent);
            }
            return data;
        },
        addDeleteChildren = function (children) {
            children.forEach(function(child){
                datas.push(deleteNodeData(child));
                addDeleteChildren(child.children);
            });
        };
    if (pre && pre.id() !== -1) {
        updateData = {};
        updateData['updateType'] = 'update';
        updateData['updateData'] = {};
        updateData['updateData'][Tree.setting.tree.id] = pre.id();
        updateData['updateData'][Tree.setting.tree.nid] = node ? node.nid() : -1;
        datas.push(updateData);
    }
    datas.push(deleteNodeData(node));
    addDeleteChildren(node.children);
    return datas;
};

/**
 * 获取父级所有名称
 *
 * @return {Array}
 */
function GetFullFolder (node) {
    let fullFolder = [];
    let cur = node;
    while (cur && cur.data) {
        fullFolder.unshift(cur.data.name);
        cur = cur.parent;
    }
    return fullFolder;
}

/**
 * 获取需要更新的前节点
 *
 * @param {Object} parent
 * @param {Object} next
 * @return {Object}
 */
function GetNeedUpdatePreNode(parent, next) {
    if (next) {
        return next.preSibling();
    } else if (parent) {
        return parent.firstChild();
    } else {
        return null;
    }
}

/**
 * 获取最新id
 *
 * @param {function} callback
 * @return {void}
 */
function GetNewProjectId(callback) {
    CommonAjax.post('/pm/api/getNewProjectID', {count: 1}, function(data) {
        callback(data);
    });
}

/**
 * 重命名项目
 *
 * @param {Number} projectId
 * @param {String} newName
 * @param {Number} parentID
 * @param {function} callback
 * @return {void}
 */
function RenameProject(projectId, newName, parentID, callback) {
    $.ajax({
        type: "POST",
        url: '/pm/api/renameProject',
        data: {'data': JSON.stringify({"user_id": userID, "id": projectId, "newName": newName, "parentID": parentID})},
        dataType: 'json',
        cache: false,
        timeout: 5000,
        success: function(result){
            if (result.error === 0) {
                callback();
            } else {
                alert('error' + result.message);
            }
        },
        error: function(iqXHR, textStatus, errorThrown){
            alert('error ' + textStatus + " " + errorThrown)
        }
    });
}

/**
 * 转换当前树结构为zTree结构
 *
 * @param {Object} Tree
 * @param {Object} zTreeObj
 * @param {Object} filterNode
 * @return {Mixed}
 */
function ConvertTreeToZtree(Tree, zTreeObj, filterNode) {
    let setting = {
            data: {
                simpleData: {
                    enable:true,
                    idKey: "id",
                    pIdKey: "pId",
                    rootPId: "-1"
                }
            }};
        let zTreeData = [],
        exportNodesData = function (nodes) {
            nodes.forEach(function (node) {
                if (node !== filterNode) {
                    var data = {};
                    data['id'] = node.data[Tree.setting.tree.id];
                    data['pId'] = node.pid();
                    data['name'] = node.data['name'];
                    data['isParent'] = node.data.projType === 'Folder';//(node.data.projType === 'Folder' && node.children.length === 0);
                    data['open'] = node.data.projType === 'Folder';//node.children.length !== 0;
                    zTreeData.push(data);
                    exportNodesData(node.children);
                }
            })
        };
    exportNodesData(Tree._root.children);
    return $.fn.zTree.init(zTreeObj, setting, zTreeData);
}

/**
 * 获取指定zTree节点
 *
 * @param {Object} zTreeObj
 * @return {object}
 */
function GetTargetTreeNode(zTreeObj) {
    if (!zTreeObj || !Tree) {
        return null;
    }

    let ztree_selected = zTreeObj.getSelectedNodes().length === 0 ? null : zTreeObj.getSelectedNodes()[0];
    return ztree_selected ? Tree.findNode(ztree_selected.id) : null;
}

/**
 * 根据指定id获取对应的工程专业
 *
 * @param {Array} engineeringList
 * @return {String}
 */
function getEngineeringHtml(engineeringList) {
    let result = '<option>请选择对应的工程专业</option>';
    if (engineeringList.length <= 0) {
        return result;
    }
    let engineeringObject = {};
    for(let tmp of engineering) {
        engineeringObject[tmp.value] = tmp.name;
    }

    for(let tmp of engineeringList) {
        if (engineeringObject[tmp.engineering] !== undefined) {
            result += '<option value="'+ tmp.engineering +'">'+ engineeringObject[tmp.engineering] +'</option>';
        }
    }

    return result;
}

/**
 * 远程获取项目属性数据
 *
 * @param {Object} projectInfo
 * @return {void}
 */
function getProperty(projectInfo) {
    if (projectInfo.property === undefined) {
        return;
    }
    projectProperty = projectInfo.property;
    // 写入专业工程相关
    let engineeringHtml = getEngineeringHtml(projectProperty.engineeringList);
    $("#tender-engineering").html(engineeringHtml);

    // 填入计价规则
    let valuationHtml = '<option value="'+ projectProperty.valuation +'">'+ projectProperty.valuationName +'</option>';
    $("#tender-valuation").html(valuationHtml);

    // 选中计价方式
    $("input[name='tender_valuation_type']").attr('disabled', 'disabled').removeAttr('checked', 'checked');
    $("input[name='tender_valuation_type'][value='"+ projectProperty.valuationType +"']")
        .attr("checked", "checked").removeAttr('disabled', 'disabled');
}

/**
 * 获取单价文件
 *
 * @param {Number} parentID
 * @return {void}
 */
function getUnitFile(parentID) {
    parentID = parseInt(parentID);
    if (isNaN(parentID) && parentID <= 0) {
        return;
    }

    $.ajax({
        url: '/pm/api/getUnitFile',
        type: 'post',
        data: {'data': JSON.stringify({"user_id": userID, "parentID": parentID})},
        dataType: 'json',
        error: function() {
            alert('数据传输错误!');
        },
        beforeSend: function() {

        },
        success: function(response) {
            if (response.error === 1) {
                alert('获取失败!');
            } else {
                if (response.data.length <= 0) {
                    return false;
                }
                let unitFileHtml = '';
                for(let tmp of response.data) {
                    unitFileHtml += '<option value="'+ tmp.id +'">'+ tmp.name +'</option>';
                }
                $("#unit-price").children("option:not(':first')").remove();
                $("#unit-price").children("option").first().after(unitFileHtml);
            }
        }
    });

}

/**
 * 获取费率文件
 *
 * @param {Number} parentID
 * @return {void}
 */
function getFeeRateFile(parentID) {
    parentID = parseInt(parentID);
    if (isNaN(parentID) && parentID <= 0) {
        return;
    }

    $.ajax({
        url: '/pm/api/getFeeRateFile',
        type: 'post',
        data: {'data': JSON.stringify({"user_id": userID, "parentID": parentID})},
        dataType: 'json',
        error: function() {
            alert('数据传输错误!');
        },
        beforeSend: function() {

        },
        success: function(response) {
            if (response.error === 1) {
                alert('获取失败!');
            } else {
                if (response.data.length <= 0) {
                    return false;
                }
                var first = $("#tender-fee-rate").children("option").first();
                $("#tender-fee-rate").empty();
                $("#tender-fee-rate").append(first);
                for(let tmp of response.data) {
                    var option =  $("<option>").val(tmp.ID).text(tmp.name);
                    $("#tender-fee-rate").append(option);
                }
            }
        }
    });

}


/**
 * 加载数据到侧边栏
 *
 * @return {void}
 */
function setDataToSideBar() {
    // 获取当前点击的数据
    let selectedItem = Tree.selected();
    let name = selectedItem.data.name;
    let target = selectedItem.data.projType === projectType.project ? '#summary-project' : '#summary-engineering';
    $(".side-content .p-3").hide();
    $(target).show();
    $(target + '-name').html(name);

    if (selectedItem.children.length <= 0) {
        return;
    }
    // 建设项目相关
    let counter = 1;
    let html = '';
    for(let tmp of selectedItem.children) {
        html += '<tr>' +
            '<td>'+ counter +'</td>' +
            '<td>'+ counter +'</td>' +
            '<td>'+ tmp.data.name +'</td>' +
            '<td></td>' +
            '<td></td>' +
            '<td></td>' +
            '<td></td>' +
            '</tr>';

    }
    html += '<tr>' +
        '<td>'+ (counter + 1) +'</td>' +
        '<td> </td>' +
        '<td>合计</td>' +
        '<td></td>' +
        '<td></td>' +
        '<td></td>' +
        '<td></td>' +
        '</tr>';
    $(target + '-table tbody').html(html);

    // 加载单价文件与费率文件
    if (selectedItem.data.projType === projectType.project) {
        let engineeringData = selectedItem.children !== null && selectedItem.children.children !== null ?
            selectedItem.children : [];
        if (engineeringData.length <= 0) {
            return;
        }
        let unitPriceFileHtml = '';
        let feeFileHtml = '';
        let unitPriceFileCounter = 1;
        let feeFileCounter = 1;
        let unitPriceFileList = [];
        let feeFileList = [];
        for(let engineering of engineeringData) {
            let tenderData = engineering.children !== null ? engineering.children : [];
            if (tenderData.length <= 0) {
                continue;
            }
            for(let tmp of tenderData) {
                tmp = tmp.data.property !== null ? tmp.data.property : null;
                if(tmp === null) {
                    continue;
                }

                if (tmp.feeFile !== undefined && feeFileList.indexOf(tmp.feeFile.name) < 0) {
                    feeFileHtml += '<tr><td>'+ feeFileCounter +'</td><td>'+ tmp.feeFile.name +'</td></tr>';
                    feeFileCounter++;
                    feeFileList.push(tmp.feeFile.name);
                }

                if (tmp.unitPriceFile !== undefined && unitPriceFileList.indexOf(tmp.unitPriceFile.name) < 0) {
                    unitPriceFileHtml += '<tr><td>'+ unitPriceFileCounter +'</td><td>'+ tmp.unitPriceFile.name +'单价文件</td></tr>';
                    unitPriceFileCounter++;
                    unitPriceFileList.push(tmp.unitPriceFile.name);
                }
            }

            $(target + '-unit-price-table tbody').html(unitPriceFileHtml);
            $(target + '-fee-table tbody').html(feeFileHtml);
        }

    }

}