//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',
  'backgrid/moment-cell',
  'backgrid/infinator',
  
    'backgrid/grouped-columns',
],
function (app, T, Backgrid, moment) {

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

    Screen.Models.Main = Backbone.Epoxy.Model.extend({
        defaults: {

            start: new moment().subtract(5, 'days').format('MM/DD/YYYY'),
            end: new moment().format('MM/DD/YYYY'),
            shiftId:'-',
            shifts: [{ label: 'D', value: 1 }, { label: 'N', value: 2 }],
           
            crewId: '-',
            crews: [{ label: 'A', value: 'A' }, { label: 'B', value: 'B' }, { label: 'C', value: 'C' },{ label: 'D', value: 'D' }],
            hasData: false,
            isLoading: false,
        },
    });

    Screen.Models.Item = Backbone.Epoxy.Model.extend({
        parse: function (obj) {
            var result = {              
                heatName:                  obj.HeatName                 ? obj.HeatName                 : null,           
                productionDate:            obj.ProductionDate           ? obj.ProductionDate           : null,           
                steelWeight:               obj.SteelWeight              ? obj.SteelWeight              : null,           
                tareWeight:                obj.TareWeight               ? obj.TareWeight               : null,           
                finalArmWeight:            obj.FinalArmWeight           ? obj.FinalArmWeight           : null,           
                initialArmWeight:          obj.InitialArmWeight         ? obj.InitialArmWeight         : null,           
                alloyWeight:               obj.AlloyWeight              ? obj.AlloyWeight              : null,           
                bucketScrapWeight:         obj.BucketScrapWeight        ? obj.BucketScrapWeight        : null,           
                bucketOtherWeight:         obj.BucketOtherWeight        ? obj.BucketOtherWeight        : null,           
                startTap:                  obj.StartTap                 ? new moment(obj.StartTap).format('MM/DD HH:mm')                 : null,           
                drainWeight:               obj.DrainWeight              ? obj.DrainWeight              : null,           
                pourbackWeight:            obj.PourbackWeight           ? obj.PourbackWeight           : null,           
                casterInitialGrossWeight:  obj.CasterInitialGrossWeight ? obj.CasterInitialGrossWeight : null,           
                casterFinalGrossWeight:    obj.CasterFinalGrossWeight   ? obj.CasterFinalGrossWeight   : null,           
                casterProcessedWeight:     obj.CasterProcessedWeight    ? obj.CasterProcessedWeight    : null,           
                productsWeight:            obj.ProductsWeight           ? obj.ProductsWeight           : null,           
                endCast:                   obj.EndCast                  ? new moment(obj.EndCast).format('MM/DD HH:mm')                : null,           
                shiftId: obj.ShiftId ? obj.ShiftId : null,
                crewId: obj.CrewId ? obj.CrewId : null
            };

            return result;
        }
    })

    Screen.Collections.Items = Backbone.Collection.extend({
        model: Screen.Models.Item,

        isFetching: false,
        currentPage: 1,
        pageSize: 100,
        fixedParameters: [],

        fetch(params) {
            var that = this
                qp = new Core.Database.QueryParameters(),
                options = params ? _.clone(params) : {};

            if (options.refresh) {
                this.resetPagination(true);
                this.fixedParameters = [
                    { Name: '@Start', Type: 'DATETIME', Value: new moment(params.start, 'MM/DD/YYYY').format('YYYY-MM-DD') },
                    { Name: '@End', Type: 'DATETIME', Value: new moment(params.end, 'MM/DD/YYYY').format('YYYY-MM-DD')  },
                    { Name: '@ShiftId', Type: 'INT', Value: params.shiftId != '-' ? params.shiftId : null },
                    { Name: '@CrewId', Type: 'CHAR', Value: params.crewId != '-' ? params.crewId : null },
                ];
            }
            this.isFetching = true;

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

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

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

                                newColl = _.map(records, that.model.prototype.parse);

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

                                if (options.reset)
                                    that.reset();

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

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

                                that.isFetching = false;
                            }
                            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); }
                    },
                    Secured: true,
                },
                app.ConnectionStrings.app
            );

            return this;
        },
        getNextPage: function (options) {
            if (!this.isFetching) {
                this.currentPage++;
                options = (_.isObject(options)) ? options : {};
                this.fetch(options);
            }
        },
        resetPagination: function (force) {
            if (!this.isFetching || force == true) {
                this.currentPage = 1;
            } else {
                _.delay(this.resetPagination, 100);
            }
        },
    })

    Screen.Views.Main = Backbone.Epoxy.View.extend({
        template: 'weights-report',
        id: 'weights-report',
        title: 'Weights Report',
        events: function () {
            return {
                'click #refreshBtn': this.refreshBtn_click,
                "click .btn-export-to-excel": this.exportToExcel,
            };
        },
        bindings: 'data-bind',

        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.items = new Screen.Collections.Items();

            this.bindEvents();
        },
        
        bindEvents: function () {
            this.listenTo(this.items, 'fetch', this.items_fetched);
        },


        render: function (container, urlParams) {
            var that = this;
            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.applyBindings();

                            that.$el.find('.input-date').datepicker();
                            var columns = [
                                {
                                    name: 'heatName',
                                    label: app.translate(that, 'item_heatName_col_label'),
                                    cell: Backgrid.StringCell.extend({
                                        className: 'string-cell align-center-cell',
                                    }),
                                    editable: false,
                                },

                                {
                                    name: 'shiftId',
                                    label: 'Shift',
                                    cell: Backgrid.StringCell.extend({
                                        className: 'string-cell align-center-cell',
                                    }),
                                    editable: false,
                                },
                                {
                                    name: 'crewId',
                                    label: 'Crew',
                                    cell: Backgrid.StringCell.extend({
                                        className: 'string-cell align-center-cell',
                                    }),
                                    editable: false,
                                },
                                {
                                    name: 'startTap',
                                    label: 'Start Tap',
                                    cell: Backgrid.StringCell.extend({
                                        className: 'string-cell align-center-cell',
                                    }),
                                    editable: false,
                                },
                                {
                                    name: 'endCast',
                                    label: 'End Cast',
                                    cell: Backgrid.StringCell.extend({
                                        className: 'string-cell align-center-cell',
                                    }),
                                    editable: false,
                                },
                                {
                                    name: 'steelWeight',
                                    label: app.translate(that, 'item_steelWeight_col_label'),
                                    cell: Backgrid.StringCell.extend({
                                        className: 'string-cell align-center-cell',
                                    }),
                                    editable: false,
                                },
                                {
                                    name: 'tareWeight',
                                    label: app.translate(that, 'item_tareWeight_col_label'),
                                    cell: Backgrid.StringCell.extend({
                                        className: 'string-cell align-center-cell',
                                    }),
                                    editable: false,
                                },                                
                                {
                                    name: 'alloyWeight',
                                    label: app.translate(that, 'item_alloyWeight_col_label'),
                                    cell: Backgrid.StringCell.extend({
                                        className: 'string-cell align-center-cell',
                                    }),
                                    editable: false,
                                },
                                {
                                    name: 'bucketScrapWeight',
                                    label: app.translate(that, 'item_bucketScrapWeight_col_label'),
                                    cell: Backgrid.StringCell.extend({
                                        className: 'string-cell align-center-cell',
                                    }),
                                    editable: false,
                                },
                                {
                                    name: 'bucketOtherWeight',
                                    label: app.translate(that, 'item_bucketOtherWeight_col_label'),
                                    cell: Backgrid.StringCell.extend({
                                        className: 'string-cell align-center-cell',
                                    }),
                                    editable: false,
                                },
                                                     
                               
                                {
                                    name: 'casterInitialGrossWeight',
                                    label: app.translate(that, 'item_casterInitialGrossWeight_col_label'),
                                    cell: Backgrid.StringCell.extend({
                                        className: 'string-cell align-center-cell',
                                    }),
                                    editable: false,
                                },
                                {
                                    name: 'casterFinalGrossWeight',
                                    label: app.translate(that, 'item_casterFinalGrossWeight_col_label'),
                                    cell: Backgrid.StringCell.extend({
                                        className: 'string-cell align-center-cell',
                                    }),
                                    editable: false,
                                },
                                {
                                    name: 'casterProcessedWeight',
                                    label: app.translate(that, 'item_casterProcessedWeight_col_label'),
                                    cell: Backgrid.StringCell.extend({
                                        className: 'string-cell align-center-cell',
                                    }),
                                    editable: false,
                                },
                                {
                                    name: 'productsWeight',
                                    label: app.translate(that, 'item_productsWeight_col_label'),
                                    cell: Backgrid.StringCell.extend({
                                        className: 'string-cell align-center-cell',
                                    }),
                                    editable: false,
                                },
                                {
                                    name: 'drainWeight',
                                    label: app.translate(that, 'item_drainWeight_col_label'),
                                    cell: Backgrid.StringCell.extend({
                                        className: 'string-cell align-center-cell',
                                    }),
                                    editable: false,
                                },
                                {
                                    name: 'pourbackWeight',
                                    label: app.translate(that, 'item_pourbackWeight_col_label'),
                                    cell: Backgrid.StringCell.extend({
                                        className: 'string-cell align-center-cell',
                                    }),
                                    editable: false,
                                },        
                               
                            ];
                            var grid = new Backgrid.Grid({
                                className: 'backgrid table table-hover table-condensed production-table',
                                collection: that.items,
                                footer: Backgrid.Extension.Infinator.extend({
                                    scrollToTop: false,
                                }),
                                columns: columns,
                               
                            });

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

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

                            var fixedParams = _.extend({}, urlParams);


                            if (fixedParams.start)
                                fixedParams.start = new moment(fixedParams.start, 'YYYYMMDD').format('MM/DD/YYYY');
                            if (fixedParams.end)
                                fixedParams.end = new moment(fixedParams.end, 'YYYYMMDD').format('MM/DD/YYYY');



                            that.model.set(fixedParams);

                            that.refresh(); 
                                                       
                        },
                        true,
                        customPath
                    );
                },
                customPath
            );
        },

        setExportButtonExporting: function (val) {
            var btn_export = this.$el.find('.btn-export-to-excel');
            var export_state = btn_export.find('.excel-export-state');
            var loading_state = btn_export.find('.loading-state');

            if (val) {
                export_state.css('display', 'none', 'important');
                loading_state.removeClass('hide');

                btn_export.attr('disabled', true);
            } else {
                loading_state.addClass('hide');
                export_state.css('display', 'inline-block', 'important');

                btn_export.attr('disabled', false);
            }
        },
        refresh: function () {
            this.model.set({
                isLoading: true,
                hasData: false,
            });
            params = this.model.toJSON();
            this.items.fetch({
                start: params.start,
                end: params.end,
                ladleFurnaceCode: params.ladleFurnaceCode,
                bucketId: params.bucketId,
                shiftId: params.shiftId,
                refresh: true,
            });
        },
        UpdateURL: function () {
            try {
                var params = this.model.toJSON();
                app.router.navigate(
                    app.router.resolveURL(
                        app.router.currentModule,
                        _.extend(
                            {},
                            params,
                            {
                                start: new moment(params.start, 'MM/DD/YYYY').format('YYYYMMDD'),
                                end: new moment(params.end, 'MM/DD/YYYY').format('YYYYMMDD'),
                                shiftId: params.shiftId,
                                crewId: params.crewId,
                            }
                        ),
                        false
                    ),
                    { trigger: false, }
                );
            }
            catch (e) { console.error((e.stack) ? e.stack : new Error(e).stack); }
        },

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

        items_fetched: function () {
            try {
                var that = this;
                setTimeout(
                    function () {
                        that.model.set({
                            hasData: (that.items.length > 0),
                            isLoading: false,
                        });

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


        exportToExcel: function () {
            var that = this,
                attrs = this.model.toJSON();
            that.setExportButtonExporting(true);
            var params = [
                { Name: '@start', Type: 'DATETIME', Value: new moment(attrs.start, 'MM/DD/YYYY').format('YYYY-MM-DD') },
                { Name: '@end', Type: 'DATETIME', Value: new moment(attrs.end, 'MM/DD/YYYY').format('YYYY-MM-DD') },
                { Name: '@shiftId', Type: 'INT', Value: attrs.shiftId != '-' ? attrs.shiftId : null },
                { Name: '@crewId', Type: 'CHAR', Value: attrs.crewId != '-' ? attrs.crewId : null },
                { Name: '@ExportToExcel', Type: 'BIT', Value: 1 },

                

            ];
            console.log("params", params);
            var QP = new QueryParameters();

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


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

            /* -------------------------------------------------------- 1st Table ------------------------------------------------------------ */
            data.Data.push({
                SheetName: 'Data',
                RowsData: [{
                    CellsData:
                        [
                            { Column: 'A', Value: 'Heat' },
                            { Column: 'B', Value: 'Shift' },
                            { Column: 'C', Value: 'Crew' },
                            { Column: 'D', Value: 'Start Tap' },
                            { Column: 'E', Value: 'End Cast' },
                            { Column: 'F', Value: 'Steel Weight' },
                            { Column: 'G', Value: 'Tare Weight' },
                            { Column: 'H', Value: 'Alloy Weight' },
                            { Column: 'I', Value: 'Bucket Scrap Weight' },
                            { Column: 'J', Value: 'Bucket Other Weight' },
                            { Column: 'K', Value: 'Caster Initial Gross Weight' },
                            { Column: 'L', Value: 'Caster Final Gross Weight' },
                            { Column: 'M', Value: 'Caster Processed Weight' },
                            { Column: 'N', Value: 'Products Weight' },
                            { Column: 'O', Value: 'Drain Weight' },
                            { Column: 'P', Value: 'Pourback Weight' },                           


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

            data.Data.push({
                SheetName: 'Data',
                RowsData: [],
                StartRowIndex: 2,
                DataSourceName: 'data',
                DataSourceTableIndex: 0,
                SQLCellsData:
                    [
                        { ExcelColumnName: 'A', SQLDataColumnName: 'HeatName', DataType: 'String' },
                        { ExcelColumnName: 'B', SQLDataColumnName: 'ShiftId', DataType: 'String' },
                        { ExcelColumnName: 'C', SQLDataColumnName: 'CrewId', DataType: 'String' },
                        { ExcelColumnName: 'D', SQLDataColumnName: 'StartTap', DataType: 'String' },
                        { ExcelColumnName: 'E', SQLDataColumnName: 'EndCast', DataType: 'String' },
                        { ExcelColumnName: 'F', SQLDataColumnName: 'SteelWeight', DataType: 'Float' },
                        { ExcelColumnName: 'G', SQLDataColumnName: 'TareWeight', DataType: 'Float' },
                        { ExcelColumnName: 'H', SQLDataColumnName: 'AlloyWeight', DataType: 'Float' },
                        { ExcelColumnName: 'I', SQLDataColumnName: 'BucketScrapWeight', DataType: 'Float' },
                        { ExcelColumnName: 'J', SQLDataColumnName: 'BucketOtherWeight', DataType: 'Float' },
                        { ExcelColumnName: 'K', SQLDataColumnName: 'CasterInitialGrossWeight', DataType: 'Float' },
                        { ExcelColumnName: 'L', SQLDataColumnName: 'CasterFinalGrossWeight', DataType: 'Float' },
                        { ExcelColumnName: 'M', SQLDataColumnName: 'CasterProcessedWeight', DataType: 'Float' },
                        { ExcelColumnName: 'N', SQLDataColumnName: 'ProductsWeight', DataType: 'Float' },
                        { ExcelColumnName: 'O', SQLDataColumnName: 'DrainWeight', DataType: 'Float' },
                        { ExcelColumnName: 'P', SQLDataColumnName: 'PourbackWeight', DataType: 'Float' },


                    ],
            });

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

                                that.setExportButtonExporting(false);
                            }
                            else {
                                console.error('Server response not valid.');

                                that.setExportButtonExporting(false);
                            }
                        }
                    }
                    catch (Error) {

                        that.setExportButtonExporting(false);
                        console.error(Error);
                    }

                    that.setExportButtonExporting(false);
                },
                function (resp) {
                    that.model.refreshProcesses();
                    that.setExportButtonExporting(false);
                    console.error(resp);

                }
            );
        },

        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 {
                this.refresh(viewParams);
            } catch (Error) { }
        },

    });

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