(function ($) {
    var headerUtil = function () {
        var createFirstRow = function () {
            var cols = [
                "شرح", "تراز آزمایشی", "تعدیلات و طبقه بندی", "مانده نهایی"
            ];
            var frHeader = _hh.createTag({
                name: "div",
                className: "balancereport-set",
                parent: $("#br_Table")[0]
            });
            for (var i = 0; i < cols.length; i++) {
                _hh.createTag({
                    name: "div",
                    text: cols[i],
                    parent: frHeader,
                    className: "col-title text-center",
                    styles: i !== 0 ? "width:21.6%;display:inline-block;padding:24px;font-weight:bold;color: white;" :
                        "width:35.2%;display:inline-block;padding:24px;font-weight:bold;color: white;"
                });
            }
        }
        var setSortIcon = function (tag, direction) {
            switch (direction) {
                case "Ascending":
                    _hh.setClassName(tag, 'fa fa-sort-amount-asc');
                    break;
                case "Descending":
                    _hh.setClassName(tag, 'fa fa-sort-amount-desc');
                    break;
                case "None":
                    _hh.setClassName(tag, 'fa fa-sort');
                    break;
            }
        }
        var createSecondRow = function (cols) {
            var table = document.getElementById("br_Table");
            var srHeader = _hh.createTag({
                name: "div", className: "balancereport-second-set",
                parent: table,
                styles: "direction: ltr;"
            });
            var groupCol, groupDiv;
            for (var i = 0; i < cols.length; i++) {
                var col = cols[i];
                if (!col.tablecol)
                    continue;
                if (col.groupBy !== groupCol) {
                    groupCol = col.groupBy;
                    groupDiv = _hh.createTag({
                        name: "div",
                        parent: srHeader,
                        addBefore: true,
                        styles: groupCol === "desc" ? "width:35.2%;display:inline-block;" : "width:21.6%;display:inline-block;"
                    });
                }
                var tag = _hh.createTag({
                    name: "div",
                    className: "tbl-col-second ver-mid column-cell",
                    parent: groupDiv,
                    addBefore: true,
                    attributes: { "col-name": col.name },
                    styles: col.name !== "name"
                        ? "width:" + col.size + "%;padding:13px 0px 13px 13px;"
                        : "width:" + col.size + "%;padding:13px;",
                    onclick: function () {
                        var colName = this.getAttribute("col-name");
                        var opts = ttvUtil.getOptions();
                        var col;
                        for (var j = 0; j < _h.kocnx().brvm().tableProperties().length; j++) {
                            var sortItem = _h.kocnx().brvm().tableProperties()[j];
                            if (colName === sortItem.name) {
                                col = sortItem;
                                if (sortItem.sortDir() === "Ascending") {
                                    sortItem.sortDir("Descending");
                                    setSortIcon(this.childNodes[1], sortItem.sortDir());
                                } else {
                                    sortItem.sortDir("Ascending");
                                    setSortIcon(this.childNodes[1], sortItem.sortDir());
                                }
                            } else {
                                sortItem.sortDir("None");
                                setSortIcon(this.childNodes[1], "None");
                            }
                        }

                        if (col["alias"] !== null && col["alias"] !== undefined && col["alias"] !== "")
                            _h.kocnx().brvm().sortProperty(col.alias);
                        else
                            _h.kocnx().brvm().sortProperty(col.name);
                        _h.kocnx().brvm().sortDirection(col.sortDir());
                        _h.kocnx().brvm().getRecords();
                        if (col)
                            opts.cols = ko.toJS(_h.kocnx().brvm().tableProperties());
                    }
                });
                var span = _hh.createTag({
                    name: "div",
                    parent: tag,
                    addBefore: true
                });
                setSortIcon(span, col.sortDir);
                _hh.createTag({
                    name: "div",
                    html: col.fa,
                    parent: tag,
                    addBefore: true,
                    styles: "margin-right:5px;display: inline-block;"
                });
            }
        }
        var create = function (cols) {
            createFirstRow();
            createSecondRow(cols);
        };
        return {
            create: create,
            setSortIcon: setSortIcon
        };
    }();
    var bodyUtil = function () {
        var createDriveButtons = function (row, data, options) {
            if (options.worksheetView === 1)
                return;
            var btnBox = _hh.createTag({ name: "div", className: "lvl-btn-box", parent: row });
            var btnDown = _hh.createTag({
                name: "a",
                className: "pull-left",
                parent: btnBox, attributes: {
                    "title": "پیمایش به سطح پایین", "data-id": data.id, "data-lv": data.lv, "data-ppa": data.ppa, "data-pa": data.pa
                }, children: [
                    {
                        name: "img",
                        className: "icon-image-xxsmall",
                        attributes: { "src": "/App/src/images/ico/down.png" }

                    }]
                , attach: false
            });
            var btnUp = _hh.createTag({
                name: "a",
                className: "pull-right",
                parent: btnBox, attributes: {
                    "title": "پیمایش به سطح بالا", "data-id": data.id, "data-pa": data.pa, "data-lv": data.lv, "data-ppa": data.ppa
                }, children: [
                    {
                        name: "img",
                        className: "icon-image-xxsmall",
                        attributes: { "src": "/App/src/images/ico/up.png" }

                    }]
                , attach: false
            });
            btnDown.onclick = function (e) {
                var opts = ttvUtil.getOptions();
                _h.kocnx().brvm().downTableNode({ level: Number(this.getAttribute("data-lv")), id: Number(this.getAttribute("data-id")), path: this.getAttribute("data-pa"), pathParent: this.getAttribute("data-ppa") }, e);
            }
            btnUp.onclick = function (e) {
                var opts = ttvUtil.getOptions();
                _h.kocnx().brvm().upTableNode({ level: Number(this.getAttribute("data-lv")), id: Number(this.getAttribute("data-id")), pathParent: this.getAttribute("data-ppa"), path: this.getAttribute("data-pa") }, e);
            }

            if (!data.il) {
                btnBox.prepend(btnDown);
                if (data.lv > 1)
                    btnBox.prepend(btnUp);
            } else {
                if (data.lv > 1)
                    btnBox.prepend(btnUp);
            }
        }
        var addDepth = function (row, data) {
            var parent = row.parentNode;
            var depth = 0;
            if (parent !== null) {
                depth = parent.getAttribute("dep");
                if (!depth)
                    depth = 0;
                _hh.setAttributes(row,
                    {
                        "dep": Number(depth) + 1,
                        "did": data.id,
                        "dco": data.co
                    });
            }

            return depth;
        }
        var addEvent = function (type) {
            switch (type) {
            case "Tree":
            case "Total":
                return function (e) {
                    _h.kocnx().brvm().balanceReportDetailsBtn({
                            code: this.getAttribute("data-co"),
                            id: Number(this.getAttribute("data-id"))
                        },
                        e);
                };
            case "creditorFlow":
            case "debtorFlow":
                return function (e) {
                    _h.kocnx().brvm().amendmentsDetailsBtn(type, { id: Number(this.getAttribute("data-id")) }, e);
                };
            case "Balance":
                return function (e) {
                    _h.kocnx().brvm().totalDetailsBtn({ id: Number(this.getAttribute("data-id")) }, e);
                };
            }
        };
        var createPlusMinusButtons = function (row, data, options) {
            if (options.worksheetView === 0)
                return;
            switch (data.nt) {
                case 2:
                case 0:
                    _hh.createTag({ name: "i", className: "dmn-att fa fa-file-o node-va", parent: row });
                    break;
                case 1:
                    _hh.createTag({
                        name: "i", className: "dmn-p fa fa-plus node-va", parent: row,
                        onclick: function () {
                            ttvUtil.toggleOpenButtons(this);
                        }
                    });
                    _hh.createTag({ name: "i", className: "dmn-fld fa fa-folder node-va", parent: row });
                    break;
            }
        };
        var createTreeColGroup = function (groupColDiv, data, options) {
            var row = _hh.createTag({
                name: "div", className: "table-node",
                parent: groupColDiv,
                styles: options.worksheetView === 0 ? "border-bottom: 1px solid #dee6ea;" : ""
            });
            var depth = addDepth(row, data);
            createDriveButtons(row, data, options);
            createPlusMinusButtons(row, data, options);
            _hh.createTag({
                name: "div", className: "table-node-title",
                parent: row, text: _h.shortName(data.na)[0], attributes: { "title": data.pa },
                styles: options.worksheetView === 0 ? "margin-right:38px;" : ""
            });
            var codeConfig = {
                name: "span",
                parent: row,
                text: "( " + data.co + " )",
                className: "table-node-code",
                attributes: { "data-id": data.id, "data-co": data.co }
            };
            if (data.il && options.companyType === 1 && (data.tc !== 0 || data.td !== 0)) {
                codeConfig.className = "table-node-code link-underline clickable";
                codeConfig.onclick = addEvent("Tree");
            }
            _hh.createTag(codeConfig);

            if (data.nt === 1 || data.nt === 2) {
                var ul = _hh.createTag({
                    name: "div", className: "node-ch dmn-c", parent: row,
                    attributes: { "dep": Number(depth) + 1 }
                });
                if (data.children && data.children.length)
                    for (var i = 0; i < data.children.length; i++) {
                        bodyUtil.createTreeColGroup(ul, data.children[i], options);
                    }
            }
        }
        var createTotalColGroup = function (groupColDiv, data, options) {
            var groupDiv = document.createElement("div");
            groupColDiv.appendChild(groupDiv);
            var depth = addDepth(groupDiv, data);
            var tdDiv = _hh.createTag({
                name: "div", className: "table-cell",
                parent: groupDiv,
                styles: "width:50%;"
            });
            var tcDiv = _hh.createTag({
                name: "div", className: "table-cell",
                parent: groupDiv,
                styles: "width:50%;"
            });
            var tdSpan = _hh.createTag({
                name: "span", parent: tdDiv, text: _h.shortValue(data.td)
                , attributes: { "title": _h.shortValue(data.td), "data-id": data.id, "data-co": data.co }
            });
            var tcSpan = _hh.createTag({
                name: "span", parent: tcDiv, text: _h.shortValue(data.tc)
                , attributes: { "title": _h.shortValue(data.tc), "data-id": data.id, "data-co": data.co }
            });

            if ((data.tc !== 0 || data.td !== 0) && data.il && options.companyType === 0) {
                tdSpan.className = "link-underline clickable";
                tcSpan.className = "link-underline clickable";
                tdSpan.onclick = addEvent("Total");
                tcSpan.onclick = addEvent("Total");
            }


            if (_h.isNumberNegative(data.td))
                tdSpan.style.color = "red";
            if (_h.isNumberNegative(data.tc))
                tcSpan.style.color = "red";

            if (data.nt === 1 || data.nt === 2) {
                var ul = _hh.createTag({
                    name: "div", className: "dmn-c", parent: groupDiv,
                    attributes: { "dep": Number(depth) + 1 }
                });
                if (data.children && data.children.length)
                    for (var i = 0; i < data.children.length; i++) {
                        bodyUtil.createTotalColGroup(ul, data.children[i], options);
                    }
            }

        }
        var createFlowColGroup = function (groupColDiv, data, options) {
            var groupDiv = document.createElement("div");
            groupColDiv.appendChild(groupDiv);
            var depth = addDepth(groupDiv, data);
            var fldDiv = _hh.createTag({
                name: "div", className: "table-cell",
                parent: groupDiv
            });
            _hh.setAttributes(fldDiv,
                {
                    "style": "width:50%;display:inline-block;"
                });
            var flcDiv = _hh.createTag({
                name: "div", className: "table-cell",
                parent: groupDiv
            });
            _hh.setAttributes(flcDiv,
                {
                    "style": "width:50%;display:inline-block;"
                });
            var flcA = _hh.createTag({
                name: "a", className: "link-underline", parent: flcDiv, text: _h.shortValue(data.flc)
                , attributes: { "title": _h.shortValue(data.flc), "data-id": data.id }
            });
            var fldA = _hh.createTag({
                name: "a", className: "link-underline", parent: fldDiv, text: _h.shortValue(data.fld)
                , attributes: { "title": _h.shortValue(data.fld), "data-id": data.id }
            });

            flcA.onclick = addEvent("creditorFlow");
            fldA.onclick = addEvent("debtorFlow");

            if (data.nt === 1 || data.nt === 2) {
                var ul = _hh.createTag({
                    name: "div", className: "dmn-c", parent: groupDiv,
                    attributes: { "dep": Number(depth) + 1 }
                });
                if (data.children && data.children.length)
                    for (var i = 0; i < data.children.length; i++) {
                        bodyUtil.createFlowColGroup(ul, data.children[i], options);
                    }
            }
        }
        var createBalanceColGroup = function (groupColDiv, data, options) {
            var groupDiv = document.createElement("div");
            groupColDiv.appendChild(groupDiv);
            var depth = addDepth(groupDiv, data);
            var bdDiv = _hh.createTag({
                name: "div", className: "table-cell",
                parent: groupDiv,
                styles: "width:50%;display:inline-block;"
            });
            var bcDiv = _hh.createTag({
                name: "div", className: "table-cell",
                parent: groupDiv,
                styles: "width:50%;display:inline-block;"
            });
            var bdSpan = _hh.createTag({
                name: "span", parent: bdDiv, text: _h.shortValue(data.bd)
                , attributes: { "title": _h.shortValue(data.bd), "data-id": data.id }
            });
            var bcSpan = _hh.createTag({
                name: "span", parent: bcDiv, text: _h.shortValue(data.bc)
                , attributes: { "title": _h.shortValue(data.bc), "data-id": data.id }
            });

            if (_h.isNumberNegative(data.bc))
                bcSpan.style.color = "red";
            if (_h.isNumberNegative(data.bd))
                bdSpan.style.color = "red";
            if (options.companyType === 0) {
                bcSpan.className = "link-underline clickable";
                bdSpan.className = "link-underline clickable";
                bcSpan.onclick = addEvent("Balance");
                bdSpan.onclick = addEvent("Balance");
            }

            if (data.nt === 1 || data.nt === 2) {
                var ul = _hh.createTag({
                    name: "div", className: "dmn-c", parent: groupDiv,
                    attributes: { "dep": Number(depth) + 1 }
                });
                if (data.children && data.children.length)
                    for (var i = 0; i < data.children.length; i++) {
                        bodyUtil.createBalanceColGroup(ul, data.children[i], options);
                    }
            }
        }
        var create = function (options) {
            var table = document.getElementById("br_Table");
            var body = _hh.createTag({ name: "div", className: "body-table", parent: table });
            for (var j = 0; j < 4; j++) {
                var groupColDiv = _hh.createTag({
                    name: "div",
                    className: "body-table", parent: table,
                    styles: j === 0 ?
                        "width:35.2%;height:100%;display:inline-block;font-size:12px;" :
                        "width:21.6%;height:100%;display:inline-block;font-size:12px;",
                    attributes: { "col": j + 1 }
                });
                body.appendChild(groupColDiv);
            }
            for (var i = 0; i < options.nodes.length; i++) {
                var data = options.nodes[i];
                createTreeColGroup(body.childNodes[0], data, options);
                createTotalColGroup(body.childNodes[1], data, options);
                createFlowColGroup(body.childNodes[2], data, options);
                createBalanceColGroup(body.childNodes[3], data, options);
            }
            if (options.nodeCodeSelected)
                $(table).find("[dco='" + options.nodeCodeSelected + "']").addClass("table-row-selected");

        };
        return {
            create: create,
            createTreeColGroup: createTreeColGroup,
            createTotalColGroup: createTotalColGroup,
            createFlowColGroup: createFlowColGroup,
            createBalanceColGroup: createBalanceColGroup
        };
    }();
    var footerUtil = function () {
        var createCell = function (data, parent) {
            var cell = document.createElement("div");
            cell.innerHTML = data;
            if (data != "0")
                _hh.setAttributes(cell, { "title": data });
            $(cell).css({
                "width": "50%", "font-size": "12px", "cursor": "pointer", "text-align": "right",
                "padding": "13px 1px 13px 1px", "font-weight": "bold", "display": "inline-block"
            });
            parent.appendChild(cell);
        }
        var create = function (options) {
            var table = document.getElementById("br_Table");
            var footer = document.createElement("div");
            _hh.setClassName(footer, "font-bold footer-table");
            table.appendChild(footer);
            var data = options.footerData;
            var groupDiv = document.createElement("div");
            _hh.setAttributes(groupDiv,
                {
                    "style": "width:35.2%;display:inline-block;text-align: center;"
                });

            createCell("جمع کل", groupDiv);
            footer.appendChild(groupDiv);
            groupDiv = document.createElement("div");
            _hh.setAttributes(groupDiv,
                {
                    "style": "width:21.6%;display:inline-block;"
                });
            createCell(data.totalDebtor, groupDiv);
            createCell(data.totalCreditor, groupDiv);
            footer.appendChild(groupDiv);
            groupDiv = document.createElement("div");
            _hh.setAttributes(groupDiv,
                {
                    "style": "width:21.6%;display:inline-block;"
                });
            createCell(data.totalDebtorFlow, groupDiv);
            createCell(data.totalCreditorFlow, groupDiv);
            footer.appendChild(groupDiv);
            groupDiv = document.createElement("div");
            _hh.setAttributes(groupDiv,
                {
                    "style": "width:21.6%;display:inline-block;"
                });
            createCell(data.totalDebtorBalance, groupDiv);
            createCell(data.totalCreditorBalance, groupDiv);
            footer.appendChild(groupDiv);
        }
        return {
            create: create
        };
    }();
    var ttvUtil = function () {
        var toggleOpenButtons = function(sign){
            var parent = sign.parentNode;
            var ulParent = parent.parentNode;
            var id = parent.getAttribute("did");
            var parts = document.querySelectorAll('[did="' + id + '"]');
            var fld = parent.getElementsByClassName("dmn-fld")[0];
            var ul = parent.childNodes[4];
            var dep = Number(ul.getAttribute("dep"));
            if ($(ul).hasClass('dmn-c')) {
                for (var i = 0; i < parts.length; i++) {
                    if (parts[i].childNodes.length === 5)
                        parts[i].childNodes[4].className = "node-ch";
                    else
                        parts[i].childNodes[2].className = "";
                }
                _hh.setClassName(sign, "dmn-p fa fa-minus text-danger node-va");
                if (fld) {
                    _hh.setAttributes(fld,
                        { "class": "dmn-fld fa fa-folder-open" });
                }
                $(parent).next().addClass("fix-margin");
                if (dep > 1) {
                    if (ulParent.childNodes[ulParent.childNodes.length - 1].getAttribute("did") !== id)
                        $(ul).addClass("fix-border");
                }

            } else {
                _hh.setClassName(sign, "dmn-p fa fa-plus node-va");
                if (fld) {
                    _hh.setAttributes(fld,
                        { "class": "dmn-fld fa fa-folder" });
                }
                setTimeout(function () {
                        for (var j = 0; j < parts.length; j++) {
                            if (parts[j].childNodes.length === 5)
                                parts[j].childNodes[4].className = "node-ch dmn-c";
                            else
                                parts[j].childNodes[2].className = "dmn-c";
                        }
                    },
                    150);
                $(parent).next().removeClass("fix-margin");
                if (dep > 1) {
                    $(ul).removeClass("fix-border");
                }
            }
            _h.activeTooltip(true);
        }
        var getOptions = function () {
            return $.fn.tableTreeView.options.instances[0].opts;
        };
        var build = function (target, options) {
            if (!target.length)
                return false;
            target = target.get(0);
            options.treeEl = target;
            target.innerHTML = "";
            var randomId = Number((Math.random() * (10000000 - 100) + 100).toString().replace(".", ""));
            $.fn.tableTreeView.options.instances.push({ id: randomId, opts: options });
            _hh.setAttributes(target,
                {
                    "ttv-rootId": options.rootId,
                    "ttv-id": randomId
                });
            headerUtil.create(options.cols);
            bodyUtil.create(options);
            footerUtil.create(options);
            setTimeout(function () {
                _h.activeTooltip(true);
            }, 300);
        }
        return {
            build: build,
            getOptions: getOptions,
            toggleOpenButtons: toggleOpenButtons
        };
    }();
    var ttvMethods = {
        init: function (options) {
            ttvUtil.build(this, options);
        },
        expand:function(list){
            if(_h.any(list)){
                for (let i = 0; i < list.length; i++) {
                     var li = $(".table-node[did=" + list[i] +" ]");
                     var sign = li.find(".dmn-p")[0];
                    ttvUtil.toggleOpenButtons(sign);
                }
            }
        }
    };
    $.fn.tableTreeView = function (methodOrOptions) {
        if (ttvMethods[methodOrOptions]) {
            return ttvMethods[methodOrOptions].apply(this, Array.prototype.slice.call(arguments, 1));
        } else if (typeof methodOrOptions === 'object' || !methodOrOptions) {

            return ttvMethods.init.apply(this, arguments);
        } else {
            $.error('Method ' + methodOrOptions + ' does not exist on jQuery.tableTreeView');
        }
    };
    $.fn.tableTreeView.options = {
        instances: []
    };
})(jQuery);