
define([   
    'app',
    'js/templates-loader',
    'moment',
    'components/ag-grid/ag-grid-module',
    'components/modal-assign-melt-order-grade/modal-assign-melt-order-grade',
    'js/multiselect/virtual-select.min'
],
    function (app, T, moment, AgGridModule, AssignMeltOrderGrade) {

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

        Screen.Models.Main = Backbone.Epoxy.Model.extend({
            defaults: {
                screenTitle: 'Melt Orders Assignments',
                isLoading: false,
                renderCompleted: false,
                heatName: '',
                productsFromSDIColl: null,
                currentMeltOrder: null,
                currentGrade:'',
                hideAssignBtn: true,

            },
            fetchCatalogs: function () {
                var that = this;
                var qp = new Core.Database.QueryParameters();
                qp.Add('@HeatName', 'VARCHAR(10)', that.get('heatName'));
                qp.Add('@Asset', 'CHAR(3)', 'CAS');
                Core.Json.CallProcedure(
                    app.DatabaseNames.MES + '.MES.GetAutocompleteHeats',
                    qp,
                    {
                        onSuccess: function (resp) {
                            try {
                                if (resp && resp.Table) {
                                    that.set({
                                        heatNames: resp.Table,
                                        heatName: resp.Table[0] && resp.Table[0].value ? resp.Table[0].value : '',
                                        processId: resp.Table[0] && resp.Table[0].processId ? resp.Table[0].processId : null,
                                    });
                                    that.trigger('catalogs-fetched');
                                }
                                else {
                                    if ((resp) && (resp.Message)) {
                                        app.views.topMessages.showMessage(resp.Message, { stay: 5000, });
                                        console.error(resp.Message);
                                        that.set({
                                            hasData_process: false,
                                            isLoading_process: false,
    
    
                                        });
                                    }
                                    else {
                                        app.views.topMessages.showMessage("Server response not valid.", { stay: 5000, });
                                        console.error("Server response not valid.");
                                        that.set({
                                            hasData_process: false,
                                            isLoading_process: false,
                                        });
                                    }
    
                                }
    
    
                            }
                            catch (error) { console.error((error.stack) ? error.stack : new Error(error).stack); }
                        },
                        Secured: true,
                        Async: false,
                    },
                    app.ConnectionStrings.app
                );
            },

            fetch: function (params) {
                var that = this,
                    qp = new Core.Database.QueryParameters();
                var fixedParameters = [
                    { Name: '@HeatName', Type: 'VARCHAR', Value: that.get('heatName'), }
                ];
                _.each(fixedParameters, function (qpParams) {
                    qp.Add(qpParams.Name, qpParams.Type, qpParams.Value);
                });

                var coll = null;

                Core.Json.CallProcedure(
                    app.DatabaseNames.SDIXFER + '.MES.Get_MESvsSDIProductComparison',
                    qp,
                    {
                        onSuccess: function (resp) {
                            try {
                                if (resp) {       
                                    if (resp.Table) {
                                        coll = new Backbone.Collection(resp.Table);
                                        that.set({
                                            productsFromMESColl:coll,
                                            currentMeltOrder:resp.Table[0].MeltOrder,
                                            currentGrade: resp.Table[0].Grade
                                        }); 
                                        
                                    }
                                    if (resp.Table1) {
                                        coll = new Backbone.Collection(resp.Table1);                                        
                                        that.set({productsFromSDIColl:coll});         
                                    }

                                    that.trigger('fetch-collections-ready');
                                    
                                }
                                else {
                                    if ((resp) && (resp.Message)) {
                                        console.error(new Error(resp.Message).stack);
                                        app.views.topMessages.showMessage('CALL TO DATABASE FAILED', { stay: 5000, });
                                    }
                                    else {
                                        app.views.topMessages.showMessage('SERVER RESPONSE NOT VALID', { stay: 5000, });
                                        console.error(new Error('SERVER_RESPONSE_NOT_VALID').stack);
                                    }
                                }
                            }
                            catch (e) { console.error((e.stack) ? e.stack : new Error(e).stack); }
                        },
                        onFailure: function (resp) {
                            console.error(resp);
                        },
                        Secured: true,
                        Async: true,
                    },
                    app.ConnectionStrings.app
                );
                return this;
            },
            
           
        });


        var CustomAgGridModule = AgGridModule.extend({
            initialize: function(options) {
                AgGridModule.prototype.initialize.call(this, options);
        
                // Override or add gridOptions to include onSelectionChanged
                const originalGridOptions = options.gridOptions || {};
                this.gridOptions = {
                    ...this.gridOptions,
                    ...originalGridOptions,
                    onSelectionChanged: this.onSelectionChanged.bind(this) // Bind custom method
                };

                this.columnDefs.unshift({
                    headerCheckboxSelection: options.headerCheckboxSelection != null ?  options.headerCheckboxSelection : false, // Global select-all checkbox
                    checkboxSelection: options.checkboxSelection != null ? options.checkboxSelection : false, // Checkbox for each row
                    headerCheckboxSelectionFilteredOnly: true, // Apply only to visible/filtered rows
                    width: 50,
                    pinned: 'left',
                    lockPosition: true,
                    suppressSizeToFit: true
                });

            },
       
            
            onSelectionChanged: function(event) {
                // Get selected rows
                const selectedRows = this.getGridApi().getSelectedRows();
                // Trigger a custom Backbone event with the selected rows
                this.trigger('selection:changed', selectedRows);
            },
        
            getGridApi: function () {
                return AgGridModule.prototype.getGridApi.call(this);
            },
            // New method to clear selected rows
            clearSelectedRows: function() {
                const gridApi = this.getGridApi();
                if (gridApi) {
                    gridApi.deselectAll();
                } else {
                    console.warn("Grid API is not available to clear selections");
                }
            },
      
        });
      

        Screen.Views.Main = Backbone.Epoxy.View.extend({
            template: 'melt-orders-assignments',
            id: 'melt-orders-assignments',
            title: 'Melt Orders Assignments',
            events: function () {
                return {
                    'click #refreshBtn': this.refreshBtn_click,
                    'click #refreshBtnRt': this.refreshBtnRt_click,
                    'click #assignBtn': this.assignBtn_click,
                   
                };
            },
            bindings: 'data-bind',
            bindingSources: {},
            subviews: {},
            viewParams: null,              
            AssignMeltOrderGrade : {},
           
            columnsProductsFromSDI : [
                { field: 'PIECE_ID', headerName: 'Product', flex: 1, showFilter: false },
                { field: 'HEAT_ID', headerName: 'Heat', flex: 1, showFilter: false },
                { field: 'STRAND', headerName: 'Strand', flex: 1, showFilter: true },
                { field: 'PIECE_INDEX', headerName: 'Sequence', flex: 1, showFilter: true },
                { field: 'MELT_ORDER_ID', headerName: 'Melt Order', flex: 1, showFilter: false },
                { field: 'GRADE_ID', headerName: 'Grade', minWidth: 200, showFilter: false },
               
            ],  
  
           
            initialize: function () {
                var that = this;
                this.options.state = app.view_states.loading;
                this.options.onappend = (_.isFunction(this.options.onappend)) ? this.options.onappend : function () { };              
                
                if (!this.model) this.model = new Screen.Models.Main();

               

                // ------------------- 
                // -- AgGrid instances --                
                // ------------------- 
                // Products from SDI      
                if (!this.agGridModuleProductsFromSDI) {      
                    this.agGridModuleProductsFromSDI = new CustomAgGridModule({
                        columnDefs: this.columnsProductsFromSDI,
                        rowData: [],
                        fileName:'melt-orders-assignments-products-from-sdi',
                        headerCheckboxSelection: true,
                        checkboxSelection: true,
                        pagination: 'hidden',
                        allowMultipleSelection: true, // Enable or disable multiple row selection
                        suppressRowClickSelection: true
                    });
                }
               
                this.bindEvents();
            },

            bindEvents: function () {
                this.listenTo(this.model,'fetch-collections-ready',this.fetchCollections_ready);
                this.listenTo(this.agGridModuleProductsFromSDI, 'selection:changed', this.agGridModuleProductsFromSDI_changed);
                this.listenTo(this.model, 'change:hideAssignBtn', this.disableEnableAssignBtn);
            },
            disableEnableAssignBtn: function() {
                var that = this;

                // Get the value of 'hideAssignBtn' from the model
                var isHidden = that.model.get('hideAssignBtn');

                // Find the button by its ID
                var assignButton = document.getElementById('assignBtn');

                // Enable or disable the button based on 'hideAssignBtn' value
                if (isHidden) {
                    assignButton.setAttribute('disabled', 'disabled'); // Disable the button
                    assignButton.classList.add('opacity-50', 'cursor-not-allowed'); // Add Tailwind classes for visual feedback
                } else {
                    assignButton.removeAttribute('disabled'); // Enable the button
                    assignButton.classList.remove('opacity-50', 'cursor-not-allowed'); // Remove visual feedback classes
                }
                
            },
            destroyPage: function() {
                this.agGridModuleProductsFromSDI.destroy();
                // Select the div
                const div = document.querySelector('.grid-container-products-from-sdi');
                // Remove its content
                div.innerHTML = ''; // Clears all content inside the div
                
            },
            agGridModuleProductsFromSDI_changed: function(){
                const selectedRows = this.agGridModuleProductsFromSDI.getGridApi().getSelectedRows();
                
                // Check if at least one row is selected
                const isRowSelected = selectedRows.length > 0;
                if (isRowSelected) this.model.set({hideAssignBtn: false});
                else this.model.set({hideAssignBtn: true});

            },
            fetchCollections_ready: function(){
                var model = this.model.toJSON();
                var that = this;

                const { productsFromSDIColl } = model;

                if (productsFromSDIColl)
                    that.agGridModuleProductsFromSDI.setRowDataAsCollection(productsFromSDIColl);
                else
                that.agGridModuleProductsFromSDI.setRowDataAsCollection([]);
                
                
                that.model.set({
                    isLoading: false
                });      
                

            },

            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/pages/caster/' + 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();

                               
                                that.$el.find('.input-date').datepicker();                         


                                that.agGridModuleProductsFromSDI.render();
                                that.$el.find('.grid-container-products-from-sdi').append(that.agGridModuleProductsFromSDI.$el);
                                                            

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

                               
                                var fixedParams = _.extend({}, viewParams);
                                if (fixedParams && fixedParams.heatName && fixedParams.heatName.length === 7) {
                                    that.model.set(fixedParams);
                                } else {
                                    that.UpdateURL();
                                }


                                //Call first refresh.
                                var params = that.model.toJSON();
                                that._refresh({
                                    reset: true,
                                    params: _.extend(
                                        {},
                                        params,
                                        {
                                        }
                                    ),
                                });

                                
                                
                         
                                // Render the catalogs and the data after getting the url heat name
                                that.model.fetchCatalogs();
                              
                                if (!fixedParams.heatName){
                                    that.refresh();
                                    that.UpdateURL();
                                }

                                
                                that.renderMultipicker();
                                that.disableEnableAssignBtn();
                            },
                            true,
                            customPath
                        );
                    },
                    customPath
                );
            },

            // ------------------------
            // -------- History -------
            // ------------------------
            refresh: function (viewParams) {

                var fixedParams = {heatName: this.model.get('heatName')};

                this._refresh({
                    reset: true,
                    params: _.extend(
                        {},
                        fixedParams,
                        {}
                    ),
                });
            },
     
            _refresh: function (opt) {
                var that = this;
                var model = this.model.toJSON();
                // Reset collections:
                if (model && model.productsFromSDIColl)
                    that.model.get('productsFromSDIColl').reset();
             

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

                this.model.set('isLoading', true);
                that.agGridModuleProductsFromSDI.showLoadingOverlay();
                this.model.fetch();        

            },
        
            refreshBtn_click: function (e) {
                try {
                    var params = this.model.toJSON();                  

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

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





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

            },

            onSampleSelectServerSearch: function (searchValue, virtualSelect) {
                var qp = new Core.Database.QueryParameters();
                qp.Add('@HeatName', 'VARCHAR(10)', searchValue);
                qp.Add('@SelectedHeatName', 'VARCHAR(10)', this.selectedValues[0]);
                qp.Add('@Asset', 'CHAR(3)', 'CAS');
                Core.Json.CallProcedure(
                    app.DatabaseNames.MES + '.MES.GetAutocompleteHeats',
                    qp,
                    {
                        onSuccess: function (resp) {
                            try {
                                virtualSelect.setServerOptions(resp.Table);

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

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

                    app.router.navigate(
                        app.router.resolveURL(
                            app.router.currentModule,
                            _.extend(
                                {},
                                params,
                                {
                                    heatName: params.heatName,
                                }
                            ),
                            false
                        ),
                        { trigger: false, }
                    );
                }
                catch (e) { console.error((e.stack) ? e.stack : new Error(e).stack); }
            },
            
       
            
            // ---------------------------------
            // -------- Common functions -------
            // ---------------------------------

            //Common functions
            append: function (container, el) {
                var that = this;
                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);

                    setTimeout(function() {
                        that.model.set({renderCompleted: true});
                    }, 1000);  
                }

                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.destroyPage();
                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) { }
            },
         
            assignBtn_click: function() {
                var that = this;
                var currentMeltOrder = this.model.get('currentMeltOrder');
                var currentGrade = this.model.get('currentGrade');
                const selectedRows = this.agGridModuleProductsFromSDI.getGridApi().getSelectedRows();
                this.AssignMeltOrderGrade = new AssignMeltOrderGrade.Views.AssignMeltOrderGrade({
                    parent: this,
                    bus: null,
                    meltOrder: currentMeltOrder,
                    grade:currentGrade,
                    selectedProducts: selectedRows,
                });
                this.listenTo(that.AssignMeltOrderGrade, 'close', function () {
                    try {
                        that.model.set({hideAssignBtn:true});
                        that.agGridModuleProductsFromSDI.clearSelectedRows();
                        
                        var params = this.model.toJSON();                  

                        this._refresh({
                            reset: true,
                            params: _.extend(
                                {},
                                params,
                                {}
                            ),
                        });
                    }
                    catch (e) { console.error((e.stack) ? e.stack : new Error(e).stack); }
                });
                this.AssignMeltOrderGrade.show();

            },            
        });

        Screen.Collections.Items = Backbone.Collection.extend({
            fetch: function (params) {
                var that = this,
                    qp = new Core.Database.QueryParameters();

                var fixedParameters = [
                    { Name: '@HeatName', Type: 'VARCHAR', Value: 'A244639', }
                ];
                _.each(fixedParameters, function (qpParams) {
                    qp.Add(qpParams.Name, qpParams.Type, qpParams.Value);
                });


                Core.Json.CallProcedure(
                    app.DatabaseNames.SDIXFER + '.MES.Get_MESvsSDIProductComparison',
                    qp,
                    {
                        onSuccess: function (resp) {
                            try {
                                if ((resp) && (resp.Table)) {                                    
                                    that.set(resp.Table);
                                    that.trigger('fetch', that,resp);
                                }
                                else {
                                    if ((resp) && (resp.Message)) {
                                        console.error(new Error(resp.Message).stack);
                                        app.views.topMessages.showMessage('CALL TO DATABASE FAILED', { stay: 5000, });
                                    }
                                    else {
                                        app.views.topMessages.showMessage('SERVER RESPONSE NOT VALID', { stay: 5000, });
                                        console.error(new Error('SERVER_RESPONSE_NOT_VALID').stack);
                                    }
                                }
                            }
                            catch (e) { console.error((e.stack) ? e.stack : new Error(e).stack); }
                        },
                        onFailure: function (resp) {
                            console.error(resp);
                        },
                        Secured: true,
                        Async: true,
                    },
                    app.ConnectionStrings.app
                );
                return this;
            },

        });


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