//SCREEN-BOILERPLATE
//this boilerplate builds screens that are gonna be shown in the <div class='content'> tag of our main HTML.
//do not build app components with this boilerplate, only screens (reports)

define([
    // Application variable, always include it to have access to app methods.
    'app',

    //templates-loader: this loads templates async.
    'js/templates-loader',
    'backgrid',
    'moment',

    'modules/modal2',
    'modules/modal-sulpher-print/modal-sulpher-print',
    'backgrid/infinator',
    'backgrid/moment-cell',
    'backgrid/grouped-columns',

    "js/jquery.floatThead/jquery.floatThead",
    'js/jquery.contextMenu/jquery.contextMenu'
],
    function (app, T, Backgrid, moment, Modal, SulpherPrintModal) {

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

        Screen.Models.Main = Backbone.Epoxy.Model.extend({
            defaults: {
                start: new moment().subtract(2, 'days').format('YYYY-MM-DD'),
                end: new moment().format('YYYY-MM-DD'),

                printerCode: null,
                printers: [{ label: 'All', value: null }, { label: '1', value: 1 }, { label: '2', value: 2 }],

                crewId: null,
                crews: [{ label: 'A', value: 'A' }, { label: 'B', value: 'B' }, { label: 'C', value: 'C' }, { label: 'D', value: 'D' }],

                shiftId: null,
                shifts: [{ label: 'D', value: 1 }, { label: 'N', value: 2 }],


                strandId: null,
                //strands: [{ label: '1', value: 1 }, { label: '2', value: 2 }, { label: '3', value: 3 }, { label: '4', value: 4 }],

                hasData: false,
                isLoading: false,
                grid: [],
                searchText: '',
            },
            computeds: {
                start$: {
                    deps: ['start'],
                    get: function (value) {
                        return value;
                    },
                    set: function (value) {
                        return { start: (value) ? new moment(value, app.translate(app, 'MM/DD/YYYY')).format('YYYY-MM-DD') : value, };
                    },
                },
                end$: {
                    deps: ['end'],
                    get: function (value) {
                        return value;
                    },
                    set: function (value) {
                        return { end: (value) ? new moment(value, app.translate(app, 'MM/DD/YYYY')).format('YYYY-MM-DD') : value, };
                    },
                },
            },
            
           
        });


        Screen.Views.Main = Backbone.Epoxy.View.extend({
            template: 'caster-tag-report',
            id: 'caster-tag-report',
            title: 'Caster Tag Report',
            events: function () {
                return {
                    'click #refreshBtn': this.refreshBtn_click,
                    "click .btn-export-to-excel": this.exportToExcel
                };
            },
            bindings: 'data-bind',
            bindingSources: null,
            grids: null,
            itemsColl: null,
            subviews: null,
            viewParams: null,

            initialize: function () {
                this.options.state = app.view_states.loading;
                this.options.onappend = (_.isFunction(this.options.onappend)) ? this.options.onappend : function () { };

                var that = this;

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

                this.grids = {};

                this.itemsColl = new Screen.Collections.Items();

                this.bindingSources = {};

                this.subviews = {};
                this.autoRefresh = {
                    enabled: null
                    , toid: null
                    , every: 5 * 1000
                };


                this.bindEvents();
                this.bus = _.extend({}, Backbone.Events);
                this.bus.on("modalAcceptBtn", this.onModalAcceptBtn, this);
            },
            onModalAcceptBtn: function () {
                this.refreshBtn_click();
            },
            bindEvents: function () {
                this.listenTo(this.itemsColl, 'backgrid:rowclick', this.processes_backgrid_rowclick)
                    .listenTo(this.itemsColl, 'fetch', this.processes_ready)
                    .listenTo(this.model, 'triggerFetch', this.refreshBtn_click);


            },
            removeHighlightRow: function () {
                var previousIndex = this.model.get('index');
                var rowsView = this.model.get('grid').body.rows;


                if (rowsView && rowsView[previousIndex] && rowsView[previousIndex].$el)
                    rowsView[previousIndex].$el.removeClass("onRightClickSelectedRow");


            },
            _refresh: function (opt) {
                this.itemsColl.reset();

                this.model.set({
                    hasData: false,
                    isLoading: true,
                });

                if (this.autoRefresh.toid != null) {
                    clearTimeout(this.autoRefresh.toid);
                    this.autoRefresh.toid = null;
                }

                this.refreshProcesses(opt);

                if (this.autoRefresh.enabled == true) {
                    var that = this;

                    this.autoRefresh.toid = setTimeout(
                        function () { that._refresh(); },
                        this.autoRefresh.every
                    );
                }
            },
            refresh: function (viewParams) {

                var fixedParams = _.extend({}, Screen.Models.Main.prototype.defaults, viewParams);

                if (viewParams.start)
                    fixedParams.start = new moment(fixedParams.start, 'YYYYMMDD').format('YYYY-MM-DD');
                if (viewParams.end)
                    fixedParams.end = new moment(fixedParams.end, 'YYYYMMDD').format('YYYY-MM-DD');
                if (viewParams.printerCode)
                    fixedParams.printerCode = (viewParams.printerCode != '-' && viewParams.printerCode != null) ? parseInt(viewParams.printerCode, 10) : null;
                if (viewParams.crewId)
                    fixedParams.crewId = (viewParams.crewId != '-' && viewParams.crewId != null) ? viewParams.crewId : null;
                if (viewParams.shiftId)
                    fixedParams.shiftId = (viewParams.shiftId != '-' && viewParams.shiftId != null) ? parseInt(viewParams.shiftId, 10) : null;
                if (viewParams.strandId)
                    fixedParams.strandId = (viewParams.strandId != '-' && viewParams.strandId != null) ? parseInt(viewParams.strandId, 10) : null;

                this.model.set(fixedParams);

                this._refresh({
                    reset: true,
                    params: _.extend(
                        {},
                        fixedParams,
                        {}
                    ),
                });
            },
            render: function (container, viewParams) {
                var that = this;

                this.viewParams = viewParams;

                var thatContainer = (this.options.container) ? this.options.container : container;
                this.options.container = thatContainer;

                //the screens have a custompath, so it has to be specified in the customPath variable that is
                //then sent to the template loader.
                var customPath = '/app/custom-screens/' + this.template + '/';

                T.render.call(
                    this,
                    this.template,
                    function (tmp) {
                        if (!that.options.i18n) that.options.i18n = {};

                        app.getI18NJed(
                            that,
                            that.template,
                            function (i18nJED) {
                                //storing internationalization data
                                that.options.i18n[that.template] = i18nJED;

                                //loading the view and appeding it to the views's $el.
                                that.$el.html(tmp());

                                that.applyBindings();

                                //start: the view was already loaded an is on a div element, but not appended to the main container
                                //here you can perform anything you want DOM related, by getting the dom element via that.$el.find('#id')
                                //or this.$('#id')

                                that.$el.find('.input-date').datepicker();
                                var grid = that.grids.production = new Backgrid.Grid({
                                    className: 'backgrid table table-hover table-condensed production-table',
                                    row: Backgrid.Row.extend({
                                        events: function () {
                                            return {
                                                'click': this.click,
                                            };
                                        },
                                        click: function (e) {
                                            try {
                                                this.model.trigger('backgrid:rowclick', this.model);
                                            }
                                            catch (Error) { console.error(Error.stack); }
                                        }
                                    }),
                                    columns: [
                                        {
                                            name: 'TaggingCommandTypeCode',
                                            label: app.translate([that, app], 'Command Type'),
                                            cell: Backgrid.StringCell.extend({
                                                className: 'string-cell align-center-cell heat-row',
                                            }),
                                            editable: false,
                                        },
                                        {
                                            name: 'HeatNumber',
                                            label: app.translate([that, app], 'Heat Number'),
                                            cell: Backgrid.StringCell.extend({
                                                className: 'string-cell align-center-cell',
                                            }),
                                            editable: false,
                                        },
                                        {
                                            name: 'StrandNumber',
                                            label: app.translate([that, app], 'Strand'),
                                            cell: Backgrid.StringCell.extend({
                                                className: 'string-cell align-center-cell',
                                            }),
                                            editable: false,
                                        },
                                        {
                                            name: 'ProductNumber',
                                            label: app.translate([that, app], 'Product'),
                                            cell: Backgrid.StringCell.extend({
                                                className: 'string-cell align-center-cell',
                                            }),
                                            editable: false,
                                        },
                                        {
                                            name: 'HeatGrade',
                                            label: app.translate([that, app], 'Grade'),
                                            cell: Backgrid.StringCell.extend({
                                                className: 'string-cell align-center-cell',
                                            }),
                                            editable: false,
                                        },
                                        {
                                            name: 'Length',
                                            label: app.translate([that, app], 'Length'),
                                            cell: Backgrid.StringCell.extend({
                                                className: 'string-cell align-center-cell',
                                            }),
                                            editable: false,
                                        },
                                        {
                                            name: 'Weight',
                                            label: app.translate([that, app], 'Weight'),
                                            cell: Backgrid.StringCell.extend({
                                                className: 'string-cell align-center-cell',
                                            }),
                                            editable: false,
                                        },
                                        {
                                            name: 'MoldType',
                                            label: app.translate([that, app], 'Mold Type'),
                                            cell: Backgrid.StringCell.extend({
                                                className: 'string-cell align-center-cell',
                                            }),
                                            editable: false,
                                        },
                                        {
                                            name: 'TaggingCommandStatusCode',
                                            label: app.translate([that, app], 'Command Status'),
                                            cell: Backgrid.StringCell.extend({
                                                className: 'string-cell align-center-cell',
                                            }),
                                            editable: false,
                                        },
                                        {
                                            name: 'Printer',
                                            label: app.translate([that, app], 'Printer'),
                                            cell: Backgrid.StringCell.extend({
                                                className: 'string-cell align-center-cell',
                                            }),
                                            editable: false,
                                        },
                                        {
                                            name: 'Timestamp',
                                            label: 'Timestamp',
                                            editable: false,
                                            cell: Backgrid.Extension.MomentCell.extend({
                                                className: 'momment-cell align-center-cell timestamp',
                                                modelFormat: 'YYYY-MM-DD HH:mm:ss',
                                                displayFormat: 'MM/DD/YYYY HH:mm:ss',
                                                initialize: function (options) {
                                                    this.momentValue = new moment(options.model.get('Timestamp')).format('YYYY-MM-DD HH:mm:ss') || null;
                                                    Backgrid.Extension.MomentCell.prototype.initialize.apply(this, arguments);
                                                },
                                                render: function () {
                                                    // Use this.momentValue to display the Moment value in your custom rendering logic
                                                    // You can format and display it as needed.
                                                    this.$el.html(this.formatter.fromRaw(this.momentValue, this.model));
                                                    this.delegateEvents();
                                                    return this;
                                                }
                                            }),
                                        },
                                        {
                                            name: 'User',
                                            label: app.translate([that, app], 'User'),
                                            cell: Backgrid.StringCell.extend({
                                                className: 'string-cell align-center-cell',
                                            }),
                                            editable: false,
                                        },
                                        {
                                            name: 'Comments',
                                            label: app.translate([that, app], 'Comments'),
                                            cell: Backgrid.StringCell.extend({
                                                className: 'string-cell align-center-cell',
                                            }),
                                            editable: false,
                                        },
                                        {
                                            name: 'Employee',
                                            label: app.translate([that, app], 'Employee'),
                                            cell: Backgrid.StringCell.extend({
                                                className: 'string-cell align-center-cell',
                                            }),
                                            editable: false,
                                        },
                                        {
                                            name: 'Reason',
                                            label: app.translate([that, app], 'Reason'),
                                            cell: Backgrid.StringCell.extend({
                                                className: 'string-cell align-center-cell',
                                            }),
                                            editable: false,
                                        },
                                        //{
                                        //    name: 'CrewId',
                                        //    label: app.translate([that, app], 'Crew'),
                                        //    cell: Backgrid.StringCell.extend({
                                        //        className: 'string-cell align-center-cell',
                                        //    }),
                                        //    editable: false,
                                        //},
                                        //{
                                        //    name: 'Shift',
                                        //    label: app.translate([that, app], 'Shift'),
                                        //    cell: Backgrid.StringCell.extend({
                                        //        className: 'string-cell align-center-cell',
                                        //    }),
                                        //    editable: false,
                                        //},

                                    ],
                                    collection: that.itemsColl,
                                    row: Backgrid.Row.extend({
                                        initialize: function (options) {
                                            Backgrid.Row.prototype.initialize.apply(this, arguments);
                                        },
                                        events: {
                                            //contextmenu: 'onRightClick',
                                        },
                                        onRightClick: function (e) {
                                            e.preventDefault();
                                            var model = this.model.toJSON();
                                            var write = that.getPermissions();
                                            if (write) {
                                                var rowsView = that.model.get('grid').body.rows;
                                                var newIndex = _.indexOf(rowsView, this);
                                                this.$el.addClass("onRightClickSelectedRow");

                                                that.model.set({
                                                    rowModel: model,
                                                    index: newIndex,
                                                });
                                            }
                                        },

                                    }),
                                    footer: Backgrid.Extension.Infinator.extend({
                                        scrollToTop: false,
                                    }),

                                });


                                that.model.set({ grid: grid });
                                //container.append(grid.render().el);
                                that.$el.find('.processes-grid-container').append(grid.render().el);



                                //
                                $.contextMenu('destroy');

                                const write = true;
                                if (write) {
                                    $(function (obj) {
                                        $.contextMenu({
                                            selector: '.production-table',
                                            callback: function (key, options) {
                                                that.model.set({ contextMenuOption: key });
                                                that.contextMenuOptionPressed();
                                            },
                                            items: {
                                                "opt-send-to-l3": {
                                                    name: "Send To L3",
                                                    icon: "fa-share-square",
                                                },
                                                separator1: {
                                                    "type": "cm_separator",
                                                },
                                                "opt-print-tag": {
                                                    name: "Print Tag",
                                                    icon: "fa-tag",
                                                },
                                                separator2: {
                                                    "type": "cm_separator",
                                                },
                                                "sulfur-print-rating": {
                                                    name: "Edit Sulfur Rating",
                                                    icon: "fa-pencil",
                                                },


                                            },
                                            events: {
                                                hide: function (options) {
                                                    that.pauseRealTime = false;
                                                    that.removeHighlightRow();
                                                },
                                                show: function () {
                                                    that.pauseRealTime = true;
                                                }
                                            }
                                        });
                                    });

                                }











                                //appending view to the main container
                                that.append(thatContainer, that.$el);



                                //Set model with view params here to prevent changes on the model when the view bindings are applied.
                                var fixedParams = _.extend({}, viewParams);

                                if (fixedParams.start)
                                    fixedParams.start = new moment(fixedParams.start, 'YYYYMMDD').format('YYYY-MM-DD');
                                if (fixedParams.end)
                                    fixedParams.end = new moment(fixedParams.end, 'YYYYMMDD').format('YYYY-MM-DD');
                                if (viewParams.printerCode)
                                    fixedParams.printerCode = (viewParams.printerCode != '-' && viewParams.printerCode != null) ? parseInt(viewParams.printerCode, 10) : null;
                                if (viewParams.crewId)
                                    fixedParams.crewId = (viewParams.crewId != '-' && viewParams.crewId != null) ? viewParams.crewId : null;
                                if (viewParams.shiftId)
                                    fixedParams.shiftId = (viewParams.shiftId != '-' && viewParams.shiftId != null) ? parseInt(viewParams.shiftId, 10) : null;
                                if (viewParams.strandId)
                                    fixedParams.strandId = (viewParams.strandId != '-' && viewParams.strandId != null) ? parseInt(viewParams.strandId, 10) : null;

                                that.model.set(fixedParams);

                                //Call first refresh.
                                var params = that.model.toJSON();

                                that._refresh({
                                    reset: true,
                                    params: _.extend(
                                        {},
                                        params,
                                        {
                                        }
                                    ),
                                });


                            },
                            true,
                            customPath
                        );
                    },
                    customPath
                );
            },
            contextMenuOptionPressed: function () {
                var that = this;
                rowModel = this.model.get('rowModel'),
                    contextMenuOption = this.model.get('contextMenuOption');

                switch (contextMenuOption) {
                    case "opt-send-to-l3":
                        message = 'The product ' + rowModel.ProductNumber + ' will be sent to L3. Do you want to continue?'
                        modal = new Modal.Views.Main({
                            focusOk: false,
                            focusSelector: '#btn-cancel',
                            title: app.translate([this, app], "resend_item_modal_confirm_title"),
                            message: message,
                            buttons_type: "CONTINUE-CANCEL",
                        });
                        this.listenToOnce(modal, "continue", function (modal) {
                            try {

                                that.model.resendToL3({
                                    productId: rowModel.Id
                                })
                            }
                            catch (error) { console.error((error.stack) ? error.stack : new Error(error).stack); }
                        });
                        modal.show();
                        break;
                    case "opt-print-tag":
                        var modal = new Screen.Views.PrintTagConfirmationModal({
                            data: rowModel,
                            bus: this.bus
                        });
                        modal.show();
                        break;
                    case "opt-print-tag-cas2":
                        message = 'The tag ' + rowModel.ProductNumber + ' will be printed with CAS 2 printer. Do you want to continue?'
                        modal = new Modal.Views.Main({
                            focusOk: false,
                            focusSelector: '#btn-cancel',
                            title: 'Print Tag Confirmation',
                            message: message,
                            buttons_type: "CONTINUE-CANCEL",
                        });
                        this.listenToOnce(modal, "continue", function (modal) {
                            try {
                                that.model.printTag({
                                    productId: rowModel.Id,
                                    printer: 2,
                                })
                            }
                            catch (error) { console.error((error.stack) ? error.stack : new Error(error).stack); }
                        });
                        modal.show();
                        break;
                    //case "opt-reprint-tag":
                    //    message = 'The tag ' + rowModel.ProductNumber + ' will be printed. Do you want to continue?'
                    //    modal = new Modal.Views.Main({
                    //        focusOk: false,
                    //        focusSelector: '#btn-cancel',
                    //        title: 'Reprint Tag CAS 2 Confirmation',
                    //        message: message,
                    //        buttons_type: "CONTINUE-CANCEL",
                    //    });
                    //    this.listenToOnce(modal, "continue", function (modal) {
                    //        try {
                    //            that.model.printTag({
                    //                productId: rowModel.Id,
                    //                printer: rowModel.CasterCode,
                    //            })
                    //        }
                    //        catch (error) { console.error((error.stack) ? error.stack : new Error(error).stack); }
                    //    });
                    //    modal.show();
                    //    break;
                    case "sulfur-print-rating":
                        var data = [];
                        data = {
                            ProductNumber: that.model.get('rowModel').ProductNumber,
                            HeatNumber: that.model.get('rowModel').HeatName,
                            Strand: that.model.get('rowModel').StrandId,
                            Cut: that.model.get('rowModel').Sequence,
                            Date: that.model.get('rowModel').CutStart,
                            Grade: that.model.get('rowModel').GradeName,
                            ProductId: that.model.get('rowModel').Id
                        };
                        modal = new SulpherPrintModal.Views.SulfurPrintRatings({
                            parent: this,
                            data: data,
                            rowModel: that.model.get('rowModel'),
                            bus: that.bus,
                        });
                        modal.show();
                        break;
                }
            },
            processes_ready: function () {
                try {
                    var that = this;
                    setTimeout(
                        function () {
                            if (that.itemsColl.length > 0) that.show_backgrid();
                            that.model.set({
                                hasData: (that.itemsColl.length > 0),
                                isLoading: false,
                            });
                        },
                        100
                    );
                }
                catch (e) { console.error((e.stack) ? e.stack : new Error(e).stack); }
            },
            show_backgrid: function () {
                var container = this.$el.find(".processes-grid-container");
                container.empty();

                container.append(this.grids.production.render().el);

                var table = container.find(".production-table")
                table.floatThead({
                    scrollingTop: function () {
                        try {
                            return $(".fixed-subnavbar").height() + ($("header").height() / 2);
                        } catch (error) { return 111; }
                    },
                    zIndex: 500,
                    useAbsolutePositioning: false,
                });

            },
            search_keypress: function (e) {
                if (e.keyCode === 13) {
                    $('#search').blur();
                    this.refreshBtn_click();
                }
            },
            refreshProcesses: function (options) {
                var that = this,
                    attrs = this.model.toJSON(),
                    opt = _.extend({}, options, { params: {}, });

                if ((opt.refresh == true) || (opt.reset == true))
                    this.model.set('isLoading', true);

                this.itemsColl.fetch({
                    start: attrs.start,
                    end: attrs.end,
                    //crewId: (attrs.crewId == "") ? null : attrs.crewId,
                   // shiftId: (attrs.shiftId == "") ? null : attrs.shiftId,
                    //strandId: (attrs.strandId == "") ? null : attrs.strandId,
                    printerCode: attrs.printerCode === "1" || attrs.printerCode === "2" ? attrs.printerCode : null,
                    searchText: attrs.searchText,
                    refresh: true,
                });





            },

            exportToExcel: function () {
                var that = this,
                    params = this.model.toJSON();

                var params = [
                    { Name: '@start', Type: 'DATETIME', Value: params.start, },
                    { Name: '@end', Type: 'DATETIME', Value: params.end, },
                    { Name: '@printer', Type: 'INT', Value: params.printerCode == "" ? null : params.printerCode, },
                ];
                var QP = new QueryParameters();

                _.each(params, function (qpParams) {
                    QP.Add(qpParams.Name, qpParams.Type, qpParams.Value);
                });


                var data = {
                    Data: [],
                    ConnectionStringName: 'APP',
                    ExportMethod: 3,
                    FileName: 'CAS-TagReport',
                    TemplateFileFullPath: 'generic.xls',
                    SQLDataSources: [
                        {
                            Name: 'data',
                            DatabaseParameters: {
                                DBEngine: 'SQLSERVER',
                                Procedure: app.DatabaseNames.MES + '.CAS.GetTagReport',
                                QueryParameters: QP,
                            },
                        },
                    ]
                };

                /* -------------------------------------------------------- 1st Table ------------------------------------------------------------ */
                data.Data.push({
                    SheetName: 'Data',
                    RowsData: [{
                        CellsData:
                            [
                                { Column: 'A', Value: 'Command Type' },
                                { Column: 'B', Value: 'Heat Number' },
                                { Column: 'C', Value: 'Strand' },
                                { Column: 'D', Value: 'Product' },
                                { Column: 'E', Value: 'Grade' },
                                { Column: 'F', Value: 'Length' },
                                { Column: 'G', Value: 'Weight' },
                                { Column: 'H', Value: 'Mold Type' },
                                { Column: 'I', Value: 'Command Status' },
                                { Column: 'J', Value: 'Printer' },
                                { Column: 'K', Value: 'Timestamp' },
                                { Column: 'L', Value: 'User' },
                                { Column: 'M', Value: 'Comments' },
                                { Column: 'N', Value: 'Employee' },
                                { Column: 'O', Value: 'Reason' },

                            ],
                    }],
                    StartRowIndex: 1,
                });

                data.Data.push({
                    SheetName: 'Data',
                    RowsData: [],
                    StartRowIndex: 2,
                    DataSourceName: 'data',
                    DataSourceTableIndex: 0,
                    SQLCellsData:
                        [
                            { ExcelColumnName: 'A', SQLDataColumnName: 'TaggingCommandTypeCode', DataType: 'String' },
                            { ExcelColumnName: 'B', SQLDataColumnName: 'HeatNumber', DataType: 'String' },
                            { ExcelColumnName: 'C', SQLDataColumnName: 'StrandNumber', DataType: 'String' },
                            { ExcelColumnName: 'D', SQLDataColumnName: 'ProductNumber', DataType: 'String' },
                            { ExcelColumnName: 'E', SQLDataColumnName: 'HeatGrade', DataType: 'String' },
                            { ExcelColumnName: 'F', SQLDataColumnName: 'Length', DataType: 'String' },
                            { ExcelColumnName: 'G', SQLDataColumnName: 'Weight', DataType: 'String' },
                            { ExcelColumnName: 'H', SQLDataColumnName: 'MoldType', DataType: 'String' },
                            { ExcelColumnName: 'I', SQLDataColumnName: 'TaggingCommandStatusCode', DataType: 'String' },
                            { ExcelColumnName: 'J', SQLDataColumnName: 'Printer', DataType: 'Integer' },
                            { ExcelColumnName: 'K', SQLDataColumnName: 'Timestamp', DataType: 'String' },
                            { ExcelColumnName: 'L', SQLDataColumnName: 'User', DataType: 'String' },
                            { ExcelColumnName: 'M', SQLDataColumnName: 'Comments', DataType: 'String' },
                            { ExcelColumnName: 'N', SQLDataColumnName: 'Employee', DataType: 'String' },
                            { ExcelColumnName: 'O', SQLDataColumnName: 'Reason', DataType: 'String' },
                        ],
                });

                Core.Export.Excel(
                    data,
                    function (resp) {
                        try {
                            if ((resp) && (resp.Success == true) && (resp.Data)) {
                                location.href = app.foldersRoot + '/excel/' + resp.Data;

                            }
                            else {
                                if ((resp) && (resp.Message))
                                    console.error(resp.Message);
                                else
                                    console.error('Server response not valid.');
                            }
                        }
                        catch (Error) { console.error(Error); }
                        that.model.setExportButtonExporting(false);
                    },
                    function (resp) {
                        that.model.refreshProcesses();
                        that.model.setExportButtonExporting(false);
                        console.error(resp);
                    }
                );
            },
            processes_backgrid_rowclick: function (model) {
                try {
                    //app.router.navigate(
                    //    app.router.resolveURL(
                    //        'eaf-heat-report',
                    //        {
                    //            heatName: model.get('heatName'),
                    //        },
                    //        false
                    //    ),
                    //    { trigger: true, }
                    //);
                }
                catch (Error) { console.error(Error.stack); }
            },
            refreshBtn_click: function (e) {
                try {
                    var params = this.model.toJSON();
                    app.router.navigate(
                        app.router.resolveURL(
                            app.router.currentModule,
                            _.extend(
                                {},
                                params,
                                {
                                    start: new moment(params.start, 'YYYY-MM-DD').format('YYYYMMDD'),
                                    end: new moment(params.end, 'YYYY-MM-DD').format('YYYYMMDD'),
                                    printerCode: (params.printerCode == null || params.printerCode == "") ? '-' : params.printerCode,
                                    //crewId: (params.crewId == null || params.crewId == "") ? '-' : params.crewId,
                                    //shiftId: (params.shiftId == null || params.shiftId == "") ? '-' : params.shiftId,
                                    //strandId: (params.strandId == null || params.strandId == "") ? '-' : params.strandId,
                                }
                            ),
                            false
                        ),
                        { trigger: false, }
                    );

                    this._refresh({
                        reset: true,
                        params: _.extend(
                            {},
                            params,
                            {}
                        ),
                    });

                    window.scrollTo(0, 0);
                }
                catch (Error) { console.error(Error.stack); }
            },

            //Common functions
            append: function (container, el) {
                el = (el != null && el != undefined) ? el : this.$el;

                if (this.options.state == app.view_states.loading
                    || this.options.state == app.view_states.shown) {
                    //appending view to the main container and set state to shown

                    this.options.state = app.view_states.shown;
                    container.append(el);

                    this.options.onappend(this);
                }

                if (this.options.state == app.view_states.hidden) {
                    //append and remain hidden
                    container.append(el);
                }

                if (this.options.state == app.view_states.closed) {
                    //return without appending.
                    return;
                }
            },
            bindViewScopedEvents: function () {
                var that = this;
            },
            unbindViewScopedEvents: function () {

            },
            close: function () {
                this.options.state = app.view_states.closed;

                this.closeSubviews();
                this.remove();
                this.unbindViewScopedEvents();
                this.unbind();
            },
            closeSubviews: function () {
                _.each(this.subviews, function (sview) {
                    sview.close();
                });
            },
            show: function () {
                this.options.state = app.view_states.shown;

                this.showSubviews();
                this.bindEvents();
                this.$el.show();
            },
            showSubviews: function () {
                _.each(this.subviews, function (sview) {
                    sview.show();
                });
            },
            hide: function () {
                this.options.state = app.view_states.hidden;

                this.hideSubviews();

                this.$el.hide();
                this.unbind();
                this.stopListening();
            },
            hideSubviews: function () {
                _.each(this.subviews, function (sview) {
                    sview.hide();
                });
            },
            preRender: function () {
                app.models.subnavbar.set("subnavbar", false);
            },
            reRender: function (viewParams) {
                try {
                    this.refresh(viewParams);
                } catch (Error) { }
            },
        });

        Screen.Collections.Items = Backbone.Collection.extend({
            isFetching: false,
            currentPage: 1,
            pageSize: 100,

            fixedParameters: [],

            fetch: function (params) {
                var that = this,
                    qp = new Core.Database.QueryParameters(),
                    options = params ? _.clone(params) : {};
                if (options.refresh) {
                    this.resetPagination(true);
                    this.fixedParameters = [
                        { Name: '@Start', Type: 'DATETIME', Value: params.start, },
                        { Name: '@End', Type: 'DATETIME', Value: params.end, },
                        //{ Name: '@CrewId', Type: 'CHAR', Value: params.crewId != '-' ? params.crewId : null, },
                        //{ Name: '@ShiftId', Type: 'INT', Value: params.shiftId != '-' ? params.shiftId : null, },
                        //{ Name: '@StrandId', Type: 'INT', Value: params.strandId != '-' ? params.strandId : null, },
                        //{ Name: '@TimeZoneCode', Type: 'CHAR', Value: app.models.user.get('timezoneCode'), },
                        { Name: '@printer', Type: 'INT', Value: params.printerCode, },
                        //{ Name: '@SearchText', Type: 'VARCHAR', Value: params.searchText != '' ? params.searchText : null, },
                    ];
                }
                this.isFetching = true;

                _.each(this.fixedParameters, function (qpParams) {
                    qp.Add(qpParams.Name, qpParams.Type, qpParams.Value);
                });

                //if (!options.refresh) {
                //    qp.Add('@fromRow', 'INT', (this.currentPage - 1) * this.pageSize + 1);
                //    qp.Add('@rowsToFetch', 'INT', this.pageSize - 1);
                //} else {
                //    qp.Add('@fromRow', 'INT', 0);
                //    qp.Add('@toRow', 'INT', this.currentPage * this.pageSize);
                //    qp.Add('@rowsToFetch', 'INT', this.pageSize);
                //}


                Core.Json.CallProcedure(
                    app.DatabaseNames.MES + '.CAS.GetTagReport',
                    qp,
                    {
                        onSuccess: function (resp) {
                            try {

                                if ((resp) && (resp.Table)) {
                                    //var newColl = _.map(resp.Table, that.model.prototype.parse);
                                    newColl = resp.Table;
                                    var method = (options.refresh) ? 'set' : 'add';

                                    that[method](newColl);
                                    that.trigger('fetch', that, newColl);

                                    if (newColl.length == 0 && method == 'add')
                                        that.currentPage--;

                                    that.isFetching = false;


                                }
                                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;
            },
            getNextPage: function (options) {
                if (!this.isFetching) {
                    this.currentPage++;
                    options = (_.isObject(options)) ? options : {};
                    this.fetch(options);
                }
            },
            resetPagination: function (force) {
                if (!this.isFetching || force == true) {
                    this.currentPage = 1;
                } else {
                    _.delay(this.resetPagination, 100);
                }
            },

        });


        //-------------------------------//
        //------ Print Tag Confirmation -------//
        //------------------------------//
        Screen.Models.PrintTagConfirmation = Backbone.Epoxy.Model.extend({
            defaults: {
                productNumber: null,
                printerId: 1,
                comments: '',
                rowModel: null,
                printers: [{ value: 1, label: 1 }, { value: 2, label: 2 }],
                reasonPhrases: null,
                employeeNumber: null,
                reasonPhraseId: 1
            },
            initialize: function () {
                var reasonPhrases =  this.fetchReasonPhrases();
                this.set('reasonPhrases', reasonPhrases);

            },
            fetchReasonPhrases: function () {
                var reasonPhrases = [];
                var qp = new Core.Database.QueryParameters();
                Core.Json.CallProcedure(
                    app.DatabaseNames.MES + '.CAS.GetTagPrintReasonPhrases',
                    qp,
                    {
                        onSuccess: function (resp) {
                            try {

                                if (resp.Table) {
                                    reasonPhrases = resp.Table.map(item => {
                                        return {
                                            value: item.ReasonPhraseId,
                                            label: item.Name
                                        };
                                    });
                                }
                                else {
                                    if ((resp) && (resp.Message)) {
                                        app.views.topMessages.showMessage(resp.Message, { stay: 5000, });
                                        console.error(resp.Message);
                                        that.set({
                                            hasData: false,
                                            isLoading: false,

                                        });

                                    }
                                    else {
                                        app.views.topMessages.showMessage("Server response not valid.", { stay: 5000, });
                                        console.error("Server response not valid.");
                                        that.set({
                                            hasData: false,
                                            isLoading: false,
                                        });
                                    }

                                }


                            }
                            catch (error) { console.error((error.stack) ? error.stack : new Error(error).stack); }
                        },
                        Async: false,
                        Secured: true,
                    },
                    app.ConnectionStrings.app
                );

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