//  //
$(document).ready(function () {
    loadlab_id();
    labtype();
    loadCBG();
    ShowLabPrescription();
    
});

function ShowLabPrescription() {
    var Prescriptiondata = {
        iplab_Indicator: "IP",
        Dml_Indicator: "IPL",
        visit_report_id: $("#IPVisitReport_Id").val()
    }

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

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

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

                tr.append("<thead><tr><th>Date</th><th>Test Type</th><th>Test Name</th><th>Frequency Notes</th><th>When to execute</th><th>Action</th></tr></thead><tbody>");

                $.each(data1, function (i, emp) {
                    var patient_photo = emp.photo;
                    var photoSrc;
                    var PatientPhoto = $('#patphotopath').val();
                    if ($.trim(patient_photo) == "" || patient_photo == null) {
                        photoSrc = "/Content/img/profile_icon.png";
                    }
                    else {
                        photoSrc = PatientPhoto + patient_photo;
                    }
                    var Action = '';

                    Del = "<a href=# class='label label-success' onclick=DelLap('" + emp.prescription_scan_id + "');>Delete</a>";
                    samplePickUp = "<a href=# class='label label-success' id='btnSamplePickUp_" + i + "' style='margin-left: 5px;' onclick=BookIPLabOrder('" + emp.prescription_scan_id + "','" + emp.Sdate + "','" + i + "');>Sample Pick Up</a>";
                    addResult = '<a href="javascript:void(0)" class="label label-success" style="margin-left: 5px;" id="btnAddResult_' + i + '" data-toggle="modal" data-target="#myResultviewModal_result" data-backdrop="static" data-keyboard="false"  onclick=\'ontestid(\"' + emp.first_name + '\",\"' + emp.phone_number_1 + '\",\"' + photoSrc + '\",\"' + emp.order_id + '\",\"' + emp.job_id + '\",\"' + emp.test_id + '\",\"(Pending)\")\';>Add Result</a>';
                    showResult = '<a href="javascript:void(0)" class="label label-success" style="margin-left: 5px;" id="btnShowResult_' + i + '" data-toggle="modal" data-target="#myResultviewModal_result" data-backdrop="static" data-keyboard="false"  onclick=\'completedtestid(\"' + emp.first_name + '\",\"' + emp.phone_number_1 + '\",\"' + photoSrc + '\",\"' + emp.order_id + '\",\"' + emp.job_id + '\",\"' + emp.test_id + '\",\"(Completed)\")\'; >Show Result</a>';


                    if (emp.ip_lab_Investigations_status == 1) {
                        Action = Del + samplePickUp;
                    }
                    else if (emp.ip_lab_Investigations_status == 2) {
                        Action = "Cancelled";
                    }
                    else if (emp.ip_lab_Investigations_status == 3) {
                        Action = Del + addResult;
                    }
                    else if (emp.ip_lab_Investigations_status == 4) {
                        Action = Del + showResult;
                    }

                    if ($("#IPDischarge_Id").val() == "2") {
                        Action = "";
                    }
                    //Pas = "<a id='Pause' href=# class='label label-success'onclick=Pause('" + emp.prescription_scan_id + "');>pause</a>";
                    //start = "<a id='Start' href=# class='label label-success'onclick=Start('" + emp.prescription_scan_id + "');>Start</a>";

                    row_data = "<tr><td>" + emp.suggested_date + "</td><td>" + emp.lab_type_name + "</td><td>" + emp.lab_prescription + "</td><td>" + emp.ip_frequency_notes + "</td><td>" + emp.ip_when_to_execute + "</td><td>" + Action + "</td></tr>";
                    tr.append(row_data);
                });
                tr.append("</tbody></table>");
                $('#tbl_lab').html(tr);
            }
            else {
                console.log(data);
            }
            
        },
        error: function (data) {
            toastr.warning('some issue');
        }
    });
}


function BookIPLabOrder(prescription_scan_id, suggested_date, val) {
    if ($("#IPDischarge_Id").val() != "2")
    {
        var job_due_date = suggested_date.split('T');
        job_due_date = job_due_date[0];

        var Template = {
            lab_id: $('#lab_id').val(),
            patient_id: $("#IPPatient_Id").val(),
            visit_report_id: $("#IPVisitReport_Id").val(),
            doctor_id: $('#HiddenDoctorID').val(),
            order_status: 1,
            created_by: $('#HiddenDoctorID').val(),
            Dml_Indicator: 'IPO',
            job_due_date: job_due_date,
            job_status: 1,
            prescription_scan_id: prescription_scan_id
        }
        $.ajax({
            async: true,
            type: 'POST',
            url: '/Template/lab_home',
            contentType: 'application/json; charset=UTF-8',
            data: JSON.stringify(Template),
            success: function (data) {
                var data2 = JSON.parse(data);
                if (jQuery.isEmptyObject((data2.data))) {
                    toastr.warning('Something wrong! Try again');
                }
                else {

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

                        if (data[0].test_p_status == "0") {
                            toastr.warning("No parameters  for this test, Please add Parameters to this test");
                            $('#loaderimg').hide();
                        }
                        else {
                            ShowLabPrescription();
                        }
                    }
                    else {
                        console.log(data);
                    }
                }

            }
        });
    }
    
}

function ontestid(first_name, phone_number_1, photoSrc, order_id, job_id, test_id, jobstatus) {
    if ($("#IPDischarge_Id").val() != "2") {

        debugger;
        var visit_report_id = $("#IPVisitReport_Id").val();
        var patient_id = $("#IPPatient_Id").val();
        $('#patientdetails').show();
        $('#labParameters_body').empty();
        var print = '<a href=javascript:void(0); onclick=jobprint("' + job_id + '","' + $('#HiddenDoctorID').val() + '");><span class="f14" role="button" data-backdrop="static" data-keyboard="false"><i class="fa fa-print"></i>Print</span></a>';
        $('#mparamPrint1').html(print);
        $('#labparameterss').show();
        $('#mparamPrint1').val(job_id);
        $('#Mjobid').html(job_id);
        $('#MJobstatusid').html(jobstatus);
        $('#MpatientPhoto_1').html('<img class="img-responsive text-center imgphoto" src=' + photoSrc + ' alt="Patient Image" width="40" onerror="changedefault(this)"/>')
        $('#MPatient_id_1').html(patient_id);
        $('#MPatientName_1').html(first_name);
        $('#MphoneNo_1').html(phone_number_1);
        if (visit_report_id != null || visit_report_id != "") {
            $('#labvid_1').html(visit_report_id);
        }
        else {
            $('#labvid_1').html('-');
        }
        var Template = {
            order_id: order_id,
            job_id: job_id,
            added_by: $('#HiddenDoctorID').val(),
            test_id: test_id,
            lab_id: $('#lab_id').val(),
            Dml_Indicator: 'PSS'
        }
        $.ajax({
            async: true,
            type: 'POST',
            url: '/Template/lab_home',
            contentType: 'application/json; charset=UTF-8',
            data: JSON.stringify(Template),
            success: function (data) {
                $('#labParameters_body').empty();
                var data2 = JSON.parse(data);
                if (jQuery.isEmptyObject((data2.data))) {
                }
                else {

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

                        $('#labParameters_body').empty();
                        var tr = '', observation = '';
                        var j = 0;
                        if (data.length > 0) {
                            console.log(data);
                            for (var i = 0; i < data.length; i++) {
                                j++;
                                if (data[i].observation == null || data[i].observation == '') {
                                    observation = '';
                                }
                                else {
                                    observation = data[i].observation;
                                }
                                tr = tr + '<tr><td>' + data[i].result_id + '</td><td>' + data[i].parameter_name + '</td><td><input type="text" class="sm-field" name="obs_val" value="' + observation + '" id="obs_val_' + j + '" /></td><td>' + data[i].reference_value + '</td><td>' + data[i].unit + '</td></tr>';
                            }
                            $('#DoctorName').html(data[0].doctor_name);
                            $('#DoctorName_1').html(data[0].doctor_name);
                            $('#txtconclusion').val(data[0].conclusion);
                            $('#labParameters_body').html(tr);
                        }
                    }
                    else {
                        console.log(data);
                    }
                }
            }
        });
    }
   
}


function completedtestid(first_name, phone_number_1, photoSrc, order_id, job_id, test_id, jobstatus) {

    if ($("#IPDischarge_Id").val() != "2") {
        var visit_report_id = $("#IPVisitReport_Id").val();
        var patient_id = $("#IPPatient_Id").val();
        $('#patientdetails').show();
        var print = '<a href=javascript:void(0); onclick=jobprint("' + job_id + '","' + $('#HiddenDoctorID').val() + '");><span class="f14" role="button" data-backdrop="static" data-keyboard="false"><i class="fa fa-print"></i>Print</span></a>';
        $('#mparamPrint1').html(print);
        $('#labparameterss').show();
        $('#mparamPrint1').val(job_id);
        $('#Mjobid').html(job_id);
        $('#MJobstatusid').html(jobstatus);


        //$('#labparameterss').hide();
        $('#MpatientPhoto_1').html('<img class="img-responsive text-center imgphoto" src=' + photoSrc + ' alt="Patient Image" width="40" onerror="changedefault(this)"/>')
        $('#MPatient_id_1').html(patient_id);
        $('#MPatientName_1').html(first_name);
        $('#MphoneNo_1').html(phone_number_1);
        debugger;
        if (visit_report_id != null && visit_report_id != "" && visit_report_id != "null") {
            $('#labvid_1').html(visit_report_id);
        }
        else { $('#labvid_1').html('-'); }


        var print = '<a href=javascript:void(0); onclick=jobprint("' + job_id + '","' + $('#HiddenDoctorID').val() + '");><span class="f14" role="button" data-backdrop="static" data-keyboard="false"><i class="fa fa-print"></i>Print</span></a>';
        $('#mparamPrint1').html(print);

        var Template = {
            order_id: order_id,
            job_id: job_id,
            added_by: $('#HiddenDoctorID').val(),
            test_id: test_id,
            lab_id: $('#lab_id').val(),
            Dml_Indicator: 'PIS'
        }
        $.ajax({
            async: true,
            type: 'POST',
            url: '/Template/lab_home',
            contentType: 'application/json; charset=UTF-8',
            data: JSON.stringify(Template),
            success: function (data) {
                $('#labParameters_body').empty();
                var data2 = JSON.parse(data);
                if (jQuery.isEmptyObject((data2.data))) {

                }
                else {

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

                        console.log(data);
                        var tr = '', observation = '', reference_value = '', unit = '';
                        var j = 0;

                        if (data.length > 0) {
                            for (var i = 0; i < data.length; i++) {
                                j++;
                                if (data[i].observation == null || data[i].observation == '') {
                                    observation = '';
                                }
                                else {
                                    observation = data[i].observation;
                                }
                                if (data[i].reference_value == null || data[i].reference_value == '') {
                                    reference_value = '';
                                }
                                else {
                                    reference_value = data[i].reference_value;
                                }
                                if (data[i].unit == null || data[i].unit == '') {
                                    unit = '';
                                }
                                else {
                                    unit = data[i].unit;
                                }
                                if (data[i].result_id == null || data[i].result_id == '') {

                                }
                                else {
                                    tr = tr + '<tr><td>' + data[i].result_id + '</td><td>' + data[i].parameter_name + '</td><td><input type="text" class="sm-field" name="obs_val" value="' + observation + '" id="obs_val_' + j + '" /></td><td>' + reference_value + '</td><td>' + unit + '</td></tr>';
                                }
                            }
                            $('#DoctorName_1').html(data[0].doctor_name);
                            if (data[0].conclusion == null || data[0].conclusion == "") $('#txtconclusion').val('');
                            else $('#txtconclusion').val(data[0].conclusion);
                            $('#labParameters_body').html(tr);
                        }
                    }
                    else {
                        console.log(data);
                    }
                }
            }
        });
    }
    
}


function jobprint(job_id, doctorId) {
    window.open('/PatientDashboard/labresult?jobid=' + job_id + '&doctorId=' + doctorId);
}


function labtype() {
    var country = {
        Dml_Indicator: "TS"
    }
    $.ajax({
        async: true,
        type: 'POST',
        url: '/PatientDashboard/Lab_Prescription_Ins_Upd',
        contentType: 'application/json; charset=UTF-8',
        data: JSON.stringify(country),
        success: function (data) {

            $('#labtype').empty();
            var data2 = JSON.parse(data);

            if (jQuery.isEmptyObject((data2.data))) {

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

                    var Country;
                    $.each(data1, function (i, emp) {

                        Country = Country + '<option value="' + emp.lab_type_id + '">' + emp.lab_type_name + '</option>';

                    });
                    $('#labtype').append(Country);
                }
                else {
                    console.log(data);
                }
                
            }
        }
    });
}

function loadCBG() {
    var CBGdata = {
        iplab_Indicator: "IP",
        Dml_Indicator: "CBG"
    }

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

            }
            else {

                if (data2.msg == "Success") {
                    var data1 = data2.data;
                    var medicine;
                    $('#ddCBG').empty();
                    $.each(data1, function (i, emp) {
                        medicine = medicine + '<option value="' + emp.ipwhen_to_take_value + '">' + emp.ipwhen_to_take_value + '</option>';
                    });
                    $('#ddCBG').append(medicine);
                }
                else {
                    console.log(data);
                }
            }
        }
    });
}

$('#txtTestName').autocomplete({

    source: function (request, response) {
        $.ajax({
            async: true,
            url: '/CaseStudy/labAutoCompletelist?TestName=' + $('#txtTestName').val() + "&testid=" + 1 + "&labid=" + $('#lab_id').val() + "&labdatatype=" + $('#lab_data_flag').val(),
            type: "POST",
            dataType: "json",
            data: { Prefix: request.term },
            success: function (data) {
                response($.map(data, function (item) {
                    return { label: item.testname, value: item.testname };
                }))
            }
        })
    }
});

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

    if ($("#IPDischarge_Id").val() != "2")
    {
        var StartDate = $('#txtStartDate').val();
        var StartDate1 = StartDate.split('/');
        StartDate = StartDate1[2] + '-' + StartDate1[1] + '-' + StartDate1[0];

        var EndDate = $('#txtEndDate').val();
        var EndDate1 = EndDate.split('/');
        EndDate = EndDate1[2] + '-' + EndDate1[1] + '-' + EndDate1[0];


        var lab = {
            Dml_Indicator: 'IPI',
            iplab_Indicator: "IP",
            patient_id: $("#IPPatient_Id").val(),
            visit_report_id: $("#IPReportId").val(),
            lab_prescription: $("#txtTestName").val(),
            lab_type: $("#labtype").val(),
            suggested_date: StartDate,
            //slot_start_time: $('#Hdnappointment_date').val(),
            labtypetest: $('#labtypetest').val(),
            ip_cbg: $("#ddCBG").val(),
            ip_patient_notes: $("#txtPatientNotes").val(),
            ip_frequency_notes: $("#txtFrequencyNotes").val(),
            ip_when_to_execute: $("#txtexecute").val(),
            ip_end_date: EndDate,
            prescription_scan_id: $("#hlabID").val()
        }
        $.ajax({
            async: true,
            type: 'POST',
            url: '/PatientDashboard/Lab_Prescription_Ins_Upd',
            contentType: 'application/json; charset=UTF-8',
            data: JSON.stringify(lab),
            success: function (data) {

                clearlab();
                ShowLabPrescription();
            }
        });
    }
    
});

function clearlab() {

    $("#txtTestName").val(""),
    $("#labtype").val(1),
    $('#txtStartDate').val(""),
    $('#txtEndDate').val("")
    //$('#labtypetest').val(""),
    $("#ddCBG").val(1),
    $("#txtPatientNotes").val(""),
    $("#txtFrequencyNotes").val(""),
    $("#txtexecute").val(""),
    $("#hlabID").val("")
}

function Pause(val) {
    debugger;

    var labdata = {
        prescription_scan_id: val,
        Dml_Indicator: 'IPPS',
        iplab_Indicator: "IP",
        ip_lab_Investigations_status: 0
    }

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

        }
    });
}

function Start(val) {
    debugger;

    var labdata = {
        prescription_scan_id: val,
        Dml_Indicator: 'IPPS',
        iplab_Indicator: "IP",
        ip_lab_Investigations_status: 1
    }

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

        }
    });
}

function DelLap(val) {
  
    if ($("#IPDischarge_Id").val() != "2")
    {
        var labdata = {
            prescription_scan_id: val,
            Dml_Indicator: 'IPD',
            iplab_Indicator: "IP"
        }

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

                    toastr.success("Value Deleted Successfully");
                    ShowLabPrescription();
                }
                else {
                    console.log(data);
                }
                
            }
        });
    }
    
}

function loadlab_id() {
    var country = {
        Dml_Indicator: "DI",
        doctor_id: $('#HiddenDoctorID').val()
    }
    $.ajax({
        async: true,
        type: 'POST',
        url: '/Template/labtest',
        contentType: 'application/json; charset=UTF-8',
        data: JSON.stringify(country),
        success: function (data) {
            var data2 = JSON.parse(data);
            if (jQuery.isEmptyObject((data2.data))) {
            }
            else {

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

                    var Country;
                    $.each(data1, function (i, emp) {
                        $('#lab_id').val(emp.lab_id);
                    });
                }
                else {
                    console.log(data);
                }
            }
        }
    });
}


$("#btnLabParamSave").click(function () {
    var array = [];
    var j = 0;
    $('#labParameters_body tr').each(function () {
        var values = [], lblval = [];
        $(this).find("input").each(function () {
            j++;
            values.push($(this).val());
        });
        if (values == "") {
            $('#Pobs_val').show();
            $('#Pobs_val').fadeOut(8000);
            $('#Pobs_val').html('Observation Value cannot be empty');
            $('#obs_val_' + j).focus();
            $('#obs_val_' + j).val('');
            return false;
        }
        array.push(values);
    });
    var conclusion = $('#txtconclusion').val();
   
    //after validation
    var arrays = [];
    var j = 0;
    var ptsID = '', obsval = '';

    var rowCount = $('#labParameters_body tr').length;
    if (rowCount > 0) {
        $('#labParameters_body tr').each(function () {
            var $row = jQuery(this).closest('tr');
            var $columns = $row.find('td');
            var values = "";
            jQuery.each($columns, function (i, item) {
                ptsID = $(this).parent("tr").find("td:first").text();
            });
            var values = [];
            $(this).find("input").each(function () {
                values.push($(this).val());
                obsval = ($(this).val());
            });

            var ParameterResult = {              
                result_id: ptsID,
                observation: obsval,
                added_by: $('#HiddenDoctorID').val(),
                conclusion: $('#txtconclusion').val(),
                Dml_Indicator: 'RU'
            }
            $.ajax({
                async: true,
                type: 'POST',
                url: '/Template/lab_home',
                contentType: 'application/json; charset=UTF-8',
                data: JSON.stringify(ParameterResult),
                success: function (data) {
                    var data2 = JSON.parse(data);
                    var order_id = '';
                    if (jQuery.isEmptyObject((data2.data))) {

                    }
                    else {

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

                            if (data.length > 0) {
                                var a = data[0].VOrder_status;
                                if (a == null || a == '') {
                                    $('#Morderstatusid').html('(Completed)');
                                }
                                else {
                                    $('#Morderstatusid').html('(Pending)');
                                }
                            }
                        }
                        else {
                            console.log(data);
                        }
                    }

                    $('#myResultviewModal').animate({ scrollTop: 600 }, 'slow');
                    $('#labJob-section').removeClass('in');
                    $('#labJob-section').addClass('in');
                    $('#labparameterss').hide();
                    $('.close').click();
                    ShowLabPrescription();
                    $('#txtconclusion').val('');
                    $('#labParameters_body').empty();
                }

            });
        });
    }
    else {

        var ParameterResult = {
            added_by: $('#HiddenDoctorID').val(),
            conclusion: $('#txtconclusion').val(),
            job_id: $('#Mjobid').html(),
            Dml_Indicator: 'RUJ'
        }
        $.ajax({
            async: true,
            type: 'POST',
            url: '/Template/lab_home',
            contentType: 'application/json; charset=UTF-8',
            data: JSON.stringify(ParameterResult),
            success: function (data) {
                var order_id = '';
                var data2 = JSON.parse(data);
                if (jQuery.isEmptyObject((data2.data))) {

                }
                else {

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

                        if (data.length > 0) {
                            var a = data[0].VOrder_status;

                            if (a == null || a == '') {
                                $('#Morderstatusid').html('(Completed)');
                            }
                            else {
                                $('#Morderstatusid').html('(Pending)');
                            }
                        }
                    }
                    else {
                        console.log(data);
                    }
                }
                $('#txtconclusion').val('');
                $('#myResultviewModal').animate({ scrollTop: 600 }, 'slow');
                $('#labJob-section').removeClass('in');
                $('#labJob-section').addClass('in');
                $('#labparameterss').hide();
                ShowLabPrescription();
            }

        });
    }

})