// VitalsMonitoring JS //

$(document).ready(function () {
    ShowVitals();
    $('#txtLogdate').datepicker({
        autoclose: true,
        todayHighlight: true,
        format: "dd/mm/yyyy"
        //endDate: new Date()
    });

    //$('#txtLogtime').timepicker({
    //    showInputs: false
    //});
});

function ShowVitals() {
    var Vitalsdata = {

        Dml_Indicator: "S",
        ip_visit_report_id: $("#IPVisitReport_Id").val()
    }

    $.ajax({
        async: true,
        type: 'POST',
        url: 'Vitalsmonitoring_Ins_Upd_sel',
        contentType: 'application/json; charset=UTF-8',
        data: JSON.stringify(Vitalsdata),
        success: function (data) {

            $('#tblvitalsmonitoring').empty();
            var data2 = JSON.parse(data);
            
            if (jQuery.isEmptyObject((data2.data))) {
                $('#tblvitalsmonitoring').empty();
            }
            else {

                if (data2.msg == "Success") {
                    var data1 = data2.data;

                    var tr = "";
                    tr = $('<table id="example1" class="table table-responsive table-bordered table-striped dataTable tablecolumnsticky" />');

                    tr.append("<thead><tr><th>Pulse</th><th>SYS</th><th>DIA</th><th>CVP</th><th>RR</th><th>Spo2</th><th>Fio2</th><th>Temp</th><th>Date</th><th>Visual Analogue Scale</th><th>Created By</th><th>Actions</th></tr></thead><tbody>");

                    $.each(data1, function (i, emp) {


                        view = "<a title='Edit' href='javascript:void(0)' class='edit_icon'onclick=loadVitals('" + emp.IP_Vitals_number + "');><i class='fa fa-pencil' aria-hidden='true'></i></a>";
                        Del = "<a itile='Delete' href='javascript:void(0)' class='delete_icon' onclick=DeledeVitals('" + emp.IP_Vitals_number + "');><i class='fa fa-trash-o' aria-hidden='true'></i></a>";
                        var other_info = '<div class="dropdown"><i class="fa fa-ellipsis-h dropdown-toggle pull-right" data-toggle="dropdown" aria-expanded="true"></i> <ul class="dropdown-menu info-dropdown-new"><div class="disp_if mb-10"><li>' + view + '</li><li>' + Del + '</li></div></ul></div>';

                        row_data = "<tr><td>" + emp.IP_Pulse + " </td><td> " + emp.IP_SYSBp + "</td><td> " + emp.IP_DIABp + "</td><td>" + emp.IP_CVP + "</td><td>" + emp.IP_RR + "</td><td>" + emp.IP_Spo2 + "</td><td>" + emp.IP_Fio2 + "</td><td>" + emp.IP_Temp + "</td><td>" + emp.Created_on + "</td><td>" + emp.vitals_vas + "</td><td>" + emp.CreatedName + "</td><td>" + other_info + "</td></tr>";
                        tr.append(row_data);
                    });
                    tr.append("</tbody></table>");
                    $('#tblvitalsmonitoring').html(tr);
                }
                else {
                    console.log(data);
                }
            }

        },
        error: function (data) {
            toastr.warning('some issue');
        }
    });
}

$('#btnVitalAdd').click(function () {

    if ($.trim($('#txtPulse').val()) == "") {
        //$('#PtxtPulse').show();
        //$('#PtxtPulse').fadeOut(8000);
        //$('#PtxtPulse').html('Enter The Pulse');
        toastr.warning('Please Enter Pulse');
        $('#txtPulse').focus();
        $('#txtPulse').val('');
        return false;
    }

    if ($.trim($('#txtSYS').val()) == "") {
        //$('#PtxtSYS').show();
        //$('#PtxtSYS').fadeOut(8000);
        //$('#PtxtSYS').html('Enter The SYS');
        toastr.warning('Please Enter SYS');
        $('#txtSYS').focus();
        $('#txtSYS').val('');
        return false;
    }

    if ($.trim($('#txtDIA').val()) == "") {
        //$('#PtxtDIA').show();
        //$('#PtxtDIA').fadeOut(8000);
        //$('#PtxtDIA').html('Enter The DIA');
        toastr.warning('Please Enter DIA');
        $('#txtDIA').focus();
        $('#txtDIA').val('');
        return false;
    }

    if ($.trim($('#txtLogdate').val()) == "") {
        //$('#PtxtLogtime').show();
        //$('#PtxtLogtime').fadeOut(8000);
        //$('#PtxtLogtime').html('Enter The Date');
        toastr.warning('Please Enter Date');
        $('#txtLogdate').focus();
        $('#txtLogdate').val('');
        return false;
    }

    if ($("#IPDischarge_Id").val() != "2") {
        var LDT = $('#txtLogdate').val();
        if (LDT == '') {
            LDT = '';
        }
        else {
            var a = LDT.split('/');
            LDT = a[2] + '-' + a[1] + '-' + a[0];
        }
        debugger;
        var time = $("#txtLogtime").val();
        var convertedTime = moment(time, 'hh:mm A').format('HH:mm');


        //var time = $("#txtLogtime").val();
        //var hours = Number(time.match(/^(\d+)/)[1]);
        //var minutes = Number(time.match(/:(\d+)/)[1]);
        //var AMPM = time.match(/\s(.*)$/)[1];
        //if (AMPM == "PM" && hours < 12) hours = hours + 12;
        //if (AMPM == "AM" && hours == 12) hours = hours - 12;
        //var sHours = hours.toString();
        //var sMinutes = minutes.toString();
        //if (hours < 10) sHours = "0" + sHours;
        //if (minutes < 10) sMinutes = "0" + sMinutes;
        //var LTM = sHours + ":" + sMinutes;

        var Vitaldata = {
            IP_Vitals_number: $('#HVID').val(),
            IP_Pulse: $('#txtPulse').val(),
            IP_SYSBp: $('#txtSYS').val(),
            IP_CVP: $('#txtCVP').val(),
            IP_RR: $('#txtRR').val(),
            IP_Spo2: $('#txtSpo2').val(),
            IP_Fio2: $('#txtFio2').val(),
            IP_Temp: $('#txtTemp').val(),
            Dml_Indicator: "I",
            IP_DIABp: $('#txtDIA').val(),
            ip_visit_report_id: $("#IPVisitReport_Id").val(),
            vitalsdatetime: LDT + " " + convertedTime,
            vitals_vas: $('#NPDRradio').val()
        }

        $.ajax({
            async: true,
            type: 'POST',
            url: 'Vitalsmonitoring_Ins_Upd_sel',
            contentType: 'application/json; charset=UTF-8',
            data: JSON.stringify(Vitaldata),
            success: function (data) {
                debugger;
                var data2 = JSON.parse(data);
                if (data2.msg == "Success") {
                    var data1 = data2.data;

                    if ($('#HVID').val() == "") {
                        toastr.success("Vitals Added Successfully");
                    }
                    else {
                        toastr.success("Vitals Updated Successfully");
                    }

                    Level();
                    clearVitals();
                    ShowVitals();




                }
                else {
                    console.log(data);
                }

            },
            error: function (data) {
            }
        });
    }

});

function clearVitals() {

    $('#HVID').val(""),
    $('#txtPulse').val(""),
    $('#txtSYS').val(""),
    $('#txtCVP').val(""),
    $('#txtRR').val(""),
    $('#txtSpo2').val(""),
    $('#txtFio2').val(""),
    $('#txtTemp').val(""),
    $('#txtDIA').val(""),
    $('#txtLogdate').val("")
}

function loadVitals(val) {

    if ($("#IPDischarge_Id").val() != "2") {
        var Vitalsdata = {
            IP_Vitals_number: val,
            Dml_Indicator: "ID"
        }

        $.ajax({
            async: true,
            type: 'POST',
            url: 'Vitalsmonitoring_Ins_Upd_sel',
            contentType: 'application/json; charset=UTF-8',
            data: JSON.stringify(Vitalsdata),
            success: function (data) {
                var data2 = JSON.parse(data);
                if (jQuery.isEmptyObject((data2.data))) {
                }
                else {

                    if (data2.msg == "Success") {
                        var data1 = data2.data;
                        $.each(data1, function (i, emp) {

                            $('#HVID').val(emp.IP_Vitals_number),
                            $('#txtPulse').val(emp.IP_Pulse),
                            $('#txtSYS').val(emp.IP_SYSBp),
                            $('#txtCVP').val(emp.IP_CVP),
                            $('#txtRR').val(emp.IP_RR),
                            $('#txtSpo2').val(emp.IP_Spo2),
                            $('#txtFio2').val(emp.IP_Fio2),
                            $('#txtTemp').val(emp.IP_Temp),
                            $('#txtDIA').val(emp.IP_DIABp),
                            $("#txtLogdate").val(emp.vitals_date),
                            $("#txtLogtime").val(emp.vitals_time),
                            $('#NPDRradio').val(emp.vitals_vas);
                            $('a[data-toggle=NPDRradio][data-title="' + emp.vitals_vas + '"]').removeClass('not-active');
                            $('a[data-toggle=NPDRradio][data-title="' + emp.vitals_vas + '"]').addClass('active');
                            emoji(emp.vitals_vas);
                        });
                    }
                    else {
                        console.log(data);
                    }
                }
            }
        });
    }
}

function DeledeVitals(val) {

    if ($("#IPDischarge_Id").val() != "2") {


        status = "'Are You Sure, You want to Delete Vitals?'";

        toastr.warning("<button type='button' id='confirmationRevertYes' class='btn btn-warning btn-xs mt20'>Yes</button> <button type='button' id='confirmationRevertNo' class='btn btn-warning btn-xs mt20'>No</button>", status,
     {
         closeButton: true,
         progressBar: true,
         allowHtml: true,
         timeOut: 0,

         onShown: function (toast) {
             debugger
             $("#confirmationRevertYes").click(function () {

                 var Vitalsdata = {
                     IP_Vitals_number: val,
                     Dml_Indicator: "DEL"
                 }

                 $.ajax({
                     async: true,
                     type: 'POST',
                     url: 'Vitalsmonitoring_Ins_Upd_sel',
                     contentType: 'application/json; charset=UTF-8',
                     data: JSON.stringify(Vitalsdata),
                     success: function (data) {
                         //alert('vitals Deleted Successfully');
                         toastr.success("Vitals Deleted Successfully");
                         ShowVitals();
                     }
                 });

             });
         }
     });
    }
}

// graph //

$("#ddVitals").change(function () {
    $('#canvas').val("");
    $('.divcanvas').val("");
    $('#stats-patientstreated').modal('show');

    var Dml_Indicator = "", GF1Name = "", GF2Name = "";

    if ($('#ddVitals').val() == "Pulse") {
        Dml_Indicator = "PL";
        GF1Name = "Pulse";
    }
    else if ($('#ddVitals').val() == "BP") {
        Dml_Indicator = "BP";
        GF1Name = "SYS";
        GF2Name = "DIA";
    }
    else if ($('#ddVitals').val() == "CVP") {
        Dml_Indicator = "CVP";
        GF1Name = "CVP";
    }
    else if ($('#ddVitals').val() == "RR") {
        Dml_Indicator = "RR";
        GF1Name = "RR";
    }
    else if ($('#ddVitals').val() == "Spo2") {
        Dml_Indicator = "Spo2";
        GF1Name = "Spo2";
    }
    else if ($('#ddVitals').val() == "Fio2") {
        Dml_Indicator = "Fio2";
        GF1Name = "Fio2";
    }
    else if ($('#ddVitals').val() == "Temp") {
        Dml_Indicator = "Temp";
    }
    else {
        Dml_Indicator = "";
    }

    $('.da-load-graph').show();
    $('#VitalsName').html($('#ddVitals').val());


    var Oldlabel = [];
    var PaitentsTrend = {
        Dml_Indicator: Dml_Indicator,
        ip_visit_report_id: $("#IPVisitReport_Id").val()
    }

    $.ajax({
        async: false,
        //async: false, //Arul Change-- always should be false for async call back function ,
        type: 'POST',
        url: '/Ipmanagement/Vitalsmonitoring_Ins_Upd_sel',
        contentType: 'application/json; charset=UTF-8',
        data: JSON.stringify(PaitentsTrend),
        success: function (datass) {
            if (jQuery.isEmptyObject((datass))) {
                $('.divcanvas').removeClass('da-load-pp-wl-vip-ma');
            }
            else {
                var data11 = JSON.parse(datass);
                var data11 = data11.data;

                for (var i = 0; i < data11.length; i++) {
                    Oldlabel.push(data11[i].Vitalgf1);
                }
                //var data1 = JSON.parse(datass);


                var gFdata = [], value, label, labelname = [];
                var DateValue;
                for (var i = 0; i < data11.length; i++) {
                    gFdata.push(data11[i].Vitalgf2);
                    labelname.push(data11[i].VitalDate);
                }

                var chartColors = {
                    green: 'rgb(75, 192, 192)',
                    blue: 'rgb(54, 162, 235)',
                    greenfade: 'rgba(75, 192, 192,0.8)',
                    bluefade: 'rgba(54, 162, 235,0.4)',
                    white: 'rgb(255, 255, 255)',
                    whitefade: 'rgba(255, 255, 255,0.7)',
                    newgreen: '#94fc13',
                    neworange: '#ff502f',
                    darkblue: '#36a2eb',
                    darkpink: '#ff6b8b',
                    lightwhite: '#fff'
                };
                var config = "";
                if ($('#ddVitals').val() == "BP") {
                    var config = {
                        type: 'line',
                        //type: 'bar',

                        data: {
                            type: 'column',
                            //labels: gFlabel,
                            labels: labelname,

                            datasets: [{
                                label: GF2Name,
                                backgroundColor: chartColors.lightwhite,
                                borderColor: chartColors.newgreen,
                                data: gFdata,

                            }, {
                                label: GF1Name,
                                backgroundColor: chartColors.lightwhite,
                                borderColor: chartColors.darkblue,
                                data: Oldlabel,
                            }]
                        },
                        options: {
                            responsive: true,
                            tooltips: {
                                mode: 'label',
                            },
                            legend: {
                                display: false,
                            },

                            scales: {
                                xAxes: [{
                                    //stacked: true,
                                    display: true,
                                    scaleLabel: {
                                        display: true,
                                        labelString: 'Date',
                                        fontSize: 9,
                                        // 
                                    },
                                    ticks: {
                                        fontSize: 9,
                                        //fontColor: "#222"
                                    },
                                    gridLines: {
                                        display: false,
                                        //color: '#aaa'
                                    }
                                }],
                                yAxes: [{
                                    //stacked: true,
                                    display: true,
                                    scaleLabel: {
                                        display: false,
                                        labelString: 'Value',
                                        fontSize: 9
                                    },
                                    ticks: {
                                        fontSize: 9,
                                        beginAtZero: true,
                                    },
                                    gridLines: {
                                        display: false,
                                        //color: '#aaa'
                                    }
                                }]
                            }
                        }
                    };
                }
                else {
                    var config = {
                        type: 'line',
                        //type: 'bar',

                        data: {
                            type: 'column',
                            //labels: gFlabel,
                            labels: labelname,

                            datasets: [{
                                label: GF1Name,
                                backgroundColor: chartColors.lightwhite,
                                borderColor: chartColors.darkblue,
                                data: Oldlabel,
                            }]
                        },
                        options: {
                            responsive: true,
                            tooltips: {
                                mode: 'label',
                            },
                            legend: {
                                display: false,
                            },

                            //responsive: true,

                            scales: {
                                xAxes: [{
                                    //stacked: true,
                                    display: true,
                                    //barPercentage: barPercentage,
                                    scaleLabel: {
                                        display: true,
                                        labelString: 'Date',
                                        fontSize: 9,
                                        // 
                                    },
                                    ticks: {
                                        fontSize: 9,
                                        //fontColor: "#222"
                                    },
                                    gridLines: {
                                        display: false,
                                        //color: '#aaa'
                                    }
                                }],
                                yAxes: [{
                                    //stacked: true,
                                    display: true,
                                    scaleLabel: {
                                        display: false,
                                        labelString: 'Value',
                                        fontSize: 9
                                    },
                                    ticks: {
                                        fontSize: 9,
                                        beginAtZero: true,
                                        //fontColor: "#222"
                                        //callback: function (value) {
                                        //    return Number(value).toFixed(0);
                                        //}
                                    },
                                    gridLines: {
                                        display: false,
                                        //color: '#aaa'
                                    }
                                }]
                            }
                        }
                    };
                }
                var ctx = document.getElementById("canvas").getContext("2d");
                window.myLine = new Chart(ctx, config);
                $('.da-load-graph').hide();
                $('.divcanvas').removeClass('da-load-pp-wl-vip-ma');
            }
        }
    });
});