//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,
            casters: [{ label: '1', value: 1 }, { label: '2', value: 2 }],
            casterId: '-',
        },
    });

    Screen.Models.Item = Backbone.Epoxy.Model.extend({
        parse: function (obj) {

            var result = {              

                 
                castStart: obj.CastStart ? new moment(obj.CastStart).format('MM/DD HH:mm'): null,
                castEnd: obj.CastEnd ? new moment(obj.CastEnd).format('MM/DD HH:mm'): null, 
                casterCode: obj.CasterCode ? obj.CasterCode : null,           
                skullWeight: obj.SkullWeight ? obj.SkullWeight.toFixed(2)           : null,           
                kerfLoss: obj.KerfLoss ? obj.KerfLoss.toFixed(2)              : null,           
                primeWeight: obj.PrimeWeight ? obj.PrimeWeight.toFixed(2)               : null,           
                headCropWeight: obj.HeadCropWeight ? obj.HeadCropWeight.toFixed(2)           : null,           
                tailCropWeight: obj.TailCropWeight ? obj.TailCropWeight.toFixed(2) : null,    


                steelWeight: obj.SteelWeight ? obj.SteelWeight.toFixed(2) : null, 
                alloyWeight: obj.AlloyWeight ? obj.AlloyWeight.toFixed(2) : null, 
                bucketScrapWeight: obj.BucketScrapWeight ? obj.BucketScrapWeight.toFixed(2) : null, 
                bucketOtherWeight: obj.BucketOtherWeight ? obj.BucketOtherWeight.toFixed(2) : 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: '@CasterCode', Type: 'INT', Value: params.casterId != '-' ? params.casterId : null },
                   
                ];
            }
            console.log("fixedParameters", this.fixedParameters);
            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.GetSequenceWeightsReport',
                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: 'sequence-weights-report',
        id: 'sequence-weights-report',
        title: 'Sequence 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: 'castStart',
                                    label: 'Cast Start',
                                    cell: Backgrid.StringCell.extend({
                                        className: 'string-cell align-center-cell',
                                    }),
                                    editable: false,
                                },

                                {
                                    name: 'castEnd',
                                    label: 'Cast End',
                                    cell: Backgrid.StringCell.extend({
                                        className: 'string-cell align-center-cell',
                                    }),
                                    editable: false,
                                },
                                {
                                    name: 'casterCode',
                                    label: 'Caster',
                                    cell: Backgrid.StringCell.extend({
                                        className: 'string-cell align-center-cell',
                                    }),
                                    editable: false,
                                },

                                {
                                    name: 'primeWeight',
                                    label: 'Prime Weight',
                                    cell: Backgrid.StringCell.extend({
                                        className: 'string-cell align-center-cell',
                                    }),
                                    editable: false,
                                },

                                {
                                    name: 'steelWeight',
                                    label: 'Steel Weight',
                                    cell: Backgrid.StringCell.extend({
                                        className: 'string-cell align-center-cell',
                                    }),
                                    editable: false,
                                },

                                {
                                    name: 'alloyWeight',
                                    label: 'Alloy Weight',
                                    cell: Backgrid.StringCell.extend({
                                        className: 'string-cell align-center-cell',
                                    }),
                                    editable: false,
                                },

                                {
                                    name: 'bucketScrapWeight',
                                    label: 'Bucket Scrap Weight',
                                    cell: Backgrid.StringCell.extend({
                                        className: 'string-cell align-center-cell',
                                    }),
                                    editable: false,
                                },
                                {
                                    name: 'bucketOtherWeight',
                                    label: 'Bucket Other Weight',
                                    cell: Backgrid.StringCell.extend({
                                        className: 'string-cell align-center-cell',
                                    }),
                                    editable: false,
                                },
                                {
                                    name: 'skullWeight',
                                    label: 'Skull Weight',
                                    cell: Backgrid.StringCell.extend({
                                        className: 'string-cell align-center-cell',
                                    }),
                                    editable: false,
                                },
                                {
                                    name: 'kerfLoss',
                                    label: 'Kerf Loss',
                                    cell: Backgrid.StringCell.extend({
                                        className: 'string-cell align-center-cell',
                                    }),
                                    editable: false,
                                },
                                {
                                    name: 'headCropWeight',
                                    label: 'Head Crop Weight',
                                    cell: Backgrid.StringCell.extend({
                                        className: 'string-cell align-center-cell',
                                    }),
                                    editable: false,
                                },                                
                                {
                                    name: 'tailCropWeight',
                                    label: 'Tail Crop Weight',
                                    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,
                casterId: params.casterId,
                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: '@CasterCode', Type: 'INT', Value: attrs.casterId != '-' ? attrs.casterId : 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: 'sequence-weights-report',
                TemplateFileFullPath: 'generic.xls',
                SQLDataSources: [
                    {
                        Name: 'data',
                        DatabaseParameters: {
                            DBEngine: 'SQLSERVER',
                            Procedure: app.DatabaseNames.MES + '.MES.GetSequenceWeightsReport',
                            QueryParameters: QP,
                        },
                    },
                ]
            };

            /* -------------------------------------------------------- 1st Table ------------------------------------------------------------ */
            data.Data.push({
                SheetName: 'Data',
                RowsData: [{
                    CellsData:
                        [
                            { Column: 'A', Value: 'Cast Start' },
                            { Column: 'B', Value: 'Cast End' },
                            { Column: 'C', Value: 'Caster Code' },
                            { Column: 'D', Value: 'Prime Weight' },
                            { Column: 'E', Value: 'Steel Weight' },
                            { Column: 'F', Value: 'Alloy Weight' },
                            { Column: 'G', Value: 'Bucket Scrap Weight' },
                            { Column: 'H', Value: 'Bucket Other Weight' },
                            { Column: 'I', Value: 'Skull Weight' },
                            { Column: 'J', Value: 'Kerf Loss' },
                            { Column: 'K', Value: 'Head Crop Weight' },
                            { Column: 'L', Value: 'Tail Crop Weight' },                     


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

            data.Data.push({
                SheetName: 'Data',
                RowsData: [],
                StartRowIndex: 2,
                DataSourceName: 'data',
                DataSourceTableIndex: 0,
                SQLCellsData:
                    [
                        { ExcelColumnName: 'A', SQLDataColumnName: 'CastStart', DataType: 'String' },
                        { ExcelColumnName: 'B', SQLDataColumnName: 'CastEnd', DataType: 'String' },
                        { ExcelColumnName: 'C', SQLDataColumnName: 'CasterCode', DataType: 'String' },
                        { ExcelColumnName: 'D', SQLDataColumnName: 'PrimeWeight', DataType: 'String' },
                        { ExcelColumnName: 'E', SQLDataColumnName: 'SteelWeight', DataType: 'String' },
                        { ExcelColumnName: 'F', SQLDataColumnName: 'AlloyWeight', DataType: 'Float' },
                        { ExcelColumnName: 'G', SQLDataColumnName: 'BucketScrapWeight', DataType: 'Float' },
                        { ExcelColumnName: 'H', SQLDataColumnName: 'BucketOtherWeight', DataType: 'Float' },
                        { ExcelColumnName: 'I', SQLDataColumnName: 'SkullWeight', DataType: 'Float' },
                        { ExcelColumnName: 'J', SQLDataColumnName: 'KerfLoss', DataType: 'Float' },
                        { ExcelColumnName: 'K', SQLDataColumnName: 'HeadCropWeight', DataType: 'Float' },
                        { ExcelColumnName: 'L', SQLDataColumnName: 'TailCropWeight', 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;
});