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

    function (app, T, Backgrid, moment, select2Module) {

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

        Screen.Models.SulfurPrintRatings = Backbone.Epoxy.Model.extend({
            defaults: {
                ratedByNames: null,
                ratedBy:null,
                ratedById: null,
                rating: null,
                ratingId: null,
                surfaceCracksRatingId: null,
                subsurfaceCracksRatingId: null,
                pinholesRatingId: null,
                internalCracksRatingId: null,
                centerCracksRatingId: null,
                centerSegregationId: null,
                d1Input: null,
                d2Input: null,
                h1Input: null,
                h2Input: null,
                h3Input: null,
                h4Input: null,
                h5Input: null,
                w1Input: null,
                w2Input: null,
                w3Input: null,
                w4Input: null,
                w5Input: null,
                ProductNumber: "",
                HeatNumber: "",
                Strand: "",
                Cut: "",
                Grade: "",
                Title: "",
                Date:"",
            },
            upsertSulfurRating: function (params) {
                try {
                    var that = this;
                    qp = new Core.Database.QueryParameters();

                    this.fixedParameters = [
                        { Name: '@ProductId', Type: 'INT', Value: params.ProductId, },
                        { Name: '@SurfaceCracksId', Type: 'INT', Value: params.SurfaceCracks, },
                        { Name: '@SubsurfaceCracksId', Type: 'INT', Value: params.SubsurfaceCracks, },
                        { Name: '@PinholesId', Type: 'INT', Value: params.Pinholes, },
                        { Name: '@InternalCracksId', Type: 'INT', Value: params.InternalCracks, },
                        { Name: '@CenterCracksId', Type: 'INT', Value: params.CenterCracks, },
                        { Name: '@CenterSegregationId', Type: 'INT', Value: params.CenterSegregation, },
                        { Name: '@RatedBy', Type: 'VARCHAR', Value: params.RatedBy, },
                        { Name: '@H1', Type: 'INT', Value: params.H1, },
                        { Name: '@H2', Type: 'INT', Value: params.H2, },
                        { Name: '@H3', Type: 'INT', Value: params.H3, },
                        { Name: '@H4', Type: 'INT', Value: params.H4, },
                        { Name: '@H5', Type: 'INT', Value: params.H5, },
                        { Name: '@W1', Type: 'INT', Value: params.W1, },
                        { Name: '@W2', Type: 'INT', Value: params.W2, },
                        { Name: '@W3', Type: 'INT', Value: params.W3, },
                        { Name: '@W4', Type: 'INT', Value: params.W4, },
                        { Name: '@W5', Type: 'INT', Value: params.W5, },
                        { Name: '@D1', Type: 'INT', Value: params.D1, },
                        { Name: '@D2', Type: 'INT', Value: params.D2, },


                    ];
                    _.each(this.fixedParameters, function (qpParams) {
                        qp.Add(qpParams.Name, qpParams.Type, qpParams.Value);
                    });
                    Core.Json.CallProcedure(
                        app.DatabaseNames.MES + '.SUL.UpsertSulfurRating',
                        qp,
                        {
                            onSuccess: function (resp) {
                                try {
                                    if (resp && !resp.Message) {
                                        app.views.topMessages.showMessage('Sulfur Print Rating edited on Product: ' + params.ProductName, { stay: 2000, });
                                        that.trigger('edited');
                                    }
                                    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.SulfurPrintRatings = Backbone.Epoxy.View.extend({
            template: "modal-sulpher-print",
            className: "modal hide fade",
            bindings: "data-bind",
            title: "Sulfur Print Ratings",
            isCacheable: true,
            events: function () {
                return {
                    "click #acceptBtn": this.acceptBtn_click,
                    "click #cancelBtn": this.cancelBtn_click,
                    "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,
                };
            },
            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.SulfurPrintRatings();
                }

                const row = options.rowModel;

                this.bus = options.bus;

                if (options.data) {
                    var data = options.data;
                    this.model.set({
                        ProductNumber: data.ProductNumber,
                        HeatNumber: data.HeatNumber,
                        Date: data.Date,
                        Strand: data.Strand,
                        Cut: data.Cut,
                        Grade: data.Grade,
                        ProductId: data.ProductId,
                        surfaceCracksRatingId: row.SurfaceCracks,
                        subsurfaceCracksRatingId: row.SubsurfaceCracks,
                        pinholesRatingId: row.Pinholes,
                        internalCracksRatingId: row.InternalCracks,
                        centerCracksRatingId: row.CenterCracks,
                        centerSegregationId: row.CenterSegregation,
                        d1Input: row.D1,
                        d2Input: row.D2,
                        h1Input: row.H1,
                        h2Input: row.H2,
                        h3Input: row.H3,
                        h4Input: row.H4,
                        h5Input: row.H5,
                        w1Input: row.W1,
                        w2Input: row.W2,
                        w3Input: row.W3,
                        w4Input: row.W4,
                        w5Input: row.W5,
                        ratedById: row.RatedById,

                    });
                    this.model.set({ Title: "Sulfur Print Ratings - [" + data.ProductNumber + "]" });
                }
               
                this.parent = options.parent;
                this.bindEvents();
                var that = this;
                that.fetchPickers({ async: false });

                return this;
            },
            renderSelectInputs: function () {

                var that = this;
                const typeSelect = new select2Module.Views.Main({
                    el: '#RatedBy',
                    data: that.model.get('ratedByNames'),
                    disabledByDefault: false,
                    tagging: true
                });
                const RatedBy = that.model.get('ratedById');
                $('#RatedBy').val(RatedBy).trigger('change');
                //$('#RatedBy').select2().trigger('change');
            },
            hide: function (preventDispose) {
                this.preventDispose = (preventDispose);

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

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

                var that = this;
                var customPath = '/app/templates/' + this.template + '/';
                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, "sulpher_print");

            },
            show: function () {
                if (!this.isRendered) {

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

                return this;
            },

            bindEvents: function () {
                var that = this;
                this.listenToOnce(that, "render", that.view_render);
                this.listenTo(that.model, 'edited', () => { that.bus.trigger("modalAcceptBtn") });


            },

            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;
                    var selectedRatedBy = $('#RatedBy').find('option:selected');
                    var selectedLabel = selectedRatedBy.text();
                    var attrs = this.model.toJSON();

                    this.model.upsertSulfurRating({
                        ProductId: that.data.ProductId,
                        ProductName: attrs.ProductNumber,
                        SurfaceCracks: attrs.surfaceCracksRatingId,
                        SubsurfaceCracks: attrs.subsurfaceCracksRatingId,
                        Pinholes: attrs.pinholesRatingId,
                        InternalCracks: attrs.internalCracksRatingId,
                        CenterCracks: attrs.centerCracksRatingId,
                        CenterSegregation: attrs.centerSegregationId,
                        RatedBy: selectedLabel,
                        H1: attrs.h1Input,
                        H2: attrs.h2Input,
                        H3: attrs.h3Input,
                        H4: attrs.h4Input,
                        H5: attrs.h5Input,
                        W1: attrs.w1Input,
                        W2: attrs.w2Input,
                        W3: attrs.w3Input,
                        W4: attrs.w4Input,
                        W5: attrs.w5Input,
                        D1: attrs.d1Input,
                        D2: attrs.d2Input,
                    })

                    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.renderSelectInputs();
                }
                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); }
            },
            fetchPickers: function (options) {
                var that = this,
                    qp = new Core.Database.QueryParameters(),
                    opt = _.extend({ async: true, }, options);

                Core.Json.CallProcedure(
                    app.DatabaseNames.MES + '.SUL.GetSulpherPrintCatalog',
                    qp,
                    {
                        onSuccess: function (resp) {
                            try {
                                if ((resp) && (resp.Table)) {
                                    _.each(resp.Table, function (obj) {
                                        var tableKey = 'Table' + obj.Index;
                                        switch (obj.Name) {
                                            case 'RATEDBY':
                                                that.model.set('ratedByNames', _.map(resp[tableKey], function (obj) {

                                                    return {
                                                        id: obj.Id,
                                                        text: obj.Description,
                                                    };
                                                }));
                                                break;
                                            case 'RATING':
                                                that.model.set('rating', _.map(resp[tableKey], function (obj) {

                                                    return {
                                                        value: obj.Id,
                                                        label: obj.Description,
                                                    };
                                                }));
                                                break;
                                        }
                                    });
                                }
                                else {
                                    if ((resp) && (resp.Message))
                                        console.error(new Error(resp.Message).stack);
                                    else
                                        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: opt.async,
                    },
                    app.ConnectionStrings.app
                );

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

    });