(function (paw, utils, inventoryFixedAssetsIdentService, fn) {
    function InventoryFixedAssetsIdents(context, settings, localization, formatting, editMode) {
        var self = this;
        this.context = context;
        this.settings = paw.lang.append({
            acKey: undefined,
            $identSearch: undefined,
            $identTable: undefined,
            $identRows: undefined,
            $noteModal: undefined,
            $noteInput: undefined
        }, settings);
        this.localization = paw.lang.append({
            notePopupTitle: '@Loc.Note',
            save: '@Loc.Save',
            cancel: '@Loc.Cancel',
            noResults: '@Loc.NoResults',
            name: '@Loc.Name',
            location: '@Loc.Location',
            gridName: '@Loc.GridName',
            company: '@Loc.Company',
            department: '@Loc.Department',
            costCarrier: '@Loc.CostCarrier'

        }, localization || {});
        this.formatting = formatting;
        this.editMode = editMode;

        this.selectedIdent = null;
        this.idents = [];
        this.noteModal = new paw.com.noteEditor.NoteEditorPopup({}, {
            popupTitle: this.localization.notePopupTitle,
            save: this.localization.save,
            cancel: this.localization.cancel
        });
        this.addFa = {
            fa: null
        };

        this.debouncedItemSearch = fn.debouncer(function (req, process) {
            inventoryFixedAssetsIdentService.findItems(req).then(function (response) {
                var taItems = [];
                paw.utils.iterable.iterate(response.data, function (item, i) {
                    item.$$index = i;
                });
                process(response.data);
                $(".sticky-header").floatThead();
            });
        }, 300);

        this.onRemoveIdent = function () {
            var $elt = $(this);
            var anNo = $elt.attr('data-remove-ident-position');
            var ident = utils.iterable.get(self.idents, function (ident) {
                return ident.AnNo === anNo;
            });
            self.removeIdentPosition(ident);
        };

        this.onOpenNoteModal = function (e) {
            var anNo = $(this).attr('data-note-ident-position');
            var ident = paw.utils.iterable.get(self.idents, function (item) {
                return item.AnNo === anNo;
            });
            self.noteModal.show(ident.Note, {
                onSave: function (content) {
                    ident.Note = content;
                    $("#noteModal-" + anNo)
                        .removeClass("btn-link btn-active")
                        .addClass(content != "" ? "btn-link btn-active" : "btn-link");
                }
            });
        };
    }

    InventoryFixedAssetsIdents.prototype.init = function () {
        this.initIdentSearch();
        if (this.editMode) {
            this.fetchIdents(this.context.model.acKey);
        }          
    };

    InventoryFixedAssetsIdents.prototype.destroy = function () {
        self.settings.$identRows.find('button[data-note-ident-position]').on('off', this.onOpenNoteModal);
        this.settings.$identRows.find('[data-remove-ident-position]').on('off', this.onRemoveIdent);
        this.noteModal.destroy();
        
    };

    InventoryFixedAssetsIdents.prototype.initIdentSearch = function () {
        var self = this;
        $('#faItemsSearch.custom-typeahead').customTypeahead({
            value: "AnQid",
            display: "Name",
            minWidth: "330px",
            minSearchLength: 0,
            focusOpen: true,
            paginate: false,
            typeaheadClass: "custom-typeahead-dropdown-invoice",
            columns: [
                { name: this.localization.name, value: 'Name' }
            ],
            localization: { noResults: this.localization.noResults },
            url: inventoryFixedAssetsIdentService.settings.itemsSearchApiUrl,
            urlSearchProp: 'searchTerm',
            urlPropsFunction: function () {
                return {
                    searchTerm: $('#faItemsSearch.custom-typeahead').val()
                };
            },
            urlRequestMethod: "POST",
            onSelect: function (item) {
                self.addFa.fa = item;
                $('#faItemQty').val(self.addFa.fa.Qty);
                fn.formatNumberInput($("#faItemQty"))
                return item;
            }
        }); 

        this.initLocationSelection($('#faItemLocation.custom-typeahead'), function (location) {
            self.addFa.itemLocation = location;
        });
        
        $('#faAddItem').on('click', function () {
            if (self.context.model.status === 'P') {
                return;
            }
            var fa = self.addFa.fa;
            if (utils.value.notSet(fa)) {
                return;
            }
            if (utils.value.notSet(fa.Type)) {
                fa.Type = $('#faItemType').val();
            }
            if (utils.value.isSet(self.addFa.itemLocation)) {
                fa.LocationId = self.addFa.itemLocation.LocId;
            }
            if (utils.value.isSet($('#faItemQty').val())) {
                fa.Qty = utils.value.strToNum($('#faItemQty').val());
            }

            if (utils.value.isSet(self.context.model.acKey)) {
                fa.AcKey = self.context.model.acKey;
                inventoryFixedAssetsIdentService.addFixedAsset(fa).then(function () {
                    self.addFa.fa = null;
                    self.addFa.itemLocation = null;
                    $('#faItemsSearch.custom-typeahead').val('').next('.custom-typeahead-display').val('');
                    $('#faItemQty').val('');
                    $('#faItemLocation.custom-typeahead').val('').next('.custom-typeahead-display').val('');

                    self.fetchIdents(self.context.model.acKey);
                });
            }
            else {
                self.context.saveData().then(function () {
                    fa.AcKey = self.context.model.acKey;
                    inventoryFixedAssetsIdentService.addFixedAsset(fa);
                    location.reload();
                });
            }
        });
    };

    InventoryFixedAssetsIdents.prototype.fetchIdents = function (id) {
        var self = this;
        return inventoryFixedAssetsIdentService.fetchIdents(id).then(function (idents) {
            self.idents = idents;
            self.renderTable();
            self.settings.$identRows.find('button[data-note-ident-position]').on('click', self.onOpenNoteModal);
            self.settings.$identRows.find('[data-remove-ident-position]').on('click', self.onRemoveIdent);
        });
    };

    InventoryFixedAssetsIdents.prototype.renderTable = function () {
        var self = this;
        this.settings.$identRows.empty();
        utils.iterable.iterate(this.idents, function (ident) {
            self.renderRow(ident)
        });
        
    };

    InventoryFixedAssetsIdents.prototype.renderRow = function (ident) {
        let row = this.renderColumns(ident);

        setTimeout(function () {
            fn.initializeNumberInputs();
        });
        fn.reorderColumns(true, row);
        this.settings.$identRows.append(row);
        return row;
    };

    InventoryFixedAssetsIdents.prototype.renderColumns = function (ident) {
        var self = this;
        var isConfirmed = this.context.model.status === 'P';
        var row = fn.createTableRowElement("tr", "position-" + ident.AnNo, "", null, false, "row");
        var itemActiveClass = (ident.IsActive === false ? " text-danger" : "");
        row.appendChild(fn.createTableRowElement("input", "anNo-" + ident.AnNo, "form-control", ident.AnNo, true, null, "text", null, null, true));

        var chboxMarkup = [
            '<td >',
            '   <label class="custom-checkbox-container ifa-custom-checkbox">',
            '      <input id="register-' + ident.AnNo + '" name="register-' + ident.AnNo + '" type="checkbox" ' + (isConfirmed? "disabled" : "")  + ' />',
            '      <span class="custom-checkbox-checkmark"></span>',
            '   </label>',
            '</td>'
        ];
        var $chboxCol = $(chboxMarkup.join('\n'));

        var $chbox = $chboxCol.find('input');
        $chbox.customCheckbox();
        $chbox.prop('checked', ident.Register);
        $chbox.change(function () {
            ident.Register = $(this).is(':checked');
        });
        
        row.appendChild($chboxCol[0]);

        row.appendChild(fn.createTableRowElement("input", "name-" + ident.AnNo, "form-control" + itemActiveClass, ident.Name, isConfirmed, null, "text", null, function (a) {
            ident.Name = $('input#name-' + ident.AnNo).val();
        }, true));

        var qtyCol = fn.createTableRowElement("input", "qty-" + ident.AnNo, "form-control numberInput text-right" + itemActiveClass, ident.Qty, isConfirmed, null, "text", null, function (a) {
            ident.Qty = utils.value.strToNum($('input#qty-' + ident.AnNo).val());
        }, true);
        var $qty = $(qtyCol).find('input');
        $qty.attr('step', this.context.settings.formatting.decimalPlacesQuantity);
        row.appendChild(qtyCol);

        var locationCol = fn.createTableRowElement("input", "location-" + ident.AnNo, "form-control custom-typeahead fa-location" + itemActiveClass, ident.LocationId, isConfirmed, null, "text", null, () => updateIdentBasicData(ident.AnNo), true);
        row.appendChild(locationCol);

        var $locationSelect = $(locationCol).find('input.fa-location');
        if (isConfirmed) {
            $locationSelect.attr('disabled', true);
        }
        setTimeout(function () {
            self.initLocationSelection($locationSelect, function (location) {
                ident.LocationId = location.LocId;
            }, ident.LocationId);
        }, 50);

        var faTypeSelectNode = fn.createTableRowElement("select", "type-" + ident.AnNo, "form-control" + itemActiveClass, ident.Type, isConfirmed, null, "text", null, function () {
            ident.Type = $faTypeSelect.val();
        }, true);
        row.appendChild(faTypeSelectNode);
        var $faTypeSelect = $(faTypeSelectNode).children('select');
        if (isConfirmed) {
            $faTypeSelect.attr('disabled', true);
        }
        utils.iterable.iterate(this.context.settings.faTypes, function (faType) {
            var $opt = $('<option value="' + faType.Key + '"' + (ident.Type === faType.Key? ' selected' : '') + '>' + faType.Value + '</option>');
            $faTypeSelect.append($opt[0]);
            
        });

        var actions = fn.createTableRowElement("td", null, "actions-cell");
        var button = docTypePermissionCtrl.decorateElt(
            fn.createTableRowElement("button", "noteModal-" + ident.AnNo, "identNote btn btn-link " + (utils.value.isSet(ident.Note) ? "btn-active" : ""), null, isConfirmed, null, "button", null),
            'Write',
            'disabled');
        if (isConfirmed) {
            $(button).attr('disabled', true);
        }
        button.setAttribute('data-note-ident-position', ident.AnNo);
        button.appendChild(fn.createTableRowElement("i", null, "fa fa-comment"));
        button.appendChild(docTypePermissionCtrl.decorateElt(
            fn.createTableRowElement("input", "note-" + ident.AnNo, "hidden", ident.Note),
            'Write',
            'disabled'));
        button.appendChild(docTypePermissionCtrl.decorateElt(
            fn.createTableRowElement("input", "acKey-" + ident.AnNo, "hidden", ident.AcKey),
            'Write',
            'disabled'));
        button.appendChild(docTypePermissionCtrl.decorateElt(
            fn.createTableRowElement("input", "vat-" + ident.AnNo, "hidden", ident.VAT),
            'Write',
            'disabled'));
        button.appendChild(docTypePermissionCtrl.decorateElt(
            fn.createTableRowElement("input", "priceCurrency-" + ident.AnNo, "hidden", ident.PriceCurrency),
            'Write',
            'disabled'));
        button.appendChild(docTypePermissionCtrl.decorateElt(
            fn.createTableRowElement("input", "serialNo-" + ident.AnNo, "hidden", ident.SerialNo),
            'Write',
            'disabled'));
        button.appendChild(docTypePermissionCtrl.decorateElt(
            fn.createTableRowElement("input", "dateDue-" + ident.AnNo, "hidden", ident.DateDue),
            'Write',
            'disabled'));
        button.appendChild(docTypePermissionCtrl.decorateElt(
            fn.createTableRowElement("input", "qtyOld-" + ident.AnNo, "hidden", 0),
            'Write',
            'disabled'));
        actions.appendChild(button);

        var deleteBtn = docTypePermissionCtrl.decorateElt(
            fn.createTableRowElement("button", "identRemove-" + ident.AnNo, "btn btn-outline editableInput", null, isConfirmed, null, "button", null),
            'Delete',
            'disabled');
        if (isConfirmed) {
            $(deleteBtn).attr('disabled', true);
        }
        deleteBtn.setAttribute('data-remove-ident-position', ident.AnNo);
        deleteBtn.appendChild(fn.createTableRowElement("span", null, "far fa-trash-alt"));
        actions.appendChild(deleteBtn);
        row.appendChild(actions);

        return row;
    };

    InventoryFixedAssetsIdents.prototype.removeIdentPosition = function (ident) {
        var self = this;
        $().customModal({
            title: "",
            destroyOnClose: true,
            showCloseButton: true,
            id: "removeInventoryFixedAssetsIdentConfirmation",
            type: "question",
            text: this.context.localization.confirmDeleteMsg,
            buttons: [
                {
                    icon: 'fa fa-times',
                    text: this.context.localization.no,
                    closeOnAction: true,
                    type: 'ghost'
                },
                {
                    icon: 'fa fa-check',
                    text: this.context.localization.yes,
                    action: function () {
                        inventoryFixedAssetsIdentService.removeIdentPosition(ident).then(function () {
                            return self.fetchIdents(self.context.model.acKey);
                        });
                    },
                    closeOnAction: true,
                    type: 'primary'
                }
            ]
        });
    };

    InventoryFixedAssetsIdents.prototype.initLocationSelection = function ($elt, onSelected, value) {
        $elt.val(value);
        $elt.customTypeahead({
            value: "LocId",
            display: "Name",
            minWidth: "330px",
            minSearchLength: 0,
            focusOpen: true,
            paginate: false,
            typeaheadClass: "custom-typeahead-dropdown-invoice",
            columns: [
                { name: this.localization.location, value: "LocId" },
                { name: this.localization.gridName, value: "Name" },
                { name: this.localization.company, value: "Company" },
                { name: this.localization.department, value: "Department" },
                { name: this.localization.costCarrier, value: "CostDrv" }
            ],
            localization: { noResults: this.localization.noResults },
            url: inventoryFixedAssetsIdentService.settings.locationSearchApiUrl,
            urlSearchProp: 'searchTerm',
            urlPropsFunction: function () {
                return {
                    searchTerm: $elt.val()
                };
            },
            urlRequestMethod: "POST",
            onSelect: function (location) {
                onSelected(location);
                return location;
            }
        });
        
    };


    paw.view.inventoryFixedAssets.InventoryFixedAssetsIdents = InventoryFixedAssetsIdents;
})(paw, paw.utils, paw.view.inventoryFixedAssets.inventoryFixedAssetsIdentService, fn = {
    initializeNumberInputs: initializeNumberInputs,
    reorderColumns: reorderColumns,
    createTableRowElement: createTableRowElement,
    initializeInvoiceIdentInputs: initializeInvoiceIdentInputs,
    debouncer: debouncer,
    formatNumberInput: formatNumberInput
});