//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',
    'chart',
    'moment',
    'chartjs-date-fns-adapter',
    'modules/navigation-buttons/navigation-buttons',
    'backgrid/moment-cell',
    'js/autocomplete/backbone.autocomplete',
    'backgrid/grouped-columns',
    'js/multiselect/virtual-select.min',

    'js/jquery.contextMenu/jquery.contextMenu',

],
    function (app, T, Backgrid, ChartJS, moment, ChartJsDateFnsAdapter, NavigationButton) {

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


        Screen.Models.SecondaryInfo1 = Backbone.Epoxy.Model.extend({
            defaults: {
                grade: null,
                ladle: null,
                argonVolume1: null,
                argonVolume2: null,
                minimumTorr: null,

            },
            setDataModel: function (model) {
                if (model && model[0]) {
                    var obj = model[0];
                    this.set({
                        grade: obj.GradeName ? obj.GradeName : '-',
                        ladle: obj.LadleName ? obj.LadleName : '-',
                        argonVolume1: obj.ArgonVolume1 ? obj.ArgonVolume1.toFixed(2) : '-',
                        argonVolume2: obj.ArgonVolume2 ? obj.ArgonVolume2.toFixed(2) : '-',
                        minimumTorr: obj.MinimumTorr ? obj.MinimumTorr : '-',
                    }).trigger('fetch', this, obj);

                }
                else this.trigger('fetch', this, model);
            },
        });
        Screen.Models.SecondaryInfo2 = Backbone.Epoxy.Model.extend({
            defaults: {
                argonBypassTime1: null,
                argonBypassTime2: null,
                vacuumTime: null,
                argonTime1: null,
                argonTime2: null,
                totalTreatmentTime: null,
                totalSequenceTime: null,
                minimumTorrTime: null,


            },
            setDataModel: function (model) {
                if (model && model[0]) {
                    var obj = model[0];
                    this.set({

                        argonBypassTime1: obj.ArgonBypassTime1 ? obj.ArgonBypassTime1 : null,
                        argonBypassTime2: obj.ArgonBypassTime2 ? obj.ArgonBypassTime2 : null,
                        vacuumTime: obj.VacuumTime ? obj.VacuumTime : null,
                        argonTime1: obj.ArgonTime1 ? obj.ArgonTime1 : null,
                        argonTime2: obj.ArgonTime2 ? obj.ArgonTime2 : null,
                        totalTreatmentTime: obj.TotalTreatmentTime ? obj.TotalTreatmentTime : '-',
                        totalSequenceTime: obj.TotalSequenceTime ? obj.TotalSequenceTime : '-',
                        minimumTorrTime: obj.MinimumTorrTime ? obj.MinimumTorrTime : '-',

                    }).trigger('fetch', this, obj);

                }
                else this.trigger('fetch', this, model);
            },
        });
        Screen.Models.HeatReportMainData = Backbone.Epoxy.Model.extend({
            defaults: {
                heatName: null,
                treatment: null,
                meltOrder: null,
                date: null,
                shift: null,
                crew: null,
                start: null,
                end: null,
                tankCode: null,
                startEnd: null,
                headerInfo: null,
                temperature: null,
                foamed: null,
                stirredWell: null,
                totalTime: null,
                wireAdditions: null

            },
            setDataModel: function (model) {
                if (model && model[0]) {
                    var obj = model[0];

                    var shift = obj.ShiftId === 1 ? 'Day' : 'Night';
                    this.set({
                        heatName: obj.HeatName ? obj.HeatName : '-',
                        treatment: obj.TreatmentCurrentAndTotal ? obj.TreatmentCurrentAndTotal : '-',
                        tankCode: obj.TankCode === 1 ? 'Tank 1' : 'Tank 2',
                        meltOrder: obj.MeltOrder ? obj.MeltOrder : '-',
                        date: obj.StartLocal ? new moment(obj.StartLocal).format('MM/DD/YYYY') : '-',
                        shift: obj.ShiftId === 1 ? 'D / ' + obj.CrewId : 'N / ' + obj.CrewId,
                        crew: obj.CrewId ? obj.CrewId : '-',
                        start: obj.StartLocal ? new moment(obj.StartLocal).format('HH:mm') : null,
                        end: obj.EndLocal ? new moment(obj.EndLocal).format('HH:mm') : null,
                        startEnd: new moment(obj.StartLocal).format('HH:mm') + ' / ' + new moment(obj.EndLocal).format('HH:mm'),
                        headerInfo: `Heat: ${obj.HeatName ? obj.HeatName : ''} | Tank ${obj.TankCode === 1 ? '1' : '2'} | Treatment: ${obj.TreatmentCurrentAndTotal ? obj.TreatmentCurrentAndTotal : '1'} | Date: ${obj.StartLocal ? new moment(obj.StartLocal).format('MM/DD/YYYY') : ''} | Shift: ${shift} | Crew: ${obj.CrewId ? obj.CrewId : obj.CrewId} | Start : ${obj.StartLocal ? new moment(obj.StartLocal).format('HH:mm') : ''} | End: ${obj.EndLocal ? new moment(obj.EndLocal).format('HH:mm') : ''} | Grade: ${obj.GradeName ? obj.GradeName : ''} | Ladle: ${obj.LadleName ? obj.LadleName : ''}`,
                        foamed: obj.isFoamed ? 'Yes' : 'No',
                        stirredWell: obj.isStirredWell ? 'Yes' : 'No',

                    }).trigger('fetch', this, obj);

                }
                else this.trigger('fetch', this, model);
            },
        });

        Screen.Models.Main = Backbone.Epoxy.Model.extend({
            defaults: {
                furnaces: [{ label: 'South', value: 1 }, { label: 'North', value: 2 }],

                //URL parameters
                furnaceCode: 1,

                hasData_process: false,
                isLoading_process: false,
                hasData_probes: false,
                isLoading_probes: false,
                hasData_alloysDetails: false,
                isLoading_alloysDetails: false,


                heatId: null,
                direction: null,
                navigation: null,
                enterPress: false,

                //Picker 
                heatAndTreatments: [], // it has the list of heats with treatments --> ex: {value:'A15895-1',label:'A15895-1'} --> it replaces the old "heatNames" variable            
                heatAndTreatment: null, // it has the selected heat with treatment --> ex: 'A15895-1' --> it replaces the old "heatName" variable

                heat: null,
                treatment: null,
                processId: null,
                readOnlyPermissions: true,
                siblingProcesses: [],
                materials: [],
                clickOnRow: false,
            },
            computeds: {
                hasData: {
                    deps: ['hasData_process', 'hasData_probes', 'hasData_heatings'],
                    get: function (process, probes, heatings, alloys) {
                        return process || probes || heatings || alloys;
                    },
                },
                isLoading: {
                    deps: ['isLoading_process', 'isLoading_probes', 'isLoading_heatings'],
                    get: function (process, probes, heatings, alloys) {
                        return process || probes || heatings || alloys;
                    },
                },
            },
            initialize: function () {
                this.probesColl = new Screen.Collections.ProbesColl();
                this.alloysDetailsColl = new Screen.Collections.AlloysDetailsColl();
                this.process = new Screen.Models.Process();
                this.mainData = new Screen.Models.HeatReportMainData();
                this.secondaryData1 = new Screen.Models.SecondaryInfo1();
                this.secondaryData2 = new Screen.Models.SecondaryInfo2();


                this.alloysColl = new Screen.Collections.AlloysColl();
            },

            fetchCatalogs: function () {
                var that = this;
                var qp = new Core.Database.QueryParameters();
                qp.Add('@HeatName', 'VARCHAR(10)', that.get('heat'));
                qp.Add('@Treatment', 'INT', that.get('treatment'));
                qp.Add('@Asset', 'CHAR(3)', 'VTD');
                Core.Json.CallProcedure(
                    app.DatabaseNames.MES + '.MES.GetAutocompleteHeats',
                    qp,
                    {
                        onSuccess: function (resp) {
                            try {
                                if (resp && resp.Table) {
                                    if (resp.Table[0] && resp.Table[0].value) {
                                        splitHeat = resp.Table[0].value.split('-');
                                    }
                                    that.set({
                                        heatAndTreatments: _.map(resp.Table, function (obj) {
                                            return { label: obj.label, value: obj.value }
                                        }),
                                        heatAndTreatment: resp.Table[0] && resp.Table[0].value ? resp.Table[0].value : '',

                                    });
                                    that.trigger('catalogs-fetched');
                                }
                                else {
                                    if ((resp) && (resp.Message)) {
                                        app.views.topMessages.showMessage(resp.Message, { stay: 5000, });
                                        console.error(resp.Message);
                                        that.set({
                                            hasData_process: false,
                                            isLoading_process: false,


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

                                }


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

            fetchNavigateHeat: function (params) {
                var qp = new Core.Database.QueryParameters();
                var that = this;
                qp.Add('@heatName', 'VARCHAR(10)', params.heatName);
                qp.Add('@treatment', 'SMALLINT', params.treatment);
                qp.Add('@direction', 'SMALLINT', params.direction);
                qp.Add('@Asset', 'CHAR(3)', 'VTD');
                Core.Json.CallProcedure(
                    app.DatabaseNames.MES + '.MES.GetNavigatedHeat',
                    qp,
                    {
                        onSuccess: function (resp) {
                            try {
                                if (resp && resp.Table && resp.Table[0] && resp.Table[0].HeatName && resp.Table[0].HeatName !== '') {
                                    that.set({
                                        heatAndTreatments: _.map(resp.Table, function (obj) {
                                            return { label: obj.HeatName + '-' + obj.Treatment, value: obj.HeatName + '-' + obj.Treatment }
                                        }),
                                        heatAndTreatment: resp.Table[0] && resp.Table[0].HeatName ? resp.Table[0].HeatName + '-' + resp.Table[0].Treatment : '',
                                        heat: resp.Table[0] && resp.Table[0].HeatName ? resp.Table[0].HeatName : null,
                                        treatment: resp.Table[0] && resp.Table[0].Treatment ? resp.Table[0].Treatment : 1,

                                    });
                                    that.trigger('heat-name-changed');
                                }
                                else {
                                    if ((resp) && (resp.Message)) {
                                        app.views.topMessages.showMessage(resp.Message, { stay: 5000, });
                                        console.error(resp.Message);
                                        that.set({
                                            hasData_process: false,
                                            isLoading_process: false,
                                        });
                                    }
                                    else {
                                        app.views.topMessages.showMessage("Server response not valid.", { stay: 5000, });
                                        console.error("Server response not valid.");
                                        that.set({
                                            hasData_process: false,
                                            isLoading_process: false,
                                        });
                                    }

                                }


                            }
                            catch (error) { console.error((error.stack) ? error.stack : new Error(error).stack); }
                        },
                        Secured: true,
                        Async: false,
                    },
                    app.ConnectionStrings.app
                );
            },
            fetch: function (params) {
                var that = this;
                var qp = new Core.Database.QueryParameters();

                qp.Add('@heatName', 'VARCHAR', params.heatName);
                qp.Add('@treatment', 'INT', params.treatment);

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

                                if (resp && resp.Table) {
                                    if (resp.Table) that.process.setDataModel(resp.Table);
                                    if (resp.Table1) that.probesColl.setDataColl(resp.Table1);
                                    if (resp.Table2) that.trigger('fetch-nav-buttons', resp.Table2);
                                    if (resp.Table3) that.trigger('chart-data-ready', resp.Table3, resp.Table4);

                                    if (resp.Table) that.mainData.setDataModel(resp.Table);
                                    if (resp.Table) that.secondaryData1.setDataModel(resp.Table);
                                    if (resp.Table) that.secondaryData2.setDataModel(resp.Table);
                                    if (resp.Table5) that.alloysColl.setDataColl(resp.Table5);

                                    that.set({ siblingProcesses: resp.Table6, materials: resp.Table7 });
                                    that.trigger('fetch');
                                }
                                else {
                                    if ((resp) && (resp.Message)) {
                                        app.views.topMessages.showMessage(resp.Message, { stay: 5000, });
                                        console.error(resp.Message);
                                        that.set({
                                            hasData_process: false,
                                            isLoading_process: false,
                                            hasData_probes: false,
                                            isLoading_probes: false,
                                            hasData_alloysDetails: false,
                                        });
                                    }
                                    else {
                                        app.views.topMessages.showMessage("Server response not valid.", { stay: 5000, });
                                        console.error("Server response not valid.");
                                        that.set({
                                            hasData_process: false,
                                            isLoading_process: false,
                                            hasData_probes: false,
                                            isLoading_probes: false,
                                            hasData_alloysDetails: false,
                                        });
                                    }

                                }


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

                return this;

            },
        });

        Screen.generateID = function (viewParams) {
            try {
                //if the viewparams change the view id, then evaluate the viewparams here
                //and return the appropiate id.refreshbtn
                return 'vtd-heat-report';
            } catch (Error) { }
        }

        Screen.Views.Main = Backbone.Epoxy.View.extend({
            template: 'vtd-heat-report',
            id: 'vtd-heat-report',
            title: 'VTD Heat Report',
            isCacheable: false,
            events: function () {
                return {
                    'click #refreshBtn': this.refreshBtn_click,
                    'click #backNavBtn': this.heatNavigationBtn_click,
                    'click #forwardNavBtn': this.heatNavigationBtn_click,
                    //'mouseover .highlightRed': this.mouseOver_tooltipCurrent,
                };
            },
            bindings: 'data-bind',
            subviews: null,
            viewParams: null,

            process: null,
            alloysTableView: null,

            autoCompleteCollection: null,
            autocompleteView: null,

            lfChart: null,
            lfChartPrint: null,
            NavigationButtonView: null,

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

                var that = this;
                this.model = new Screen.Models.Main();

                this.NavigationButtonView = new NavigationButton.Views.Main();

                this.bindingSources = {
                    process: that.model.process,
                    alloysTableColl: that.model.alloysDetailsColl,
                    mainData: that.model.mainData,
                    secondaryData1: that.model.secondaryData1,
                    secondaryData2: that.model.secondaryData2,
                };

                this.bus = _.extend({}, Backbone.Events);
                this.bus.on("modalAcceptTrigger", this.onModalAcceptTrigger, this);
                var write = this.getPermissions();
                this.model.set({
                    readOnlyPermissions: !write
                })

                this.bindEvents();

            },
            onModalAcceptTrigger: function (obj) {
                this.refreshBtn_click();
            },

            getPermissions: function () {
                var write = $.inArray('vtdp_w', app.models.user.get('roles'));
                var ctx = {
                    write: write != -1 ? true : false,
                };
                return ctx.write;
            },
            bindEvents: function () {
                this.listenTo(this.model, 'fetch', this.process_ready);
                this.listenTo(this.model.process, 'fetch', this.process_fetched);
                this.listenTo(this.model.probesColl, 'fetch', this.probesColl_fetched);
                this.listenTo(this.model.alloysDetailsColl, 'fetch', this.alloysDetailsColl_fetched);
                this.listenTo(this.model, 'fetch-nav-buttons', this.fetchnavbuttons);
                this.listenTo(this.model, 'catalogs-fetched', this.catalogsFetched);
                this.listenTo(this.model, 'heat-name-changed', this.heatNameChanged);
                this.listenTo(this.model, 'chart-data-ready', this.buildChart);

            },
            heatNameChanged: function () {
                const value = this.model.get('heatAndTreatment');
                const options = this.model.get('heatAndTreatments');
                document.querySelector('#heat-picker-multi-select').setOptions(options);
                document.querySelector('#heat-picker-multi-select').setValue(value);
                this.UpdateURL();
                this.refresh();

            },
            catalogsFetched: function () {
                this.UpdateURL();
            },
            renderMultipicker: function () {
                var that = this;
                var heatNamesPicker = new VirtualSelect.init({
                    ele: '#heat-picker-multi-select',
                    options: that.model.get('heatAndTreatments'),
                    multiple: false,
                    search: true,
                    placeholder: 'Select Heat',
                    hasOptionDescription: false,
                    showSelectedOptionsFirst: true,
                    hideClearButton: true,
                    onServerSearch: that.onSampleSelectServerSearch,
                });
                document.querySelector('#heat-picker-multi-select').setValue(that.model.get('heatAndTreatment'));
                document.querySelector('#heat-picker-multi-select').addEventListener('change', function (e) {
                    $('.vscomp-search-clear').click();
                    if (this.value === that.model.get('heatAndTreatment')) {
                        return 0;
                    }
                    else {
                        var newHeatName = this.value;
                        if (newHeatName && newHeatName != '') {
                            that.model.set({
                                heatAndTreatment: newHeatName
                            });
                            that.refresh();
                            that.UpdateURL();
                        }
                    }
                });

            },
            onSampleSelectServerSearch: function (searchValue, virtualSelect) {
                var qp = new Core.Database.QueryParameters();
                var splitSelectedValue = this.selectedValues && this.selectedValues[0] && this.selectedValues[0].length > 0 ? this.selectedValues[0] : null;
                if (splitSelectedValue) {
                    splitSelectedValue = splitSelectedValue.split('-');
                }
                qp.Add('@HeatName', 'VARCHAR(10)', searchValue);
                qp.Add('@SelectedHeatName', 'VARCHAR(10)', splitSelectedValue && splitSelectedValue[0] ? splitSelectedValue[0] : null);
                qp.Add('@SelectedTreatment', 'INT', splitSelectedValue && splitSelectedValue[1] ? parseInt(splitSelectedValue[1]) : null);
                qp.Add('@Asset', 'CHAR(3)', 'VTD');
                Core.Json.CallProcedure(
                    app.DatabaseNames.MES + '.MES.GetAutocompleteHeats',
                    qp,
                    {
                        onSuccess: function (resp) {
                            try {
                                virtualSelect.setServerOptions(resp.Table);

                            }
                            catch (error) { console.error((error.stack) ? error.stack : new Error(error).stack); }
                        },
                        Secured: true,
                        Async: false,
                    },
                    app.ConnectionStrings.app
                );
            },
            heatNavigationBtn_click: function (e) {
                const { id } = e.target;
                const params = this.model.toJSON();
                const splitHeat = params.heatAndTreatment.split('-');
                const direction = id === 'backNavBtn' ? -1 : 1;
                this.model.fetchNavigateHeat({
                    heatName: splitHeat[0],
                    treatment: splitHeat[1],
                    direction
                });

            },

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


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

                this.model.set({ clickOnRow: false });
            },

            contextMenuOptionPressed: function () {
                var that = this;
                rowModel = this.model.get('rowModel'),
                    contextMenuOption = this.model.get('contextMenuOption');
                var message = '';
                switch (contextMenuOption) {

                    case "opt-move-to-other-heat":
                        that.editAddition(rowModel, this.model.get('siblingProcesses'), this.model.get('materials'), 'MOVE');
                        break;
                    case "opt-change-addition":
                        that.editAddition(rowModel, this.model.get('siblingProcesses'), this.model.get('materials'), 'CHANGE');
                        break;
                    case "opt-create-new-addition":
                        that.editAddition(rowModel, this.model.get('siblingProcesses'), this.model.get('materials'), 'ADD');
                        break;
                    case "opt-remove-addition":
                        that.editAddition(rowModel, this.model.get('siblingProcesses'), this.model.get('materials'), 'REMOVE');
                        break;
                }
            },
            editAddition: function (model, siblingProcesses, materials, type) {
                var m = this.model.process.toJSON();
                var modal = new Screen.Views.EditAddition({
                    data: model,
                    type: type,
                    siblingProcesses: siblingProcesses,
                    materials: materials,
                    bus: this.bus,
                    processId: m.id,
                });
                modal.show();
            },
            render: function (container, urlParams) {
                var that = this;
                var currentStart = null;
                var processEnd = null;
                var thatContainer = (this.options.container) ? this.options.container : container;
                this.options.container = thatContainer;

                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) {
                                that.options.i18n[that.template] = i18nJED;
                                that.$el.html(tmp());

                                that.alloysTableView = Screen.Views.AlloysTable.extend({
                                    template: Handlebars.compile(that.$el.find('#alloysTableViewTemplate').html()),
                                });

                                var probesColumns = [
                                    {
                                        name: 'datetime',
                                        label: 'Start',
                                        cell: Backgrid.StringCell.extend({
                                            className: function () {
                                                currentStart = new moment(this.model.get('datetime'), 'DD/MM/YYYY HH:mm:ss').format('YYYY-MM-DD HH:mm:ss');
                                                processEnd = new moment(that.model.process.get('endProcessLimit'), 'DD/MM/YYYY HH:mm:ss').format('YYYY-MM-DD HH:mm:ss');
                                                //if (moment(currentStart).isAfter(processEnd, 'second')) return 'string-cell align-center-cell twenty-percent highlightRed';
                                                //else return 'string-cell align-center-cell twenty-percent';
                                                return 'string-cell align-center-cell twenty-percent';
                                            }
                                        }),
                                        editable: false,
                                    },
                                    {
                                        name: 'temperature',
                                        label: app.translate(that, 'item_temperature_col_label'),
                                        cell: Backgrid.StringCell.extend({
                                            className: 'string-cell align-center-cell twenty-percent',
                                        }),
                                        editable: false,
                                    },
                                    {
                                        name: 'oxygen',
                                        label: app.translate(that, 'item_oxygen_col_label'),
                                        cell: Backgrid.StringCell.extend({
                                            className: 'string-cell align-center-cell twenty-percent',
                                        }),
                                        editable: false,
                                    },
                                    {
                                        name: 'carbon',
                                        label: app.translate(that, 'item_carbon_col_label'),
                                        cell: Backgrid.StringCell.extend({
                                            className: 'string-cell align-center-cell twenty-percent',
                                        }),
                                        editable: false,
                                    },

                                ];
                                var probesGrid = new Backgrid.Grid({
                                    className: 'grid-styles table',

                                    header: Backgrid.Extension.GroupedHeader.extend({
                                        columnLayout:
                                            [
                                                {
                                                    name: 'Probes', children:
                                                        [
                                                            { name: 'datetime' }
                                                            , { name: 'temperature' }
                                                            , { name: 'oxygen' }
                                                            , { name: 'carbon' }
                                                        ]
                                                },
                                            ],
                                        initialize: function (options) {
                                            Backgrid.Extension.GroupedHeader.prototype.initialize.apply(this, arguments);
                                        },
                                        render: function () {
                                            var that = this;
                                            Backgrid.Extension.GroupedHeader.prototype.render.apply(this, arguments);
                                            return this;
                                        },
                                    }),
                                    collection: that.model.probesColl,
                                    columns: probesColumns,
                                });
                                container.append(probesGrid.render().el);
                                that.$el.find('.probes-items-grid-container').append(probesGrid.render().el);





                                // Alloys

                                var gridAlloys = new Backgrid.Grid({
                                    className: 'grid-styles table alloys-table',
                                    columns: [
                                        {
                                            name: 'timestamp',
                                            label: app.translate([that, app], 'Timestamp'),
                                            cell: Backgrid.StringCell.extend({
                                                className: 'string-cell align-center-cell',
                                            }),
                                            editable: false,
                                            sortable: false,
                                        },
                                        {
                                            name: 'material',
                                            label: app.translate([that, app], 'Material'),
                                            cell: Backgrid.StringCell.extend({
                                                className: 'string-cell align-center-cell',
                                            }),
                                            editable: false,
                                            sortable: false,
                                        },
                                        {
                                            name: 'weight',
                                            label: app.translate([that, app], 'Value'),
                                            cell: Backgrid.NumberCell.extend({
                                                className: 'number-cell align-center-cell',
                                            }),
                                            editable: false,
                                            sortable: false,
                                        },
                                        {
                                            name: 'weightSP',
                                            label: app.translate([that, app], 'Value SP'),
                                            cell: Backgrid.NumberCell.extend({
                                                className: 'number-cell align-center-cell',
                                            }),
                                            editable: false,
                                            sortable: false,
                                        },
                                        {
                                            name: 'UoM',
                                            label: app.translate([that, app], 'UoM'),
                                            cell: Backgrid.StringCell.extend({
                                                className: 'string-cell align-center-cell',
                                            }),
                                            editable: false,
                                            sortable: false,
                                        },
                                        {
                                            name: 'bin',
                                            label: app.translate([that, app], 'Bin'),
                                            cell: Backgrid.StringCell.extend({
                                                className: 'string-cell align-center-cell',
                                            }),
                                            editable: false,
                                            sortable: false,
                                        },
                                        {
                                            name: 'source',
                                            label: app.translate([that, app], 'Source'),
                                            cell: Backgrid.StringCell.extend({
                                                className: 'string-cell align-center-cell',
                                            }),
                                            editable: false,
                                            sortable: false,
                                        },
                                    ],

                                    header: Backgrid.Extension.GroupedHeader.extend({
                                        columnLayout:
                                            [
                                                {
                                                    name: 'Additions', children:
                                                        [
                                                            { name: 'timestamp' }
                                                            , { name: 'material' }
                                                            , { name: 'weight' }
                                                            , { name: 'weightSP' }
                                                            , { name: 'UoM' }
                                                            , { name: 'bin' }
                                                            , { name: 'source' }
                                                        ]
                                                },
                                            ],
                                        initialize: function (options) {
                                            Backgrid.Extension.GroupedHeader.prototype.initialize.apply(this, arguments);
                                        },
                                        render: function () {
                                            var that = this;
                                            Backgrid.Extension.GroupedHeader.prototype.render.apply(this, arguments);
                                            return this;
                                        },
                                    }),
                                    row: Backgrid.Row.extend({
                                        initialize: function (options) {
                                            Backgrid.Row.prototype.initialize.apply(this, arguments);
                                            var model = this.model.toJSON();
                                            if (model.isManual) this.$el.addClass("is-manual");
                                            else this.$el.removeClass("is-manual");
                                        },
                                        events: {
                                            contextmenu: 'onRightClick',
                                        },
                                        onRightClick: function (e) {
                                            e.preventDefault();
                                            var model = this.model.toJSON();
                                            var write = that.getPermissions();
                                            if (write) {
                                                var rowsView = that.model.get('gridAlloys').body.rows;
                                                var newIndex = _.indexOf(rowsView, this);
                                                this.$el.addClass("onRightClickSelectedRow");
                                                that.model.set({
                                                    rowModel: model,
                                                    index: newIndex,
                                                    clickOnRow: true,
                                                });
                                            }
                                        },

                                    }),
                                    collection: that.model.alloysColl,

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













                                $.contextMenu('destroy');

                                var write = that.getPermissions();

                                if (write) {
                                    $(function (obj) {
                                        $.contextMenu({
                                            selector: '.alloys-table',
                                            callback: function (key, options) {
                                                that.model.set({ contextMenuOption: key });
                                                that.contextMenuOptionPressed();
                                            },
                                            items: {
                                                "opt-move-to-other-heat": {
                                                    name: "Move to Other Heat",
                                                    icon: "fa-share-square",
                                                    disabled: function (key, opt) {                                                    
                                                        return !that.model.get('clickOnRow')
                                                    }
                                                    
                                                },
                                                separator1: {
                                                    "type": "cm_separator",
                                                },
                                                "opt-change-addition": {
                                                    name: "Change Addition",
                                                    icon: "edit",
                                                    disabled: function (key, opt) {
                                                        return !that.model.get('clickOnRow')
                                                    }
                                                },
                                                "opt-create-new-addition": {
                                                    name: "Create New Addition",
                                                    icon: "fa-plus",
                                                },
                                                "opt-remove-addition": {
                                                    name: "Remove Addition",
                                                    icon: "fa-close",
                                                    disabled: function (key, opt) {
                                                        return !that.model.get('clickOnRow')
                                                    }
                                                },
                                            },
                                            events: {
                                                hide: function (options) {
                                                    that.removeHighlightRow();
                                                },
                                            }
                                        });
                                    });

                                }



                                that.applyBindings();
                                //rendering Navigation Buttons
                                that.NavigationButtonView.render(that.$el.find(".navigation-buttons"), null);

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






                                // urlParams ??
                                //!/vtd-heat-report(/:heatName)(/:treatmentNumber)(/)
                                var fixedParams = _.extend({}, urlParams);
                                var urlTreatment = 1;
                                if (fixedParams && fixedParams.heatName && fixedParams.heatName.length === 7) {
                                    if (fixedParams.treatmentNumber) {
                                        urlTreatment = fixedParams.treatmentNumber;
                                    }
                                    that.model.set({
                                        heat: fixedParams.heatName,
                                        treatment: urlTreatment,
                                    });
                                } else {
                                    that.UpdateURL();
                                }
                                that.model.fetchCatalogs();

                                that.renderMultipicker();

                                that.refresh();


                            },
                            true,
                            customPath
                        );
                    },
                    customPath
                );
            },

            buildChart: function (names, all) {
                var ctx = document.getElementById('myChart').getContext('2d');
                var datasets = [];
                var scales = {};
                var position = 'left';
                var radius = 1;
                var type = 'line';
                var pointStyle = 'circle';
                var displayLegend = true;
                var displayLegendByType = true;
                if (this.chart) {
                    this.chart.destroy();
                };
                _.each(names, function (obj, i) {
                    if (obj.isEvent == true) {
                        radius = 5
                        type = 'bubble';
                        displayLegendByType = false;
                        pointStyle = 'triangle';
                    }
                    else {
                        radius = 1;
                        type = 'line';
                        displayLegendByType = true;
                        pointStyle = 'circle';
                    }
                    displayLegend = names[i].ShowYAxis != null ? names[i].ShowYAxis : displayLegendByType;
                    datasets.push({
                        label: obj.Name,
                        data: _.where(all, { Name: obj.Name }),
                        fill: false,
                        yAxisID: 'y' + i,
                        borderColor: obj.Color,
                        backgroundColor: obj.FillColor,
                        tension: 0.1,
                        borderWidth: 1,
                        radius: radius,
                        type: type,
                        pointStyle: pointStyle,

                    })
                    //position = i % 2 == 0 ? 'left' : 'right';
                    position = names[i].YAxisPosition ? names[i].YAxisPosition.replaceAll(/\s/g, '') : 'left';
                    if (i === 0) {
                        scales['x'] = {
                            type: 'time',
                            ticks: {
                                maxTicksLimit: 16,
                                autoSkip: true,
                                maxRotation: 0,
                                minRotation: 0
                            },
                        };
                        scales['y' + i] = {
                            type: names[i] && names[i].yScaleType ? names[i].yScaleType : 'linear',
                            position: position,
                            min: names[i].MinValue,
                            max: names[i].MaxValue,
                            display: true,
                            ticks: {
                                color: names[i].Color,
                                callback: function (value, index, values) {
                                    if (obj.UnitName) {
                                        return value + ' ' + obj.UnitName
                                    } else
                                        return value;
                                },

                            }
                        };

                    } else {
                        scales['y' + i] = {
                            type: names[i] && names[i].yScaleType ? names[i].yScaleType : 'linear',
                            position: position,
                            min: names[i].MinValue,
                            max: names[i].MaxValue,
                            display: displayLegend,
                            ticks: {
                                color: names[i].Color,
                                callback: function (value, index, values) {
                                    if (obj.UnitName) {
                                        return value + ' ' + obj.UnitName
                                    } else
                                        return value;
                                },
                            },
                            grid: {
                                drawOnChartArea: false, // only want the grid lines for one axis to show up
                            },

                        };
                    }
                });
                var pluginLabels = {
                    id: 'plugin_labels',
                    afterDatasetsDraw: (chart, args, options) => {
                        var { ctx } = chart;
                        ctx.save();
                        ctx.font = '12px sans-serif';
                        for (let x = 0; x < chart.config.data.datasets.length; x++) {
                            if (chart.config.data.datasets[x].type === 'bubble') {

                                for (let i = 0; i < chart.config.data.datasets[x].data.length; i++) {
                                    if (chart.config.data.datasets[x].data[i].isEvent === true) {
                                        let textWidth = ctx.measureText(chart.config.data.datasets[x].data[i].EventDescription).width;
                                        let text = chart.config.data.datasets[x].data[i].EventDescription;
                                        ctx.fillText(text, chart.getDatasetMeta(x).data[i].x - (textWidth / 2), chart.getDatasetMeta(x).data[i].y - 10);
                                    }
                                }
                            }

                        }
                        ctx.restore();
                    },

                }
                this.chart = new Chart(ctx, {
                    type: 'line',
                    data: {
                        datasets: datasets
                    },
                    options: {
                        responsive: true,
                        spanGaps: true,
                        plugins: {
                            title: {
                                display: true,
                            },
                        },
                        scales: scales,

                    },
                    plugins: [pluginLabels],
                });



            },
            mouseOver_tooltipCurrent: function () {
                app.views.topMessages.showMessage("The data does not belong to the current process.", { stay: 2500, });
            },


            refresh: function () {
                var params = this.model.toJSON();

                this.model.set({
                    isLoading_process: true,
                    hasData_process: false,
                    isLoading_probes: true,
                    hasData_probes: false,
                    hasData_alloysDetails: false,
                });

                var splitHeat = params.heatAndTreatment.split('-');
                this.model.fetch({
                    heatName: splitHeat[0],
                    treatment: parseInt(splitHeat[1]),
                });

            },


            fetchnavbuttons: function (resp) {
                this.NavigationButtonView.setDataColl(resp);
            },
            alloysDetailsColl_fetched: function () {
                try {
                    var that = this;
                    if (that.model.alloysDetailsColl.length > 0)
                        this.spanAlloysTableRows();

                    setTimeout(
                        function () {
                            that.model.set({
                                hasData_alloysDetails: (that.model.alloysDetailsColl.length > 0),
                                isLoading_alloysDetails: false,
                            });

                        },
                        100
                    );
                    that.alloysNotBelongToProcess();

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

            alloysNotBelongToProcess: function () {
                var that = this;
                var aTags = document.getElementsByClassName("spanrow1");
                var bachStart = null;
                var processEnd = new moment(that.model.process.get('endProcessLimit'), 'DD/MM/YYYY HH:mm:ss').format('YYYY-MM-DD HH:mm:ss');
                //for (var i = 0; i < aTags.length; i++) {
                //    bachStart = new moment(aTags[i].textContent, 'DD/MM/YYYY HH:mm:ss').format('YYYY-MM-DD HH:mm:ss');
                //    found = aTags[i];
                //    //if (moment(bachStart).isAfter(processEnd, 'second')) {
                //    //    $(found).addClass('highlightRed');
                //    //} else {
                //    //    $(found).removeClass('highlightRed');
                //    //}
                //}
            },

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


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


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


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

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

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

                        if (count > 1) {
                            element.additionBatchId = 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';
                        }
                        //rowDelete = document.getElementsByClassName(obj2)[obj.startPos + 1];
                        //rowDelete.style.display = 'none';

                    })
                });

            },



            probesColl_fetched: function () {
                try {
                    var that = this;
                    setTimeout(
                        function () {
                            that.model.set({
                                hasData_probes: (that.model.probesColl.length > 0),
                                isLoading_probes: false,
                            });

                        },
                        100
                    );
                }
                catch (e) { console.error((e.stack) ? e.stack : new Error(e).stack); }
            },
            process_fetched: function () {
                try {
                    var that = this;
                    setTimeout(
                        function () {
                            that.model.set({
                                hasData_process: that.model.process.get('id') ? true : false,
                                isLoading_process: false,
                            });

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

            UpdateURL: function () {
                try {
                    var params = this.model.toJSON();
                    var splitHeat = null;
                    if (params.heatAndTreatment && params.heatAndTreatment.length > 0) {
                        splitHeat = params.heatAndTreatment.split('-');
                        if (splitHeat && splitHeat[0] && splitHeat[1])
                            app.router.navigate('!/vtd-heat-report/' + (splitHeat[0] ? splitHeat[0] : '-') + '/' + (splitHeat[1] ? splitHeat[1] : '-'), { trigger: false });
                    }
                }
                catch (e) { console.error((e.stack) ? e.stack : new Error(e).stack); }
            },

            refreshBtn_click: function (e) {
                this.refresh();
            },


            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 (urlParams) {
                try {
                } catch (Error) { }
            },

        });


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

        Screen.Models.Process = Backbone.Epoxy.Model.extend({
            defaults: {
                argonLanceUsed: null,
                argonLanceVolume: null,
                argonVolume1: null,
                argonVolume2: null,
                arriveDatetime: null,
                comments: null,
                crewId: null,
                end: null,
                energy: null,
                heatId: null,
                id: null,
                operatorId: null,
                powerOn: null,
                productionDate: null,
                shiftId: null,
                shipDatetime: null,
                start: null,
                treatment: null,
                meltOrder: null,
                heatName: null,
                gradeName: null,
                tankCode: null,
                ladleName: null,
                operatorName: null,

                preparationTime: null,
                heatingTime: null,
                lastStage: null,
                totalTreatmentTime: null,
                steelWeight: null,
                powerOff: null,
            },
            computeds: {
                furnaceLabel: {
                    deps: ['tankCode'],
                    get: function (code) {
                        if (code == 1) return 'Tank 1'
                        else if (code == 2) return 'Tank 2'
                    },
                },
                shiftName: {
                    deps: ['shiftId'],
                    get: function (shift) {
                        if (shift == 1) return 'Day'
                        else if (shift == 2) return 'Night'
                    },
                },
                productionDateAndShift: {
                    deps: ['shiftId', 'productionDate'],
                    get: function (shift, date) {
                        if (shift == 1) return date + ' - ' + 'Day'
                        else if (shift == 2) return date + ' - ' + 'Night'
                    },
                }
            },
            setDataModel: function (model) {
                if (model && model[0]) {
                    var obj = model[0];
                    this.set({
                        argonLanceUsed: obj.ArgonLanceUsed ? obj.ArgonLanceUsed : null,
                        argonLanceVolume: obj.ArgonLanceVolume ? obj.ArgonLanceVolume.toFixed(1) : null,
                        argonVolume1: obj.ArgonVolume1 ? obj.ArgonVolume1.toFixed(1) : null,
                        argonVolume2: obj.ArgonVolume2 ? obj.ArgonVolume2.toFixed(1) : null,
                        arriveDatetime: obj.ArriveTimestampLocal ? new moment(obj.ArriveTimestampLocal).format('HH:mm') : null,
                        comments: obj.Comments ? obj.Comments : null,
                        crewId: obj.CrewId ? obj.CrewId : null,
                        end: obj.EndLocal ? new moment(obj.EndLocal).format('HH:mm') : null,
                        energy: obj.Energy ? obj.Energy.toFixed(2) / 1000 : null,
                        heatId: obj.HeatId ? obj.HeatId : null,
                        id: obj.Id ? obj.Id : null,
                        operatorId: obj.OperatorId ? obj.OperatorId : null,
                        powerOn: obj.PowerOn ? obj.PowerOn : null,
                        productionDate: obj.ProductionDate ? new moment(obj.ProductionDate).format('MM/DD/YYYY') : null,
                        shiftId: obj.ShiftId ? obj.ShiftId : null,
                        shipDatetime: obj.ShipTimestamp ? new moment(obj.ShipTimestamp).format('HH:mm') : null,
                        start: obj.StartLocal ? new moment(obj.StartLocal).format('HH:mm') : null,
                        treatment: obj.Treatment ? obj.Treatment : null,
                        meltOrder: obj.MeltOrder ? obj.MeltOrder : null,
                        heatName: obj.HeatName ? obj.HeatName : null,
                        gradeName: obj.GradeName ? obj.GradeName : null,
                        tankCode: obj.TankCode ? obj.TankCode : null,
                        ladleName: obj.LadleName ? obj.LadleName : null,
                        operatorName: obj.OperatorName ? obj.OperatorName : null,
                        preparationTime: obj.PreparationTime ? obj.PreparationTime : null,
                        heatingTime: obj.HeatingTime ? obj.HeatingTime : null,
                        lastStage: obj.LastStage ? obj.LastStage : null,
                        totalTreatmentTime: obj.TotalTreatmentTime ? obj.TotalTreatmentTime : null,
                        steelWeight: obj.SteelWeight ? obj.SteelWeight : null,
                        powerOff: obj.PowerOff ? obj.PowerOff : null,

                        endProcessLimit: obj.EndLocal ? new moment(obj.EndLocal).format('DD/MM/YYYY HH:mm:ss') : null,
                    }).trigger('fetch', this, obj);

                }
                else this.trigger('fetch', this, model);
            },
        });



        Screen.Models.ProbesColl = Backbone.Epoxy.Model.extend({
            defaults: {
                datetime: null,
                oxygen: null,
                temperature: null,
                carbon: null,
            },

            parse: function (obj) {
                var result = {
                    datetime: obj.Datetime ? new moment(obj.Datetime).format('MM/DD HH:mm') : null,
                    oxygen: obj.O,
                    temperature: obj.T,
                    carbon: obj.C,
                };
                return result;
            }

        });
        Screen.Collections.ProbesColl = Backbone.Collection.extend({
            model: Screen.Models.ProbesColl,
            comparator: 'datetime',
            setDataColl: function (data) {
                var newColl,
                    that = this;
                newColl = _.map(data, that.model.prototype.parse);
                that.set(newColl).trigger('fetch', that, data);
            },
        });


        Screen.Models.AlloysDetailsColl = Backbone.Epoxy.Model.extend({
            defaults: {
                id: null,
                additionBatchId: null,
                weightSP: null,
                weightPV: null,
                materialName: null,
                sourceCode: null,
                batchStart: null,
                batchEnd: null,
                dumpStart: null,
                dumpEnd: null,
                parameter1: null,
                binNumber: null,
                uom: null,
            },

            parse: function (det, all) {
                var result = {
                    id: det.ID ? det.ID : null,
                    additionBatchId: det.AdditionBatchID ? det.AdditionBatchID : null,
                    weightSP: det.WeightSP ? det.WeightSP : '',
                    weightPV: det.WeightPV ? det.WeightPV : '',
                    materialName: det.MaterialName ? det.MaterialName : null,
                    parameter1: det.Parameter1 ? det.Parameter1 : '',
                    sourceCode: _.where(all, { ID: det.AdditionBatchID })[0].SourceCode,
                    start: new moment(_.where(all, { ID: det.AdditionBatchID })[0].BatchStart).format('YYYY-MM-DD HH:mm:ss'),
                    batchStart: new moment(_.where(all, { ID: det.AdditionBatchID })[0].BatchStart).format('MM/DD HH:mm'),
                    batchEnd: new moment(_.where(all, { ID: det.AdditionBatchID })[0].BatchEnd).format('MM/DD HH:mm'),
                    dumpStart: new moment(_.where(all, { ID: det.AdditionBatchID })[0].DumpStart).format('HH:mm'),
                    dumpEnd: new moment(_.where(all, { ID: det.AdditionBatchID })[0].DumpEnd).format('HH:mm'),
                    binNumber: det.BinNumber ? det.BinNumber : '',
                    uom: 'lbs',
                };
                return result;
            }

        });
        Screen.Collections.AlloysDetailsColl = Backbone.Collection.extend({
            model: Screen.Models.AlloysDetailsColl,
            comparator: 'start',
            setDataColl: function (data, all) {
                var newColl,
                    that = this;
                newColl = _.map(data, function (obj) { return that.model.prototype.parse(obj, all); });
                that.set(newColl).trigger('fetch', that, data);
            },
        });

        Screen.Models.AlloysColl = Backbone.Epoxy.Model.extend({
            defaults: {
                timestamp: null,
                material: null,
                weight: 0,
                weightSP: 0,
                bin: null,
                source: null,
                id: null,
                processId: null,
                isManual: false,
                material: null,
                dumpStart: null,
                UoM: null,
            },

            parse: function (obj) {
                var result = {
                    timestamp: obj.Timestamp ? obj.Timestamp : '',
                    material: obj.MaterialName ? obj.MaterialName : '',
                    weight: obj.WeightPV ? obj.WeightPV : 0,
                    weightSP: obj.WeightSP ? obj.WeightSP : 0,
                    UoM: obj.UoM ? obj.UoM : '',
                    bin: obj.BinNumber ? obj.BinNumber : '',
                    source: obj.SourceCode ? obj.SourceCode : '',
                    id: obj.Id,
                    processId: obj.ProcessId,
                    isManual: obj.isManual,
                    materialId: obj.MaterialId ? obj.MaterialId : null,
                    dumpStart: obj.DumpStart,
                };
                return result;
            }

        });
        Screen.Collections.AlloysColl = Backbone.Collection.extend({
            model: Screen.Models.AlloysColl,
            setDataColl: function (data) {
                var newColl,
                    that = this;

                newColl = _.map(data, that.model.prototype.parse);
                that.set(newColl).trigger('fetch', that, data);
            },
        });

        Screen.Collections.SingleAlloyColl = Backbone.Collection.extend({
            setDataColl: function (data) {
                var newColl,
                    that = this;
                newColl = data;
                that.set(newColl).trigger('fetch', that, data);
            },
        });
        Screen.Models.EditAddition = Backbone.Epoxy.Model.extend({
            defaults: {
                siblingProcesses: [],
                siblingProcessId: null,
                materials: [],
                materialId: null,
                comment: '',
                commentEnabled: false,
                id: null,
                processId: null,
                moveMode: true,
                changeMode: false,
                addMode: false,
                removeMode: false,
                weight: null,
                weightSP: null,
                dumpStart: null
            },
        });

        Screen.Views.EditAddition = Backbone.Epoxy.View.extend({
            template: "vtd-heat-report",
            id: "move-addition",
            className: "modal modal-move-addition hide fade",
            bindings: "data-bind",
            isCacheable: true,
            events: function () {
                return {
                    "click #acceptBtn": this.acceptBtn_click,
                    "click #cancelBtn": this.cancelBtn_click,
                    "submit form": this.form_submit,
                    "keypress": this.modal_keypress,
                    "show.bs.modal": this.modal_show,
                    "shown.bs.modal": this.modal_shown,
                    "hidden.bs.modal": this.modal_hidden,
                    'keyup #comment-textarea': this.comment_changed,
                };
            },
            container: null,
            disposed: false,
            isRendered: false,
            preventDispose: false,
            visible: false,
            data: [],
            lastHeatsColl: [],
            grid: [],
            productId: null,
            initialize: function (options) {
                _.extend(this, options);
                if (!this.model) {
                    this.model = new Screen.Models.EditAddition();
                }
                this.singleAlloyColl = new Screen.Collections.SingleAlloyColl();

                var data = options.data;
                this.model.set({
                    id: data?.id ? data.id : null,
                    siblingProcesses: options.siblingProcesses,
                    siblingProcessId: options.siblingProcesses[0].currentProcessId,
                    materials: options.materials,
                    materialId: data?.materialId ? data.materialId : null,
                    weight: options.type === 'ADD' ? null : data.weight,
                    weightSP: options.type === 'ADD' ? null : data.weightSP,
                    processId: options.processId ? options.processId : null,
                    moveMode: options.type === 'MOVE' ? true : false,
                    changeMode: options.type === 'CHANGE' ? true : false,
                    addMode: options.type === 'ADD' ? true : false,
                    removeMode: options.type === 'REMOVE' ? true : false,
                    dumpStart: data?.dumpStart ? data.processId : null,
                });

                this.singleAlloyColl.setDataColl(data);
                this.bus = options.bus;
                this.bindEvents();

                return this;
            },


            hide: function (preventDispose) {
                this.preventDispose = (preventDispose);

                this.$el.modal('hide');
            },
            render: function (container) {
                if (container)
                    this.container = container;

                var that = this;
                var customPath = '/app/custom-screens/' + this.template + '/';
                T.render.call(this, this.template, function (tmp) {
                    if (!that.i18n) that.i18n = {};
                    app.getI18NJed(that, that.template, function (i18nJED) {
                        that.i18n[that.template] = i18nJED;
                        that.$el.html(tmp(that.model.toJSON()));
                        that.applyBindings();

                        var gridAlloys = new Backgrid.Grid({
                            className: 'grid-styles table production-table',
                            columns: [
                                {
                                    name: 'timestamp',
                                    label: app.translate([that, app], 'Timestamp'),
                                    cell: Backgrid.StringCell.extend({
                                        className: 'string-cell align-center-cell',
                                    }),
                                    editable: false,
                                    sortable: false,
                                },
                                {
                                    name: 'material',
                                    label: app.translate([that, app], 'Material'),
                                    cell: Backgrid.StringCell.extend({
                                        className: 'string-cell align-center-cell',
                                    }),
                                    editable: false,
                                    sortable: false,
                                },
                                {
                                    name: 'weight',
                                    label: app.translate([that, app], 'Weight'),
                                    cell: Backgrid.StringCell.extend({
                                        className: 'string-cell align-center-cell',
                                    }),
                                    editable: false,
                                    sortable: false,
                                },
                                {
                                    name: 'weightSP',
                                    label: app.translate([that, app], 'Weight SP'),
                                    cell: Backgrid.StringCell.extend({
                                        className: 'string-cell align-center-cell',
                                    }),
                                    editable: false,
                                    sortable: false,
                                },
                                {
                                    name: 'bin',
                                    label: app.translate([that, app], 'Bin'),
                                    cell: Backgrid.StringCell.extend({
                                        className: 'string-cell align-center-cell',
                                    }),
                                    editable: false,
                                    sortable: false,
                                },
                                {
                                    name: 'source',
                                    label: app.translate([that, app], 'Source'),
                                    cell: Backgrid.StringCell.extend({
                                        className: 'string-cell align-center-cell',
                                    }),
                                    editable: false,
                                    sortable: false,
                                },
                            ],
                            collection: that.singleAlloyColl,

                        });
                        that.$el.find('.alloys-grid-container').append(gridAlloys.render().el);

                        that.isRendered = true;
                        that.trigger("render");


                    }, true, customPath);

                }, customPath, "vtd_move_addition_template");

            },



            show: function () {
                if (!this.isRendered) {
                    this.render();
                }
                else {
                    this.$el.modal({
                        keyboard: true,
                        backdrop: 'both',
                    });
                }

                return this;
            },

            bindEvents: function () {
                this.listenToOnce(this, "render", this.view_render);
            },


            comment_changed: _.debounce(function (a, b, c) {
                this.model.set({
                    comment: $("#comment-textarea").val()
                })
                if (this.model.get('comment') === null || this.model.get('comment') === '') this.model.set({ commentEnabled: false });
                else this.model.set({ commentEnabled: true });
            }, 300),

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

                        this.remove();
                        this.unbind();

                        this.disposed = true;
                    }
                }
            },
            preRender: function () {
                app.models.subnavbar.set("dateControl", false);
            },
            reRender: function () {
            },
            acceptBtn_click: function (e) {
                try {
                    var that = this;
                    var model = this.model.toJSON();
                    if (model.id && model.comment && model.comment.length > 0 && model.comment !== '') {
                        if (model.processId === parseInt(model.siblingProcessId) && model.moveMode) {
                            app.views.topMessages.showMessage('The current process is the same as the selected one', { stay: 2000, });
                        } else if (model.moveMode) {
                            this.moveAddition({
                                id: model.id,
                                newProcessId: model.siblingProcessId,
                                comment: model.comment,
                            });
                        } else if (model.changeMode) {
                            this.changeAddition({
                                id: model.id,
                                materialId: model.materialId,
                                weight: model.weight,
                                weightSP: model.weightSP,
                                comment: model.comment,
                            });
                        } else if (model.addMode && model.weight && model.weightSP && !isNaN(model.weight) && !isNaN(model.weightSP)) {
                            this.addAddition({
                                processId: model.processId,
                                dumpStart: model.dumpStart,
                                materialId: model.materialId,
                                weight: model.weight,
                                weightSP: model.weightSP,
                                comment: model.comment,
                            });
                        } else if (model.addMode && (!model.weight || !model.weightSP || isNaN(model.weight) || isNaN(model.weightSP))) {
                            app.views.topMessages.showMessage('It is not possible to add the addition. Some information is missing or wrong', { stay: 2000, });

                        } else if (model.removeMode) {
                            this.removeAddition({
                                id: model.id,
                                comment: model.comment,
                            });
                        }
                        this.close();
                    } else {
                        if (model.addMode) {
                            this.addAddition({
                                processId:  model.processId,
                                dumpStart:  model.dumpStart,
                                materialId: model.materialId,
                                weight:     model.weight,
                                weightSP:   model.weightSP,
                                comment:    model.comment,
                            });
                        }
                        app.views.topMessages.showMessage('It is not possible to move or edit the addition. Some information is missing', { stay: 2000, });

                    }

                }
                catch (e) { console.error((e.stack) ? e.stack : new Error(e).stack); }
            },
            removeAddition: function (params) {
                var that = this,
                    qp = new Core.Database.QueryParameters();

                this.fixedParameters = [
                    { Name: '@id', Type: 'INT', Value: params.id, },
                    { Name: '@comment', Type: 'VARCHAR', Value: params.comment, },
                ];
                _.each(this.fixedParameters, function (qpParams) {
                    qp.Add(qpParams.Name, qpParams.Type, qpParams.Value);
                });
                Core.Json.CallProcedure(
                    app.DatabaseNames.MES + '.VTD.RemoveAdditionManually',
                    qp,
                    {
                        onSuccess: function (resp) {
                            try {
                                if ((resp) && (resp.Table)) {
                                    app.views.topMessages.showMessage('The addition was removed successfully', { stay: 5000, });
                                    //that.trigger('fetch');
                                    that.bus.trigger("modalAcceptTrigger");
                                }
                                else {
                                    that.trigger('fetch');
                                    if ((resp) && (resp.Message)) {
                                        console.error(new Error(resp.Message).stack);
                                        app.views.topMessages.showMessage('CALL TO DATABASE FAILED', { stay: 3000, });
                                    }
                                    else {
                                        app.views.topMessages.showMessage('SERVER RESPONSE NOT VALID', { stay: 3000, });
                                        console.error(new Error('SERVER_RESPONSE_NOT_VALID').stack);
                                    }

                                }
                            }
                            catch (e) { console.error((e.stack) ? e.stack : new Error(e).stack); }
                        },
                        onFailure: function (resp) {
                            that.trigger('fetch');
                            console.error(resp);
                        },
                        Secured: true,
                        Async: true,
                    },
                    app.ConnectionStrings.app
                );
                return this;
            },
            changeAddition: function (params) {
                var that = this,
                    qp = new Core.Database.QueryParameters();

                this.fixedParameters = [
                    { Name: '@id', Type: 'INT', Value: params.id, },
                    { Name: '@materialId', Type: 'INT', Value: params.materialId, },
                    { Name: '@weight', Type: 'FLOAT', Value: params.weight, },
                    { Name: '@weightSP', Type: 'FLOAT', Value: params.weightSP, },
                    { Name: '@comment', Type: 'VARCHAR', Value: params.comment, },
                ];
                _.each(this.fixedParameters, function (qpParams) {
                    qp.Add(qpParams.Name, qpParams.Type, qpParams.Value);
                });
                Core.Json.CallProcedure(
                    app.DatabaseNames.MES + '.VTD.UpdateAdditionManually',
                    qp,
                    {
                        onSuccess: function (resp) {
                            try {
                                if ((resp) && (resp.Table)) {
                                    app.views.topMessages.showMessage('The addition was updated', { stay: 5000, });
                                    that.bus.trigger("modalAcceptTrigger");
                                }
                                else {
                                    that.bus.trigger("modalAcceptTrigger");
                                    if ((resp) && (resp.Message)) {
                                        console.error(new Error(resp.Message).stack);
                                        app.views.topMessages.showMessage('CALL TO DATABASE FAILED', { stay: 3000, });
                                    }
                                    else {
                                        app.views.topMessages.showMessage('SERVER RESPONSE NOT VALID', { stay: 3000, });
                                        console.error(new Error('SERVER_RESPONSE_NOT_VALID').stack);
                                    }

                                }
                            }
                            catch (e) { console.error((e.stack) ? e.stack : new Error(e).stack); }
                        },
                        onFailure: function (resp) {
                            that.bus.trigger("modalAcceptTrigger");
                            console.error(resp);
                        },
                        Secured: true,
                        Async: true,
                    },
                    app.ConnectionStrings.app
                );
                return this;
            },
            addAddition: function (params) {
                var that = this,
                    qp = new Core.Database.QueryParameters();

                this.fixedParameters = [
                    { Name: '@processId', Type: 'INT', Value: params.processId, },
                    { Name: '@dumpStart', Type: 'DATETIME', Value: params.dumpStart ? new moment(params.dumpStart).format('YYYY-MM-DD HH:mm:ss.SSS') : null, },
                    { Name: '@materialId', Type: 'INT', Value: params.materialId, },
                    { Name: '@weight', Type: 'FLOAT', Value: params.weight, },
                    { Name: '@weightSP', Type: 'FLOAT', Value: params.weightSP, },
                    { Name: '@comment', Type: 'VARCHAR', Value: params.comment, },
                ];
                _.each(this.fixedParameters, function (qpParams) {
                    qp.Add(qpParams.Name, qpParams.Type, qpParams.Value);
                });
                Core.Json.CallProcedure(
                    app.DatabaseNames.MES + '.VTD.InsertAdditionManually',
                    qp,
                    {
                        onSuccess: function (resp) {
                            try {
                                if ((resp) && (resp.Table)) {
                                    app.views.topMessages.showMessage('The addition was created successfully', { stay: 5000, });
                                    that.bus.trigger("modalAcceptTrigger");
                                }
                                else {
                                    that.bus.trigger("modalAcceptTrigger");
                                    if ((resp) && (resp.Message)) {
                                        console.error(new Error(resp.Message).stack);
                                        app.views.topMessages.showMessage('CALL TO DATABASE FAILED', { stay: 3000, });
                                    }
                                    else {
                                        app.views.topMessages.showMessage('SERVER RESPONSE NOT VALID', { stay: 3000, });
                                        console.error(new Error('SERVER_RESPONSE_NOT_VALID').stack);
                                    }

                                }
                            }
                            catch (e) { console.error((e.stack) ? e.stack : new Error(e).stack); }
                        },
                        onFailure: function (resp) {
                            that.bus.trigger("modalAcceptTrigger");
                            console.error(resp);
                        },
                        Secured: true,
                        Async: true,
                    },
                    app.ConnectionStrings.app
                );
                return this;
            },
            moveAddition: function (params) {
                var that = this,
                    qp = new Core.Database.QueryParameters();

                this.fixedParameters = [
                    { Name: '@id', Type: 'INT', Value: params.id, },
                    { Name: '@newProcessId', Type: 'INT', Value: params.newProcessId, },
                    { Name: '@comment', Type: 'VARCHAR', Value: params.comment, },
                ];
                _.each(this.fixedParameters, function (qpParams) {
                    qp.Add(qpParams.Name, qpParams.Type, qpParams.Value);
                });
                Core.Json.CallProcedure(
                    app.DatabaseNames.MES + '.VTD.MoveAddition',
                    qp,
                    {
                        onSuccess: function (resp) {
                            try {
                                if ((resp) && (resp.Table)) {
                                    app.views.topMessages.showMessage('The addition was moved to other treatment', { stay: 5000, });
                                    that.bus.trigger("modalAcceptTrigger");
                                }
                                else {
                                    that.bus.trigger("modalAcceptTrigger");
                                    if ((resp) && (resp.Message)) {
                                        console.error(new Error(resp.Message).stack);
                                        app.views.topMessages.showMessage('CALL TO DATABASE FAILED', { stay: 3000, });
                                    }
                                    else {
                                        app.views.topMessages.showMessage('SERVER RESPONSE NOT VALID', { stay: 3000, });
                                        console.error(new Error('SERVER_RESPONSE_NOT_VALID').stack);
                                    }

                                }
                            }
                            catch (e) { console.error((e.stack) ? e.stack : new Error(e).stack); }
                        },
                        onFailure: function (resp) {
                            that.bus.trigger("modalAcceptTrigger");
                            console.error(resp);
                        },
                        Secured: true,
                        Async: true,
                    },
                    app.ConnectionStrings.app
                );
                return this;
            },



            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); }
            },
            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); }
            },
        });


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