SearchResultLayoutView.js 49.1 KB
Newer Older
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20
/**
 * Licensed to the Apache Software Foundation (ASF) under one
 * or more contributor license agreements.  See the NOTICE file
 * distributed with this work for additional information
 * regarding copyright ownership.  The ASF licenses this file
 * to you under the Apache License, Version 2.0 (the
 * "License"); you may not use this file except in compliance
 * with the License.  You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

define(['require',
    'backbone',
21
    'hbs!tmpl/search/SearchResultLayoutView_tmpl',
22 23 24 25
    'modules/Modal',
    'models/VEntity',
    'utils/Utils',
    'utils/Globals',
26
    'collection/VSearchList',
27
    'models/VCommon',
28
    'utils/CommonViewFunction',
29 30 31 32
    'utils/Messages',
    'utils/Enums',
    'utils/UrlLinks'
], function(require, Backbone, SearchResultLayoutViewTmpl, Modal, VEntity, Utils, Globals, VSearchList, VCommon, CommonViewFunction, Messages, Enums, UrlLinks) {
33 34
    'use strict';

35 36
    var SearchResultLayoutView = Backbone.Marionette.LayoutView.extend(
        /** @lends SearchResultLayoutView */
37
        {
38
            _viewName: 'SearchResultLayoutView',
39

40
            template: SearchResultLayoutViewTmpl,
41 42 43 44 45

            /** Layout sub regions */
            regions: {
                RTagLayoutView: "#r_tagLayoutView",
                RSearchLayoutView: "#r_searchLayoutView",
46
                REntityTableLayoutView: "#r_searchResultTableLayoutView",
47
                RSearchQuery: '#r_searchQuery'
48 49 50 51 52 53
            },

            /** ui selector cache */
            ui: {
                tagClick: '[data-id="tagClick"]',
                addTag: '[data-id="addTag"]',
54
                addTerm: '[data-id="addTerm"]',
55
                showMoreLess: '[data-id="showMoreLess"]',
56 57 58
                showMoreLessTerm: '[data-id="showMoreLessTerm"]',
                paginationDiv: '[data-id="paginationDiv"]',
                previousData: "[data-id='previousData']",
59
                nextData: "[data-id='nextData']",
60
                pageRecordText: "[data-id='pageRecordText']",
61
                addAssignTag: "[data-id='addAssignTag']",
62
                createEntity: "[data-id='createEntity']",
63
                checkDeletedEntity: "[data-id='checkDeletedEntity']",
64
                colManager: "[data-id='colManager']",
65
                containerCheckBox: "[data-id='containerCheckBox']",
66 67 68 69 70
                columnEmptyInfo: "[data-id='columnEmptyInfo']",
                showPage: "[data-id='showPage']",
                gotoPage: "[data-id='gotoPage']",
                gotoPagebtn: "[data-id='gotoPagebtn']",
                activePage: "[data-id='activePage']",
71 72 73
            },
            templateHelpers: function() {
                return {
74
                    entityCreate: Globals.entityCreate,
75 76
                    searchType: this.searchType,
                    taxonomy: Globals.taxonomy
77
                };
78 79 80
            },
            /** ui events hash */
            events: function() {
81 82
                var events = {},
                    that = this;
83
                events["click " + this.ui.tagClick] = function(e) {
84
                    var scope = $(e.currentTarget);
85 86 87
                    if (e.target.nodeName.toLocaleLowerCase() == "i") {
                        this.onClickTagCross(e);
                    } else {
88 89
                        if (scope.hasClass('term')) {
                            var url = scope.data('href').split(".").join("/terms/");
90
                            this.triggerUrl({
91
                                url: '#!/taxonomy/detailCatalog' + UrlLinks.taxonomiesApiUrl() + '/' + url,
92
                                urlParams: null,
93
                                mergeBrowserUrl: false,
94 95
                                trigger: true,
                                updateTabState: null
96 97
                            });
                        } else {
98
                            this.triggerUrl({
99
                                url: '#!/tag/tagAttribute/' + scope.text(),
100
                                urlParams: null,
101
                                mergeBrowserUrl: false,
102 103
                                trigger: true,
                                updateTabState: null
104 105
                            });
                        }
106 107
                    }
                };
108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123
                events["keyup " + this.ui.gotoPage] = function(e) {
                    var code = e.which,
                        goToPage = parseInt(e.currentTarget.value);
                    if (e.currentTarget.value) {
                        that.ui.gotoPagebtn.attr('disabled', false);
                    } else {
                        that.ui.gotoPagebtn.attr('disabled', true);
                    }
                    if (code == 13) {
                        if (e.currentTarget.value) {
                            that.gotoPagebtn();
                        }
                    }
                };
                events["change " + this.ui.showPage] = 'changePageLimit';
                events["click " + this.ui.gotoPagebtn] = 'gotoPagebtn';
124
                events["click " + this.ui.addTag] = 'checkedValue';
125
                events["click " + this.ui.addTerm] = 'checkedValue';
126
                events["click " + this.ui.addAssignTag] = 'checkedValue';
127
                events["click " + this.ui.showMoreLessTerm] = function(e) {
128
                    e.stopPropagation();
129 130 131 132 133 134 135 136
                    $(e.currentTarget).find('i').toggleClass('fa fa-angle-right fa fa-angle-up');
                    $(e.currentTarget).parents('.searchTerm').find('div.termTableBreadcrumb>div.showHideDiv').toggleClass('hide');
                    if ($(e.currentTarget).find('i').hasClass('fa-angle-right')) {
                        $(e.currentTarget).find('span').text('Show More');
                    } else {
                        $(e.currentTarget).find('span').text('Show less');
                    }
                };
137 138
                events["click " + this.ui.nextData] = "onClicknextData";
                events["click " + this.ui.previousData] = "onClickpreviousData";
139
                events["click " + this.ui.createEntity] = 'onClickCreateEntity';
140
                events["click " + this.ui.checkDeletedEntity] = 'onCheckDeletedEntity';
141 142 143
                return events;
            },
            /**
144
             * intialize a new SearchResultLayoutView Layout
145 146 147
             * @constructs
             */
            initialize: function(options) {
148
                _.extend(this, _.pick(options, 'value', 'initialView', 'entityDefCollection', 'typeHeaders', 'searchVent', 'enumDefCollection', 'tagCollection', 'searchTableColumns'));
149
                this.entityModel = new VEntity();
150
                this.searchCollection = new VSearchList();
151
                this.limit = 25;
152
                this.asyncFetchCounter = 0;
153
                this.offset = 0;
154
                this.bindEvents();
155
                this.bradCrumbList = [];
156
                this.arr = [];
157
                this.searchType = 'Basic Search';
158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179
                if (this.value) {
                    if (this.value.searchType && this.value.searchType == 'dsl') {
                        this.searchType = 'Advanced Search';
                    }
                    if (this.value.pageLimit) {
                        var pageLimit = parseInt(this.value.pageLimit, 10);
                        if (_.isNaN(pageLimit) || pageLimit == 0 || pageLimit <= -1) {
                            this.value.pageLimit = this.limit;
                            this.triggerUrl();
                        } else {
                            this.limit = pageLimit;
                        }
                    }
                    if (this.value.pageOffset) {
                        var pageOffset = parseInt(this.value.pageOffset, 10);
                        if (_.isNaN(pageOffset) || pageLimit <= -1) {
                            this.value.pageOffset = this.offset;
                            this.triggerUrl();
                        } else {
                            this.offset = pageOffset;
                        }
                    }
180
                }
181 182
            },
            bindEvents: function() {
183
                var that = this;
184
                this.listenTo(this.searchCollection, 'backgrid:selected', function(model, checked) {
185
                    this.arr = [];
186 187 188 189 190 191 192 193
                    if (checked === true) {
                        model.set("isEnable", true);
                    } else {
                        model.set("isEnable", false);
                    }
                    this.searchCollection.find(function(item) {
                        if (item.get('isEnable')) {
                            var term = [];
194
                            var obj = item.toJSON();
195
                            that.arr.push({
196 197
                                id: obj.guid,
                                model: obj
198 199 200
                            });
                        }
                    });
201

202
                    if (this.arr.length > 0) {
203 204 205 206
                        if (Globals.taxonomy) {
                            this.$('.multiSelectTerm').show();
                        }
                        this.$('.multiSelectTag').show();
207
                    } else {
208 209 210 211
                        if (Globals.taxonomy) {
                            this.$('.multiSelectTerm').hide();
                        }
                        this.$('.multiSelectTag').hide();
212
                    }
213
                });
214
                this.listenTo(this.searchCollection, "error", function(model, response) {
215
                    this.$('.fontLoader').hide();
216
                    this.$('.tableOverlay').hide();
217 218
                    var responseJSON = response && response.responseJSON ? response.responseJSON : null;
                    if (responseJSON && (responseJSON.errorMessage || responseJSON.message || responseJSON.error)) {
219 220 221 222
                        Utils.notifyError({
                            content: responseJSON.errorMessage || responseJSON.message || responseJSON.error
                        });
                    } else {
223 224
                        if (response.statusText !== "abort") {
                            Utils.notifyError({
225
                                content: "Invalid Expression"
226 227
                            });
                        }
228
                    }
229
                }, this);
230 231 232
                this.listenTo(this.searchCollection, "state-changed", function(state) {
                    if (Utils.getUrlState.isSearchTab()) {
                        this.updateColumnList(state);
233 234 235 236 237 238 239 240
                        var excludeDefaultColumn = [];
                        if (this.value && this.value.type) {
                            excludeDefaultColumn = _.without(this.searchTableColumns[this.value.type], "selected", "name", "description", "typeName", "owner", "tag", "terms");
                            if (this.searchTableColumns[this.value.type] === null) {
                                this.ui.columnEmptyInfo.show();
                            } else {
                                this.ui.columnEmptyInfo.hide();
                            }
241
                        }
242
                        this.triggerUrl();
243 244 245 246
                        if (excludeDefaultColumn.length > this.searchCollection.filterObj.attributes.length) {
                            this.fetchCollection(this.value);
                        }

247 248
                    }
                }, this);
249 250 251
                this.listenTo(this.searchVent, "search:refresh", function(model, response) {
                    this.fetchCollection();
                }, this);
252 253
            },
            onRender: function() {
254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279
                var that = this;
                this.commonTableOptions = {
                    collection: this.searchCollection,
                    includePagination: false,
                    includeFooterRecords: false,
                    includeColumnManager: (Utils.getUrlState.isSearchTab() && this.value && this.value.searchType === "basic" && !this.value.profileDBView ? true : false),
                    includeOrderAbleColumns: false,
                    includeSizeAbleColumns: false,
                    includeTableLoader: false,
                    columnOpts: {
                        opts: {
                            initialColumnsVisible: null,
                            saveState: false
                        },
                        visibilityControlOpts: {
                            buttonTemplate: _.template("<button class='btn btn-action btn-md pull-right'>Columns&nbsp<i class='fa fa-caret-down'></i></button>")
                        },
                        el: this.ui.colManager
                    },
                    gridOpts: {
                        emptyText: 'No Record found!',
                        className: 'table table-hover backgrid table-quickMenu'
                    },
                    filterOpts: {},
                    paginatorOpts: {}
                };
280 281 282 283 284
                if (!this.initialView) {
                    var value = {},
                        that = this;
                    if (this.value) {
                        value = this.value;
285 286 287
                        if (value && value.includeDE) {
                            this.ui.checkDeletedEntity.prop('checked', true);
                        }
288 289
                    } else {
                        value = {
290
                            'query': null,
291
                            'searchType': 'basic'
292 293
                        };
                    }
294
                    this.updateColumnList();
295 296 297 298 299
                    if (this.value && this.searchTableColumns && this.searchTableColumns[this.value.type] === null) {
                        this.ui.columnEmptyInfo.show();
                    } else {
                        this.ui.columnEmptyInfo.hide();
                    }
300
                    this.fetchCollection(value, _.extend({ 'fromUrl': true }, (this.value && this.value.pageOffset ? { 'next': true } : null)));
301 302 303
                } else {
                    if (Globals.entityTypeConfList) {
                        this.$(".entityLink").show();
304
                    }
305
                }
306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323
                this.ui.showPage.select2({
                    data: _.sortBy(_.union([25, 50, 100, 150, 200, 250, 300, 350, 400, 450, 500], [this.limit])),
                    tags: true,
                    dropdownCssClass: "number-input",
                    multiple: false
                });
                if (this.value && this.value.pageLimit) {
                    this.ui.showPage.val(this.limit).trigger('change', { "skipViewChange": true });
                }
            },
            triggerUrl: function(options) {
                Utils.setUrl(_.extend({
                    url: Utils.getUrlState.getQueryUrl().queyParams[0],
                    urlParams: this.value,
                    mergeBrowserUrl: false,
                    trigger: false,
                    updateTabState: true
                }, options));
324
            },
325 326
            updateColumnList: function(updatedList) {
                if (updatedList) {
327
                    var listOfColumns = [];
328 329 330 331 332 333
                    _.map(updatedList, function(obj) {
                        var key = obj.name;
                        if (obj.renderable) {
                            listOfColumns.push(obj.name);
                        }
                    });
334
                    listOfColumns = _.sortBy(listOfColumns);
335
                    this.value.attributes = listOfColumns.length ? listOfColumns.join(",") : null;
336
                    if (this.value && this.value.type && this.searchTableColumns) {
337 338 339 340
                        this.searchTableColumns[this.value.type] = listOfColumns.length ? listOfColumns : null;
                    }
                } else if (this.value && this.value.type && this.searchTableColumns && this.value.attributes) {
                    this.searchTableColumns[this.value.type] = this.value.attributes.split(",");
341 342
                }
            },
343
            fetchCollection: function(value, options) {
344
                var that = this,
345 346 347 348 349 350
                    isPostMethod = (this.value && this.value.searchType === "basic"),
                    isSearchTab = Utils.getUrlState.isSearchTab(),
                    tagFilters = null,
                    entityFilters = null;
                if (isSearchTab) {
                    tagFilters = CommonViewFunction.attributeFilter.generateAPIObj(this.value.tagFilters);
351
                    entityFilters = CommonViewFunction.attributeFilter.generateAPIObj(this.value.entityFilters);
352 353 354
                }

                if (isPostMethod && isSearchTab) {
355
                    var excludeDefaultColumn = this.value.type && this.searchTableColumns ? _.without(this.searchTableColumns[this.value.type], "selected", "name", "description", "typeName", "owner", "tag", "terms") : null,
356 357 358 359 360 361 362
                        filterObj = {
                            'entityFilters': entityFilters,
                            'tagFilters': tagFilters,
                            'attributes': excludeDefaultColumn ? excludeDefaultColumn : null
                        };
                }

363
                this.showLoader();
364
                if (Globals.searchApiCallRef && Globals.searchApiCallRef.readyState === 1) {
365 366
                    Globals.searchApiCallRef.abort();
                }
367
                var apiObj = {
368
                    skipDefaultError: true,
369
                    sort: false,
370
                    success: function(dataOrCollection, response) {
371
                        Globals.searchApiCallRef = undefined;
372 373 374
                        var isFirstPage = that.offset === 0,
                            dataLength = 0,
                            goToPage = that.ui.gotoPage.val();
375 376 377
                        if (!(that.ui.pageRecordText instanceof jQuery)) {
                            return;
                        }
378 379 380 381 382 383 384 385 386 387
                        if (isPostMethod && dataOrCollection && dataOrCollection.entities) {
                            dataLength = dataOrCollection.entities.length;
                        } else {
                            dataLength = dataOrCollection.length;
                        }

                        if (!dataLength && that.offset >= that.limit && ((options && options.next) || goToPage) && (options && !options.fromUrl)) {
                            /* User clicks on next button and server returns 
                            empty response then disabled the next button without rendering table*/

388
                            that.hideLoader();
389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404
                            var pageNumber = that.activePage + 1;
                            if (goToPage) {
                                pageNumber = goToPage;
                                that.offset = that.offset - ((parseInt(pageNumber, 10) - 1) * that.limit);
                            } else {
                                that.ui.nextData.attr('disabled', true);
                                that.offset = that.offset - that.limit;
                            }
                            if (that.value) {
                                that.value.pageOffset = that.offset;
                                that.triggerUrl();
                            }
                            Utils.notifyInfo({
                                html: true,
                                content: Messages.search.noRecordForPage + '<b>' + Utils.getNumberSuffix({ number: pageNumber, sup: true }) + '</b> page'
                            });
405 406
                            return;
                        }
407
                        if (isPostMethod) {
408
                            that.searchCollection.referredEntities = dataOrCollection.rnoRecordFoeferredEntities;
409
                            that.searchCollection.reset(dataOrCollection.entities);
410
                        }
411 412 413 414 415

                        /*Next button check.
                        It's outside of Previous button else condition 
                        because when user comes from 2 page to 1 page than we need to check next button.*/
                        if (dataLength < that.limit) {
416 417 418 419
                            that.ui.nextData.attr('disabled', true);
                        } else {
                            that.ui.nextData.attr('disabled', false);
                        }
420 421 422 423 424 425 426 427 428 429

                        if (isFirstPage && (!dataLength || dataLength < that.limit)) {
                            that.ui.paginationDiv.hide();
                        } else {
                            that.ui.paginationDiv.show();
                        }

                        // Previous button check.
                        if (isFirstPage) {
                            that.ui.previousData.attr('disabled', true);
430 431
                            that.pageFrom = 1;
                            that.pageTo = that.limit;
432 433 434 435 436
                        } else {
                            that.ui.previousData.attr('disabled', false);
                        }

                        if (options && options.next) {
437 438 439
                            //on next click, adding "1" for showing the another records.
                            that.pageTo = that.offset + that.limit;
                            that.pageFrom = that.offset + 1;
440
                        } else if (!isFirstPage && options && options.previous) {
441 442 443
                            that.pageTo = that.pageTo - that.limit;
                            that.pageFrom = (that.pageTo - that.limit) + 1;
                        }
444
                        that.ui.pageRecordText.html("Showing  <u>" + that.searchCollection.models.length + " records</u> From " + that.pageFrom + " - " + that.pageTo);
445 446 447
                        that.activePage = Math.round(that.pageTo / that.limit);
                        that.ui.activePage.attr('title', "Page " + that.activePage);
                        that.ui.activePage.text(that.activePage);
448
                        that.renderTableLayoutView();
449 450

                        if (value && !value.profileDBView) {
451
                            var searchString = 'Results for: <span class="filterQuery">' + CommonViewFunction.generateQueryOfFilter(that.value) + "</span>";
452 453 454 455
                            if (Globals.entityCreate && Globals.entityTypeConfList && Utils.getUrlState.isSearchTab()) {
                                searchString += "<p>If you do not find the entity in search result below then you can" + '<a href="javascript:void(0)" data-id="createEntity"> create new entity</a></p>';
                            }
                            that.$('.searchResult').html(searchString);
456
                        }
457
                    },
458 459
                    silent: true,
                    reset: true
460 461 462 463 464
                }
                if (value) {
                    if (value.searchType) {
                        this.searchCollection.url = UrlLinks.searchApiUrl(value.searchType);
                    }
465
                    _.extend(this.searchCollection.queryParams, { 'limit': this.limit, 'offset': this.offset, 'query': (value.query ? value.query.trim() : null), 'typeName': value.type || null, 'classification': value.tag || null });
466 467 468 469 470 471
                    if (value.profileDBView && value.guid) {
                        var profileParam = {};
                        profileParam['guid'] = value.guid;
                        profileParam['relation'] = '__hive_table.db';
                        profileParam['sortBy'] = 'name';
                        profileParam['sortOrder'] = 'ASCENDING';
472
                        _.extend(this.searchCollection.queryParams, profileParam);
473
                    }
474
                    if (isPostMethod) {
475
                        this.searchCollection.filterObj = _.extend({}, filterObj);
476 477
                        apiObj['data'] = _.extend({
                            'excludeDeletedEntities': (this.value && this.value.includeDE ? false : true)
478
                        }, filterObj, _.pick(this.searchCollection.queryParams, 'query', 'excludeDeletedEntities', 'limit', 'offset', 'typeName', 'classification'))
479 480 481
                        Globals.searchApiCallRef = this.searchCollection.getBasicRearchResult(apiObj);
                    } else {
                        apiObj.data = null;
482
                        this.searchCollection.filterObj = null;
483 484 485 486
                        Globals.searchApiCallRef = this.searchCollection.fetch(apiObj);
                    }
                } else {
                    if (isPostMethod) {
487 488
                        apiObj['data'] = _.extend({
                            'excludeDeletedEntities': (this.value && this.value.includeDE ? false : true)
489
                        }, filterObj, _.pick(this.searchCollection.queryParams, 'query', 'excludeDeletedEntities', 'limit', 'offset', 'typeName', 'classification'));
490 491 492 493 494 495 496 497 498 499 500 501 502 503
                        Globals.searchApiCallRef = this.searchCollection.getBasicRearchResult(apiObj);
                    } else {
                        apiObj.data = null;
                        Globals.searchApiCallRef = this.searchCollection.fetch(apiObj);
                    }
                }
            },
            renderSearchQueryView: function() {
                var that = this;
                require(['views/search/SearchQueryView'], function(SearchQueryView) {
                    that.RSearchQuery.show(new SearchQueryView({
                        value: that.value,
                        searchVent: that.searchVent
                    }));
504
                });
505
            },
506
            renderTableLayoutView: function(col) {
507
                var that = this;
508
                require(['utils/TableLayout'], function(TableLayout) {
509
                    // displayOrder added for column manager
510
                    var columnCollection = Backgrid.Columns.extend({
511
                        sortKey: "displayOrder",
512 513 514 515 516
                        comparator: function(item) {
                            return item.get(this.sortKey) || 999;
                        },
                        setPositions: function() {
                            _.each(this.models, function(model, index) {
517
                                model.set("displayOrder", index + 1, { silent: true });
518 519 520 521 522 523
                            });
                            return this;
                        }
                    });
                    var columns = new columnCollection(that.getFixedDslColumn());
                    columns.setPositions().sort();
524
                    that.REntityTableLayoutView.show(new TableLayout(_.extend({}, that.commonTableOptions, {
525
                        columns: columns
526
                    })));
527 528
                    if (that.value.searchType !== "dsl") {
                        that.ui.containerCheckBox.show();
529
                    } else {
530
                        that.ui.containerCheckBox.hide();
531
                    }
532
                    that.$(".ellipsis .inputAssignTag").hide();
533
                    that.renderBreadcrumb();
534
                    that.checkTableFetch();
535 536 537 538 539
                });
            },
            renderBreadcrumb: function() {
                var that = this;
                _.each(this.bradCrumbList, function(object) {
540 541 542 543
                    _.each(object.value, function(subObj) {
                        var scopeObject = that.$('[dataterm-id="' + object.scopeId + '"]').find('[dataterm-name="' + subObj.name + '"] .liContent');
                        CommonViewFunction.breadcrumbMaker({ urlList: subObj.valueUrl, scope: scopeObject });
                    });
544 545
                });
            },
546
            checkTableFetch: function() {
547
                if (this.asyncFetchCounter <= 0) {
548
                    this.hideLoader();
549 550 551 552 553 554 555 556 557 558
                    Utils.generatePopover({
                        el: this.$('[data-id="showMoreLess"]'),
                        container: this.$el,
                        contentClass: 'popover-tag',
                        popoverOptions: {
                            content: function() {
                                return $(this).find('.popup-tag').children().clone();
                            }
                        }
                    });
559 560
                }
            },
561 562
            getFixedDslColumn: function() {
                var that = this,
563
                    nameCheck = 0,
564
                    columnToShow = null,
565
                    col = {};
566 567 568
                if (this.value && this.searchTableColumns && (this.searchTableColumns[this.value.type] !== undefined)) {
                    columnToShow = this.searchTableColumns[this.value.type] == null ? [] : this.searchTableColumns[this.value.type];
                }
569 570
                col['Check'] = {
                    name: "selected",
571
                    label: "Select",
572
                    cell: "select-row",
573 574
                    resizeable: false,
                    orderable: false,
575
                    renderable: (columnToShow ? _.contains(columnToShow, 'selected') : true),
576 577
                    headerCell: "select-all"
                };
578

579
                col['name'] = {
580
                    label: this.value && this.value.profileDBView ? "Table Name" : "Name",
581 582 583
                    cell: "html",
                    editable: false,
                    sortable: false,
584 585 586
                    resizeable: true,
                    orderable: true,
                    renderable: true,
587 588 589
                    className: "searchTableName",
                    formatter: _.extend({}, Backgrid.CellFormatter.prototype, {
                        fromRaw: function(rawValue, model) {
590 591 592
                            var obj = model.toJSON(),
                                nameHtml = "",
                                name = Utils.getName(obj);
593 594 595
                            if (obj.guid) {
                                nameHtml = '<a title="' + name + '" href="#!/detailPage/' + obj.guid + '">' + name + '</a>';
                            } else {
596
                                nameHtml = '<span title="' + name + '">' + name + '</span>';
597 598
                            }
                            if (obj.status && Enums.entityStateReadOnly[obj.status]) {
599
                                nameHtml += '<button type="button" title="Deleted" class="btn btn-action btn-md deleteBtn"><i class="fa fa-trash"></i></button>';
600
                                return '<div class="readOnly readOnlyLink">' + nameHtml + '</div>';
601
                            }
602
                            return nameHtml;
603 604 605
                        }
                    })
                };
606 607
                col['owner'] = {
                    label: "Owner",
608 609
                    cell: "String",
                    editable: false,
610
                    sortable: false,
611 612 613
                    resizeable: true,
                    orderable: true,
                    renderable: true,
614 615
                    formatter: _.extend({}, Backgrid.CellFormatter.prototype, {
                        fromRaw: function(rawValue, model) {
616
                            var obj = model.toJSON();
617 618
                            if (obj && obj.attributes && obj.attributes.owner) {
                                return obj.attributes.owner;
619 620 621
                            }
                        }
                    })
622
                };
623 624 625 626 627 628 629 630 631 632 633 634 635 636
                if (this.value && this.value.profileDBView) {
                    col['createTime'] = {
                        label: "Date Created",
                        cell: "Html",
                        editable: false,
                        sortable: false,
                        formatter: _.extend({}, Backgrid.CellFormatter.prototype, {
                            fromRaw: function(rawValue, model) {
                                var obj = model.toJSON();
                                if (obj && obj.attributes && obj.attributes.createTime) {
                                    return new Date(obj.attributes.createTime);
                                } else {
                                    return '-'
                                }
637
                            }
638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655
                        })
                    }
                }
                if (this.value && !this.value.profileDBView) {
                    col['description'] = {
                        label: "Description",
                        cell: "String",
                        editable: false,
                        sortable: false,
                        resizeable: true,
                        orderable: true,
                        renderable: true,
                        formatter: _.extend({}, Backgrid.CellFormatter.prototype, {
                            fromRaw: function(rawValue, model) {
                                var obj = model.toJSON();
                                if (obj && obj.attributes && obj.attributes.description) {
                                    return obj.attributes.description;
                                }
656
                            }
657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672
                        })
                    };
                    col['typeName'] = {
                        label: "Type",
                        cell: "Html",
                        editable: false,
                        sortable: false,
                        resizeable: true,
                        orderable: true,
                        renderable: (columnToShow ? _.contains(columnToShow, 'typeName') : true),
                        formatter: _.extend({}, Backgrid.CellFormatter.prototype, {
                            fromRaw: function(rawValue, model) {
                                var obj = model.toJSON();
                                if (obj && obj.typeName) {
                                    return '<a title="Search ' + obj.typeName + '" href="#!/search/searchResult?query=' + obj.typeName + ' &searchType=dsl&dslChecked=true">' + obj.typeName + '</a>';
                                }
673
                            }
674 675
                        })
                    };
676

677 678
                    col['tag'] = {
                        label: "Tags",
679 680 681
                        cell: "Html",
                        editable: false,
                        sortable: false,
682
                        resizeable: true,
683
                        orderable: true,
684 685
                        renderable: (columnToShow ? _.contains(columnToShow, 'tag') : true),
                        className: 'searchTag',
686 687
                        formatter: _.extend({}, Backgrid.CellFormatter.prototype, {
                            fromRaw: function(rawValue, model) {
688
                                var obj = model.toJSON();
689
                                if (obj.status && Enums.entityStateReadOnly[obj.status]) {
690
                                    return '<div class="readOnly">' + CommonViewFunction.tagForTable(obj); + '</div>';
691
                                } else {
692
                                    return CommonViewFunction.tagForTable(obj);
693
                                }
694

695 696 697
                            }
                        })
                    };
698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719
                    if (Globals.taxonomy) {
                        col['terms'] = {
                            label: "Terms",
                            cell: "Html",
                            editable: false,
                            sortable: false,
                            resizeable: true,
                            orderable: true,
                            renderable: (columnToShow ? _.contains(columnToShow, 'terms') : true),
                            className: 'searchTerm',
                            formatter: _.extend({}, Backgrid.CellFormatter.prototype, {
                                fromRaw: function(rawValue, model) {
                                    var obj = model.toJSON();
                                    var returnObject = CommonViewFunction.termTableBreadcrumbMaker(obj);
                                    if (returnObject.object) {
                                        that.bradCrumbList.push(returnObject.object);
                                    }
                                    if (obj.status && Enums.entityStateReadOnly[obj.status]) {
                                        return '<div class="readOnly">' + returnObject.html + '</div>';
                                    } else {
                                        return returnObject.html;
                                    }
720
                                }
721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747
                            })
                        };
                    }
                    if (this.value && this.value.searchType === "basic") {
                        var def = this.entityDefCollection.fullCollection.find({ name: this.value.type });
                        if (def) {
                            var attrObj = Utils.getNestedSuperTypeObj({ data: def.toJSON(), collection: this.entityDefCollection, attrMerge: true });
                            _.each(attrObj, function(obj, key) {
                                var key = obj.name,
                                    isRenderable = _.contains(columnToShow, key)
                                if (key == "name" || key == "description" || key == "owner") {
                                    if (columnToShow) {
                                        col[key].renderable = isRenderable;
                                    }
                                    return;
                                }
                                col[obj.name] = {
                                    label: obj.name.capitalize(),
                                    cell: "Html",
                                    editable: false,
                                    sortable: false,
                                    resizeable: true,
                                    orderable: true,
                                    renderable: isRenderable,
                                    formatter: _.extend({}, Backgrid.CellFormatter.prototype, {
                                        fromRaw: function(rawValue, model) {
                                            var modelObj = model.toJSON();
748

749 750 751 752 753 754 755
                                            if (modelObj && modelObj.attributes && !_.isUndefined(modelObj.attributes[key])) {
                                                var tempObj = {
                                                    'scope': that,
                                                    'attributeDefs': [obj],
                                                    'valueObject': {},
                                                    'isTable': false
                                                }
756

757 758 759 760
                                                tempObj.valueObject[key] = modelObj.attributes[key]
                                                Utils.findAndMergeRefEntity(tempObj.valueObject, that.searchCollection.referredEntities);
                                                return CommonViewFunction.propertyTable(tempObj);
                                            }
761
                                        }
762 763 764 765
                                    })
                                };
                            });
                        }
766 767
                    }
                }
768 769
                return this.searchCollection.constructor.getTableCols(col, this.searchCollection);
            },
770
            addTagModalView: function(guid, multiple) {
771
                var that = this;
772 773
                require(['views/tag/addTagModalView'], function(AddTagModalView) {
                    var view = new AddTagModalView({
774 775
                        guid: guid,
                        multiple: multiple,
776 777
                        callback: function() {
                            that.fetchCollection();
778 779
                            that.arr = [];
                        },
780
                        tagList: that.getTagList(guid, multiple),
781
                        showLoader: that.showLoader.bind(that),
782 783
                        hideLoader: that.hideLoader.bind(that),
                        enumDefCollection: that.enumDefCollection
784 785 786
                    });
                });
            },
787 788 789
            getTagList: function(guid, multiple) {
                var that = this;
                if (!multiple || multiple.length === 0) {
790 791
                    var model = this.searchCollection.find(function(item) {
                        var obj = item.toJSON();
792 793 794 795
                        if (obj.guid === guid) {
                            return true;
                        }
                    });
796
                    if (model) {
797
                        var obj = model.toJSON();
798 799 800 801 802 803 804 805
                    } else {
                        return [];
                    }
                    return obj.classificationNames;
                } else {
                    return [];
                }
            },
806
            showLoader: function() {
807
                this.$('.fontLoader:not(.for-ignore)').show();
808
                this.$('.tableOverlay').show();
809 810
            },
            hideLoader: function() {
811
                this.$('.fontLoader:not(.for-ignore)').hide();
812
                this.$('.ellipsis,.pagination-box').show(); // only for first time
813
                this.$('.tableOverlay').hide();
814
            },
815 816
            checkedValue: function(e) {
                var guid = "",
817 818 819 820 821 822
                    that = this,
                    isTagMultiSelect = $(e.currentTarget).hasClass('multiSelectTag'),
                    isTermMultiSelect = $(e.currentTarget).hasClass('multiSelectTerm'),
                    isTagButton = $(e.currentTarget).hasClass('assignTag');
                if (isTagButton) {
                    if (isTagMultiSelect && this.arr && this.arr.length) {
823 824 825 826 827
                        that.addTagModalView(guid, this.arr);
                    } else {
                        guid = that.$(e.currentTarget).data("guid");
                        that.addTagModalView(guid);
                    }
828
                } else {
829
                    if (isTermMultiSelect && this.arr && this.arr.length) {
830 831 832 833 834
                        that.addTermModalView(guid, this.arr);
                    } else {
                        guid = that.$(e.currentTarget).data("guid");
                        that.addTermModalView(guid);
                    }
835 836 837
                }
            },
            addTermModalView: function(guid, multiple) {
838 839 840 841 842
                var that = this;
                require([
                    'views/business_catalog/AddTermToEntityLayoutView',
                ], function(AddTermToEntityLayoutView) {
                    var view = new AddTermToEntityLayoutView({
843 844
                        guid: guid,
                        multiple: multiple,
845
                        callback: function() {
846
                            that.fetchCollection();
847 848
                            that.arr = [];
                        },
849 850
                        showLoader: that.showLoader.bind(that),
                        hideLoader: that.hideLoader.bind(that)
851 852 853
                    });
                });
            },
854
            onClickTagCross: function(e) {
855
                var tagName = $(e.target).data("name"),
856
                    guid = $(e.target).data("guid"),
857
                    assetName = $(e.target).data("assetname"),
858 859 860
                    tagOrTerm = $(e.target).data("type"),
                    that = this;
                if (tagOrTerm === "term") {
861
                    var modal = CommonViewFunction.deleteTagModel({
862
                        msg: "<div class='ellipsis'>Remove: " + "<b>" + _.escape(tagName) + "</b> assignment from" + " " + "<b>" + assetName + " ?</b></div>",
863 864 865
                        titleMessage: Messages.removeTerm,
                        buttonText: "Remove"
                    });
866
                } else if (tagOrTerm === "tag") {
867
                    var modal = CommonViewFunction.deleteTagModel({
868
                        msg: "<div class='ellipsis'>Remove: " + "<b>" + _.escape(tagName) + "</b> assignment from" + " " + "<b>" + assetName + " ?</b></div>",
869 870 871 872
                        titleMessage: Messages.removeTag,
                        buttonText: "Remove"
                    });
                }
873 874 875 876 877 878 879 880
                if (modal) {
                    modal.on('ok', function() {
                        that.deleteTagData(e, tagOrTerm);
                    });
                    modal.on('closeModal', function() {
                        modal.trigger('cancel');
                    });
                }
881
            },
882
            deleteTagData: function(e, tagOrTerm) {
883
                var that = this,
884 885
                    tagName = $(e.target).data("name"),
                    guid = $(e.target).data("guid");
886 887 888
                CommonViewFunction.deleteTag({
                    'tagName': tagName,
                    'guid': guid,
889
                    'tagOrTerm': tagOrTerm,
890 891
                    showLoader: that.showLoader.bind(that),
                    hideLoader: that.hideLoader.bind(that),
892 893 894
                    callback: function() {
                        that.fetchCollection();
                    }
895
                });
896 897
            },
            onClicknextData: function() {
898 899 900
                this.offset = this.offset + this.limit;
                _.extend(this.searchCollection.queryParams, {
                    offset: this.offset
901
                });
902 903 904 905 906 907
                if (this.value) {
                    this.value.pageOffset = this.offset;
                    this.triggerUrl();
                }
                this.ui.gotoPage.val('');
                this.ui.gotoPage.parent().removeClass('has-error');
908 909 910
                this.fetchCollection(null, {
                    next: true
                });
911 912
            },
            onClickpreviousData: function() {
913 914 915 916 917 918
                this.offset = this.offset - this.limit;
                if (this.offset <= -1) {
                    this.offset = 0;
                }
                _.extend(this.searchCollection.queryParams, {
                    offset: this.offset
919
                });
920 921 922 923 924 925
                if (this.value) {
                    this.value.pageOffset = this.offset;
                    this.triggerUrl();
                }
                this.ui.gotoPage.val('');
                this.ui.gotoPage.parent().removeClass('has-error');
926 927 928
                this.fetchCollection(null, {
                    previous: true
                });
929
            },
930 931 932 933 934 935 936
            onClickCreateEntity: function(e) {
                var that = this;
                $(e.currentTarget).blur();
                require([
                    'views/entity/CreateEntityLayoutView'
                ], function(CreateEntityLayoutView) {
                    var view = new CreateEntityLayoutView({
937
                        entityDefCollection: that.entityDefCollection,
938
                        typeHeaders: that.typeHeaders,
939 940 941 942 943
                        callback: function() {
                            that.fetchCollection();
                        }
                    });
                });
944 945
            },
            onCheckDeletedEntity: function(e) {
946
                var includeDE = false;
947
                if (e.target.checked) {
948
                    includeDE = true;
949
                }
950 951
                if (this.value) {
                    this.value.includeDE = includeDE;
952
                    this.triggerUrl();
953
                }
954
                _.extend(this.searchCollection.queryParams, { limit: this.limit, offset: this.offset });
955
                this.fetchCollection();
956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000
            },
            changePageLimit: function(e, obj) {
                if (!obj || (obj && !obj.skipViewChange)) {
                    var limit = parseInt(this.ui.showPage.val());
                    if (limit == 0) {
                        this.ui.showPage.data('select2').$container.addClass('has-error');
                        return;
                    } else {
                        this.ui.showPage.data('select2').$container.removeClass('has-error');
                    }
                    this.limit = limit;
                    this.offset = 0;
                    if (this.value) {
                        this.value.pageLimit = this.limit;
                        this.value.pageOffset = this.offset;
                        this.triggerUrl();
                    }
                    this.ui.gotoPage.val('');
                    this.ui.gotoPage.parent().removeClass('has-error');
                    _.extend(this.searchCollection.queryParams, { limit: this.limit, offset: this.offset });
                    this.fetchCollection();
                }
            },
            gotoPagebtn: function(e) {
                var that = this;
                var goToPage = parseInt(this.ui.gotoPage.val());
                if (!(_.isNaN(goToPage) || goToPage <= -1)) {
                    this.offset = (goToPage - 1) * this.limit;
                    if (this.offset <= -1) {
                        this.offset = 0;
                    }
                    _.extend(this.searchCollection.queryParams, { limit: this.limit, offset: this.offset });
                    if (this.offset == (this.pageFrom - 1)) {
                        Utils.notifyInfo({
                            content: Messages.search.onSamePage
                        });
                    } else {
                        if (this.value) {
                            this.value.pageOffset = this.offset;
                            this.triggerUrl();
                        }
                        // this.offset is updated in gotoPagebtn function so use next button calculation.
                        this.fetchCollection(null, { 'next': true });
                    }
                }
1001
            }
1002
        });
1003
    return SearchResultLayoutView;
1004
});