//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',
    'modules/modal2',
    '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, Modal) {

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


        Screen.Models.SecondaryInfo1 = Backbone.Epoxy.Model.extend({
            defaults: {
                grade: null,
                ladle: null,
                argonLanceUsed: null,
                argonLanceVolume: null,
                argonVolume1: null,
                argonVolume2: null,
                operatorName: null,
                energy: null,
                argonLanceUsedAndVolume: null,
                argonVolumes: null,
                argonCar: null,

            },
            setDataModel: function (model) {
                if (model && model[0]) {
                    var obj = model[0];
                    this.set({
                        grade: obj.GradeName ? obj.GradeName : '-',
                        ladle: obj.LadleName ? obj.LadleName : '-',
                        energy: obj.Energy ? obj.Energy.toFixed(2) / 1000 : '-',
                        argonLanceUsed: obj.ArgonLanceUsed ? 'Yes' : 'No',
                        argonLanceVolume: obj.ArgonLanceVolume ? obj.ArgonLanceVolume.toFixed(2) : '-',
                        argonVolume1: obj.ArgonVolume1 ? obj.ArgonVolume1.toFixed(2) : '-',
                        argonVolume2: obj.ArgonVolume2 ? obj.ArgonVolume2.toFixed(2) : '-',
                        operatorName: obj.OperatorName ? obj.OperatorName : '-',
                        argonLanceUsedAndVolume: (obj.ArgonLanceUsed ? 'Yes' : 'No') + ' / ' + (obj.ArgonLanceVolume ? obj.ArgonLanceVolume.toFixed(2) : '-'),
                        argonVolumes: (obj.ArgonVolume1 ? obj.ArgonVolume1.toFixed(2) : '-') + ' / ' + (obj.ArgonVolume2 ? obj.ArgonVolume2.toFixed(2) : '-'),
                        argonCar: obj.ArgonCar ? obj.ArgonCar : '-',
                    }).trigger('fetch', this, obj);

                }
                else this.trigger('fetch', this, model);
            },
        });
        Screen.Models.SecondaryInfo2 = Backbone.Epoxy.Model.extend({
            defaults: {
                arrive: null,
                powerOn: null,
                powerOff: null,
                treatmentTime: null,
                preparationTime: null,
                heatingTime: null,
                lastStage: null,
                energy: null,

            },
            setDataModel: function (model) {
                if (model && model[0]) {
                    var obj = model[0];
                    this.set({
                        arrive: obj.ArriveTimestampLocal ? new moment(obj.ArriveTimestampLocal).format('HH:mm') : '-',
                        powerOn: obj.PowerOn ? obj.PowerOn : '-',
                        powerOff: obj.PowerOff ? obj.PowerOff : '-',
                        treatmentTime: obj.TotalTreatmentTime ? obj.TotalTreatmentTime : '-',
                        preparationTime: obj.PreparationTime ? obj.PreparationTime : '-',
                        heatingTime: obj.HeatingTime ? obj.HeatingTime : '-',
                        lastStage: obj.LastStage ? obj.LastStage : '-',
                        energy: obj.Energy ? obj.Energy.toFixed(2) / 1000 : '',
                    }).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,
                furnace: null,
                startEnd: null,
                lmf: 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 : '-',
                        furnace: obj.LadleFurnaceCode === 1 ? 'South' : 'North',
                        lmf: `Heat: ${obj.HeatName ? obj.HeatName : ''} | LMF ${obj.LadleFurnaceCode ? obj.LadleFurnaceCode : ''} | Production 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 : ''}`,
                        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'),
                    }).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_heatings: false,
                isLoading_heatings: 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

                heatNames: [],
                heatName: null,

                heat: null,
                treatment: null,
                processId: null,

                gridAlloys: [],
                rowModel: [],
                index: null,
                contextMenuOption: null,
                strands: [{ label: 'Strand 1', value: 1 }, { label: 'Strand 2', value: 2 }, { label: 'Strand 3', value: 3 }, { label: 'Strand 4', value: 4 }],
                strandId: 1,
                siblingProcesses: [],
                materials: [],

            },
            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.heatingsColl = new Screen.Collections.HeatingsColl();
                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.phases = new Screen.Collections.PhasesColl();
                this.alloysColl = new Screen.Collections.AlloysColl();
            },

            fetchCatalogs: function () {
               var that = this;
                var qp = new Core.Database.QueryParameters();
                qp.Add('@HeatName', 'VARCHAR(10)', that.get('heatName'));
                qp.Add('@Asset', 'CHAR(3)', 'LMFTOTAL');

                Core.Json.CallProcedure(
                    app.DatabaseNames.MES + '.MES.GetAutocompleteHeats',
                    qp,
                    {
                        onSuccess: function (resp) {
                            try {
                                if (resp && resp.Table) {
                                    that.set({
                                        heatNames: resp.Table,
                                        heatName: resp.Table[0] && resp.Table[0].value ? resp.Table[0].value : '',
                                        processId: resp.Table[0] && resp.Table[0].processId ? resp.Table[0].processId : null,
                                    });
                                    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', 1);
                qp.Add('@direction', 'SMALLINT', params.direction);
                qp.Add('@Asset', 'CHAR(3)', 'LMFTOTAL');
                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({
                                        heatName: resp.Table[0].HeatName,
                                        heatNames: [{
                                            value: resp.Table[0].HeatName,
                                            label: resp.Table[0].HeatName
                                        }],
                                    });
                                    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);

                Core.Json.CallProcedure(
                    app.DatabaseNames.MES + '.LF.GetHeatSummary',
                    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.heatingsColl.setDataColl(resp.Table2);
                                    /* if (resp.Table4 && resp.Table3) that.alloysDetailsColl.setDataColl(resp.Table4, resp.Table3);*/
                                    if (resp.Table3) that.alloysColl.setDataColl(resp.Table3);
                                    that.set({ siblingProcesses: resp.Table4, materials: resp.Table5 });
                                    if (resp.Table6) that.phases.setDataColl(resp.Table6);
                                    if (resp.Table7) that.trigger('fetch-nav-buttons', resp.Table7);
                                    if (resp.Table8) that.trigger('chart-data-ready', resp.Table8, resp.Table9);

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

                                    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_heatings: false,
                                            isLoading_heatings: false,
                                            hasData_alloysDetails: false,
                                            isLoading_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_heatings: false,
                                            isLoading_heatings: false,
                                            hasData_alloysDetails: false,
                                            isLoading_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 'lmf-heat-summary';
            } catch (Error) { }
        }

        Screen.Views.Main = Backbone.Epoxy.View.extend({
            template: 'lmf-heat-summary',
            id: 'lmf-heat-summary',
            title: 'LMF Heat Summary',
            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,
                    'click #printBtn': this.printBtn_click,
                };
            },
            bindings: 'data-bind',
            subviews: null,
            viewParams: null,

            process: null,
            alloysTableView: null,

            autoCompleteCollection: null,
            autocompleteView: null,

            lfChart: null,
            lfChartPrint: null,
            NavigationButtonView: null,
            phaseChartView: 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,
                    phases: that.model.phases,
                    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('lmfh_w', app.models.user.get('roles'));
                var ctx = {
                    write: write != -1 ? true : false,
                };
                return ctx.write;
            },
            bindEvents: function () {
                this.listenTo(this.model.phases, 'fetch', this.phases_fetched);
                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.heatingsColl, 'fetch', this.heatingsColl_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('heatName');
                const options = this.model.get('heatNames');
                document.querySelector('#heat-picker-multi-select').setOptions(options);
                document.querySelector('#heat-picker-multi-select').setValue(value);
                this.UpdateURL();
                this.refresh();

            },
            catalogsFetched: function () {
                this.UpdateURL();
            },
            phases_fetched: function () {
                try {
                    var that = this;
                }
                catch (e) { console.error((e.stack) ? e.stack : new Error(e).stack); }
            },
            printBtn_click: function () {
                window.print();
                return false;
            },

            renderMultipicker: function () {
                var that = this;
                var heatNamesPicker = new VirtualSelect.init({
                    ele: '#heat-picker-multi-select',
                    options: that.model.get('heatNames'),
                    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('heatName'));
                document.querySelector('#heat-picker-multi-select').addEventListener('change', function (e) {
                    $('.vscomp-search-clear').click();
                    if (this.value === that.model.get('heatName')) {
                        return 0;
                    }
                    else {
                        var newHeatName = this.value;
                        if (newHeatName && newHeatName != '') {
                            that.model.set({
                                heatName: 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',1);
                qp.Add('@Asset', 'CHAR(3)', 'LMFTOTAL');
                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: params.heatName,
                    treatment: 1,
                    direction
                });

            },

            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.phaseChartView = Backbone.Epoxy.View.extend({
                                    template: Handlebars.compile(that.$el.find('#phase_chart_view').html()),
                                    initialize: function () {
                                        this.render();
                                    },
                                    render: function () {
                                        this.$el.html(this.template(this.model.toJSON()));
                                        return this;
                                    },
                                });

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

                                    {
                                        name: 'source',
                                        label: 'Source',
                                        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' }
                                                            , { 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;
                                        },
                                    }),
                                    collection: that.model.probesColl,
                                    row: Backgrid.Row.extend({
                                        initialize: function (options) {
                                            Backgrid.Row.prototype.initialize.apply(this, arguments);
                                            var model = this.model.toJSON();
                                            if (model.source === 'EAF')
                                                this.$el.addClass("eaf-probes");
                                        },

                                    }),
                                    columns: probesColumns,
                                });
                                container.append(probesGrid.render().el);
                                that.$el.find('.probes-items-grid-container').append(probesGrid.render().el);

                                var heatingsColumns = [
                                    {
                                        name: 'start',
                                        label: 'Start',
                                        cell: Backgrid.StringCell.extend({
                                            className: function () {
                                                currentStart = new moment(this.model.get('start'), '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';
                                            }
                                        }),
                                        editable: false,
                                    },
                                    {
                                        name: 'duration',
                                        label: app.translate(that, 'item_duration_col_label'),
                                        cell: Backgrid.StringCell.extend({
                                            className: 'string-cell align-center-cell twenty-percent',
                                        }),
                                        editable: false,
                                    },
                                    {
                                        name: 'tap',
                                        label: app.translate(that, 'item_tap_col_label'),
                                        cell: Backgrid.StringCell.extend({
                                            className: 'string-cell align-center-cell twenty-percent',
                                        }),
                                        editable: false,
                                    },
                                    {
                                        name: 'energy',
                                        label: app.translate(that, 'item_energy_col_label'),
                                        cell: Backgrid.StringCell.extend({
                                            className: 'string-cell align-center-cell twenty-percent',
                                        }),
                                        editable: false,
                                    },

                                ];
                                var heatingsGrid = new Backgrid.Grid({
                                    className: 'grid-styles table',
                                    header: Backgrid.Extension.GroupedHeader.extend({
                                        columnLayout:
                                            [
                                                {
                                                    name: 'Heatings', children:
                                                        [
                                                            { name: 'start' }
                                                            , { name: 'duration' }
                                                            , { name: 'tap' }
                                                            , { name: 'energy' }
                                                        ]
                                                },
                                            ],
                                        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.heatingsColl,
                                    columns: heatingsColumns,
                                });
                                container.append(heatingsGrid.render().el);
                                that.$el.find('.heatings-items-grid-container').append(heatingsGrid.render().el);


                                var grid = new Backgrid.Grid({
                                    //className: 'backgrid table table-hover table-condensed',
                                    className: 'grid-styles table',
                                    columns: [
                                        {
                                            name: 'code',
                                            label: app.translate([that, app], 'process_phases_code_col'),
                                            editable: false,
                                            cell: Backgrid.StringCell.extend({
                                                className: Backgrid.StringCell.prototype.className + ' align-left-cell',
                                                template: Handlebars.compile('<div class="bullet pull-left phase-{{order}}-color"></div><span>{{value}}</span>'),
                                                render: function () {
                                                    this.$el.html(this.template({
                                                        value: this.formatter.fromRaw(this.model.get(this.column.get('name')), this.model),
                                                        order: this.model.get('order'),
                                                    }));

                                                    this.delegateEvents();

                                                    return this;
                                                },
                                            }),
                                        },

                                        {
                                            name: 'formattedDuration',
                                            editable: false,
                                            label: app.translate([that, app], 'process_phases_formattedDuration_col'),
                                            cell: Backgrid.StringCell.extend({
                                                decimals: 0,
                                                className: 'string-cell align-left-cell',
                                            }),
                                        },
                                    ],
                                    collection: that.model.phases,
                                });
                                that.$el.find('.process-phases-grid-container').append(grid.render().el);



                                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], 'Value'),
                                            cell: Backgrid.StringCell.extend({
                                                className: 'string-cell align-center-cell',
                                            }),
                                            editable: false,
                                            sortable: false,
                                        },
                                        {
                                            name: 'weightSP',
                                            label: app.translate([that, app], 'Value SP'),
                                            cell: Backgrid.StringCell.extend({
                                                className: 'string-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,
                                                });
                                            }
                                        },

                                    }),
                                    collection: that.model.alloysColl,

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

                                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 ??
                                //!/lmf-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({
                                        heatName: fixedParams.heatName,
                                        treatment: urlTreatment,
                                    });
                                } else {
                                    that.UpdateURL();
                                }
                                that.model.fetchCatalogs();

                                that.renderMultipicker();





                                $.contextMenu('destroy');

                                var write = that.getPermissions();

                                if (write) {
                                    $(function (obj) {
                                        $.contextMenu({
                                            selector: '.production-table tbody',
                                            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",
                                                },
                                                separator1: {
                                                    "type": "cm_separator",
                                                },
                                                "opt-change-addition": {
                                                    name: "Change Addition",
                                                    icon: "edit",
                                                },
                                                "opt-create-new-addition": {
                                                    name: "Create New Addition",
                                                    icon: "fa-plus",
                                                },
                                                "opt-remove-addition": {
                                                    name: "Remove Addition",
                                                    icon: "fa-close",
                                                },
                                            },
                                            events: {
                                                hide: function (options) {
                                                    that.removeHighlightRow();
                                                },
                                            }
                                        });
                                    });

                                }
                                that.refresh();


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

            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 modal = new Screen.Views.EditAddition({
                    data: model,
                    type: type,
                    siblingProcesses: siblingProcesses,
                    materials: materials,
                    bus: this.bus,
                });
                modal.show();
            },
            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");
            },
            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: '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: '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,
                    isLoading_heatings: true,
                    hasData_heatings: false,
                    isLoading_alloysDetails: true,
                    hasData_alloysDetails: false,
                });

                //var splitHeat = params.heatAndTreatment.split('-');


                this.model.fetch({
                    heatName: params.heatName ,
                    treatment: 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';

                    })
                });

            },


            heatingsColl_fetched: function () {
                try {
                    var that = this;
                    setTimeout(
                        function () {
                            that.model.set({
                                hasData_heatings: (that.model.heatingsColl.length > 0),
                                isLoading_heatings: false,
                            });

                        },
                        100
                    );
                }
                catch (e) { console.error((e.stack) ? e.stack : new Error(e).stack); }
            },
            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();

                    app.router.navigate(
                        app.router.resolveURL(
                            app.router.currentModule,
                            _.extend(
                                {},
                                params,
                                {
                                    heatName: params.heatName,
                                }
                            ),
                            false
                        ),
                        { 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,
                ladleFurnaceCode: null,
                operatorId: null,
                powerOn: null,
                productionDate: null,
                shiftId: null,
                shipDatetime: null,
                start: null,
                treatment: null,
                meltOrder: null,
                heatName: null,
                gradeName: null,
                initGradeName: null,
                ladleFurnaceName: null,
                ladleName: null,
                operatorName: null,

                preparationTime: null,
                heatingTime: null,
                lastStage: null,
                totalTreatmentTime: null,
                steelWeight: null,
                powerOff: null,
            },
            computeds: {
                furnaceLabel: {
                    deps: ['ladleFurnaceCode'],
                    get: function (code) {
                        if (code == 1) return 'South'
                        else if (code == 2) return 'North'
                    },
                },
                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,
                        ladleFurnaceCode: obj.LadleFurnaceCode ? obj.LadleFurnaceCode : 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,
                        initGradeName: obj.InitGradeName ? obj.InitGradeName : null,
                        ladleFurnaceName: obj.ladleFurnaceName ? obj.LadleFurnaceName : 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,
                source: 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,
                    source: obj.Source,
                };
                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.HeatingsColl = Backbone.Epoxy.Model.extend({
            defaults: {
                id: null,
                processId: null,
                start: null,
                end: null,
                tap: null,
                energy: null,
                duration: null,
            },

            parse: function (obj) {
                var result = {
                    id: obj.Id ? obj.Id : null,
                    processId: obj.ProcessId ? obj.ProcessId : null,
                    start: obj.Start ? new moment(obj.Start).format('MM/DD HH:mm') : null,
                    end: obj.End ? new moment(obj.End).format('MM/DD HH:mm') : null,
                    tap: obj.Tap ? obj.Tap : null,
                    energy: obj.Energy ? obj.Energy.toFixed(2) : null,
                    duration: obj.Duration ? moment.utc(obj.Duration * 1000).format('mm:ss') : null,
                };
                return result;
            }

        });
        Screen.Collections.HeatingsColl = Backbone.Collection.extend({
            model: Screen.Models.HeatingsColl,
            comparator: 'start',
            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 : '',
                    UoM: det.UoM ? det.UoM : '',
                    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 : '',
                };
                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.PhasesColl = Backbone.Epoxy.Model.extend({
            defaults: {
                code: null,
                order: null,
                duration: null,
                processDuration: null,
                formattedDuration: null,
                currDuration: null,
            },

            parse: function (obj) {
                var result = {
                    code: obj.Code ? obj.Code : null,
                    order: obj.Order ? obj.Order : null,
                    duration: obj.Duration ? obj.Duration : null,
                    processDuration: obj.ProcessDuration ? obj.ProcessDuration : null,
                    formattedDuration: obj.FormattedDuration ? new moment(obj.FormattedDuration, 'HH:mm:ss').format('mm:ss') : '',
                    percentage: obj.Percentage,
                };
                return result;
            }

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

                newColl = _.map(data, that.model.prototype.parse);
                that.set(newColl).trigger('fetch', that, data);
            },
        });
        Screen.Models.AlloysColl = Backbone.Epoxy.Model.extend({
            defaults: {
                timestamp: null,
                material: null,
                weight: null,
                weightSP: null,
                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 : '',
                    weightSP: obj.WeightSP ? obj.WeightSP : '',
                    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: "lmf-heat-summary",
            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,
                    siblingProcesses: options.siblingProcesses,
                    siblingProcessId: options.siblingProcesses[0].currentProcessId,
                    materials: options.materials,
                    materialId: data.materialId,
                    weight: options.type === 'ADD' ? null : data.weight,
                    weightSP: options.type === 'ADD' ? null : data.weightSP,
                    processId: data.processId,
                    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,
                });
                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, "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 {
                        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 + '.LF.RemoveAdditionManually',
                    qp,
                    {
                        onSuccess: function (resp) {
                            try {
                                if ((resp) && (resp.Table)) {
                                    app.views.topMessages.showMessage('The addition was removed successfully', { stay: 5000, });
                                    that.trigger('fetch');
                                }
                                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 + '.LF.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 + '.LF.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 + '.LF.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;
    });