define([
    'app',
    'js/templates-loader',
    'backgrid',
    'moment',
    'js/multiselect/virtual-select.min',
    'js/bootstrap-input-spinner/bootstrap-input-spinner',
    'js/multiselect/virtual-select.min',
],

    function (app, T, Backgrid, moment) {

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

        Screen.Models.ModalChangeMeltOrder = Backbone.Epoxy.Model.extend({
            defaults: {
                GradeName: "",
                HeatNumber: "",
                MeltOrderNumber: null,
                Size:"",
                MeltOrders: [],
                hasMeltOrders: false,

                ModalTitle: "",
                FromMeltOrder: "",
                FromGradeName: "",
                FromMaterialSize: "",
                Comments: "",

            },
            initialize: function () {

                this.fetchMeltOrders();
            },
            update: function (params) {
                try {
                    var that = this;
                    qp = new Core.Database.QueryParameters();
                    var model = this.toJSON();
                    this.fixedParameters = [
                        { Name: '@heatNumber', Type: 'VARCHAR', Value: model.HeatNumber, },
                        { Name: '@meltOrderNumber', Type: 'VARCHAR', Value: model.MeltOrderNumber, },
                        { Name: '@comments', Type: 'VARCHAR', Value: model.Comments, },
                    ];
              
                    _.each(this.fixedParameters, function (qpParams) {
                        qp.Add(qpParams.Name, qpParams.Type, qpParams.Value);
                    });

                    Core.Json.CallProcedure(
                        app.DatabaseNames.MES + '.LAD.AssignMeltOrderToHeatWeb',
                        qp,
                        {
                            onSuccess: function (resp) {
                                try {
                                    if (resp && !resp.Message) {
                                        app.views.topMessages.showMessage('Melt Order Changed Successfully', { stay: 2000, });
                                    }
                                    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); }
            },
            fetchMeltOrders: function () {
                try {
                    var that = this;
                    qp = new Core.Database.QueryParameters();
   
                    Core.Json.CallProcedure(
                        app.DatabaseNames.MES + '.MES.GetAutocompleteMeltOrders',
                        qp,
                        {
                            onSuccess: function (resp) {
                                try {
                                    if (resp && !resp.Message) {
                                        var mappedMeltOrder = _.map(resp.Table, function (r) {
                                            return { value: r.value, label: r.label }
                                        });
                                        that.set({ MeltOrders: mappedMeltOrder });
                                    }
                                    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.ModalChangeMeltOrder = Backbone.Epoxy.View.extend({
            template: "modal-change-melt-order",
            id: "modal-change-melt-order",
            className: "modal modal-change-melt-order hide fade",
            //default not cacheable, change this if you want the view to be cacheable
            // if the view is set as cacheable should also have a refresh method to reset the view without erasing the DOM.
            bindings: "data-bind",
            isCacheable: true,
            events: function () {
                return {
                    "click #acceptBtn": this.acceptBtn_click,
                    "click #cancelBtn": this.cancelBtn_click,
                    "click #dismissBtn": this.cancelBtn_click,
                    "submit form": this.form_submit,
                    "show.bs.modal": this.modal_show,
                    "shown.bs.modal": this.modal_shown,
                    "hidden.bs.modal": this.modal_hidden,
                };
            },

            container: null,
            content: null,
            disposed: false,
            isRendered: false,
            parent: null,
            preventDispose: false,
            visible: false,
            bus: null,
            isManual: false,

            initialize: function (options) {
                _.extend(this, options);

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

                if (options.data) {
                    var data = options.data;
                    this.model.set({
                        GradeName: data.GradeName,
                        HeatNumber: data.HeatNumber,
                        MeltOrderNumber: data.MeltOrderNumber,
                        Size: data.MaterialSize,
                        ModalTitle: 'Change Melt Order: Heat ' + data.HeatNumber + ' | Ladle: ' + data.LadleID,
                        FromMeltOrder: data.FromMeltOrder,
                        FromGradeName: data.FromGradeName,
                        FromMaterialSize: data.FromMaterialSize,
                    });
                }
                this.model.fetchMeltOrders();

                this.bus = options.bus;

                this.bindEvents();


                return this;
            },

            renderMultipicker: function () {
                var that = this;
                var meltOrder = this.model.get('MeltOrderNumber');
                var modelMeltOrders = this.model.get('MeltOrders');
                var meltOrders = modelMeltOrders.push({value: meltOrder, label: meltOrder });
                var picker = new VirtualSelect.init({
                    ele: '#melt-order-picker-multi-select',
                    options: that.model.get('MeltOrders') ? that.model.get('MeltOrders')  : meltOrders,
                    multiple: false,
                    search: true,
                    placeholder: 'Select Melt Order',
                    hasOptionDescription: false,
                    showSelectedOptionsFirst: true,
                    hideClearButton: true,
                    onServerSearch: that.onSampleSelectServerSearch,
                });
             
                document.querySelector('#melt-order-picker-multi-select').setOptions(that.model.get('MeltOrders'));
                document.querySelector('#melt-order-picker-multi-select').setValue(meltOrder);
                document.querySelector('#melt-order-picker-multi-select').addEventListener('change', function () {
                    $('.vscomp-search-clear').click();
                    var completeValues = this.value; 
                    if (completeValues) {
                        
                        var allValues = completeValues.split(',');
                        that.model.set({
                            MeltOrderNumber: allValues[0],
                        });
                        if (allValues[1]) that.model.set({ GradeName: allValues[1] });
                        if (allValues[2]) that.model.set({ Size: allValues[2] });
                        
                    }                 
                });

            },

            onSampleSelectServerSearch: function (searchValue, virtualSelect) {
                var qp = new Core.Database.QueryParameters();   
                qp.Add('@MeltOrder', 'VARCHAR(10)', searchValue);
                Core.Json.CallProcedure(
                    app.DatabaseNames.MES + '.MES.GetAutocompleteMeltOrders',
                    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
                );
            },





            bindEvents: function () {
                this.listenToOnce(this, "render", this.view_render);

                _.bindAll(this, 'on_keypress'),
                    $(document).bind('keydown', this.on_keypress);

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

                //the screens have a custompath, so it has to be specified in the customPath variable that is
                //then sent to the template loader.
                var that = this,
                    customPath = "/app/templates/modal-change-melt-order/";

                var attrs = this.model.toJSON();

                T.render.call(this, this.template, function (tmp) {
                    if (!that.i18n) that.i18n = {};
                    app.getI18NJed(that, that.template, function (i18nJED) {
                        //storing internationalization data
                        that.i18n[that.template] = i18nJED;
                        //loading the view and appeding it to the views's $el.
                        that.$el.html(tmp(that.model.toJSON()));
                        that.applyBindings();

                        that.isRendered = true;

                        that.trigger("render");



                    }, true, customPath);

                }, customPath, "modal_change_melt_order");
            },


            setData: function (attrs) {
                this.model.set(attrs);
            },
           
            show: function () {
                if (!this.isRendered) {
                    this.render();
                }
                else {
                    if (this.model.get('manual') == false) {
                        this.$el.modal({
                            keyboard: false,
                            backdrop: 'static',
                        });

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

                return this;
            },
            acceptBtn_click: function (e) {
                try {
                    var attrs = this.model.toJSON();
                    this.model.update({
                        HeatNumber: attrs.HeatNumber,
                        MeltOrderNumber: attrs.MeltOrderNumber,
                    })

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


            on_keypress: function (e) {          
                try {
                    if (e.which === 27) {
                        this.close();
                    }

                }
                catch (e) { console.error((e.stack) ? e.stack : new Error(e).stack); }
            },
            cancelBtn_click: function () {
               // this.bus.trigger("cancelBtn", this.model.toJSON());

                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;
                    }
                }
                if (this.bus) {
                    this.bus.trigger("modalClose");
                }
            },
            hide: function (preventDispose) {
                this.preventDispose = (preventDispose);
                this.$el.modal('hide');
            },
            
            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.renderMultipicker();    
                }
                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); }
            },
            preRender: function () {
                app.models.subnavbar.set("dateControl", false);
            },
            reRender: function () {
            },
        });


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

    });