define([
    'app',
    'js/templates-loader',
    'backgrid',
    'moment',
    'js/multiselect/virtual-select.min',
    'js/bootstrap-input-spinner/bootstrap-input-spinner',
],

    function (app, T, Backgrid, moment) {

        var Screen = {
            Models: {}, Views: {}, Collections: {},
        };

        Screen.Models.ModalSelectItem = Backbone.Epoxy.Model.extend({
            defaults: {
                ModalTitle: "",
                PartList: [],
                showPartList: true,

                resetMode: false,
                removeMode: false,
                selectMode: true,
                addMode: false,
                fixMode: false,
                subPartMode: false,
                spareMode: false,

                L2PartId: null,
                L1PartId: null,
                L1PositionId: null,
                L1PartTypeId: null,
                isPartNameEmpty: true,
                isMetricEmpty: true,
                metricTypeId: null,
                newPartialValue: null,

                title: '',
                PartName: '',
                PartTypeName: '',
                ParentPartName: '',
                InstalledOn: '',
                InstalledBy: '',
                ResetOn: '',
                ResetBy: '',
                hasData: false,
                isLoading: false,


                showStatusOk: false,
                showStatusEmpty: false,
                showStatusWarning: false,
                showStatusAlert: false,


                partTypesAccepted: [],
                partTypeAccepted: null,
                renderMultipicker: true,
                currentNodeL2PartId: null,
            },
            initialize: function () {
                this.itemsCollHeader = new Screen.Collections.Items();
                this.itemsCollValues = new Screen.Collections.Items();
                this.itemsCollHistory = new Screen.Collections.Items();

                this.metricsDetailsColl = new Screen.Collections.MetricsDetailsColl();
            },
            getPartIdNumber: function (partId) {
                var part = null;
                if (isNaN(partId) && partId.includes('-')) {
                    part = partId.split('-');
                    part = parseInt(part[0]);
                } else {
                    part = parseInt(partId)
                }
                return part;
            },

            fetchPartDetails: function (params) {
                var that = this,
                    qp = new Core.Database.QueryParameters();
                //var part = null;
                //if (isNaN(params.partId) && params.partId.includes('-')) {
                //    part = params.partId.split('-');
                //    part = parseInt(part[0]);
                //} else {
                //    part = parseInt(params.partId)
                //}
                //qp.Add('@PartId', 'INT', part);

                qp.Add('@PartId', 'INT', that.getPartIdNumber(params.partId));

                Core.Json.CallProcedure(
                    app.DatabaseNames.MES + ".EQP.GetPartDetails",
                    qp,
                    {
                        onSuccess: function (resp) {
                            try {

                                if ((resp) && (resp.Table)) {
                                    if (resp.Table) that.itemsCollHeader.setDataColl(resp.Table);   
                                    if (resp.Table1) that.itemsCollValues.setDataColl(resp.Table1);
                                    if (resp.Table1) that.metricsDetailsColl.setDataColl(resp.Table1);
                                    if (resp.Table2) that.itemsCollHistory.setDataColl(resp.Table2); 
                                    that.trigger('fetch', resp);
                                }
                                else {
                                    if ((resp) && (resp.Message)) {
                                        console.error(new Error(resp.Message).stack);
                                        app.views.topMessages.showMessage('CALL TO DATABASE FAILED', { stay: 5000, });
                                    }
                                    else {
                                        app.views.topMessages.showMessage('SERVER RESPONSE NOT VALID', { stay: 5000, });
                                        console.error(new Error('SERVER_RESPONSE_NOT_VALID').stack);
                                    }
                                }
                            }
                            catch (e) { console.error((e.stack) ? e.stack : new Error(e).stack); }
                        },
                        onFailure: function (resp) {
                            console.error(resp);
                        },
                        Secured: true,
                        Async: true,
                    },
                    app.ConnectionStrings.app
                );
                return this;
            },
            fetchList: function (params) {
                var mode = this.get('mode');
                if (mode === 'SUB-PART') {
                    try {
                        var that = this;
                        qp = new Core.Database.QueryParameters();

                        this.fixedParameters = [
                            { Name: '@PartTypeId', Type: 'INT', Value: that.get('partTypeAccepted'), },
                        ];
                        _.each(this.fixedParameters, function (qpParams) {
                            qp.Add(qpParams.Name, qpParams.Type, qpParams.Value);
                        });
                        Core.Json.CallProcedure(
                            app.DatabaseNames.MES + '.EQP.GetAvailableParts',
                            qp,
                            {
                                onSuccess: function (resp) {
                                    try {
                                        if (resp && !resp.Message) {


                                            that.set({
                                                PartList: resp.Table,
                                            })
                                            that.trigger('available-list-ready');
                                        }
                                        else {
                                            if ((resp) && (resp.Message)) {
                                                app.views.topMessages.showMessage(resp.Message, { stay: 5000, });
                                                console.error(resp.Message);
                                            }
                                            else {
                                                app.views.topMessages.showMessage("Server response not valid.", { stay: 5000, });
                                                console.error("Server response not valid.");
                                            }
                                        }
                                    }
                                    catch (e) { console.error((e.stack) ? e.stack : new Error(e).stack); }
                                },
                                onFailure: function (resp) {
                                    console.error(resp);
                                },
                                Secured: true,
                                Async: true,
                            },
                            app.ConnectionStrings.app
                        );
                    }
                    catch (e) { console.error((e.stack) ? e.stack : new Error(e).stack); }
                }
                else if (mode === 'SELECT') {
                    try {
                        var that = this;
                        qp = new Core.Database.QueryParameters();

                        this.fixedParameters = [
                            { Name: '@PartTypeId', Type: 'INT', Value: params.PartTypeId, },
                        ];
                        
                        _.each(this.fixedParameters, function (qpParams) {
                            qp.Add(qpParams.Name, qpParams.Type, qpParams.Value);
                        });
                        Core.Json.CallProcedure(
                            app.DatabaseNames.MES + '.EQP.GetAvailableParts',
                            qp,
                            {
                                onSuccess: function (resp) {
                                    try {
                                        if (resp && !resp.Message) {


                                            that.set({
                                                PartList: resp.Table,
                                            })
                                            that.trigger('available-list-ready');
                                        }
                                        else {
                                            if ((resp) && (resp.Message)) {
                                                app.views.topMessages.showMessage(resp.Message, { stay: 5000, });
                                                console.error(resp.Message);
                                            }
                                            else {
                                                app.views.topMessages.showMessage("Server response not valid.", { stay: 5000, });
                                                console.error("Server response not valid.");
                                            }
                                        }
                                    }
                                    catch (e) { console.error((e.stack) ? e.stack : new Error(e).stack); }
                                },
                                onFailure: function (resp) {
                                    console.error(resp);
                                },
                                Secured: true,
                                Async: true,
                            },
                            app.ConnectionStrings.app
                        );
                    }
                    catch (e) { console.error((e.stack) ? e.stack : new Error(e).stack); }
                } else if (mode === 'ADD') {

                    try {
                        var that = this;
                        qp = new Core.Database.QueryParameters();

                        this.fixedParameters = [
                            { Name: '@ParentPartTypeId', Type: 'INT', Value: params.ParentPartTypeId, },
                        ];
                        _.each(this.fixedParameters, function (qpParams) {
                            qp.Add(qpParams.Name, qpParams.Type, qpParams.Value);
                        });
                        Core.Json.CallProcedure(
                            app.DatabaseNames.MES + '.EQP.GetPartTypes',
                            qp,
                            {
                                onSuccess: function (resp) {
                                    try {
                                        if (resp && !resp.Message) {


                                            that.set({
                                                PartList: resp.Table,
                                            })
                                            that.trigger('available-list-ready');
                                        }
                                        else {
                                            if ((resp) && (resp.Message)) {
                                                app.views.topMessages.showMessage(resp.Message, { stay: 5000, });
                                                console.error(resp.Message);
                                            }
                                            else {
                                                app.views.topMessages.showMessage("Server response not valid.", { stay: 5000, });
                                                console.error("Server response not valid.");
                                            }
                                        }
                                    }
                                    catch (e) { console.error((e.stack) ? e.stack : new Error(e).stack); }
                                },
                                onFailure: function (resp) {
                                    console.error(resp);
                                },
                                Secured: true,
                                Async: true,
                            },
                            app.ConnectionStrings.app
                        );
                    }
                    catch (e) { console.error((e.stack) ? e.stack : new Error(e).stack); }
                } else {

                    try {
                        var that = this;
                        qp = new Core.Database.QueryParameters();


                        _.each(this.fixedParameters, function (qpParams) {
                            qp.Add(qpParams.Name, qpParams.Type, qpParams.Value);
                        });
                        Core.Json.CallProcedure(
                            app.DatabaseNames.MES + '.EQP.GetMetricTypes',
                            qp,
                            {
                                onSuccess: function (resp) {
                                    try {
                                        if (resp && !resp.Message) {


                                            that.set({
                                                PartList: resp.Table,
                                            })
                                            that.trigger('available-list-ready');
                                        }
                                        else {
                                            if ((resp) && (resp.Message)) {
                                                app.views.topMessages.showMessage(resp.Message, { stay: 5000, });
                                                console.error(resp.Message);
                                            }
                                            else {
                                                app.views.topMessages.showMessage("Server response not valid.", { stay: 5000, });
                                                console.error("Server response not valid.");
                                            }
                                        }
                                    }
                                    catch (e) { console.error((e.stack) ? e.stack : new Error(e).stack); }
                                },
                                onFailure: function (resp) {
                                    console.error(resp);
                                },
                                Secured: true,
                                Async: true,
                            },
                            app.ConnectionStrings.app
                        );
                    }
                    catch (e) { console.error((e.stack) ? e.stack : new Error(e).stack); }
                }
            },
        });

        Screen.Views.ModalSelectItem = Backbone.Epoxy.View.extend({
            template: "modal-select-equipment-list",
            id: "modal-select-equipment-list",
            className: "modal modal-select-equipment-list hide fade",
            //default not cacheable, change this if you want the view to be cacheable
            // if the view is set as cacheable should also have a refresh method to reset the view without erasing the DOM.
            bindings: "data-bind",
            isCacheable: true,
            
            metricsTableView: null,
            events: function () {
                return {
                    "click #acceptBtn": this.acceptBtn_click,
                    "click #cancelBtn": this.cancelBtn_click,
                    "click #dismissBtn": this.cancelBtn_click,
                    "submit form": this.form_submit,
                    "show.bs.modal": this.modal_show,
                    "shown.bs.modal": this.modal_shown,
                    "hidden.bs.modal": this.modal_hidden,
                    "change #newPartName": this.newPartName_changed,
                    "change #metric": this.metric_changed
                };
            },

            container: null,
            content: null,
            disposed: false,
            isRendered: false,
            parent: null,
            preventDispose: false,
            visible: false,          
            bus: null,
            isManual: false,

            initialize: function (options) {
                _.extend(this, options);

                if (!this.model)
                    this.model = new Screen.Models.ModalSelectItem();

                var data = [];
                if (options.data) 
                    data = options.data;

                // --------------------
                // IAccept values
                if (data.IAccept) { 
                    var partTypesAccepted = [];
                    var partTypesAcceptedNames = data.IAcceptPartNames.split(',');
                    _.each(data.IAccept.split(','), function (obj, i) {
                        partTypesAccepted.push({
                            label: partTypesAcceptedNames[i], value: parseInt(obj) 
                        })
                    });
                }
                // IAccept values
                // --------------------


                this.model.set({
                    hasData: false,
                    isLoading: true,
                    mode: options.mode,
                })
               
                if (options.mode === 'SELECT' || options.mode === 'ADD' || options.mode === 'ADD-SPARE' || options.mode === 'FIX' || options.mode === 'SUB-PART') { 
                    this.model.set({
                        ModalTitle: data.L1PartTypeName + ' - ' + data.L2PartName,
                        L1PartId: data.L1PartId,
                        L1PositionId: data.L1PositionId,
                        showPartList: true,
                        resetMode: false,
                        removeMode: false,
                        L1PartTypeId: data.L1PartTypeId,
                        selectMode: options.mode === 'SELECT' ? true : false,
                        addMode: options.mode === 'ADD' || options.mode === 'ADD-SPARE' ? true : false,
                        fixMode: options.mode === 'FIX' ? true : false,
                        subPartMode: options.mode === 'SUB-PART' ? true : false,
                        spareMode: options.mode === 'ADD-SPARE' ? true : false,
                        L2PartId: data.L2PartId,
                        partTypesAccepted: partTypesAccepted,
                        partTypeAccepted: partTypesAccepted && partTypesAccepted[0] && partTypesAccepted[0].value ? partTypesAccepted[0].value : null,
                        currentNodeL2PartId: options.mode === 'SUB-PART'? data.L2PartId : null,

                    });
                    this.model.fetchList({
                        //mode:options.mode,
                        PartTypeId: data.L1PartTypeId,
                        ParentPartTypeId: data.L1PartTypeId,
                    });
                   
                } else {
                  
                    this.model.fetchPartDetails({
                        partId: data.L2PartId,
                    })
                    this.model.set({
                        ModalTitle: options.mode === 'RESET' ? 'Reset Equipment confirmation' : 'Remove Equipment confirmation',
                        resetMode: options.mode === 'RESET' ? true : false,
                        removeMode: options.mode === 'REMOVE' ? true : false,
                        subPartMode: options.mode === 'SUB-PART' ? true : false,
                        selectMode: false,
                        addMode: false,
                        showPartList: false,
                        fixMode: false,
                        spareMode:false,
                    });
                    if (data && data.StatusCode) {
                        this.model.set({
                            showStatusOk: data.StatusCode === 'O' ? true : false,
                            showStatusEmpty: data.StatusCode === 'B' ? true : false,
                            showStatusWarning: data.StatusCode === 'W' ? true : false,
                            showStatusAlert: data.StatusCode === 'A' ? true : false,
                        })
                    }
                }

                this.bus = options.bus;

                this.bindingSources = {
                    metricsTableColl: this.model.metricsDetailsColl,
                };
                this.bindEvents();


                return this;
            },

            newPartName_changed: function () {
                this.model.set({
                    isPartNameEmpty: document.getElementById('newPartName').value === null || document.getElementById('newPartName').value === '' ? true : false,
                })
            },
            metric_changed: function () {
                this.model.set({
                    isMetricEmpty: document.getElementById('metric').value === null || document.getElementById('metric').value === '' ? true : false,
                })
            },

            bindEvents: function () {
                this.listenToOnce(this, "render", this.view_render);
                this.listenTo(this.model, 'fetch', this.details_ready);
                this.listenTo(this.model, 'available-list-ready', this.availableList_ready);
                _.bindAll(this, 'on_keypress'),
                    $(document).bind('keydown', this.on_keypress);

                this.listenTo(this.model.metricsDetailsColl, 'fetch', this.metricsDetailsColl_fetched);
                this.listenTo(this.model, 'change:partTypeAccepted', this.partTypeAccepted_changed);
            },
            partTypeAccepted_changed: function () {
                if (this.model.get('mode') === 'SUB-PART')
                    this.model.fetchList();
            },
            metricsDetailsColl_fetched: function () {
                try {
                    var that = this;
                    if (that.model.metricsDetailsColl.length > 0)
                        this.spanMetricsTableRows();

                }
                catch (e) { console.error((e.stack) ? e.stack : new Error(e).stack); }
            },

            spanMetricsTableRows: function () {
                var that = this,
                    coll = that.model.metricsDetailsColl.toJSON(),
                    count = 1,
                    prev = null,
                    curr = null;


                var element = {},
                    cart = [],
                    rowDelete = null,
                    firstrowSpan = null;


                var classes = [
                    'spanrow1',
                    'spanrow2',
                    'spanrow3',
                    'spanrow4',
                ]


                _.each(coll, function (obj, i) {
                    element = {};
                    curr = obj.metricType;

                    if (curr != prev) {
                        if (count > 1) {
                            element.metricType = prev;
                            element.rowSpan = count;
                            element.startPos = i - count;
                            cart.push(element);
                        };
                        count = 1;
                    } else {
                        count += 1;
                    }

                    prev = curr;
                    if (coll.length - 1 == i) {

                        if (count > 1) {
                            element.metricType = prev;
                            element.rowSpan = count;
                            element.startPos = i + 1 - count;
                            cart.push(element);
                        }
                    }
                });

                _.each(cart, function (obj) {
                    _.each(classes, function (obj2) {
                        firstrowSpan = document.getElementsByClassName(obj2)[obj.startPos];
                        firstrowSpan.rowSpan = obj.rowSpan;

                    })
                });


                _.each(cart, function (obj) {
                    _.each(classes, function (obj2) {
                        for (var i = obj.startPos + 1; i < obj.startPos + obj.rowSpan; i++) {
                            rowDelete = document.getElementsByClassName(obj2)[i];
                            rowDelete.style.display = 'none';
                        }

                    })
                });

            },
            availableList_ready: function () {
                var that = this;
                setTimeout(
                    function () {
                        if (that.model.get('renderMultipicker')) {
                            that.renderSearchDropDown();
                            that.renderSearchDropDown2();
                            that.model.set({ renderMultipicker: false });
                        }
                        document.querySelector('#equipmentList').setOptions(that.model.get('PartList'));
                        that.model.set({
                            isLoading: false,
                        })
                    },
                    500
                );
                
            },
            
            render: function (container) {
                if (container)
                    this.container = container;

                //the screens have a custompath, so it has to be specified in the customPath variable that is
                //then sent to the template loader.
                var that = this,
                    customPath = "/app/templates/modal-select-equipment-list/";

                var attrs = this.model.toJSON();

                T.render.call(this, this.template, function (tmp) {
                    if (!that.i18n) that.i18n = {};
                    app.getI18NJed(that, that.template, function (i18nJED) {
                        //storing internationalization data
                        that.i18n[that.template] = i18nJED;
                        //loading the view and appeding it to the views's $el.
                        that.$el.html(tmp(that.model.toJSON()));


                        that.metricsTableView = Screen.Views.MetricsTable.extend({
                            template: Handlebars.compile(that.$el.find('#metricsTableViewTemplate').html()),
                        });

                        that.applyBindings();

                        that.isRendered = true;

                        var grid = new Backgrid.Grid({
                            className: 'backgrid table table-hover table-condensed production-table',
                            columns: [
                                {
                                    name: 'MetricTypeName',
                                    label: app.translate([that, app], 'Metric'),
                                    cell: Backgrid.StringCell.extend({
                                        className: 'string-cell align-center-cell',
                                    }),
                                    editable: false,
                                },
                                {
                                    name: 'PartialValue',
                                    label: app.translate([that, app], 'Partial'),
                                    cell: Backgrid.StringCell.extend({
                                        className: function () {
                                            var model = this.model.toJSON();
                                            if (model.PartialValueStatus === 'O') return 'number-cell align-center-cell'; //'number-cell align-center-cell metric-status-ok';
                                            if (model.PartialValueStatus === 'A') return 'number-cell align-center-cell metric-status-alert';
                                            if (model.PartialValueStatus === 'W') return 'number-cell align-center-cell metric-status-warning';
                                            else return 'number-cell align-center-cell';
                                        },
                                        decimals: 2,
                                    }),
                                    editable: false,
                                },
                                {
                                    name: 'TotalValue',
                                    label: app.translate([that, app], 'Total'),
                                    cell: Backgrid.StringCell.extend({
                                        className: function () {
                                            var model = this.model.toJSON();
                                            if (model.TotalValueStatus === 'O') return 'number-cell align-center-cell'; //'number-cell align-center-cell metric-status-ok';
                                            if (model.TotalValueStatus === 'A') return 'number-cell align-center-cell metric-status-alert';
                                            if (model.TotalValueStatus === 'W') return 'number-cell align-center-cell metric-status-warning';
                                            else return 'number-cell align-center-cell';
                                        },
                                        decimals: 2,
                                    }),
                                    editable: false,
                                },
                            ],
                            collection: that.model.itemsCollValues,


                        });

                        //container.append(grid.render().el);
                        that.$el.find('.metrics-grid-container').append(grid.render().el);


                        var grid2 = new Backgrid.Grid({
                            className: 'backgrid table table-hover table-condensed production-table',
                            columns: [
                                {
                                    name: 'Timestamp',
                                    label: app.translate([that, app], 'Datetime'),
                                    cell: Backgrid.StringCell.extend({
                                        className: 'string-cell align-center-cell',
                                    }),
                                    editable: false,
                                },
                                {
                                    name: 'Action',
                                    label: app.translate([that, app], 'Action'),
                                    cell: Backgrid.StringCell.extend({
                                        className: 'string-cell align-center-cell',
                                    }),
                                    editable: false,
                                },
                                {
                                    name: 'Parent',
                                    label: app.translate([that, app], 'Parent'),
                                    cell: Backgrid.StringCell.extend({
                                        className: 'string-cell align-center-cell',
                                    }),
                                    editable: false,
                                },
                                {
                                    name: 'Position',
                                    label: app.translate([that, app], 'Tons'),
                                    cell: Backgrid.StringCell.extend({
                                        className: 'string-cell align-center-cell',
                                    }),
                                    editable: false,
                                },
                                {
                                    name: 'User',
                                    label: app.translate([that, app], 'User'),
                                    cell: Backgrid.StringCell.extend({
                                        className: 'string-cell align-center-cell',
                                    }),
                                    editable: false,
                                },
                                {
                                    name: 'Branch',
                                    label: app.translate([that, app], 'Branch'),
                                    cell: Backgrid.StringCell.extend({
                                        className: 'string-cell align-center-cell',
                                    }),
                                    editable: false,
                                },
                            ],
                            collection: that.model.itemsCollHistory,


                        });

                        that.$el.find('.metrics-history-grid-container').append(grid2.render().el);


                        var grid3 = new Backgrid.Grid({
                            className: 'backgrid table table-hover table-condensed production-table',
                            columns: [
                                {
                                    name: 'ParentPartName',
                                    label: app.translate([that, app], 'Parent'),
                                    cell: Backgrid.StringCell.extend({
                                        className: 'string-cell align-center-cell',
                                    }),
                                    editable: false,
                                },
                                {
                                    name: 'InstalledOn',
                                    label: app.translate([that, app], 'Installed On'),
                                    cell: Backgrid.StringCell.extend({
                                        className: 'string-cell align-center-cell',
                                    }),
                                    editable: false,
                                },
                                {
                                    name: 'InstalledBy',
                                    label: app.translate([that, app], 'Installed By'),
                                    cell: Backgrid.StringCell.extend({
                                        className: 'string-cell align-center-cell',
                                    }),
                                    editable: false,
                                },
                                {
                                    name: 'ResetOn',
                                    label: app.translate([that, app], 'Reset On'),
                                    cell: Backgrid.StringCell.extend({
                                        className: 'string-cell align-center-cell',
                                    }),
                                    editable: false,
                                },
                                {
                                    name: 'ResetBy',
                                    label: app.translate([that, app], 'Reset By'),
                                    cell: Backgrid.StringCell.extend({
                                        className: 'string-cell align-center-cell',
                                    }),
                                    editable: false,
                                },

                            ],
                            collection: that.model.itemsCollHeader,


                        });

                        //container.append(grid.render().el);
                        that.$el.find('.main-info-grid-container').append(grid3.render().el);

                        that.trigger("render");


                    }, true, customPath);

                }, customPath, "modal_select_equipment_list");
            },


            setData: function (attrs) {
                this.model.set(attrs);
            },
           
            show: function () {
                if (!this.isRendered) {
                    this.render();
                }
                else {
                    if (this.model.get('manual') == false) {
                        this.$el.modal({
                            keyboard: false,
                            backdrop: 'static',
                        });

                    }
                    else {
                        this.$el.modal({
                            keyboard: true,
                            backdrop: 'both',
                        });
                    }
                }

                return this;
            },
            acceptBtn_click: function (e) {
                try {
                    var attrs = this.model.toJSON();
                    if (attrs.mode === 'ADD-SPARE') {
                        var params = ({
                            partTypeId: parseInt(attrs.partTypeAccepted),
                            partName: document.getElementById('newPartName').value,
                            parentPartId: attrs.L2PartId,
                        })
                    }else
                    if (attrs.L2PartId && attrs.L1PartId && attrs.L1PositionId && attrs.selectMode === true) {
                        var params = ({
                            partId: this.model.getPartIdNumber(attrs.L2PartId),
                            parentPartId: attrs.L1PartId,
                            positionId: attrs.L1PositionId,
                        })

                    } else if (attrs.addMode) {
                        var params = ({
                            partName: document.getElementById('newPartName').value,
                            partTypeId: attrs.partTypeId,
                            parentPartId: attrs.L2PartId,
                        })
                    }
                    else if (attrs.fixMode) {
                        var params = ({
                            partId: attrs.L2PartId,
                            newPartialValue: document.getElementById('metric').value,
                            metricTypeId: attrs.metricTypeId,
                        })
                    } else if (attrs.subPartMode === true){
                        var params = ({
                            partId: this.model.getPartIdNumber(attrs.L2PartId),
                            parentPartId: attrs.currentNodeL2PartId,
                        })

                    }
                    else if (attrs.removeMode !== true && attrs.resetMode !== true) {
                        app.views.topMessages.showMessage('Part not selected', { stay: 5000, });
                        this.close();
                        return;

                    } 
                    this.trigger('accept', params);
                    this.close();
                }
                catch (e) { console.error((e.stack) ? e.stack : new Error(e).stack); }
            },


            on_keypress: function (e) {          
                try {
                    if (e.which === 27) {
                        this.close();
                    }

                }
                catch (e) { console.error((e.stack) ? e.stack : new Error(e).stack); }
            },
            cancelBtn_click: function () {
               // this.bus.trigger("cancelBtn", this.model.toJSON());

                this.close()
            },
            close: function () {
                if (this.disposed == false) {
                    if (this.visible == true) {
                        this.hide();
                    }
                    else {
                        this.trigger('close');
                        this.remove();
                        this.unbind();

                        this.disposed = true;
                    }
                }
                if (this.bus) {
                    this.bus.trigger("modalClose");
                }
            },
            hide: function (preventDispose) {
                this.preventDispose = (preventDispose);
                this.$el.modal('hide');
            },
            
            form_submit: function (e) {
                try {
                    e.preventDefault();
                }
                catch (e) { console.error((e.stack) ? e.stack : new Error(e).stack); }
            },

            modal_hidden: function (e) {
                try {
                    this.visible = false;
                    if (!this.preventDispose)
                        this.close();
                    else
                        this.preventDispose = false;
                }
                catch (e) { console.error((e.stack) ? e.stack : new Error(e).stack); }
            },
            modal_show: function (e) {
                try {
                    this.visible = true;
                }
                catch (e) { console.error((e.stack) ? e.stack : new Error(e).stack); }
            },


            renderSearchDropDown2: function () {
                var that = this;
                var mode = this.model.get('mode');
                if (mode === 'ADD-SPARE') return;
                var vsm = new VirtualSelect.init({
                    ele: '#equipmentList2',
                    options: that.model.get('partTypesAccepted'),
                    multiple: false,
                    search: true,
                    placeholder: mode === 'SELECT' ? 'Select equipment here' : 'Select Part',
                    showSelectedOptionsFirst: true,
                    hideClearButton: true,                   
                    silentInitialValueSet: true,
                });
                document.querySelector('#equipmentList2').setValue(that.model.get('partTypeAccepted'));
                if (document.querySelector('#equipmentList2'))
                    document.querySelector('#equipmentList2').addEventListener('change', function () {
                        that.model.set({
                            hasData: false,
                        });
                        document.querySelector('#equipmentList').setValue(null);
                        var value = this.value;
                        that.model.set({ partTypeAccepted: value });
                    });

            },
            renderSearchDropDown: function () {
                var that = this;
                var mode = this.model.get('mode');
                var vsm = new VirtualSelect.init({
                    ele: '#equipmentList',
                    options: that.model.get('PartList'),
                    multiple: false,
                    search: true,
                    placeholder: mode === 'SELECT' ? 'Select equipment here' : 'Select Part',
                    showSelectedOptionsFirst: true,
                    hideClearButton: true,
                    labelRenderer: function (data) {
                        var value = data.value.split('-');

                        if (value[1] == 'O') {
                            prefix = `<i class="status-ok" style="margin-right: 10px"></i>`;
                        } else if (value[1] == 'W') {

                            prefix = `<i class="status-warning" style="margin-right: 10px"></i>`;
                        } else if (value[1] == 'A') {

                            prefix = `<i class="status-alert" style="margin-right: 10px"></i>`;
                        } else {
                            prefix = `<i style="margin-right: 10px"></i>`;
                        }
                        return `${prefix}${data.label}`;
                    },
                });
                if (document.querySelector('#equipmentList'))
                    document.querySelector('#equipmentList').addEventListener('change', function () {
                       
                        var partId = this.value;
                        var part = partId.split('-');
                        if (part[0] !== '' && partId && partId !== '') {
                            if (part.length > 1) {
                                if (part[1]) {
                                    that.model.set({
                                        showStatusOk: part[1] === 'O' ? true : false,
                                        showStatusEmpty: part[1] === 'B' ? true : false,
                                        showStatusWarning: part[1] === 'W' ? true : false,
                                        showStatusAlert: part[1] === 'A' ? true : false,
                                    });
                                }
                                that.model.set({
                                    isLoading: true,
                                    hasData: false,
                                    L2PartId: partId,
                                });

                                that.model.fetchPartDetails({
                                    partId: partId,
                                })
                            } else {

                                var metricTypeId = this.value;
                                var partTypeId = this.value;
                                that.model.set({
                                    isLoading: false,
                                    hasData: true,
                                    metricTypeId: metricTypeId,
                                    partTypeId: partTypeId,
                                });
                            }
                        } else {
                            that.model.set({
                                showStatusOk:       false,
                                showStatusEmpty:    false,
                                showStatusWarning:  false,
                                showStatusAlert:    false,
                            });
                        }
                    

                      
                   
                    });

            },
            details_ready: function (resp) {
                var { Table } = resp;

                if (Table[0])
                    this.model.set({
                        title: Table[0].PartTypeName + ' - ' + Table[0].PartName,
                        PartName: Table[0].PartName,
                        PartTypeName: Table[0].PartTypeName,
                        ParentPartName: Table[0].ParentPartName,
                        InstalledOn: Table[0].InstalledOn,
                        InstalledBy: Table[0].InstalledBy,
                        ResetOn: Table[0].ResetOn,
                        ResetBy: Table[0].ResetBy,
                        hasData: true,
                        isLoading: false,
                    });
                else
                    this.model.set({
                        hasData: false,
                        isLoading: false,
                    })
                
            },
            modal_shown: function (e) {
                try {
                    this.$el.find(".autofocus").focus();
                }
                catch (e) { console.error((e.stack) ? e.stack : new Error(e).stack); }
            },
     
            view_render: function () {
                try {
                    this.show();
                  

                }
                catch (e) { console.error((e.stack) ? e.stack : new Error(e).stack); }
            },
            preRender: function () {
                app.models.subnavbar.set("dateControl", false);
            },
            reRender: function () {
            },
        });


        Screen.Collections.Items = Backbone.Collection.extend({
            setDataColl: function (data) {
                var newColl,
                    that = this;
                newColl = data;
                that.set(newColl).trigger('fetch', that, data);
            },

        });


        Screen.Collections.MetricsDetailsColl = Backbone.Collection.extend({
            setDataColl: function (details) {
                var newColl,
                    that = this;
                newColl = [];

                _.each(details, function (det) {
                    // Max Limit
                    newColl.push({
                        metricType: det.MetricTypeName === 'Heats' ? 'H' : (det.MetricTypeName === 'Tons' ? 'T' : (det.MetricTypeName === 'Contact' ? 'C' : 'L')),
                        metric: det.MetricTypeName,

                        campaignStatusAlert: det.CampaignValueStatus === 'A' ? true : false,
                        campaignStatusWarning: det.CampaignValueStatus === 'W' ? true : false,
                        partialStatusAlert: det.PartialValueStatus === 'A' ? true : false,
                        partialStatusWarning: det.PartialValueStatus === 'W' ? true : false,
                        totalStatusAlert: det.TotalValueStatus === 'A' ? true : false,
                        totalStatusWarning: det.TotalValueStatus === 'W' ? true : false,


                        campaignCurrent: det.CampaignValue ? det.CampaignValue : '',
                        partialCurrent: det.PartialValue ? det.PartialValue : '',
                        totalCurrent: det.TotalValue ? det.TotalValue : '',


                        campaignLimit: det.CampaignAlertLimit ? det.CampaignAlertLimit : '',
                        totalLimit: det.TotalAlertLimit ? det.TotalAlertLimit : '',
                        partialLimit: det.PartialAlertLimit ? det.PartialAlertLimit : '',

                        limitMax: true,
                        limitMin: false,

                    });


                    // Min Limit
                    newColl.push({

                        metricType: det.MetricTypeName === 'Heats' ? 'H' : (det.MetricTypeName === 'Tons' ? 'T' : (det.MetricTypeName === 'Contact' ? 'C' : 'L')),
                        metric: det.MetricTypeName,

                        campaignStatusAlert: det.CampaignValueStatus === 'A' ? true : false,
                        campaignStatusWarning: det.CampaignValueStatus === 'W' ? true : false,
                        partialStatusAlert: det.PartialValueStatus === 'A' ? true : false,
                        partialStatusWarning: det.PartialValueStatus === 'W' ? true : false,
                        totalStatusAlert: det.TotalValueStatus === 'A' ? true : false,
                        totalStatusWarning: det.TotalValueStatus === 'W' ? true : false,


                        campaignCurrent: det.CampaignValue ? det.CampaignValue : '',
                        partialCurrent: det.PartialValue ? det.PartialValue : '',
                        totalCurrent: det.TotalValue ? det.TotalValue : '',


                        campaignLimit: det.CampaignWarningLimit ? det.CampaignWarningLimit : '',
                        totalLimit: det.TotalWarningLimit ? det.TotalWarningLimit : '',
                        partialLimit: det.PartialWarningLimit ? det.PartialWarningLimit : '',

                        limitMax: false,
                        limitMin: true,

                    });
                });

                that.set(newColl).trigger('fetch', that);
            },
        });

        Screen.Views.MetricsTable = Backbone.Epoxy.View.extend({
            tagName: 'tr',
            template: null,
            initialize: function () {
                this.render();
            },
            render: function () {
                this.$el.html(this.template(this.model.toJSON()));
                return this;
            },
        });

        // Required, return the module for AMD compliance.
        return Screen;

    });