define([
    'app',
    'js/templates-loader',
    'js/multiselect/virtual-select.min'
],

    function (app, T ) {

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

        Screen.Models.AssignMeltOrderGrade = Backbone.Epoxy.Model.extend({
            defaults: {
                meltOrders: null,
                meltOrderId:null,
                meltOrder: null, 

                grades: null,
                gradeId: null,
                grade: null,

                selectedProducts: [],

                isMeltOrderDisabled: false,
                isGradeDisabled: true,

                disableAssignBtn : true
            },         
            fetchCatalogs: function () {
                var that = this;
                var qp = new Core.Database.QueryParameters();
                qp.Add('@AutocompleteMeltOrders', 'BIT', 1);
                qp.Add('@SelectedMeltOrder','VARCHAR(200)',that.get('meltOrder'));
                qp.Add('@AutocompleteGrades', 'BIT', 1);
                qp.Add('@SelectedGrade','VARCHAR(200)',that.get('grade'));
                Core.Json.CallProcedure(
                    app.DatabaseNames.MES + '.MES.GetAutocompleteMeltOrdersAndGrades',
                    qp,
                    {
                        onSuccess: function (resp) {
                            try {
                                if (resp && resp.Table) {
                                    that.set({
                                        meltOrders: resp.Table,
                                        meltOrder: resp.Table[0] && resp.Table[0].value ? resp.Table[0].value : '',
                                    });
                                    that.set({
                                        grades: resp.Table1,
                                        grade: resp.Table1[0] && resp.Table1[0].value ? resp.Table1[0].value : '',
                                    });
                                    
                                }
                                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
                );
            },
     
            updateMeltOrderAndGrade: function () {
                try {
                    var that = this;
                    qp = new Core.Database.QueryParameters();
                    const model = that.toJSON();
                    const selectedProducts = model.selectedProducts;
                    
                    const currentMeltOrder = that.get('currentMeltOrder');
                    const currentGrade = that.get('currentGrade');

                    const modifyMeltOrder = that.get('meltOrder') === currentMeltOrder ? false : true;
                    const modifyGrade = that.get('grade') === currentGrade? false : true


                    qp.Add('LayoutProducts','XML',app.jsonArrayToXml(
                            selectedProducts,
                            [
                                'MESSAGE_ID',
                            ]
                        )
                    );
                    qp.Add('MeltOrder','VARCHAR',that.get('meltOrder'));
                    qp.Add('ModifyMeltOrder','BIT', modifyMeltOrder);
                    
                    qp.Add('Grade','VARCHAR',that.get('grade'));
                    qp.Add('ModifyGrade','BIT',modifyGrade);
                
                    _.each(this.fixedParameters, function (qpParams) {
                        qp.Add(qpParams.Name, qpParams.Type, qpParams.Value);
                    });
                    Core.Json.CallProcedure(
                        app.DatabaseNames.SDIXFER + '.MES.Change_ProductMeltOrderAndGrade',
                        qp,
                        {
                            onSuccess: function (resp) {
                                try {
                                    if (!resp.Message) {
                                        if (modifyMeltOrder && modifyGrade)
                                            app.views.topMessages.showMessage('Melt Order and Grade Successfully Updated', { stay: 5000, });
                                        else if (modifyMeltOrder && !modifyGrade)
                                            app.views.topMessages.showMessage('Melt Order Successfully Updated', { stay: 5000, });
                                        else if (!modifyMeltOrder && modifyGrade)
                                            app.views.topMessages.showMessage('Grade Successfully Updated', { stay: 5000, });

                                    }
                                    else {
                                        if ((resp) && (resp.Message)) {
                                            app.views.topMessages.showMessage(resp.Message, { stay: 5000, });
                                            console.error(resp.Message);
                                        }
                                        else {
                                            app.views.topMessages.showMessage("Server response not valid.", { stay: 5000, });
                                            console.error("Server response not valid.");
                                        }
                                    }
                                }
                                catch (e) { console.error((e.stack) ? e.stack : new Error(e).stack); }
                            },
                            onFailure: function (resp) {
                                console.error(resp);
                            },
                            Secured: true,
                            Async: false,
                        },
                        app.ConnectionStrings.app
                    );
                }
                catch (e) { console.error((e.stack) ? e.stack : new Error(e).stack); }
            },
        });
        Screen.Views.AssignMeltOrderGrade = Backbone.Epoxy.View.extend({
            template: "modal-assign-melt-order-grade",
            className: "modal hide fade",
            bindings: "data-bind",
            title: "Assing Melt Order Grade",
            isCacheable: true,
            events: function () {
                return {
                    "click #acceptBtn": this.acceptBtn_click,
                    "click #cancelBtn": this.close,
                    "submit form": this.form_submit,
                    "keypress": this.modal_keypress,
                    "show.bs.modal": this.modal_show,
                    "shown.bs.modal": this.modal_shown,
                    "hidden.bs.modal": this.modal_hidden,
                    "click .close": this.close,
                };
            },
            container: null,
            disposed: false,
            isRendered: false,
            preventDispose: false,
            visible: false,
            row: [],
            grid: [],
            initialize: function (options) {
                _.extend(this, options);
                if (!this.model) {
                    this.model = new Screen.Models.AssignMeltOrderGrade();
                }
        
                this.bus = options.bus;
                this.model.set({
                    parentModel: options.parent,
                    meltOrder: options.meltOrder,
                    grade: options.grade,
                    currentMeltOrder: options.meltOrder,
                    currentGrade: options.grade,
                    selectedProducts: options.selectedProducts
                });
                this.model.fetchCatalogs(); // this goes in the views main init after getting the mo and grade from options
                
               
                this.parent = options.parent;
                this.bindEvents();
                var that = this;

                return this;
            },

            bindEvents: function () {
                var that = this;
                this.listenToOnce(that, "render", that.view_render);
                this.listenTo(this.model, 'change:meltOrder', this.setStatusAssignBtn);
                this.listenTo(this.model, 'change:grade', this.setStatusAssignBtn);
;

            },

            setStatusAssignBtn: function(){
                var that = this;
                const currentMeltOrder = that.model.get('currentMeltOrder');
                const currentGrade = that.model.get('currentGrade');

                const modifyMeltOrder = that.model.get('meltOrder') === currentMeltOrder ? false : true;
                const modifyGrade = that.model.get('grade') === currentGrade? false : true

                if (modifyMeltOrder || modifyGrade)
                    that.model.set({disableAssignBtn: false})
                else 
                    that.model.set({disableAssignBtn: true});
            },

            hide: function (preventDispose) {
                this.preventDispose = (preventDispose);

                this.$el.modal('hide');

            },
            render: function (container) {
                if (container)
                    this.container = container;

                var that = this;
                var customPath = '/app/components/modal-assign-melt-order-grade/';
                T.render.call(this, this.template, function (tmp) {
                    if (!that.i18n) that.i18n = {};
                    app.getI18NJed(that, that.template, function (i18nJED) {
                        that.i18n[that.template] = i18nJED;
                        that.$el.html(tmp(that.model.toJSON()));
                        that.applyBindings();

                        that.isRendered = true;

                        that.trigger("render");
                       
                    }, true, customPath);

                }, customPath, "assign_melt_order_grade");

            },

                
            // ----------------------------------
            // -------- Melt Order Picker -------
            // ----------------------------------
            renderMeltOrderPicker: function () {
                var that = this;
                let moPicker = new VirtualSelect.init({
                    ele: '#melt-order-multi-select',
                    options: that.model.get('meltOrders'),
                    multiple: false,
                    search: true,
                    placeholder: 'Select Melt Order',
                    hasOptionDescription: false,
                    showSelectedOptionsFirst: true,
                    hideClearButton: true,
                    onServerSearch: that.onSampleSelectServerSearchMeltOrder,
                });
                var mo = that.model.get('meltOrder');
                if (document.querySelector('#melt-order-multi-select')){
                    document.querySelector('#melt-order-multi-select').setOptions(that.model.get('meltOrders'));
                    document.querySelector('#melt-order-multi-select').setValue(mo);
                    document.querySelector('#melt-order-multi-select').addEventListener('change', function () {
                        $('.vscomp-search-clear').click();
                        if (this.value === that.model.get('meltOrder')) {
                            return 0;
                        }
                        else {
                            var newMeltOrder = this.value;
                            if (newMeltOrder && newMeltOrder != '') {
                                that.model.set({
                                    meltOrder: newMeltOrder
                                });
                            }
                        }
                    });
                }
                

            },

            onSampleSelectServerSearchMeltOrder: function (searchValue, virtualSelect) {
                var qp = new Core.Database.QueryParameters();
                qp.Add('@MeltOrder', 'VARCHAR(200)', searchValue);                
                qp.Add('@SelectedMeltOrder','VARCHAR(200)',this.selectedValues[0]);
                // qp.Add('@SelectedHeatName', 'VARCHAR(10)', this.selectedValues[0]);
                qp.Add('@AutocompleteMeltOrders', 'BIT', 1);
                Core.Json.CallProcedure(
                    app.DatabaseNames.MES + '.MES.GetAutocompleteMeltOrdersAndGrades',
                    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
                );
            },    



            // ----------------------------------
            // -------- Grade Picker -------
            // ----------------------------------
            renderGradePicker: function () {
                var that = this;
                let gradePicker = new VirtualSelect.init({
                    ele: '#grade-multi-select',
                    options: that.model.get('grades'),
                    multiple: false,
                    search: true,
                    placeholder: 'Select Grade',
                    hasOptionDescription: false,
                    showSelectedOptionsFirst: true,
                    hideClearButton: true,
                    onServerSearch: that.onSampleSelectServerSearchGrade,
                });
                var grade = that.model.get('grade');
                if (document.querySelector('#grade-multi-select')){
                    document.querySelector('#grade-multi-select').setOptions(that.model.get('grades'));
                    document.querySelector('#grade-multi-select').setValue(grade);
                    document.querySelector('#grade-multi-select').addEventListener('change', function () {
                        $('.vscomp-search-clear').click();
                        if (this.value === that.model.get('grade')) {
                            return 0;
                        }
                        else {
                            var newGrade = this.value;
                            if (newGrade && newGrade != '') {
                                that.model.set({
                                    grade: newGrade
                                });
                            }
                        }
                    });
                }
                

            },

            onSampleSelectServerSearchGrade: function (searchValue, virtualSelect) {
                var qp = new Core.Database.QueryParameters();
                qp.Add('@Grade', 'VARCHAR(200)', searchValue);
                // qp.Add('@SelectedHeatName', 'VARCHAR(10)', this.selectedValues[0]);
                qp.Add('@AutocompleteGrades', 'BIT', 1);
                Core.Json.CallProcedure(
                    app.DatabaseNames.MES + '.MES.GetAutocompleteMeltOrdersAndGrades',
                    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
                );
            },    

            // common functions
            show: function () {
                if (!this.isRendered) {

                    this.render();
                }
                else {
                    this.$el.modal({
                        keyboard: true,
                        backdrop: 'both',
                    });
                }

                return this;
            },

        
            cancelBtn_click: function() {
                this.close();
            },

            close: function () {
                if (this.disposed == false) {
                    if (this.visible == true) {
                        this.hide();
                    }
                    else {
                        this.trigger('close');

                        this.remove();
                        this.unbind();

                        this.disposed = true;
                    }
                }
            },
            preRender: function () {
            },
            reRender: function () {
            },

            acceptBtn_click: function () {
                try {
                    var that = this;
                    that.model.updateMeltOrderAndGrade()

                    this.close();

                }
                catch (e) { console.error((e.stack) ? e.stack : new Error(e).stack); }
            },
            form_submit: function (e) {
                try {
                    e.preventDefault();
                }
                catch (e) { console.error((e.stack) ? e.stack : new Error(e).stack); }
            },
            modal_hidden: function (e) {
                try {
                    this.visible = false;

                    if (!this.preventDispose)
                        this.close();
                    else
                        this.preventDispose = false;
                }
                catch (e) { console.error((e.stack) ? e.stack : new Error(e).stack); }
            },
            modal_show: function (e) {
                try {
                    this.visible = true;

                }
                catch (e) { console.error((e.stack) ? e.stack : new Error(e).stack); }
            },
            modal_shown: function (e) {
                try {
                    this.$el.find(".autofocus").focus();
                    this.renderMeltOrderPicker();
                    this.renderGradePicker();
                }
                catch (e) { console.error((e.stack) ? e.stack : new Error(e).stack); }
            },
            view_render: function () {
                try {
                    this.show();
                }
                catch (e) { console.error((e.stack) ? e.stack : new Error(e).stack); }
            },
        });


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

    });