import { ApiService } from "../util/apiService.js";

ko.components.register('ko-consolidate-select', {
    viewModel: function (params) {
        var self = this;
        self.randomId = _h.createRandomNumber();
        self.companyId = params.companyId;
        self.id = "consolidate-select-ul" + self.randomId;
        self.parentForm = params.parent;
        if (params.disable === true) {
            self.disable = ko.observable(true);
        }
        else if (!_h.isNullOrEmpty(params.disable)) {
            self.disable = params.disable;
        }
        else {
            self.disable = ko.observable(false);
        }
        self.list = ko.observableArray();
        self.getConsolidateCompanies = function () {
            ApiService.request(
                {
                    url: "getCompanyOwnership",
                    data: { id: self.companyId() },
                    success: function (data) {
                        self.list.removeAll();
                        if (data)
                            self.list.push(data);
                    },
                    error: function (data) {
                        toast.error("Company", 'getSelectList');
                    }
                });
        }
        self.params = params;
        self.value = params.value;
        self.input = ko.observable();
        self.refreshSign = ko.observable(false);
        self.showMenu = ko.observable(false);
        self.placeHolder = _h.getLocalizedText("selectConsolidatePlaceholder");
        self.input.subscribe(function (newValue) {
            self.buildList();
        });
        self.onSelectItem = function (item) {
            self.input(undefined);
            self.showMenu(false);
            self.parentForm.onConsolidateSelect(item);
        };
        self.onInputFocus = function (x, e) {
            if (self.disable()) {
                self.showMenu(false);
                return;
            }

            var visList = $(".drp-menu:visible");
            if (visList && visList.length > 0) {
                for (var i = 0; i < visList.length; i++) {
                    if ($(visList[i]).attr("id") !== self.id) {
                        var target = ko.contextFor(visList[i]);
                        if (target && target.$data && target.$data["showMenu"])
                            target.$data.showMenu(false);
                    }
                }
            }
            self.showMenu(true);
            self.buildList();
        };
        self.buildList = function () {
            var ul = document.getElementById(self.id);
            var table = ul.getElementsByTagName("table")[0];
            if (!table)
                return;
            table.innerHTML = "";
            self.buildTableHeader(table);
            var item, tr, name;
            var list = ko.isObservable(self.list) ? self.list() : self.list;
            if (list.length === 0) {
                self.showMenu(false);
                return;
            }
            var tbody = _hh.createElement("tbody", table);
            for (var i = 0; i < list.length; i++) {
                item = ko.toJS(list[i]);
                self.buildRow(tbody, item, true, item.children.length);
                if (item.children.length)
                    for (var j = 0; j < item.children.length; j++) {
                        self.buildRow(tbody, item.children[j], false);
                    }
            }
        };
        self.buildTableHeader = function (table) {
            var thead = _hh.createElement("thead", table);
            var trHead = _hh.createElement("tr", thead);
            var thName = _hh.createElement("th", trHead);
            _hh.setClassName(thName, "consolidate-col");
            _hh.setInnerHtml(thName, "شرکت");

            var thdirectOwnership = _hh.createElement("th", trHead);
            _hh.setClassName(thdirectOwnership, "consolidate-col");
            _hh.setInnerHtml(thdirectOwnership, "مستقیم");

            var thindirectOwnership = _hh.createElement("th", trHead);
            _hh.setClassName(thindirectOwnership, "consolidate-col");
            _hh.setInnerHtml(thindirectOwnership, "غیر مستقیم");

            var thminorityOwnership = _hh.createElement("th", trHead);
            _hh.setClassName(thminorityOwnership, "consolidate-col");
            _hh.setInnerHtml(thminorityOwnership, "اقلیت");

            var thtotalOwnership = _hh.createElement("th", trHead);
            _hh.setClassName(thtotalOwnership, "consolidate-col");
            _hh.setInnerHtml(thtotalOwnership, "کل");

        };
        self.shortName = function (name) {
            if (name !== null && name !== undefined) {
                if (name.length < 40)
                    return name;
                return name.substr(0, 37) + "...";
            }
            return "";
        };
        self.buildRow = function (table, item, isRoot, childCount) {
            var tr = _hh.createElement("tr", table);
            var nameTd = _hh.createElement("td", tr);
            _hh.setClassName(nameTd, "consolidate-col ");
            var spanNameTag;
            if (isRoot && childCount > 0) {
                var aTag = _hh.createElement("a", nameTd);
                var iTag = _hh.createElement("i", aTag);
                _hh.setClassName(iTag, "fa fa-minus text-danger");
                spanNameTag = _hh.createElement("span", nameTd);
                _hh.setInnerHtml(spanNameTag, item.name);
                spanNameTag.setAttribute("style", "margin-right: 2px;");
            } else if (isRoot && childCount === 0) {
                spanNameTag = _hh.createElement("span", nameTd);
                _hh.setInnerHtml(spanNameTag, item.name);

            } else if (!isRoot) {
                _hh.setClassName(nameTd, "pos-rel with-overflow");
                nameTd.setAttribute("style", "margin-right: 6px;");

                var divVTag = _hh.createElement("a", nameTd);
                _hh.setClassName(divVTag, "consolidate-vert-line");
                divVTag.setAttribute("style", "margin-right: 6px;");

                var spanHTag = _hh.createElement("span", nameTd);
                _hh.setClassName(spanHTag, "cat-horz-lg-line");
                spanHTag.setAttribute("style", "top: 15px;margin-right: 7px;");

                spanNameTag = _hh.createElement("span", nameTd);
                spanNameTag.setAttribute("style", "margin-right: 32px; vertical-align: middle;");
                _hh.setInnerHtml(spanNameTag, item.name);
            }

            var directOwnership = _hh.createElement("td", tr);
            _hh.setInnerHtml(directOwnership, item.directOwnership.text);
            _hh.setClassName(directOwnership, "consolidate-col link-underline");
            directOwnership.setAttribute("data-value", item.directOwnership.value);
            directOwnership.onclick = function () {
                var val = this.getAttribute("data-value");
                self.onSelectItem({
                    text: this.innerText,
                    value: val
                });
            };
            var indirectOwnership = _hh.createElement("td", tr);
            _hh.setClassName(indirectOwnership, "consolidate-col link-underline");
            _hh.setInnerHtml(indirectOwnership, item.indirectOwnership.text);
            indirectOwnership.setAttribute("data-value", item.indirectOwnership.value);
            indirectOwnership.onclick = function () {
                var val = this.getAttribute("data-value");
                self.onSelectItem({
                    text: this.innerText,
                    value: val
                });
            };

            var minorityOwnership = _hh.createElement("td", tr);
            _hh.setClassName(minorityOwnership, "consolidate-col link-underline");
            _hh.setInnerHtml(minorityOwnership, item.minorityOwnership.text);
            minorityOwnership.setAttribute("data-value", item.minorityOwnership.value);
            minorityOwnership.onclick = function () {
                var val = this.getAttribute("data-value");
                self.onSelectItem({
                    text: this.innerText,
                    value: val
                });
            };

            var totalOwnership = _hh.createElement("td", tr);
            _hh.setClassName(totalOwnership, "consolidate-col link-underline");
            _hh.setInnerHtml(totalOwnership, item.totalOwnership.text);
            totalOwnership.setAttribute("data-value", item.totalOwnership.value);
            totalOwnership.onclick = function () {
                var val = this.getAttribute("data-value");
                self.onSelectItem({
                    text: this.innerText,
                    value: val
                });
            };


        };
        if (ko.isObservable(self.list)) {
            self.list.subscribe(function (newValue, oldValue) {
                self.buildList();
            });
        }
        self.isEmpty = function (val) {
            return val === null || val === undefined || val === "";
        };
        self.getConsolidateCompanies();
    },
    template: '<div class="autocom-control select-control">' +
        '<div class="autocom-input select-input" data-bind="click: onInputFocus, attr:{dataid: id}">' +
        '<input type="text" class="select-textbox key-on" autocomplete="off" tabindex=""  data-bind="textInput: input,' +
        'visible: isEmpty(value()), attr: {placeholder: placeHolder}"><!-- /ko --></div></div>' +
        '<ul class="autocom-ul select-ul drp-menu" style="width: fit-content;min-width: 100%;" data-bind="visible: showMenu, attr:{id : id}">' +
        '<li><div class="row"><div class="col-lg-12">' +
        '<table class="table table-bordered table-striped ko-consolidate" style="font-size: 9px;"></table>' +
        '</div></div></li>' +
        '</ul>'
});

