(function ($) {
    $.fn.buildNet = function (data, options) {
        /** 用传进来的参数覆盖默认，没传则保留 */
        let settings = $.extend({
            editable: true,
            buildNodeHtmlFunc: function (o) {
                return ''
            },
            focusNodeFunc: function () {
                return false;
            },
            rightClickNodeFunc: function () {
                return false;
            },
            degree: 99,
            degreeLeft: 99,
            degreeRight: 99,
            cssLeft: ['left'],
            cssRight: ['right'],
            cssCenter: 'center',
            focusAllow: true,
            htmlNullLeft: '',
            htmlNullRight: '',
        }, options);
        /** 调整显示深度 */
        if (settings.degreeLeft > settings.degree)
            settings.degreeLeft = settings.degree
        if (settings.degreeRight > settings.degree)
            settings.degreeRight = settings.degree

        let linex = '<span class="line-x"></span>';
        let liney = '<span class="line-y"></span>';
        let linexy = linex + liney;
        let combineOptleft = '<span class="line-combine-left"><i class="iconfont iconMinusCircle"></i></span>'
        let combineOptright = '<span class="line-combine-right"><i class="iconfont iconMinusCircle"></i></span>'

        /**
         * 构建数据关系
         */
        function constructorDataRelation() {
            let node, node_sub;
            for (let i = 0; i < data.net.length; i++) {
                node = data.nodes[data.net[i][0]];
                node_sub = data.nodes[data.net[i][1]];
                if (node.cNodes === undefined)
                    node.cNodes = [node_sub];
                else node.cNodes.push(node_sub);

                if (node_sub.pNodes === undefined)
                    node_sub.pNodes = [node];
                else node_sub.pNodes.push(node);
            }
        }

        /**
         * 创建树HTML
         */
        function buildTree(id) {
            let node = data.nodes[id];
            if (!node) return '';

            let html = '<tr><td class="text-center" style="border:0">';
            /** 左树 */
            html += buildLeftTreeHtml(node.pNodes, 1);
            if (node.pNodes && node.pNodes.length >= 1) {
                html += combineOptleft;
            }
            /** 目标 */
            html += buildLeafHtml(node, 'target ' + settings.cssCenter, false);
            if (node.cNodes && node.cNodes.length >= 1) {
                html += combineOptright;
            }
            /** 右树 */
            html += buildRightTreeHtml(node.cNodes, 1);
            html += '</td></tr>';
            return html;
        }

        /**
         * 判定css
         */
        function judgeCss(css, degree) {
            if (typeof css == 'string') {
                return css;
            } else if (degree <= css.length) {
                return css[degree - 1];
            }
            return '';
        }

        /**
         * 创建目标HTML
         */
        function buildLeafHtml(node, css, focusAllow) {
            let dom = focusAllow ? 'a' : 'span';
            let href = focusAllow ? ' href="javascript:void(0);"' : '';
            return '<' + dom + ' id="' + node.id + '" pid="' + (node.pid || '') + '" class="leaf x ' + css + '"' + href + '>'
                + settings.buildNodeHtmlFunc(node)
                + '</' + dom + '>';
        }

        /**
         * 创建添加HTML
         */
        function buildAddHtml(css, css2) {
            let opt = "";
            if (css2 === "addRightNode") {
                opt = "selectOpt";
            }
            return '<span class="leafopt ' + css + ' ' + opt + '" >'
                + '<a class="operate ' + css2 + '" href="javascript:void(0);" title="' + settings.addTitle + '">' +
                '<i class="iconfont iconGear-"></i></a>'
                + '</span>';
        }

        /**
         * 创建删除HTML
         */
        function buildDeleteHtml(node) {
            return '<a id="' + node.id + '" class="operate deleteNode" href="javascript:void(0)" title="' + settings.deleteTitle + '">'
                + '<i class="iconfont iconshanchu"></i></a>'
        }

        /**
         * 创建右树HTML
         */
        function buildRightTreeHtml(nodes, degree) {

            /** 判定css */
            let css = judgeCss(settings.cssRight, degree);

            /** 叶子节点容器 */
            let html = '';
            if (nodes && nodes.length > 0) {
                /** 超过指定深度不再展开 */
                if (degree > settings.degreeRight) {
                    html += '<li><span class="label">' + nodes.length + '</span></li>';
                } else {
                    /** 生成叶子节点 */
                    for (let i = 0; i < nodes.length; i++) {
                        html += '<li>' + linexy
                        /** 删除操作 */
                        if (degree === 1 && settings.editable === true)
                            html += buildDeleteHtml(nodes[i]);
                        html += buildLeafHtml(nodes[i], css, settings.focusAllow);
                        if (nodes[i].cNodes && nodes[i].cNodes.length > 0) {
                            html += combineOptright;
                        }
                        /** 展开下一层节点 */
                        html += buildRightTreeHtml(nodes[i].cNodes, degree + 1);
                        html += '</li>';
                    }
                }
            }

            /** 添加操作 */
            if (degree === 1 && settings.editable === true) {
                html += '<li>' + linexy + buildAddHtml(css, 'addRightNode') + '</li>';
            }
            return html === '' ? '' : '<ul class="htree">' + html + '</ul>';
        }

        /**
         * 创建左树HTML
         */
        function buildLeftTreeHtml(nodes, degree) {
            /** 判定css */
            let css = judgeCss(settings.cssLeft, degree);

            let html = '';
            /** 空节点 */
            if (nodes && nodes.length > 0) {
                /** 超过指定深度不再展开 */
                if (degree > settings.degreeLeft) {
                    html += '<li><span class="label">' + nodes.length + '</span></li>';
                } else {
                    /** 生成叶子节点 */
                    for (let i = 0; i < nodes.length; i++) {
                        html += '<li>';
                        /** 展开下一层节点 */
                        html += buildLeftTreeHtml(nodes[i].pNodes, degree + 1);
                        if (nodes[i].pNodes && nodes[i].pNodes.length > 0) {
                            html += combineOptleft;
                        }
                        html += buildLeafHtml(nodes[i], css, settings.focusAllow);
                        /** 删除操作 */
                        if (degree === 1 && settings.editable === true)
                            html += buildDeleteHtml(nodes[i]);
                        html += linexy + '</li>';
                    }
                }
            }

            /** 添加操作 */
            if (degree === 1 && settings.editable === true) {
                html += '<li>' + linexy + buildAddHtml(css, 'addLeftNode') + '</li>';
            }
            return html === '' ? '' : '<ul class="htree reverse">' + html + '</ul>';
        }

        /**
         * 设置纵线位置
         */
        $.fn.resetLineyCss = function () {
            $(this).find("ul.htree").each(function () {
                $(this).children("li").children(".line-y").css("top", "0").css("bottom", "0");
                $(this).children("li:first").children(".line-y").css("top", "50%");
                $(this).children("li:last").children(".line-y").css("bottom", "50%");
            });
            /** 调整高度，表格高度小于容器时，垂直居中显示 */
            let table = document.querySelector('.text-center');
            let table_h = table.offsetHeight;
            let container_h = document.querySelector('.net-container').offsetHeight;
            let top = (container_h / 2) - (table_h / 2);
            $(this).css({'top': 0})
            if (table_h < container_h) {
                $(this).css({'top': top})
            }
        }

        /** 控件创建 */
        constructorDataRelation();
        if (parent.parent.vvv.$api.btnPms) {
            $(this).html(buildTree(data.target))
                /** 绑定聚焦事件 */
                .off("click", "a.leaf")
                .on("click", "a.leaf", function () {
                    return false;
                })
                /** 绑定双击事件 */
                .off("dblclick", "a.leaf")
                .on("dblclick", "a.leaf", settings.focusNodeFunc)
                /** 绑定右击事件 */
                .off("contextmenu", "span.leaf,a.left,a.right")
                .on("contextmenu", "span.leaf,a.left,a.right", settings.rightClickNodeFunc)
                /** 绑定左侧展开/折叠事件 */
                .off("click", "span.line-combine-left")
                .on("click", "span.line-combine-left", function () {
                    if ($(this).find("i").hasClass("iconfont iconMinusCircle")) {
                        $(this).find("i").removeClass("iconfont iconMinusCircle");
                        $(this).find("i").addClass("iconfont iconPlusCircle");
                        $(this).prev("ul").addClass('leaf-hide');
                    } else {
                        $(this).find("i").removeClass("iconfont iconPlusCircle");
                        $(this).find("i").addClass("iconfont iconMinusCircle");
                        $(this).prev("ul").removeClass('leaf-hide');
                    }
                })
                /** 绑定右侧展开/折叠事件 */
                .off("click", "span.line-combine-right")
                .on("click", "span.line-combine-right", function () {
                    if ($(this).find("i").hasClass("iconfont iconMinusCircle")) {
                        $(this).find("i").removeClass("iconfont iconMinusCircle");
                        $(this).find("i").addClass("iconfont iconPlusCircle");
                        $(this).next("ul").addClass('leaf-hide');
                    } else {
                        $(this).find("i").removeClass("iconfont iconPlusCircle");
                        $(this).find("i").addClass("iconfont iconMinusCircle");
                        $(this).next("ul").removeClass('leaf-hide');
                    }
                });
        } else {
            $(this).html(buildTree(data.target));
        }

        /** 设置纵线位置 */
        $(this).resetLineyCss();
        return $(this);
    };
})(jQuery);

/**
 * 构建结构网
 * @param elId 元素ID
 * @param data 数据
 * @param options 配置
 */
export function buildNet(elId, data, options) {
    $(elId).buildNet(data, options);
}

/**
 * 元素拖动、缩放
 * @param el dom元素
 */
export function dragZoom(el) {
    // el.style.width = "10000px";
    // 修改画布长度
    el.style.width = "200%";
    el.style.position = "absolute";
    el.style.cursor = "all-scroll";

    /** 鼠标按下 */
    el.onmousedown = (e) => {
        // 鼠标按下，计算当前元素距离可视区的距离
        let disX = e.clientX - el.offsetLeft;
        let disY = e.clientY - el.offsetTop;
        /** 鼠标移动 */
        document.onmousemove = (e) => {
            // 通过事件委托，计算移动的距离
            let l = e.clientX - disX;
            let t = e.clientY - disY;
            // 移动当前元素
            el.style.left = l + "px";
            el.style.top = t + "px";
        };
        /** 鼠标松开 */
        document.onmouseup = (e) => {
            document.onmousemove = null;
            document.onmouseup = null;
        };
        return false;
    };
    /** 滚动条监听 */
    el.onmousewheel = (e) => {
        // 按住ctrl键，滚动鼠标滑轮
        if (e.ctrlKey) {
            let zoom = parseInt(el.style.zoom) || 100;
            zoom += e.wheelDelta / 12;
            /** 最小范围 和 最大范围 的图片缩放尺度 */
            if (zoom >= 20 && zoom < 180) {
                el.style.zoom = zoom + "%";
            }
            return false;
        }
    };
}

