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

ko.components.register('ko-nodeselect', {
    viewModel: function (params) {
        var self = this;
        self.type = params.type;
        self.controlName = ko.observable(params.name);
        self.location = params.location;
        self.parentForm = params.parent;
        self.nodeMultiSelect = (params.type && params.type === "multi");
        self.substituteNode = (params.type && params.type === "single");
        self.randomId = _h.createRandomNumber();
        self.ulClass = params.name + "-sl-tv-" + self.randomId;
        self.ulClasses = self.ulClass + " autocom-ul select-ul sl-tv drp-menu";
        self.params = params;
        self.showMenu = ko.observable(false);
        self.showSelectedItems = ko.observable(false);
        self.selectedItems = ko.observableArray();
        if (params["values"] && params.values().length > 0) {
            for (var j = 0; j < params.values().length; j++) {
                self.selectedItems.push(params.values()[j]);
            }
        }
        self.list = ko.observableArray();
        self.placeHolder = _h.getLocalizedText("codePlaceholder");
        self.getData = function (term) {
            if (!self.params.treeId())
                return;
            ApiService.request(
                {
                    url: "getNodeSelection",
                    data: {
                        searchKey: term,
                        id: self.params.treeId(),
                        controllerName: self.params.controllerName,
                        branchSelectable: self.params.branchSelectable
                    },
                    success: function (data) {
                        self.list.removeAll();
                        for (var j = 0; j < data.length; j++) {
                            var target = data[j];
                            self.list.push(target);
                        }
                        self.buildTree();
                    },
                    error: function (data) {
                        var text = _h.getApiMessage("LoadTreeBranchesError");
                        _h.failToast(text);
                    }
                });
        };
        self.buildTree = function () {
            var options = {
                tType: "NodeSelect",
                multi: self.nodeMultiSelect,
                nodes: self.list(),
                substituteNode: self.substituteNode,
                rootId: self.params.treeId(),
                controllerName: self.params.controllerName,
                onClickItem: self.onSelectItemCallBack,
                onClickItems: self.onSelectItemsCallBack,
                selectedItems: self.selectedItems,
                branchSelectable: self.params.branchSelectable,
                location: self.location,
            };
            if (self.params["value"]) {
                var value = ko.isObservable(self.params["value"]) ? self.params["value"]() : self.params["value"];
                options.selectedItem = { value: value };
            }
            $("." + self.ulClass).treeView(options);
        };
        if (ko.isObservable(params.value)) {
            self.value = params.value;
            if (!_h.isNullOrEmpty(self.value()) && !_h.isNullOrEmpty(params.valName))
                self.selectedItems.push({ value: self.value(), text: params.valName });
        }
        else {
            self.value = ko.observable(params.value);
            if (!_h.isNullOrEmpty(self.value()) && !_h.isNullOrEmpty(params.valName))
                self.selectedItems.push({ value: self.value, text: params.valName });
        }
        self.toggleFocus = function (model, e) {
            if (self.parentForm["setActiveFocus"]) {
                var name = $(e.currentTarget).attr("name");
                self.parentForm.setActiveFocus(name);
            }
        };
        self.onRemoveSelectedItem = function (rItem) {
            if (self.nodeMultiSelect) {
                if (self.selectedItems().length === 1)
                    rItem = self.selectedItems()[0];

                self.selectedItems.remove(rItem);
                self.value(undefined);
                self.parentForm
                    .onNodeSelect(self.controlName(), self.selectedItems());
                $("." + self.ulClass).treeView("refreshSelectItems", self.selectedItems());
            } else {
                $("." + self.ulClass).treeView("clearSelect");
                var item = self.selectedItems()[0];
                self.selectedItems.remove(item);
                self.value(undefined);
                self.parentForm
                    .onNodeSelect(self.controlName(), undefined);
            }
        };
        self.onRemoveSelectedItems = function () {
            $("." + self.ulClass).treeView("clearSelect");
            self.selectedItems.removeAll();
            self.value(undefined);
            self.parentForm
                .onNodeSelect(self.controlName(), []);
        };
        self.onSelectItemCallBack = function (item) {
            if (item) {
                if (item.text.indexOf("-بد") !== -1) {
                    item.text = item.text.replace("-بد", "");
                }
                if (item.text.indexOf("-بس") !== -1) {
                    item.text = item.text.replace("-بس", "");
                }
                self.value(undefined);
                self.selectedItems.removeAll();
                self.selectedItems.push(item);
                self.parentForm
                    .onNodeSelect(self.controlName(), item.value, item);
                self.showMenu(false);
                if (self.parentForm.resetAfterSelect) {
                    self.value(undefined);
                    self.selectedItems.removeAll();
                }
            } else {
                self.value(undefined);
                self.selectedItems.removeAll();
                self.parentForm
                    .onNodeSelect(self.controlName(), undefined, undefined);
            }
        };
        self.onSelectItemsCallBack = function (items) {
            self.selectedItems(items);
            self.value(undefined);
            self.parentForm
                .onNodeSelect(self.controlName(), self.selectedItems());
        };
        self.onClickInput = function (model, e) {
            if (e.target && $(e.target).hasClass("mu-spn")) {
                if (self.type === "multi") {
                    var input = $(e.target).find(".autocom-textbox");
                    if (input)
                        $(input).focus();
                    self.showSelectedItems(true);
                }
            } else if (e.target && $(e.target).hasClass("autocom-remove")) {
                //
            } else {
                if (e.target)
                    $(e.target).focus();
                if (self.list().length) {
                    self.showMenu(true);
                    self.calculateOpenListLoc();
                    if (self.type === "multi")
                        self.showSelectedItems(false);
                }
            }

        };
        self.onKeypress = function (model, evt) {
            var charCode = (evt.which) ? evt.which : evt.keyCode;
            if (charCode === 13) {
                setTimeout(
                    function () {
                        self.getData(self.value());
                    },
                    100);
            } else {
                if (self.type !== "multi") {
                    if (!$(evt.target).val()) {
                        self.parentForm
                            .onNodeSelect(self.controlName(), undefined);
                    }
                }
            }
        };
        self.onInputFocus = function (x, e) {
            var input = $(e.target).find(".autocom-textbox");
            if (input)
                $(input).focus();
        };
        self.ph = " مورد انتخاب شده";
        self.multi = "multi";
        if (self.parentForm["treeId"])
            self.parentForm.treeId.subscribe(function (newValue) {
                if (newValue !== undefined && newValue !== null) {
                    if (self.parentForm["entityName"] ||
                        (self.parentForm.parentForm && // for sourcesection dynamicdoc
                            self.parentForm.parentForm["section"] &&
                            self.parentForm.parentForm.section() === "source")) {
                        self.selectedItems.removeAll();
                        self.list.removeAll();
                        self.parentForm
                            .onNodeSelect(self.controlName(), []);
                        self.getData();
                    }
                    if (self.parentForm["entityName"] === "AdjustmentDocumentItemForm") {
                        self.selectedItems.removeAll();
                        self.list.removeAll();
                        self.getData();
                    }
                } else {
                    self.selectedItems.removeAll();
                    self.list.removeAll();
                    self.parentForm
                        .onNodeSelect(self.controlName(), []);
                    $("." + self.ulClass).treeView("removeTree");
                    self.showMenu(false);
                }
            });
        self.getData();
        self.calculateOpenListLoc = function () {
            var box = $(".node-box:visible").find("#tree_view");
            if (box.length > 0) {
                box.css('top', "");
                var ulHeight = box.height();
                var pageHeight = $("body").height();
                var viewportOffset = box.get(0).getBoundingClientRect();
                var rest = pageHeight - viewportOffset.top;
                if (rest < ulHeight) {
                    var ulTop = Number(box.css('top').replace("px", ""));
                    var newTop = ulTop - ulHeight - 8;
                    box.css('top', newTop + "px");
                }
            }
        }
    },
    template: '<!-- ko if:  showMenu() === true || selectedItems().length === 0 -->' +
        '<input type="text" autocomplete="off" style="unicode-bidi: plaintext;" class="form-control autocomplate-input key-on ncls"' +
        ' data-bind="value: value, click: onClickInput , event:{keyup: onKeypress, focus: toggleFocus},' +
        'attr:{ placeholder: placeHolder, name: controlName }" /><!-- /ko -->' +
        '<!-- ko if: !showMenu() && selectedItems().length > 0 -->' +
        '<div class="autocom-control" style="display: block;"><div class="autocom-input" data-bind="click: onClickInput"><div class= "autocom-item">' +
        ' <!-- ko if: selectedItems().length === 1 -->' +
        ' <span data-bind="text: selectedItems()[0].text"></span> <a class="autocom-remove" data-bind="click: onRemoveSelectedItem.bind(selectedItems()[0])" tabindex="-1" title="حذف">×</a>' +
        ' <!-- /ko --><!-- ko if: selectedItems().length > 1 && !showMenu() --> <span class="mu-spn" data-bind="text: selectedItems().length + ph"></span>' +
        ' <a class="autocom-remove" data-bind="click: onRemoveSelectedItems" tabindex="-1" title="حذف همه">×</a>' +
        '<!-- /ko --></div></div></div><!-- /ko -->' +
        '<div class="dr-hl node-box" data-bind="visible: showMenu() === true && showSelectedItems() === false">' +
        '<ul id="tree_view" style="width: fit-content;min-width: 100%;" data-bind="attr:{class : ulClasses}"></ul></div>' +
        '<div class="dr-hl" data-bind="visible: showMenu() === false && showSelectedItems() === true">' +
        '<ul id="showSelectedList_view" class="autocom-ul select-ul drp-menu" style="width: fit-content;min-width: 100%;" data-bind="foreach: selectedItems">' +
        '<li class="autocom-item" style="display: table;"><span data-bind="text: text"></span>' +
        '<a class="autocom-remove" data-bind="click: $parent.onRemoveSelectedItem" tabindex="-1" title="حذف">×</a></li>' +
        '</ul></div>'
}); 
