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

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

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

    'modules/eaf-process/eaf-process',

    'backgrid/computed-cell',
    'backgrid/duration-cell',
    'backgrid/infinator',
    'backgrid/moment-cell',
    'js/jquery.floatThead/jquery.floatThead',
    'js/backgrid-0.3.5/extensions/valid-limit-cell/backgrid-valid-limit-cell',
],
    function (app, T, Backgrid, moment, EafProcess) {

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

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

                furnaceCode: null,
                furnaces: [{ label: 'A', value: 1 }, { label: 'B', value: 2 }],

                crewId: null,
                crews: [],

                gradeId: null,
                grades: [],

                showHighTemps: false,

                hasData: false,
                isLoading: false,
            },
            computeds: {
                start$: {
                    deps: ['start'],
                    get: function (value) {
                        return value;
                    },
                    set: function (value) {
                        return { start: (value) ? new moment(value, app.translate(app, 'MM/DD/YYYY')).format('YYYY-MM-DD') : value, };
                    },
                },
                end$: {
                    deps: ['end'],
                    get: function (value) {
                        return value;
                    },
                    set: function (value) {
                        return { end: (value) ? new moment(value, app.translate(app, 'MM/DD/YYYY')).format('YYYY-MM-DD') : value, };
                    },
                },
            },
            fetchGrades: function () {
                var that = this,
                    qp = new Core.Database.QueryParameters();

                qp.Add('@onlyActives', 'BIT', 0);

                Core.Json.CallProcedure(
                    app.DatabaseNames.MES + ".CAT.GetGrades",
                    qp,
                    {
                        onSuccess: function (resp) {
                            try {
                                if ((resp) && (resp.Table)) {
                                    var records = resp.Table;

                                    var newItems = _.map(records, function (obj) {
                                        return { value: obj.Id, label: obj.Name, };
                                    });
                                    that.set("grades", newItems);
                                }
                                else {
                                    if ((resp) && (resp.Message))
                                        console.error(resp.Message);
                                    else
                                        console.error("Server response not valid.");
                                }
                            }
                            catch (error) { console.error((error.stack) ? error.stack : new Error(error).stack); }
                        },
                        onFailure: function (resp) {
                            console.error(resp);
                        },
                        Secured: true,
                        Async: false,
                    },
                    app.ConnectionStrings.app
                );

                return this;
            },
            fetchCrews: function () {
                var that = this,
                    qp = new Core.Database.QueryParameters();

                //qp.Add('@onlyEnabled', 'BIT', 1);

                Core.Json.CallProcedure(
                    app.DatabaseNames.MES + ".SYSTEM.GetCrews",
                    qp,
                    {
                        onSuccess: function (resp) {
                            try {
                                if ((resp) && (resp.Table)) {
                                    var records = resp.Table;

                                    var newItems = _.map(records, function (obj) {
                                        return { value: obj.Id, label: obj.Id, };
                                    });

                                    that.set("crews", newItems);
                                }
                                else {
                                    if ((resp) && (resp.Message))
                                        console.error(resp.Message);
                                    else
                                        console.error("Server response not valid.");
                                }
                            }
                            catch (error) { console.error((error.stack) ? error.stack : new Error(error).stack); }
                        },
                        onFailure: function (resp) {
                            console.error(resp);
                        },
                        Secured: true,
                        Async: false,
                    },
                    app.ConnectionStrings.app
                );

                return this;
            },
        });

        Screen.Models.EafProcess = EafProcess.Models.EafProcess.extend({
            defaults: _.extend(
                {},
                EafProcess.Models.EafProcess.prototype.defaults,
                {
                    shiftName: null,

                    scrapWeight: null,
                    consumptionsInjectedCarbon: null,
                    consumptionsInjectedLime: null,
                    consumptionsNaturalGas: null,
                    consumptionsOxygen: null,
                    consumptionsO2SS: null,
                    fluxesHiCal: null,
                    fluxesCarbon: null,
                    FluxesProSlag: null,
                    FluxesDolomite: null,
                    lastTemperature: null,
                    kwhTon: null,
                    energyPerTonValidLimit: null,
                    oxygenValidLimit: null,
                    o2ssValidLimit: null,
                    powerOnValidLimit: null,
                    oxygenPlusO2SSValidLimit: null,
                }
            ),

            parse: function (obj, objManualVariables, objSummarized, objValidLimits) {
                if (!objSummarized) objSummarized = {};
                if (!objValidLimits) objValidLimits = {};

                return _.extend(EafProcess.Models.EafProcess.prototype.parse.apply(this, arguments), {
                    shiftName: obj.ShiftName,
                    scrapWeight: objSummarized.BucketsWeight,
                    consumptionsInjectedCarbon: objSummarized.ConsumptionsInjectedCarbon,
                    consumptionsInjectedLime: objSummarized.ConsumptionsInjectedLime,
                    consumptionsNaturalGas: objSummarized.ConsumptionsNaturalGas,
                    consumptionsOxygen: objSummarized.ConsumptionsOxygen,
                    consumptionsO2SS: objSummarized.ConsumptionsO2SS,

                    fluxesHiCal: objSummarized.FluxesHiCal,
                    fluxesCarbon: objSummarized.FluxesCarbon,
                    fluxesProSlag: objSummarized.FluxesProSlag,
                    fluxesDolomite: objSummarized.FluxesDolomite,

                    lastTemperature: objSummarized.LastTemperature,

                    tapTemp: obj.TapTemp,
                    energyPerTonValidLimit: objValidLimits.EnergyPerTon,
                    kwhTon: obj.KwhTon,
                    oxygenValidLimit: objValidLimits.Oxygen,
                    o2ssValidLimit: objValidLimits.O2SS,
                    powerOnValidLimit: objValidLimits.PowerOn,
                    oxygenPlusO2SSValidLimit: objValidLimits.OxygenPlusO2SS,

                    yield: objSummarized.Yield ? objSummarized.Yield.toFixed(2) : '',
                    scrapRecipe: objSummarized.ScrapRecipe,
                    latestOxygen: objSummarized.LatestOxygen,
                    charges: obj.Charges,
                    powerProgram: obj.PowerProgram,
                    burnerProgram: obj.BurnerProgram,

                    heatPouredBack: obj.HeatPouredBack ? obj.HeatPouredBack : '-',
                    co2: obj.CO2 ? obj.CO2 : '-',
                    slagIndex: obj.SlagIndex ? obj.SlagIndex : '-',

                    bypassBreakerUtilization: obj.BypassBreakerUtilization || obj.BypassBreakerUtilization === 0 ? obj.BypassBreakerUtilization : '-',
                    conditionsBypassBreakerMaintained: obj.ConditionsBypassBreakerMaintained || obj.ConditionsBypassBreakerMaintained === 0 ? obj.ConditionsBypassBreakerMaintained : '-',
                });
            },
        });

        Screen.Collections.EafProcesses = EafProcess.Collections.EafProcesses.extend({
            model: Screen.Models.EafProcess,

            parseResponse: function (resp, opt) {
                if ((resp) && (resp.Table)) {
                    var that = this,
                        newColl,
                        validLimits = resp.Table2[0];

                    newColl = _.map(resp.Table, function (obj) {
                        return that.model.prototype.parse(obj, null, _.findWhere(resp.Table1, { Id: obj.Id, }), validLimits);
                    });

                    var method = ((opt.refresh) || ((opt.reset))) ? 'set' : 'add';

                    var editingItems = _.where(this.toJSON(), { isNew: true });
                    [].push.apply(newColl, editingItems);

                    this[method](newColl, { from: 'fetch' });

                    return true;
                }

                return false;
            },
            updateFixedParameters: function (params) {
                EafProcess.Collections.EafProcesses.prototype.updateFixedParameters.apply(this, arguments);

                this.fixedParameters.push({ name: 'summarizedData', value: true, type: 'VARCHAR', });
                this.fixedParameters.push({ name: 'includeValidLimits', value: true, type: 'VARCHAR', });
            },
        });

        Screen.Views.Main = Backbone.Epoxy.View.extend({
            template: 'eaf-production',
            id: 'eaf-production',
            title: 'EAF Production',
            events: function () {
                return {
                    'click #refreshBtn': this.refreshBtn_click,
                    "click .btn-export-to-excel": this.exportToExcel,
                };
            },
            bindings: 'data-bind',
            bindingSources: null,
            grids: null,
            processes: null,
            subviews: null,
            viewParams: null,

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

                var that = this;

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

                this.model.fetchCrews();
                this.model.fetchGrades();

                this.grids = {};

                this.processes = new (Screen.Collections.EafProcesses.extend({ pageSize: 50, }))();

                this.bindingSources = {};

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

                this.bindEvents();
            },
            bindEvents: function () {
                //this function should be in every view that uses listenTo anywhere
                //all the model bindings or view-model binding should be here, to manage
                //the show/hide view easily
                this.listenTo(this.processes, 'backgrid:rowclick', this.processes_backgrid_rowclick)
                    .listenTo(this.processes, 'fetch', this.processes_ready);
                //this.listenTo(this.model, 'change:start change:end', this.model_change_pickers);
            },
            _refresh: function (opt) {
                //console.log('autorefresh: ' + new Date().toString()); 

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

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

                this.refreshProcesses(opt);

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

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

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

                if (viewParams.start)
                    fixedParams.start = new moment(fixedParams.start, 'YYYYMMDD').format('YYYY-MM-DD');
                if (viewParams.end)
                    fixedParams.end = new moment(fixedParams.end, 'YYYYMMDD').format('YYYY-MM-DD');
                if (viewParams.furnaceCode)
                    fixedParams.furnaceCode = (viewParams.furnaceCode != '-' && viewParams.furnaceCode != null) ? parseInt(viewParams.furnaceCode, 10) : null;
                if (viewParams.crewId)
                    fixedParams.crewId = (viewParams.crewId != '-' && viewParams.crewId != null) ? viewParams.crewId : null;
                if (viewParams.gradeId)
                    fixedParams.gradeId = (viewParams.gradeId != '-' && viewParams.gradeId != null) ? parseInt(viewParams.gradeId, 10) : null;
                if (!viewParams.showHighTemps)
                    fixedParams.showHighTemps = Screen.Models.Main.defaults.showHighTemps;
                else
                    fixedParams.showHighTemps = (viewParams.showHighTemps == "TRUE") ? true : false;

                this.model.set(fixedParams);

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

                this.viewParams = viewParams;

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

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

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

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

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

                                that.applyBindings();

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

                                that.$el.find('.input-date').datepicker();
                                var grid = that.grids.production = new Backgrid.Grid({
                                    className: 'backgrid table table-hover table-condensed production-table',
                                    columns: [
                                        {
                                            name: 'heatName',
                                            label: app.translate([that, app], 'process_heat_col'),
                                            cell: Backgrid.StringCell.extend({
                                                className: 'string-cell align-center-cell heatName',
                                            }),
                                            editable: false,
                                        },
                                        {
                                            name: 'start',
                                            label: app.translate([that, app], 'process_start_col'),
                                            cell: Backgrid.Extension.MomentCell.extend({
                                                className: 'momment-cell align-center-cell start',
                                                modelFormat: 'YYYY-MM-DD HH:mm:ss.SSS',
                                                displayFormat: app.translate([that, app], 'MM/DD/YYYY') + ' HH:mm',
                                            }),
                                            editable: false,
                                        },
                                        {
                                            name: 'crewId',
                                            label: app.translate([that, app], 'process_crew_col'),
                                            cell: Backgrid.StringCell.extend({
                                                className: 'string-cell align-center-cell crewId',
                                            }),
                                            editable: false,
                                        },
                                        {
                                            name: 'shiftName',
                                            label: app.translate([that, app], 'process_shift_col'),
                                            cell: Backgrid.StringCell.extend({
                                                className: 'string-cell align-center-cell shiftName',
                                            }),
                                            editable: false,
                                        },
                                        {
                                            name: 'gradeName',
                                            label: app.translate([that, app], 'process_grade_col'),
                                            cell: Backgrid.StringCell.extend({
                                                className: 'string-cell align-center-cell gradeName',
                                            }),
                                            editable: false,
                                        },
                                        {
                                            name: 'scrapRecipe',
                                            label: app.translate([that, app], 'scrap_recipe_col'),
                                            cell: Backgrid.StringCell.extend({
                                                className: 'string-cell align-center-cell',
                                            }),
                                            editable: false,
                                        },
                                        {
                                            name: 'charges',
                                            label: app.translate([that, app], 'charges_col'),
                                            cell: Backgrid.StringCell.extend({
                                                className: 'string-cell align-center-cell',
                                            }),
                                            editable: false,
                                        },
                                        {
                                            name: 'scrapWeight',
                                            label: app.translate([that, app], 'process_scrap_weight_col'),
                                            cell: Backgrid.IntegerCell.extend({
                                                className: 'integer-cell align-center-cell scrapWeight',
                                            }),
                                            editable: false,
                                        },
                                        {
                                            name: 'steelWeight',
                                            label: app.translate([that, app], 'process_steel_weight_col'),
                                            cell: Backgrid.NumberCell.extend({
                                                className: 'numeric-cell align-center-cell steelWeight',
                                            }),
                                            editable: false,
                                        },
                                        {
                                            name: 'fluxesHiCal',
                                            label: app.translate([that, app], 'process_fluxesHiCal_col'),
                                            cell: Backgrid.IntegerCell.extend({
                                                className: 'integer-cell align-center-cell process_fluxesHiCal',
                                            }),
                                            editable: false,
                                        },
                                        {
                                            name: 'fluxesDolomite',
                                            label: app.translate([that, app], 'process_fluxesDolomite_col'),
                                            cell: Backgrid.IntegerCell.extend({
                                                className: 'integer-cell align-center-cell process_fluxesDolomite',
                                            }),
                                            editable: false,
                                        },
                                        {
                                            name: 'fluxesCarbon',
                                            label: app.translate([that, app], 'process_fluxesCarbon_col'),
                                            cell: Backgrid.IntegerCell.extend({
                                                className: 'integer-cell align-center-cell process_fluxesCarbon',
                                            }),
                                            editable: false,
                                        },
                                        {
                                            name: 'yield',
                                            label: app.translate([that, app], 'process_yield_col'),
                                            cell: Backgrid.StringCell.extend({
                                                className: 'string-cell align-center-cell',
                                            }),
                                            editable: false,
                                        },
                                        {
                                            name: 'powerProgram',
                                            label: app.translate([that, app], 'power_program_col'),
                                            cell: Backgrid.StringCell.extend({
                                                className: 'string-cell align-center-cell',
                                            }),
                                            editable: false,
                                        },
                                        {
                                            name: 'tapToTap',
                                            label: app.translate([that, app], 'process_tap_to_tap_col'),
                                            cell: Backgrid.StringCell.extend({
                                                className: 'string-cell align-center-cell tapToTap',
                                                formatter: Backgrid.Extension.DurationFormatter.extend({
                                                    displayFormat: 'm:s',
                                                    modelFormat: 's',
                                                }),
                                            }),
                                            editable: false,
                                        },
                                        {
                                            name: 'powerOn',
                                            label: app.translate([that, app], 'process_power_on_col'),
                                            cell: Backgrid.Extension.MakeCellValidLimit(Backgrid.StringCell).extend({
                                                className: 'string-cell align-center-cell powerOn',
                                                formatter: Backgrid.Extension.DurationFormatter.extend({
                                                    displayFormat: 'm:s',
                                                    modelFormat: 's',
                                                }),
                                                invalidMessage: function (value, limit) {
                                                    return app.translate([that, app], 'process_power_on_invalid_value', [parseInt(limit / 60, 10),]);
                                                },
                                                validLimitProp: 'powerOnValidLimit',
                                            }),
                                            editable: false,
                                        },
                                        {
                                            name: 'powerOff',
                                            label: app.translate([that, app], 'process_power_off_col'),
                                            cell: Backgrid.StringCell.extend({
                                                className: 'string-cell align-center-cell powerOff',
                                                formatter: Backgrid.Extension.DurationFormatter.extend({
                                                    displayFormat: 'm:s',
                                                    modelFormat: 's',
                                                }),
                                            }),
                                            editable: false,
                                        },

                                        {
                                            name: 'energy',
                                            label: app.translate([that, app], 'process_energy_col'),
                                            cell: Backgrid.NumberCell.extend({
                                                className: 'numeric-cell align-center-cell energy',
                                            }),
                                            editable: false,
                                        },
                                        {
                                            name: 'kwhTon',
                                            label: app.translate([that, app], 'process_energy_per_ton_col'),
                                            cell: Backgrid.NumberCell.extend({
                                                className: 'numeric-cell align-center-cell energy',
                                                decimals: 3,
                                            }),
                                            editable: false,
                                        },
                                        {
                                            name: 'mwhMin',
                                            label: app.translate([that, app], 'process_mwhMin_col'),
                                            cell: Backgrid.NumberCell.extend({
                                                className: 'numeric-cell align-center-cell',
                                            }),
                                            editable: false,
                                        },
                                        {
                                            name: 'burnerProgram',
                                            label: app.translate([that, app], 'burner_program_col'),
                                            cell: Backgrid.StringCell.extend({
                                                className: 'string-cell align-center-cell',
                                            }),
                                            editable: false,
                                        },
                                        {
                                            name: 'consumptionsNaturalGas',
                                            label: app.translate([that, app], 'process_consumptions_natural_gas_col'),
                                            cell: Backgrid.IntegerCell.extend({
                                                className: 'integer-cell align-center-cell consumptionsInjectedLime',
                                            }),
                                            editable: false,
                                        },
                                        {
                                            name: 'consumptionsOxygen',
                                            label: app.translate([that, app], 'process_consumptions_oxygen_col'),
                                            cell: Backgrid.StringCell.extend({
                                                className: 'string-cell align-center-cell',
                                            }),
                                            //cell: Backgrid.Extension.MakeCellValidLimit(Backgrid.IntegerCell).extend({
                                            //    className: 'integer-cell align-center-cell consumptionsOxygen',
                                            //invalidMessage: function (value, limit) {
                                            //    return app.translate([that, app], 'process_oxygen_invalid_value', [limit, ]);
                                            //},
                                            //validLimitProp: 'oxygenValidLimit',
                                            //validate: function (value, limit) {
                                            //    var modelJSON = this.model.toJSON();
                                            //    var sum = modelJSON.consumptionsO2SS + modelJSON.consumptionsOxygen;
                                            //    return (parseInt(sum) >= limit);
                                            //},
                                            //}),
                                            editable: false,
                                        },

                                        {
                                            name: 'consumptionsO2SS',
                                            label: 'O2SS',
                                            cell: Backgrid.StringCell.extend({
                                                className: 'string-cell align-center-cell',
                                            }),
                                            // cell: Backgrid.Extension.MakeCellValidLimit(Backgrid.IntegerCell).extend({
                                            //     className: 'integer-cell align-center-cell consumptionsOxygen',
                                            //validLimitProp: 'oxygenValidLimit',
                                            //validate: function (value, limit) {
                                            //    var modelJSON = this.model.toJSON();
                                            //    var sum = modelJSON.consumptionsO2SS + modelJSON.consumptionsOxygen;
                                            //    return (parseInt(sum) >= limit);
                                            //},
                                            // }),
                                            editable: false,
                                        },
                                        {
                                            name: 'consumptionsInjectedCarbon',
                                            label: app.translate([that, app], 'process_consumptions_injected_carbon_col'),
                                            cell: Backgrid.IntegerCell.extend({
                                                className: 'integer-cell align-center-cell consumptionsInjectedCarbon',
                                            }),
                                            editable: false,
                                        },
                                        {
                                            name: 'consumptionsInjectedLime',
                                            label: app.translate([that, app], 'process_consumptions_injected_lime_col'),
                                            cell: Backgrid.IntegerCell.extend({
                                                className: 'integer-cell align-center-cell consumptionsInjectedLime',
                                            }),
                                            editable: false,
                                        },
                                        {
                                            name: 'lastTemperature',
                                            label: app.translate([that, app], 'process_last_temperature_col'),
                                            cell: Backgrid.Extension.MakeCellValidLimit(Backgrid.IntegerCell).extend({
                                                className: 'integer-cell align-center-cell lastTemperature',
                                                invalidMessage: function (value, limit) {
                                                    return app.translate([that, app], 'high_temperature_value', [limit,]);
                                                },
                                                validLimitProp: 'tapTemp',
                                                validate: function (value, limit) {
                                                    return (value < limit);
                                                },
                                            }),
                                            editable: false,
                                        },
                                        {
                                            name: 'latestOxygen',
                                            label: app.translate([that, app], 'latest_oxygen_col'),
                                            cell: Backgrid.IntegerCell.extend({
                                                className: 'integer-cell align-center-cell consumptionsInjectedLime',
                                            }),
                                            editable: false,
                                        },
                                        {
                                            name: 'ladleName',
                                            label: app.translate([that, app], 'process_ladle_col'),
                                            cell: Backgrid.StringCell.extend({
                                                className: 'string-cell align-center-cell ladleName',
                                            }),
                                            editable: false,
                                        },
                                        {
                                            name: 'argon',
                                            label: app.translate([that, app], 'process_ladle_argon_col'),
                                            cell: Backgrid.StringCell.extend({
                                                className: 'string-cell align-center-cell ladleName',
                                            }),
                                            editable: false,
                                        },
                                        {
                                            name: 'co2',
                                            label: app.translate([that, app], 'process_ladle_co2_col'),
                                            cell: Backgrid.StringCell.extend({
                                                className: 'string-cell align-center-cell ladleName',
                                            }),
                                            editable: false,
                                        },
                                        {
                                            name: 'heatPouredBack',
                                            label: app.translate([that, app], 'process_pourback_col'),
                                            cell: Backgrid.StringCell.extend({
                                                className: 'string-cell align-center-cell ladleName',
                                            }),
                                            editable: false,
                                        },
                                        {
                                            name: 'slagIndex',
                                            label: 'Slag Index',
                                            cell: Backgrid.StringCell.extend({
                                                className: 'string-cell align-center-cell ladleName',
                                            }),
                                            editable: false,
                                        },
                                        {
                                            name: 'bypassBreakerUtilization',
                                            label: 'Bypass Util',
                                            cell: Backgrid.StringCell.extend({
                                                className: 'string-cell align-center-cell ladleName',
                                            }),
                                            editable: false,
                                        },
                                        {
                                            name: 'conditionsBypassBreakerMaintained',
                                            label: 'Bypass Maint',
                                            cell: Backgrid.StringCell.extend({
                                                className: 'string-cell align-center-cell ladleName',
                                            }),
                                            editable: false,
                                        },
                                    ],
                                    collection: that.processes,
                                    footer: Backgrid.Extension.Infinator.extend({
                                        scrollToTop: false,
                                    }),
                                    row: Backgrid.Row.extend({
                                        events: function () {
                                            return {
                                                'click': this.click,
                                            };
                                        },
                                        click: function (e) {
                                            try {
                                                this.model.trigger('backgrid:rowclick', this.model);
                                            }
                                            catch (Error) { console.error(Error.stack); }
                                        }
                                    })
                                });

                                //var container = that.$el.find(".processes-grid-container");
                                //container.empty();

                                //var table = container.find(".production-table");

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

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

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




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

                                if (fixedParams.start)
                                    fixedParams.start = new moment(fixedParams.start, 'YYYYMMDD').format('YYYY-MM-DD');
                                if (fixedParams.end)
                                    fixedParams.end = new moment(fixedParams.end, 'YYYYMMDD').format('YYYY-MM-DD');
                                if (viewParams.furnaceCode)
                                    fixedParams.furnaceCode = (viewParams.furnaceCode != '-' && viewParams.furnaceCode != null) ? parseInt(viewParams.furnaceCode, 10) : null;
                                if (viewParams.crewId)
                                    fixedParams.crewId = (viewParams.crewId != '-' && viewParams.crewId != null) ? viewParams.crewId : null;
                                if (viewParams.gradeId)
                                    fixedParams.gradeId = (viewParams.gradeId != '-' && viewParams.gradeId != null) ? parseInt(viewParams.gradeId, 10) : null;
                                if (!viewParams.showHighTemps)
                                    fixedParams.showHighTemps = that.model.defaults.showHighTemps;
                                else
                                    fixedParams.showHighTemps = (viewParams.showHighTemps == "TRUE") ? true : false;

                                that.model.set(fixedParams);

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

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

                                //that.show_backgrid();

                                //that.startAutoRefresh();
                            },
                            true,
                            customPath
                        );
                    },
                    customPath
                );
            },

            processes_ready: function () {
                try {
                    var that = this;
                    setTimeout(
                        function () {
                            if (that.processes.length > 0) that.show_backgrid();
                            that.model.set({
                                hasData: (that.processes.length > 0),
                                isLoading: false,
                            });
                        },
                        100
                    );
                }
                catch (e) { console.error((e.stack) ? e.stack : new Error(e).stack); }
            },

            show_backgrid: function () {
                var container = this.$el.find(".processes-grid-container");
                container.empty();

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

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

                    floatContainerClass: 'production-float',
                    zIndex: 500,
                    useAbsolutePositioning: false,
                });

            },

            refreshProcesses: function (options) {
                var that = this,
                    attrs = this.model.toJSON(),
                    opt = _.extend({}, options, { params: {}, });

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

                this.processes.fetch(_.extend(opt, {
                    params: {
                        start: attrs.start,
                        end: new moment(attrs.end, 'YYYY-MM-DD').add('days', 1).format('YYYY-MM-DD'),
                        furnaceCode: (attrs.furnaceCode == "") ? null : attrs.furnaceCode,
                        crewId: (attrs.crewId == "") ? null : attrs.crewId,
                        gradeId: (attrs.gradeId == "") ? null : attrs.gradeId,
                        showHighTemps: attrs.showHighTemps,

                    },
                    success: function () {
                        //that.show_backgrid();
                    }
                }));



            },
            exportToExcel: function () {
                var that = this,
                    start = that.model.get('start'),
                    end = that.model.get('end'),
                    furnaceCode = (that.model.get('furnaceCode') == "") ? null : that.model.get('furnaceCode'),
                    crewId = (that.model.get('crewId') == "") ? null : that.model.get('crewId'),
                    gradeId = (that.model.get('gradeId') == "") ? null : that.model.get('gradeId'),
                    showHighTemps = that.model.get('showHighTemps');

                var params = [
                    { Name: '@start', Type: 'DATETIME', Value: start, },
                    { Name: '@end', Type: 'DATETIME', Value: moment(end).add(1, "d").format("YYYY-MM-DD"), },
                    { Name: '@summarizedData', Type: 'BIT', Value: 1, },
                    { Name: '@furnaceCode', Type: 'INT', Value: furnaceCode },
                    { Name: '@crewId', Type: 'VARCHAR', Value: crewId },
                    { Name: '@gradeId', Type: 'INT', Value: gradeId },
                    { Name: '@showHighTemps', Type: 'BIT', Value: showHighTemps }
                ];

                var QP = new QueryParameters();

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


                var data = {
                    Data: [],
                    ConnectionStringName: 'APP',
                    ExportMethod: 3,
                    FileName: 'EAF-Production',
                    TemplateFileFullPath: 'generic.xls',
                    SQLDataSources: [
                        {
                            Name: 'data',
                            DatabaseParameters: {
                                DBEngine: 'SQLSERVER',
                                Procedure: app.DatabaseNames.MES + '.EAF.GetProcesses',
                                QueryParameters: QP,
                            },
                        },
                    ]
                },
                    chars = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ',
                    chari = 0;

                /* -------------------------------------------------------- 1st Table ------------------------------------------------------------ */
                data.Data.push({
                    SheetName: 'Data',
                    RowsData: [{
                        CellsData:
                            [
                                { Column: 'A', Value: 'Heat' },
                                { Column: 'B', Value: 'Start' },
                                { Column: 'C', Value: 'Crew' },
                                { Column: 'D', Value: 'Shift' },
                                { Column: 'E', Value: 'Grade' },
                                //Column: 'F' -> 2nd Table
                                { Column: 'G', Value: 'Charges' },
                                //Column: 'H' -> 2nd Table
                                { Column: 'I', Value: 'SteelWeight' },
                                //Column: 'J' -> 2nd Table
                                //Column: 'K' -> 2nd Table
                                //Column: 'L' -> 2nd Table
                                //Column: 'M' -> 2nd Table
                                { Column: 'N', Value: 'PowerProgram' },
                                { Column: 'O', Value: 'TTT' },
                                { Column: 'P', Value: 'On' },
                                { Column: 'Q', Value: 'Off' },
                                { Column: 'R', Value: 'MWH' },
                                { Column: 'S', Value: 'KWH/tn' },
                                { Column: 'T', Value: 'MWH/min' },
                                { Column: 'U', Value: 'BurnerProgram' },
                                //Column: 'V' -> 2nd Table
                                //Column: 'W' -> 2nd Table
                                //Column: 'X' -> 2nd Table
                                //Column: 'Y' -> 2nd Table
                                //Column: 'Z' -> 2nd Table
                                //Column: 'AA'-> 2nd Table
                                //Column: 'AB'-> 2nd Table
                                { Column: 'AC', Value: 'Ladle' },
                                { Column: 'AD', Value: 'Melter' },
                                { Column: 'AE', Value: 'Ncc1' },
                                { Column: 'AF', Value: 'Ncc2' },
                                { Column: 'AG', Value: 'Ncc3' },
                                { Column: 'AH', Value: 'CaveIn1' },
                                { Column: 'AI', Value: 'CaveIn2' },
                                { Column: 'AJ', Value: 'CaveIn3' },
                                { Column: 'AK', Value: 'CO2' },
                                { Column: 'AL', Value: 'PourbackHeat' },
                                { Column: 'AM', Value: 'SlagIndex' },
                                { Column: 'AN', Value: 'Bypass Breaker Utilization:' },
                                { Column: 'AO', Value: 'Conditions Bypass Breaker Maintained' },





                            ],
                    }],
                    StartRowIndex: 1,
                });
                charHeaderContinue = chari;

                chari = 0;

                data.Data.push({
                    SheetName: 'Data',
                    RowsData: [],
                    StartRowIndex: 2,
                    DataSourceName: 'data',
                    DataSourceTableIndex: 0,
                    SQLCellsData:
                        [
                            { ExcelColumnName: 'A', SQLDataColumnName: 'HeatName', DataType: 'String' },
                            { ExcelColumnName: 'B', SQLDataColumnName: 'StartString', DataType: 'String' },
                            { ExcelColumnName: 'C', SQLDataColumnName: 'ShiftName', DataType: 'String' },
                            { ExcelColumnName: 'D', SQLDataColumnName: 'CrewId', DataType: 'String' },
                            { ExcelColumnName: 'E', SQLDataColumnName: 'GradeName', DataType: 'String' },
                            //ExcelColumnName: 'F' -> 2nd Table
                            { ExcelColumnName: 'G', SQLDataColumnName: 'Charges', DataType: 'String' },
                            //ExcelColumnName: 'H' -> 2nd Table
                            { ExcelColumnName: 'I', SQLDataColumnName: 'SteelWeight', DataType: 'String' },
                            //ExcelColumnName: 'J' -> 2nd Table
                            //ExcelColumnName: 'K' -> 2nd Table
                            //ExcelColumnName: 'L' -> 2nd Table
                            //ExcelColumnName: 'M' -> 2nd Table
                            { ExcelColumnName: 'N', SQLDataColumnName: 'PowerProgram', DataType: 'String' },
                            { ExcelColumnName: 'O', SQLDataColumnName: 'TapToTapString', DataType: 'String' },
                            { ExcelColumnName: 'P', SQLDataColumnName: 'PowerOnString', DataType: 'String' },
                            { ExcelColumnName: 'Q', SQLDataColumnName: 'PowerOffString', DataType: 'String' },
                            { ExcelColumnName: 'R', SQLDataColumnName: 'Energy', DataType: 'String' },
                            { ExcelColumnName: 'S', SQLDataColumnName: 'KwhTon', DataType: 'String' },
                            { ExcelColumnName: 'T', SQLDataColumnName: 'MwhMin', DataType: 'String' },
                            { ExcelColumnName: 'U', SQLDataColumnName: 'BurnerProgram', DataType: 'String' },
                            //ExcelColumnName: 'V' -> 2nd Table
                            //ExcelColumnName: 'W' -> 2nd Table
                            //ExcelColumnName: 'X' -> 2nd Table
                            //ExcelColumnName: 'Y' -> 2nd Table
                            //ExcelColumnName: 'Z' -> 2nd Table
                            //ExcelColumnName: 'AA'-> 2nd Table
                            //ExcelColumnName: 'AB'-> 2nd Table
                            { ExcelColumnName: 'AC', SQLDataColumnName: 'LadleName', DataType: 'String' },
                            { ExcelColumnName: 'AD', SQLDataColumnName: 'Melter', DataType: 'String' },
                            { ExcelColumnName: 'AE', SQLDataColumnName: 'Ncc1', DataType: 'String' },
                            { ExcelColumnName: 'AF', SQLDataColumnName: 'Ncc2', DataType: 'String' },
                            { ExcelColumnName: 'AG', SQLDataColumnName: 'Ncc3', DataType: 'String' },
                            { ExcelColumnName: 'AH', SQLDataColumnName: 'CaveIn1', DataType: 'String' },
                            { ExcelColumnName: 'AI', SQLDataColumnName: 'CaveIn2', DataType: 'String' },
                            { ExcelColumnName: 'AJ', SQLDataColumnName: 'CaveIn3', DataType: 'String' },
                            { ExcelColumnName: 'AK', SQLDataColumnName: 'CO2', DataType: 'String' },
                            { ExcelColumnName: 'AL', SQLDataColumnName: 'HeatPouredBack', DataType: 'String' },
                            { ExcelColumnName: 'AM', SQLDataColumnName: 'SlagIndex', DataType: 'String' },
                            { ExcelColumnName: 'AN', SQLDataColumnName: 'BypassBreakerUtilization', DataType: 'String' },
                            { ExcelColumnName: 'AO', SQLDataColumnName: 'ConditionsBypassBreakerMaintained', DataType: 'String' },




                        ],
                });

                charValueContinue = chari;
                /* -------------------------------------------------------- 2nd Table ------------------------------------------------------------ */
                data.Data.push({
                    SheetName: 'Data',
                    RowsData: [{
                        CellsData:
                            [
                                //Column: 'A' -> 1st Table
                                //Column: 'B' -> 1st Table
                                //Column: 'C' -> 1st Table
                                //Column: 'D' -> 1st Table
                                //Column: 'E' -> 1st Table
                                { Column: 'F', Value: 'ScrapRecipe' },
                                //Column: 'G' -> 1st Table
                                { Column: 'H', Value: 'ScrapWeight' },
                                //Column: 'I' -> 1st Table
                                { Column: 'J', Value: 'HiCal' },
                                { Column: 'K', Value: 'Dolo' },
                                { Column: 'L', Value: 'Carbon' },
                                { Column: 'M', Value: 'Yield' },
                                //Column: 'N' -> 1st Table
                                //Column: 'O' -> 1st Table
                                //Column: 'P' -> 1st Table
                                //Column: 'Q' -> 1st Table
                                //Column: 'R' -> 1st Table
                                //Column: 'S' -> 1st Table
                                //Column: 'T' -> 1st Table
                                //Column: 'U' -> 1st Table
                                { Column: 'V', Value: 'NaturalGas' },
                                { Column: 'W', Value: 'Oxygen' },
                                { Column: 'X', Value: 'O2SS' },
                                { Column: 'Y', Value: 'InjCarbon' },
                                { Column: 'Z', Value: 'InjLime' },
                                { Column: 'A', Value: 'LastTemp' },
                                { Column: 'AB', Value: 'LastO2' },
                                //Column: 'AC' -> 1st Table
                            ],
                    }],
                    StartRowIndex: 1,
                });

                data.Data.push({
                    SheetName: 'Data',
                    RowsData: [],
                    StartRowIndex: 2,
                    DataSourceName: 'data',
                    DataSourceTableIndex: 1,
                    SQLCellsData:
                        [
                            //ExcelColumnName: 'A' -> 1st Table
                            //ExcelColumnName: 'B' -> 1st Table
                            //ExcelColumnName: 'C' -> 1st Table
                            //ExcelColumnName: 'D' -> 1st Table
                            //ExcelColumnName: 'E' -> 1st Table
                            { ExcelColumnName: 'F', SQLDataColumnName: 'ScrapRecipe', DataType: 'String' },
                            //ExcelColumnName: 'G' -> 1st Table
                            { ExcelColumnName: 'H', SQLDataColumnName: 'BucketsWeight', DataType: 'String' },
                            //ExcelColumnName: 'I' -> 1st Table
                            { ExcelColumnName: 'J', SQLDataColumnName: 'FluxesHiCal', DataType: 'String' },
                            { ExcelColumnName: 'K', SQLDataColumnName: 'FluxesDolomite', DataType: 'String' },
                            { ExcelColumnName: 'L', SQLDataColumnName: 'FluxesCarbon', DataType: 'String' },
                            { ExcelColumnName: 'M', SQLDataColumnName: 'Yield', DataType: 'String' },
                            //ExcelColumnName: 'N' -> 1st Table
                            //ExcelColumnName: 'O' -> 1st Table
                            //ExcelColumnName: 'P' -> 1st Table
                            //ExcelColumnName: 'Q' -> 1st Table
                            //ExcelColumnName: 'R' -> 1st Table 
                            //ExcelColumnName: 'S' -> 1st Table
                            //ExcelColumnName: 'T' -> 1st Table
                            //ExcelColumnName: 'U' -> 1st Table
                            { ExcelColumnName: 'V', SQLDataColumnName: 'ConsumptionsNaturalGas', DataType: 'String' },
                            { ExcelColumnName: 'W', SQLDataColumnName: 'ConsumptionsOxygen', DataType: 'String' },
                            { ExcelColumnName: 'X', SQLDataColumnName: 'ConsumptionsO2SS', DataType: 'String' },
                            { ExcelColumnName: 'Y', SQLDataColumnName: 'ConsumptionsInjectedCarbon', DataType: 'String' },
                            { ExcelColumnName: 'Z', SQLDataColumnName: 'ConsumptionsInjectedLime', DataType: 'String' },
                            { ExcelColumnName: 'AA', SQLDataColumnName: 'LastTemperature', DataType: 'String' },
                            { ExcelColumnName: 'AB', SQLDataColumnName: 'LatestOxygen', DataType: 'String' },
                            //ExcelColumnName: 'AC' -> 1st Table
                        ],
                });

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

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

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

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

            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.stopAutoRefresh();

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

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

                this.hideSubviews();

                this.$el.hide();
                this.unbind();
                this.stopListening();
            },
            hideSubviews: function () {
                _.each(this.subviews, function (sview) {
                    sview.hide();
                });
            },
            preRender: function () {
                app.models.subnavbar.set("subnavbar", false);
            },
            reRender: function (viewParams) {
                try {
                    this.refresh(viewParams);
                } catch (Error) { }
            },
            startAutoRefresh: function () {
                try {
                    if (this.autoRefresh.enabled !== true) {
                        var that = this;

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

                        this.autoRefresh.enabled = true;

                        //use a timeout to execute the first refresh to return the handle to the start function caller.
                        //So when the caller finish it will do the first refresh.
                        this.autoRefresh.toid = setTimeout(
                            function () { that._refresh(); },
                            1
                        );
                    }
                } catch (Error) { console.error(Error.stack); }
            },
            stopAutoRefresh: function () {
                if (this.autoRefresh.toid != null) {
                    clearTimeout(this.autoRefresh.toid);
                    this.autoRefresh.toid = null;
                }
                this.autoRefresh.enabled = false;
            },
        });

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