(function (paw, utils) {
    function PawDocumentFinder(finder, $filtersHolder, $datagridHolder, settings, localization) {
        this.finder = finder;
        this.$filtersHolder = $filtersHolder;
        this.$datagridHolder = $datagridHolder;
        this.data = null;

        this.settings = paw.lang.append({
            gridUrl: undefined,
            subjectSearchUrl: undefined,
            documentFinderFilterDataUrl: undefined
        }, settings || {});
        this.localization = paw.lang.append({
            documentNumberShort: '@Loc.DocumentNumberHeader',
            status: '@Loc.Status',
            subjectCode: '@Loc.SubjectCode',
            subjectTitle: '@Loc.SubjectTitle',
            date: '@Loc.Date',
            dateDue: '@Loc.DateDue',
            title: '@Loc.Title',
            docTypeShort: '@Loc.DocTypeShort',
            classification: '@Loc.Classification',
            note: '@Loc.Note',
            user: '@Loc.User',
            search: '@Loc.SearchFilter',
            subject: '@Loc.Subject',
            searchPlaceholder: '@Loc.SearchPlaceholder',
            company: '@Loc.Company',
            address: '@Loc.Address',
            post: '@Loc.Post',
            partner: '@Loc.Partner',
            all: '@Loc.All',
            dateFrom: '@Loc.DateFrom',
            dateTo: '@Loc.DateTo',
            documentType: '@Loc.DocumentType',
            dateFormat: '@Loc.DateFormat'
        }, localization || {});

        this.classifications = [];
        this.selectedSubject = null;
        this.filterData = null;
    }

    PawDocumentFinder.prototype.getId = function(){
        return 'paw-document-finder';
    };

    PawDocumentFinder.prototype.gridColumnsDef = function () {
        return [
            {
                label: this.localization.documentNumberShort,
                url: this.settings.datagridItemLink,
                width: '10%',
                def: { data: "AcKeyView", name: "AcKey", filtertype: "text", render: this.settings.hasB2BGranule? undefined : $.fn.dataTable.render.link('Id') }
            },
            {
                label: this.localization.status,
                width: '7%',
                def: { data: "StatusName", name: "AcStatusNavigation.AcName", orderable: false, filtertype: "text", 
                    render: function (statusName, a, entity) {
                        switch(entity.Status){
                            case 'O':
                                return '<span class="label label-primary">' + statusName + '</span>';
                            case 'F':
                                return '<span class="label label-success">' + statusName + '</span>';
                            case 'D':
                                return '<span class="label label-danger">' + statusName + '</span>';
                            default:
                                return '<span class="label label-default">' + statusName + '</span>';
                        }
                    }
                }
            },
            {
                label: this.localization.subjectCode,
                width: '8%',
                def: { data: "Subject", name: "AcSubject", filtertype: "text", }
            },
            {
                label: this.localization.subjectTitle,
                width: '8%',
                def: { data: "SubjectName", name: "AcSubjectNavigation.AcName2", filtertype: "text", render: $.fn.dataTable.render.ellipsis(30, false) }
            },
            {
                label: this.localization.date,
                width: '6%',
                def: { data: "Date", name: "AdDate", filtertype: "dateTime" }
            },
            {
                label: this.localization.dateDue,
                width: '7%',
                def: { data: "DateDue", name: "AdDateDue", filtertype: "dateTime" }
            },
            {
                label: this.localization.title,
                width: '10%',
                def: { data: "Title", name: "AcTitle", filtertype: "text" }
            },
            {
                label: this.localization.docTypeShort,
                width: '4%',
                def: { data: "DocType", name: "AcDocType", filtertype: "text" }
            },
            {
                label: this.localization.classification,
                width: '7%',
                def: { data: "Classification", name: "AnClassification.AcTypeDesc", filtertype: "text", render: $.fn.dataTable.render.ellipsis(25, false) }
            },
            {
                label: this.localization.department,
                width: '5%',
                def: { data: "Department", name: "AcDepartment", filtertype: "text", orderable: false }
            },
            {
                label: this.localization.costCenter,
                width: '5%',
                def: { data: "CostDrv", name: "AcCostDrv", filtertype: "text", rorderable: false }
            },
            {
                label: this.localization.user,
                width: '7%',
                def: { data: "Clerk", name: "AnClerkUser.AcTitle", orderable: false, filtertype: "text" }
            }
        ];
    };

    PawDocumentFinder.prototype.datagridFilters = function(d){
        d.Keywords = this.data.search;
        d.DateFrom = moment(this.data.dateFrom, this.localization.dateFormat).format('yyyy-MM-DD'),
        d.DateTo = moment(this.data.dateTo, this.localization.dateFormat).format('yyyy-MM-DD'),
        d.DocTypes = this.data.documentType;
        d.SubjectId = utils.value.isSet(this.data.subject)? this.data.subject.id : '';
        d.Users = this.data.user;
        d.Classifications = this.data.classification;
        d.Statuses = this.data.documentStatus;
        d.ShowDeleted = false;
        d.Departments = this.data.departments;
        d.CostDrvs = this.data.costDrvs;
    };

    PawDocumentFinder.prototype.filtersDef = function () {
        var self = this;
        var classificationOptions = '';
        utils.iterable.iterate(this.filterData.Classifications, function(classification){
            classificationOptions += '<option value=' + classification.Id + '>' + classification.Name + '</option>';
        });
        var documentTypeOptions = '';
        utils.iterable.iterate(this.filterData.DocumentTypes, function(documentType){
            documentTypeOptions += '<option value=' + documentType.Id + '>' + documentType.Value + '</option>';
        });
        var documentStatusOptions = '';
        utils.iterable.iterate(this.filterData.DocumentStatuses, function(documentStatus){
            documentStatusOptions += '<option value=' + documentStatus.Status + '>' + documentStatus.Name + '</option>';
        });
        var userOptions = '';
        utils.iterable.iterate(this.filterData.Users, function(user){
            userOptions += '<option value=' + user.Id + '>' + user.Name + '</option>';
        });
        var subjectColNames = [
            this.localization.company,
            this.localization.title,
            this.localization.address,
            this.localization.post
        ];

        var filters = [
            {
                id: 'search',
                pinned: true,
                label: this.localization.search,
                ignoreStoreValue: false,
                markup: '<div class="paw-holder-rel"><input id="search" class="form-control paw-finder-input" type="text" placeholder="' + this.localization.searchPlaceholder + '" autocomplete="off" data-field-search /> <div class="paw-abs paw-abs-right paw-abs-middle paw-transform-y-middle paw-alpha-50 p-r-3x"><span class="fa fa-search"></span></div></div>',
                inputField: function($elt, data){
                    return new paw.com.Input($elt, 'search', data, undefined, function(){
                        return self.onFilterChange();
                    });
                }
            },
            {
                id: 'subject',
                label: this.localization.subject,
                pinned: true,
                markup: '<select id="subject" class="form-control select2withAPI" type="text" autocomplete="off" data-field-subject data-url="' + self.settings.subjectSearchUrl + '" data-column-names="' + subjectColNames.join(',')  + '" data-bootstrap-columns="col-md-4,col-md-4,col-md-3,col-md-1" data-splitter="," data-allow-clear="true" data-search-width="800" data-placeholder="' + this.localization.partner + '"></select>',
                inputField: function($elt, data){
                    return new paw.com.Input($elt, 'subject', data, undefined, function(e){
                        return self.onFilterChange();
                    });
                }
            },
            {
                id: 'documentType',
                label: this.localization.documentType,
                markup: '<select id="documentType" class="form-control selectpicker" type="text" autocomplete="off" multiple="multiple" data-live-search="true" title="' + this.localization.all + '" data-custom-class="paw-finder-select" data-field-document-type>' + documentTypeOptions + '</select>',
                inputField: function($elt, data){
                    return new paw.com.Input($elt, 'documentType', data, {
                        settings: {
                            container: 'body'
                        }
                    }, function(){
                        return self.onFilterChange();
                    });
                }
            },
            {
                id: 'classification',
                label: this.localization.classification,
                pinned: true,
                markup: '<select id="classification" class="form-control selectpicker" type="text" autocomplete="off" multiple="multiple" data-live-search="true" title="' + this.localization.all + '" data-custom-class="paw-finder-select" data-field-classification>' + classificationOptions + '</select>',
                inputField: function($elt, data){
                    return new paw.com.Input($elt, 'classification', data, {
                        settings: {
                            container: 'body'
                        }
                    }, function(){
                        return self.onFilterChange();
                    });
                }
            },
            {
                id: 'user',
                label: this.localization.user,
                markup: '<select id="user" class="form-control selectpicker" type="text" autocomplete="off" multiple="multiple" data-live-search="true" title="' + this.localization.all + '" data-custom-class="paw-finder-select" data-field-user>' + userOptions + '</select>',
                inputField: function($elt, data){
                    return new paw.com.Input($elt, 'user', data, {
                        settings: {
                            container: 'body'
                        }
                    }, function(){
                        return self.onFilterChange();
                    });
                }
            },
            {
                id: 'documentStatus',
                label: this.localization.status,
                markup: '<select id="documentStatus" class="form-control selectpicker" type="text" autocomplete="off" multiple="multiple" data-live-search="true" title="' + this.localization.all + '" data-custom-class="paw-finder-select" data-field-document-status>' + documentStatusOptions + '</select>',
                inputField: function($elt, data){
                    return new paw.com.Input($elt, 'documentStatus', data, {
                        settings: {
                            container: 'body'
                        }
                    }, function(){
                        return self.onFilterChange();
                    });
                }
            },
            {
                id: 'departments',
                label: this.localization.department,
                markup: '<select id="departments"' +
                            'name="Department"' +
                            'type="text"' +
                            'multiple="multiple"' +
                            'class="form-control select2withAPI"' +
                            'data-url="' + this.settings.findDepartmentsUrl + '"' +
                            'data-column-names="' + this.localization.department + ',' + this.localization.name2 + ',' + this.localization.name3 + '"' +
                            'data-bootstrap-columns="col-md-4,col-md-4,col-md-4"' +
                            'data-splitter=","' +
                            'data-search-width="800"' +
                            'data-paw-multiselect="true"' +
                            'data-right-align="true"' +
                            'data-first-column-only="true"' +
                            'data-close-onselect="false"' +
                            'data-placeholder="' + this.localization.all + '"' +
                            'data-allow-clear="true"'+
                            'data-field-departments"></select>',
                inputField: function($elt, data){
                    return new paw.com.Input($elt, 'departments', data, undefined, function(){
                        return self.onFilterChange();
                    });
                }
            },
            {
                id: 'costDrvs',
                label: this.localization.costCenter,
                markup: '<select id="costDrvs"' +
                            'name="CostDrvs"' +
                            'type="text"' +
                            'multiple="multiple"' +
                            'class="form-control select2withAPI"' +
                            'data-url="' + this.settings.findCostDrvsUrl + '"' +
                            'data-column-names="' + this.localization.costCarrier + ',' + this.localization.name + ',' + this.localization.group + ',' + this.localization.status + '"' +
                            'data-bootstrap-columns="col-md-4,col-md-4,col-md-3,col-md-1"' +
                            'data-splitter=","' +
                            'data-search-width="800"' +
                            'data-paw-multiselect="true"' +
                            'data-right-align="true"' +
                            'data-first-column-only="true"' +
                            'data-close-onselect="false"' +
                            'data-placeholder="' + this.localization.all + '"' +
                            'data-allow-clear="true"'+
                            'data-field-cost-drvs"></select>',
                inputField: function($elt, data){
                    return new paw.com.Input($elt, 'costDrvs', data, undefined, function(){
                        return self.onFilterChange();
                    });
                }
            },
            {
                id: 'dateFrom',
                label: this.localization.dateFrom,
                pinned: true,
                markup: '<div class="paw-date-picker-holder paw-finder-input-date input-group"><span class="input-group-addon"><i class="far fa-calendar alt"></i></span><input id="dateFrom" type="text" class="form-control custom-datepicker" autocomplete="off" /></div>',
                inputField: function($elt, data, $filters){
                    return new paw.com.Input($elt, 'dateFrom', data, {
                        settings: {
                            format: self.localization.dateFormat,
                            locale: $('#languageDate').val(),
                            maxDate: moment(data.dateTo, self.localization.dateFormat).endOf('day') 
                        }
                    }, function(){
                        $filters.find('#dateTo').datetimepicker('minDate', moment(data.dateFrom, self.localization.dateFormat).startOf('day'));
                        return self.onFilterChange();
                    });
                }
            },
            {
                id: 'dateTo',
                label: this.localization.dateTo,
                pinned: true,
                markup: '<div class="paw-date-picker-holder paw-finder-input-date input-group"><span class="input-group-addon"><i class="far fa-calendar alt"></i></span><input id="dateTo" type="text" class="form-control custom-datepicker" autocomplete="off" /></div>',
                inputField: function($elt, data, $filters){
                    return new paw.com.Input($elt, 'dateTo', data, {
                        settings: {
                            format: self.localization.dateFormat,
                            locale: $('#languageDate').val(),
                            minDate: moment(data.dateFrom, self.localization.dateFormat).startOf('day'),
                            maxDate: moment(self.filterData.DateTo).endOf('day')
                        }
                    }, function(){
                        $filters.find('#dateFrom').datetimepicker('maxDate', moment(data.dateTo, self.localization.dateFormat).endOf('day'));
                        return self.onFilterChange();
                    });
                }
            }
        ];
        return filters;
    };

    PawDocumentFinder.prototype.onFilterChange = function () {
        this.finder.find();
    };

    PawDocumentFinder.prototype.init = function () {
        return this.fetchDocumentFinderFilterData();
    };

    PawDocumentFinder.prototype.destroy = function () {
        
    };

    PawDocumentFinder.prototype.fetchDocumentFinderFilterData = function(){
        var self = this;
        return utils.async.get(this.settings.documentFinderFilterDataUrl).then(function(filterData){
            self.filterData = filterData;
        });
    };

    PawDocumentFinder.prototype.resetValues = function(){
        return {
            search: '',
            documentNumber: '',
            subject: null,
            classification: '',
            dateFrom: moment(this.filterData.DateFrom).format('DD.MM.YYYY'),
            dateTo: moment(this.filterData.DateTo).format('DD.MM.YYYY'),
            user: '',
            documentType: '',
            documentStatus: '',
            departments: [],
            costDrvs: []
        };
    };

    paw.mod.documentFinder.DocumentFinder = PawDocumentFinder;
})(paw, paw.utils);