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",
    'js/jquery.timepicker/jquery.timepicker',
],

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

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

        Screen.Models.LabHeatReportEdit = Backbone.Epoxy.Model.extend({
            defaults: {
                typeCodeNames: null,
                typeCodeId:null,
                HeatNumber: "",
                HeatTypeSample: "",
                Date: "",
                TypeCode: "",
                SampleIdCode: "",
                SelectedSampleId: "",
                sampleTime: null,
                sampleDate: null,
                sampleTimestamp: null,
            },
            updateSample: function (params) {
                try {
                    var that = this;
                    qp = new Core.Database.QueryParameters();

                    this.fixedParameters = [
                        { Name: '@Id', Type: 'INT', Value: params.Id, },
                        { Name: '@TypeCode', Type: 'VARCHAR', Value: params.TypeCode, },
                        { Name: '@SampleIdCode', Type: 'VARCHAR', Value: params.SampleIdCode === '' ? null : params.SampleIdCode, },
                        { Name: '@Timestamp', Type: 'DATETIME', Value: params.Timestamp._i, },
                    ];
                    _.each(this.fixedParameters, function (qpParams) {
                        qp.Add(qpParams.Name, qpParams.Type, qpParams.Value);
                    });
                    Core.Json.CallProcedure(
                        app.DatabaseNames.MES + '.LAB.UpdateChemistrySampleFromModal',
                        qp,
                        {
                            onSuccess: function (resp) {
                                try {
                                    if (resp && !resp.Message) {
                                        app.views.topMessages.showMessage('Lab heat reported for Heat: ' + that.get('HeatNumber'), { 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.EditLabReport = Backbone.Epoxy.View.extend({
            template: "modal-lab-heat-report-edit",
            className: "modal hide fade",
            bindings: "data-bind",
            title: "Edit Lab Report",
            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.LabHeatReportEdit();
                }

                //const column = options.column;

                this.bus = options.bus;

                if (options.data) {
                    var data = options.data;
                    this.model.set({
                        HeatTypeSample: data.SelectedSample.HeatTypeSample,
                        HeatNumber: data.HeatNumber,
                        sampleTime: new moment(data.SelectedSample.Timestamp).format('h:mm:ss A'),
                        sampleDate: new moment(data.SelectedSample.Timestamp).format('MM/DD/YYYY'),
                        sampleTimestamp: data.SelectedSample.Timestamp,
                        SelectedSampleId: data.SelectedSample.Id,
                        SampleIdCode: data.SelectedSample.SampleIdCode,
                        TypeCode: data.SelectedSample.TypeCode,
                    });
                    this.model.set({ Title: "Lab Heat Report - [" + data.HeatNumber + "]" });
                }
               
                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: '#TypeCode',
                    data: that.model.get('typeCodeNames'),
                    disabledByDefault: false,
                    tagging: false
                });
                
                const TypeCode = that.model.get('typeCodeNames').filter(x => x.text == that.model.get('TypeCode'))[0].id;
                $('#TypeCode').val(TypeCode).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.$el.find('#dateFormModal').datepicker();
                        that.$el.find('#timeForm').timepicker({
                            showMeridian: true,
                            showSeconds: true,
                            secondStep: 1,
                            minuteStep: 1,
                        });

                        that.isRendered = true;

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

                }, customPath, "lab_heat_report_edit");

            },
            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 attrs = this.model.toJSON();
                    var selectedTypeCode = $('#TypeCode').find('option:selected').text();

                    const formattedTime = new moment(attrs.sampleTime, 'h:mm A');
                    const convertedTime = formattedTime.format('HH:mm:ss');

                    const date = new moment(attrs.sampleDate).format('YYYY-MM-DD');

                    const datetime = new moment(date + ' ' + convertedTime, 'YYYY-MM-DD HH:mm:ss');


                    this.model.updateSample({
                        Id: attrs.SelectedSampleId,
                        TypeCode: selectedTypeCode,
                        SampleIdCode: attrs.SampleIdCode,
                        Timestamp: datetime,
                        
                    })
                    console.log(attrs);
                    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 + '.LAB.GetLabHeatReportEditCatalogs',
                    qp,
                    {
                        onSuccess: function (resp) {
                            try {
                                if ((resp) && (resp.Table)) {
                                    _.each(resp.Table, function (obj) {
                                        var tableKey = 'Table' + obj.Index;
                                        switch (obj.Name) {
                                            case 'TYPESAMPLE':
                                                that.model.set('typeCodeNames', _.map(resp[tableKey], function (obj) {

                                                    return {
                                                        id: obj.TypeSampleId,
                                                        text: obj.Name,
                                                    };
                                                }));
                                                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;

    });