/**
 * Created by Mai on 2017/2/24.
 */

var Tree = null, movetoZTree = null, copytoZTree = null;
var 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) {
                    html.push((node && node.data && node.data.projType === 'Folder') ? '&nbsp;' : '');
                    html.push('<a ');
                    if (node && node.data && node.data.projType === 'Tender') {
                        //html.push('href="/main?project=', node.id(), '"');
                        html.push('href="javacript:void(0);"');
                    }
                    html.push('>', text, '<a>');
                },
                getIcon: function (html, node) {
                    if (node.data.projType === 'Folder') {
                        html.push('<i class ="tree-icon fa fa-folder-open-o"></i>');
                    } else {
                        html.push('<span class="poj-icon">└</span>');
                    }
                },
                tdBindEvent: function (td, node) {
                    if (node.data.projType === '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) {
                    html.push(text ? new Date(text).Format('yyyy-MM-dd') : '');
                }
            }
        },
        {
            head: '创建日期',
            data: 'createDateTime',
            width: '10%',
            event: {
                getText: function (html, node, text) {
                    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) {
            // 新建文件夹 是否可见
            if (node.data.projType === 'Tender') {
                $('#addFolderBtn').hide();
            } else {
                $('#addFolderBtn').show();
            }
            // 重命名可见
            $('#renameBtn').show();
            // 删除可见
            $('#delBtn').show();
            // 移动到、复制到、共享、协同 是否可见
            if (node.data.projType === 'Tender') {
                $('#movetoBtn').show();
                $('#copytoBtn').show();
                $('#shareBtn').show();
                $('#cooperateBtn').show();
            } else {
                $('#movetoBtn').hide();
                $('#copytoBtn').hide();
                $('#shareBtn').hide();
                $('#cooperateBtn').hide();
            }
            $('td:eq(0)', node.row).append($('<i class="fa fa-sort" data-toggle="tooltip" data-placement="top" title="长安拖动"></i>'));
        }
    }
}
// 从服务器拉取数据
var LoadProjTree = function () {
    var table = $('#ProjTree');
    $('thead', table).remove();
    $('tbody', table).remove();
    GetAllProjectData(function (data) {
        Tree = $.fn.treeTable.init(table, ProjTreeSetting, data);
    });
};

var GetNeedUpdatePreNode = function (parent, next) {
    if (parent && parent.id() !== -1) {
        if (next && next.preSibling()) {
            return next.preSibling();
        } else {
            return parent.lastChild();
        }
    } else {
        return null;
    }
};
var GetPreNodeUpdateData = function (pre, nid) {
    var data = {};
    data['updateType'] = 'update';
    data['updateData'] = {};
    data.updateData[Tree.setting.tree.id] = pre.id();
    data.updateData[Tree.setting.tree.id] = nid;
    return data;
}
// 获取新建项目数据
var GetAddProjUpdateData = function (parent, next, name, newId) {
    var datas = [], updateData, pre;
    updateData = {};
    updateData['updateType'] = 'new';
    updateData['updateData'] = {};
    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;
    updateData['updateData']['name'] = name;
    updateData['updateData']['projType'] = 'Tender';
    datas.push(updateData);
    return datas;
};
var GetAddFolderProjUpdateData = function (parent, next, folderName1, folderName2, name, newId) {
    var datas = [], updateData, folderData1, folderData2, pre;
    var addUpdateData = function (parentId, nextId, name, projType) {
        var data = {};
        data['updateType'] = 'new';
        data['updateData'] = {};
        data['updateData'][Tree.setting.tree.id] = newId;
        data['updateData'][Tree.setting.tree.pid] = parentId;
        data['updateData'][Tree.setting.tree.nid] = nextId;
        data['updateData']['name'] = name;
        data['updateData']['projType'] = projType;
        newId += 1;
        datas.push(data);
        return data;
    }
    folderData1 = addUpdateData(parent.id(), next ? next.id() : -1, folderName1, 'Folder');
    folderData2 = addUpdateData(folderData1.updateData[Tree.setting.tree.id], -1, folderName2, 'Folder');
    addUpdateData(folderData2.updateData[Tree.setting.tree.id], -1, name, 'Tender');
    return datas;
};
// 获取新建文件夹数据
var GetAddForlderUpdateData = function (parent, next, folderName, newId) {
    var datas = [], updateData, pre;
    updateData = {};
    updateData['updateType'] = 'new';
    updateData['updateData'] = {};
    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;
    updateData['updateData']['name'] = folderName;
    updateData['updateData']['projType'] = 'Folder';
    datas.push(updateData);

    pre = GetNeedUpdatePreNode(parent, next);
    if (pre) {
        datas.push(GetPreNodeUpdateData(pre, newId));
    }
    return datas;
};

var GetNextChangeUpdateData = function (datas, node, next) {
    var data = null;
    if (node && node.id() !== -1) {
        data = {};
        data['updateType'] = 'update';
        data['updateData'] = {};
        data['updateData'][Tree.setting.tree.id] = node.id();
        data['updateData'][Tree.setting.tree.nid] = next ? next.id() : -1;
        datas.push(data);
    }
    return data;
}
var GetFullFolder = function (node) {
    var fullFolder = [],
        cur = node;
    while (cur && cur.data) {
        fullFolder.unshift(cur.data.name);
        cur = cur.parent;
    }
    return fullFolder;
}
var GetDeleteUpdateData = function (node) {
    var 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;
};

var GetMoveUpdateData = function (node, parent, next) {
    var datas = [], updateData;
    updateData = GetNextChangeUpdateData(datas, node.preSibling(), node.nextSibling);
    if (next) {
        updateData = GetNextChangeUpdateData(datas, next.preSibling(), node);
    }
    updateData = {};
    updateData['updateType'] = 'update';
    updateData['updateData'] = {};
    updateData['updateData'][Tree.setting.tree.id] = node.id();
    updateData['updateData'][Tree.setting.tree.pid] = parent ? parent.id() : -1;
    updateData['updateData'][Tree.setting.tree.nid] = next ? next.id() : -1;
    datas.push(updateData);
    return datas;
};

var GetCopyUpdateData = function (node, parent, next, newId){
    var datas = [], updateData, pre;
    updateData = {};
    updateData['updateType'] = 'copy';
    updateData['srcProjectId'] = node.id();
    updateData['updateData'] = {};
    updateData['updateData'][Tree.setting.tree.id] = newId + 1;
    updateData['updateData'][Tree.setting.tree.pid] = parent ? parent.id() : -1;
    updateData['updateData'][Tree.setting.tree.nid] = next ? next.id() : -1;
    updateData['updateData']['name'] = node.data.name;
    updateData['updateData']['projType'] = node.data.projType;
    datas.push(updateData);

    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;
        datas.push(updateData);
    }
    return datas;
}

var ConvertTreeToZtree = function (Tree, zTreeObj, filterNode) {
    var setting = {
            data: {
                simpleData: {
                    enable:true,
                    idKey: "id",
                    pIdKey: "pId",
                    rootPId: "-1"
                }
            }},
        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);
};
var GetTargetTreeNode = function (zTreeObj) {
    var ztree_selected;
    if (zTreeObj && Tree) {
        ztree_selected = zTreeObj.getSelectedNodes().length === 0 ? null : zTreeObj.getSelectedNodes()[0];
        return ztree_selected ? Tree.findNode(ztree_selected.id) : null;
    } else {
        return null;
    }
};

var AddFolderChildValid = function (node) {
    if (node.data.projType === 'Folder') {
        if (node.children.length === 0) {
            return true;
        } else {
            return (node.firstChild().data.projType === 'Folder');
        }
    } else {
        return false;
    }
};
var AddTenderChildValid = function (node) {
    if (node.data.projType === 'Folder') {
        if (node.children.length === 0) {
            return true;
        } else {
            return (node.firstChild().data.projType === 'Tender');
        }
    } else {
        return false;
    }
};

LoadProjTree();
$('#movetoBtn').hide();
$('#copytoBtn').hide();
$('#shareBtn').hide();
$('#cooperateBtn').hide();

// 新建文件夹
$('#addFolderBtn').click(function () {
    if (Tree) {
        $('#addFolder').modal('show');
    }
});
$('#addFolderOk').click(function () {
    var form = $('#addFolder');
    var name = $('#folder-name-input').val();
    var parent, next;
    if (name) {
        if (Tree.selected()) {
            if (Tree.selected().children.length === 0 || Tree.selected().firstChild().data.projType === 'Folder') {
                parent = Tree.selected();
                next = Tree.selected().firstChild();
            } else {
                parent = Tree.selected().parent;
                next = Tree.selected().nextSibling;
            }
        } else {
            parent = Tree._root;
            next = Tree.firstNode();
        }

        CommonAjax.post('/pm/api/getNewProjectID', {count: 1}, function (IDs) {
            var updateData = GetAddForlderUpdateData(parent, next, name, IDs.lowID);
            Tree.maxNodeId(IDs.lowID - 1);
            UpdateProjectData(updateData, function(datas){
                datas.forEach(function (data) {
                    if (data.updateType === 'new') {
                        Tree.addNodeData(data.updateData, parent, next);
                    }
                });
                form.modal('hide');
            });
        });
    }
});

// 新建工程
var AddProj = function () {
    var name = $('#tenderName').val();
    if (name !== '') {
        // if (Tree.selected()){
        //     if (Tree.selected().data.projType === 'Tender') {
        //         parent = Tree.selected().parent;
        //         next = Tree.selected().next;
        //     } else {
        //         if (Tree.selected().firstNode.data.projType === 'Tender') {
        //             parent = Tree.selected();
        //             next = Tree.selected().firstNode();
        //         } else {
        //             return;
        //         }
        //     }
        // } else {
        //     parent = Tree._root();
        //     next = Tree.firstNode();
        // }
        CommonAjax.post('/pm/api/getNewProjectID', {count: 1}, function (IDs) {
            var updateData = GetAddProjUpdateData(Tree._root, Tree.firstNode(), name, IDs.lowID);
            Tree.maxNodeId(IDs.lowID - 1);
            UpdateProjectData(updateData, function (datas) {
                datas.forEach(function (data) {
                    var parent, next;
                    if (data.updateType === 'new') {
                        parent = data.updateData.parentId === -1 ?  Tree._root : Tree.findNode(data.updateData.parentId);
                        next = data.updateData.nextId === -1 ? null : Tree.findNode(data.updateData.nextId);
                        Tree.addNodeData(data.updateData, parent, next);
                    }
                });
                $('#addProj').modal('hide');
            });
        });
    }
}
var AddFolderProj = function () {
    var nameB = $('#buildName').val(), nameX = $('#xiangName').val(), name = $('#tenderName').val();
    if (nameB !== '' && nameX !== '' && name !== '') {
        CommonAjax.post('/pm/api/getNewProjectID', {count: 3}, function (IDs) {
            var updateData = GetAddFolderProjUpdateData(Tree._root, Tree.firstNode(), nameB, nameX, name, IDs.lowID);
            Tree.maxNodeId(IDs.lowID - 1);
            UpdateProjectData(updateData, function (datas) {
                datas.forEach(function (data) {
                    var parent, next;
                    if (data.updateType === 'new') {
                        parent = data.updateData[Tree.setting.tree.pid] === -1 ?  Tree._root : Tree.findNode(data.updateData[Tree.setting.tree.pid]);
                        next = data.updateData[Tree.setting.tree.nid] === -1 ? null : Tree.findNode(data.updateData[Tree.setting.tree.nid]);
                        Tree.addNodeData(data.updateData, parent, next);
                    }
                });
                $('#addProj').modal('hide');
            });
        });
    }
}
$('#addProjBtn').click(function () {
    if (Tree) {
        $('#addProj').modal('show');
    }
});
$('#addProjOk').click(function () {
    var hasFolder = $('#isAddFolder>input').is(':checked');
    if (hasFolder) {
        AddFolderProj();
    } else {
        AddProj();
    }
});
$('#isAddFolder').change(function () {
    if ($('input',this).is(':checked')) {
        $('#moreinfo').collapse('show');
    } else {
        $('#moreinfo').collapse('hide');
    }
});

// 重命名
$('#renameBtn').click(function() {
    if (Tree && Tree.selected()) {
        $('#rename').modal('show');
    }
})
$('#rename').on('show.bs.modal', function () {
    $('#newName').attr('placeholder', Tree.selected().data.name);
});
$('#renameOk').click(function () {
    var select = Tree.selected(),
        newName = $('#newName').val(),
        form = $('#rename');
    if (select && newName !== select.data.name) {
        RenameProject(select.id(), newName, function () {
            form.modal('hide');
            select.data.name = newName;
            Tree.refreshNodesDom([select]);
        });
    } else {
        form.modal('hide');
    }
});

// 删除
$('#delBtn').click(function() {
    if (Tree && Tree.selected()) {
        $('#del').modal('show');
    }
});
$('#del').on('show.bs.modal', function() {
    var hasTenderChild = function (children) {
        var i;
        for (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;
    };
    if (Tree.selected().children.length == 0) {
        $('#tenderHint').show();
        $('#tenderHint').text('删除 "' + Tree.selected().data.name +'" ？');
        $('#folderHint').hide();
    } else {
        $('#tenderHint').hide();
        $('#folderHint').show();
        $('#folderHint').text('删除 "'+ Tree.selected().data.name +'" 以及它包含的子项？');
    }
    if (hasTenderChild([Tree.selected()])) {
        $('#restoreHint').show();
    } else {
        $('#restoreHint').hide();
    }
});
$('#deleteProjOk').click(function () {
    var updateData, form = $('#del');
    if (Tree) {
        updateData = GetDeleteUpdateData(Tree.selected());
        UpdateProjectData(updateData, function () {
            form.modal('hide');
            Tree.removeNode(Tree.selected());
        });
    }
});

// 移动至
$('#movetoBtn').click(function () {
    if (Tree && Tree.selected()) {
        $('#moveto').modal('show');
    }
});
$('#moveto').on('show.bs.modal', function () {
    movetoZTree = ConvertTreeToZtree(Tree, $('#treeDemo'), Tree.selected());
});
$('#movetoOk').click(function () {
    var updateData, form = $('#moveto'),
        target = GetTargetTreeNode($.fn.zTree.getZTreeObj('treeDemo')),
        parent, next, cur = Tree.selected();
    if (target) {
        if (target.data.projType === 'Tender') {
            parent = target.parent;
            next = target.nextSibling;
        } else {
            parent = target;
            next = target.firstChild();
        }

        if (parent !== cur.parent || (next !== cur && next !== cur.nextSibling)){
            updateData = GetMoveUpdateData(Tree.selected(), parent, next);
            UpdateProjectData(updateData, function (data) {
                form.modal('hide');
                Tree.move(Tree.selected(), parent, next);
            });
        } else {
            form.modal('hide');
        }
    } else {
        form.modal('hide');
    }
})

// 复制到
$('#copytoBtn').click(function () {
    if (Tree && Tree.selected()) {
        $('#copyto').modal('show');
    }
});
$('#copyto').on('show.bs.modal', function () {
    copytoZTree = ConvertTreeToZtree(Tree, $('#treeDemo2'));
});
$('#copytoOk').click(function() {
    var form = $('#copyto'),
        target = GetTargetTreeNode($.fn.zTree.getZTreeObj('treeDemo2')),
        parent, next, cur = Tree.selected();
    if (target && (target.data.projType === 'Tender' || target.children.length === 0 || target.firstChild().data.projType === 'Tender')) {
        if (target.data.projType === '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}, function (IDs) {
                var updateData = GetCopyUpdateData(cur, parent, next, IDs.lowID);
                Tree.maxNodeId(IDs.lowID - 1);
                CommonAjax.post('/pm/api/copyProjects', {user_id: userID, updateData: updateData}, function (data) {
                    form.modal('hide');
                    data.forEach(function (nodeData) {
                        if (nodeData.updateType === 'copy') {
                            Tree.addNodeData(nodeData.updateData, parent, next);
                        }
                    });
                }, function () {
                    form.modal('hide');
                });
            });
        } else {
            form.modal('hide');
        }
    } else {
        form.modal('hide');
    }
});
