var Norecord = '<div class="img-center"><img src="/Content/img/no_record.png" class="img-resposive no_record_img" style="height:65px; width:72px; border-radius:0px;"><br><div class="no_data_content">No data found.</div></div>';
var departmentideader = ($('#Hdepartment_id').val() == '') ? '' : $('#Hdepartment_id').val();
if ($('#hiddenRole_id').val() != 2) {
    var useridheder = $('#hiddenUser_id').val();
}
else {
    var useridheder = 0;
}
$(document).ready(function () {
    $('#photolog').text('');
    // loadpackagehospitalunscheduled(1);
    // ServiceProviderdetails();
    LoadDoctor();
    getserviceprovider(0);
    var hospitalid = $('#HospitalId').val();
    Branchdetails(hospitalid);
    $("#tbl").find("input,button,textarea,select").attr("disabled", "disabled");
    $("#viewTab>li").click(function () {
        var hrefActive = $(this).find('a').attr("href");
        ('#viewTab a[href="' + hrefActive + '"]').tab('show');
    });
    check_previlige_tabs(5);
    ServiceProviderdetails(0);
    getrejectreason();
});

function getrejectreason() {
    var servicevalues = {
        spname: "SP_Work_Order_Action",
        hospital_id: $('#HospitalId').val(),
        Dml_Indicator: "GREJR",
    }
    $.ajax({
        async: true,
        type: 'POST',
        url: '/Workorder/Get_Workorder',
        contentType: 'application/json; charset=UTF-8',
        data: JSON.stringify(servicevalues),
        success: function (data) {
            debugger;
            var data = JSON.parse(data);
            console.log(data);
            if (data.msg == "Success") {
                var data1 = data.data;
                var tr = '', j = 1;
                if (jQuery.isEmptyObject((data1))) {
                }
                else {
                    debugger;

                    var cdepartment = '';
                    var default_opt = '<option value="0" data-id="">--Select--</option>';
                    $.each(data1.Table, function (i, emp) {
                        cdepartment = cdepartment + '<option value="' + emp.master_servie_type_id + '" data-id="' + emp.master_service_name + '">' + emp.master_service_name + '</option>';
                    });

                    $('#rejectreason').html(default_opt + cdepartment);


                }
            }
        }
    })
}
function check_previlige_tabs(formid) {
    debugger;
    var RightData = {
        Stringtype: formid,
        Dml_Indicator: "CTABR"
    }
    $.ajax({
        async: true,
        type: 'POST',
        url: '/UserRight/User_rights_privileges',
        contentType: 'application/json; charset=UTF-8',
        data: JSON.stringify(RightData),
        success: function (data) {
            debugger;
            var data1 = JSON.parse(data);
            if (data1.msg == "Success") {
                var data1 = data1.data;
                if (jQuery.isEmptyObject((data1))) {

                }
                else {
                    var j = 0, k = 0, m = 0;

                    $.each(data1.Table, function (i, emp1) {
                        $("[data-id=" + emp1.tab_id + "]").removeClass('hidden');
                        if (i == 0 && emp1.tab_id == 'HM_V1') {
                            $('#homecareliclick,#tabHome').click();

                        }
                    })

                    $.each(data1.Table1, function (i, emp) {
                        if (emp.status == 0) {
                            $("[data-id=" + emp.role_rights_view + "]").addClass('hidden');
                        }
                        else if (emp.status == 1) {
                            if (j == 0 && emp.tab_id == 'HS_V1') {

                                $('#' + emp.tab_name).click();
                                m = m + 1;
                            }
                            if (k == 0 && emp.tab_id == 'HM_V1') {
                                if (m == 0) {
                                    $('#' + emp.tab_name).click();

                                    k = +1;
                                }
                            }

                            j = j + 1;
                        }
                    });
                }
            }
        }
    });
}

//load branch
//function Branchdetails(Hospitalid) {
//    var Branch_data = {
//        hospital_id: Hospitalid,
//        Dml_Indicator: 'SIGHB'
//    }
//    console.log('---->' + JSON.stringify(Branch_data));
//    $.ajax({
//        async: true,
//        type: 'POST',
//        url: '/Hospitalsetup/HospitalCreation',
//        contentType: 'application/json; charset=UTF-8',
//        data: JSON.stringify(Branch_data),
//        success: function (data) {
//            debugger;
//            var data = JSON.parse(data);
//            console.log(data);
//            if (data.msg == "Success") {
//                var data1 = data.data;
//                var tr = '', j = 1;
//                if (jQuery.isEmptyObject((data1))) {
//                }
//                else {
//                    debugger;


//                    $('.branch_id').empty();
//                    var branchname;
//                    var default_opt = '<option value="0" data-id="">--Select--</option>';
//                    $.each(data1.Table, function (i, emp) {
//                        branchname = branchname + '<option value="' + emp.hospital_branch_id + '" data-id="' + emp.branch_name + '">' + emp.branch_name + '</option>';
//                    });
//                    //$('.branch_id').append(default_opt + branchname);
//                    //if ($('#hiddenRole_id').val() == 1) {
//                    //    $('.branch_id').val($('#HospitalBranchID').val());
//                    //    $('.branch_id').attr('disabled', true);
//                    //}
//                    if (data1.Table.length == 1) {
//                        // alert('test');
//                        $('.branch_id').append(branchname);
//                    } else {
//                        $('.branch_id').append(default_opt + branchname);
//                    }

//                }
//            }
//            else {
//                console.log(data);
//            }
//        }
//    });

//}

function Branchdetails() {
    $('.branch_id').empty();
    $('#SelBranchSearchPopup').empty();
    //Only KinderSurge
    //var dml = ''
    //if (parseInt($('#hiddenRole_id').val()) == 1) {
    //    dml = 'DLBRAN'
    //}
    //else {
    //    dml = 'LBRAN'
    //}

    var subdepartment = {
        Dml_Indicator: "LBRAN",
        //Dml_Indicator: dml,
        name: $('#HiddenDoctorID').val()
    }
    $.ajax({
        async: true,
        type: 'POST',
        url: '/Hospitalsetup/Category_Department_Ins_Upd_sel',
        contentType: 'application/json; charset=UTF-8',
        data: JSON.stringify(subdepartment),
        success: function (data) {
            var data1 = JSON.parse(data);
            if (data1.msg == "Success") {
                var data1 = data1.data;
                console.log(data1);
                if (jQuery.isEmptyObject((data1))) {
                }
                else {
                    debugger;
                    var SubDepartment = '';
                    var default_opt = '<option value="0">--All--</option>';
                    $.each(data1.Table, function (i, emp) {
                        SubDepartment = SubDepartment + '<option value="' + emp.hospital_branch_id + '">' + emp.branch_name + '</option>';
                    });
                    if (data1.Table.length == 1) {
                        $('.branch_id').append(SubDepartment);

                        $('#SelBranchSearchPopup').append(SubDepartment);
                        branch_change();


                    }
                    else {
                        if ($('#hiddenRole_id').val() == 1) {
                            $('.branch_id').append(SubDepartment);
                        }
                        else {
                            $('.branch_id').append(default_opt + SubDepartment);
                        }

                        $('#SelBranchSearchPopup').append(default_opt + SubDepartment);

                    }

                    //Only KinderSurge
                    //if ($('#hiddenRole_id').val() == 1) {
                    //    $('.branch_id').val($('#HospitalBranchID').val());
                    //    branch_change();
                    //}
                    //else 
                    if ($('#hiddenRole_id').val() != 2) {
                        $('.branch_id').val($('#HospitalBranchID').val());
                        $('.branch_id').attr('disabled', true);

                        $('#SelBranchSearchPopup').val($('#HospitalBranchID').val());
                        $('#SelBranchSearchPopup').attr('disabled', true);
                        branch_change();


                    }
                }
            }
            else {
                console.log(data1);
            }

        }
    });
}
//Loading Doctor
function LoadDoctor(branchid) {
    var roleId = $('#hiddenRole_id').val();
    var DoctorId = $('#HiddenDoctorID').val();
    var DoctorData = {
        Dml_Indicator: "DL",
        hospital_id: $('#HospitalId').val(),
        branch_id: branchid
    }

    $.ajax({
        async: true,
        type: 'POST',
        url: '/CalendarConfiguration/HosiptalSelect',
        contentType: 'application/json; charset=UTF-8',
        data: JSON.stringify(DoctorData),
        success: function (data) {
            var data1 = JSON.parse(data)
            if (data1.msg == "Success") {
                if (jQuery.isEmptyObject((data1.data))) {
                }
                else {


                    var tr = '';
                    var SelRole = '';
                    $('#ldseldoctor').empty();
                    var default_opt = '<option value="0">--Select--</option>';
                    var j = 0;
                    if (data1.data.length > 0) {
                        for (var i = 0; i < data1.data.length; i++) {
                            j++;
                            SelRole = SelRole + '<option value="' + data1.data[i].doctor_id + '">' + data1.data[i].first_name + '</option>';
                        }
                        $('#ldseldoctor').html(default_opt + SelRole);
                        $('#ldoseldoctor').html(default_opt + SelRole);
                        $('#ldjseldoctor').html(default_opt + SelRole);
                        $('#ldcmseldoctor').html(default_opt + SelRole);
                        $('#ldcnseldoctor').html(default_opt + SelRole);
                        $('#phsseldoctor').html(default_opt + SelRole);

                    }

                }
            }
            else {
                console.log(data1);
            }
        }
    });
}

function getserviceprovider(work_order_id) {
    debugger;
    var servicevalues = {
        work_orderid: work_order_id,
        spname: "SP_Work_Order_Action",
        jobsflag: 2,
        Dml_Indicator: "LLHSP",
        departmentid: ($('#Hdepartment_id').val() == '') ? '' : $('#Hdepartment_id').val(),
    }
    $.ajax({
        async: true,
        type: 'POST',
        url: '/Workorder/Get_Workorder',
        contentType: 'application/json; charset=UTF-8',
        data: JSON.stringify(servicevalues),
        success: function (data) {
            debugger;
            var data = JSON.parse(data);
            console.log(data);
            if (data.msg == "Success") {
                var data1 = data.data;
                var tr = '', j = 1;
                if (jQuery.isEmptyObject((data1))) {
                }
                else {
                    debugger;

                    var cdepartment = '';
                    var default_opt = '<option value="0" data-id="">--Select--</option>';
                    $.each(data1.Table1, function (i, emp) {
                        cdepartment = cdepartment + '<option value="' + emp.labtranid + '" data-id="' + emp.lab_name + '">' + emp.lab_name + '</option>';
                    });

                    $('#lhjserviceprovidername').html(default_opt + cdepartment);
                    $('#lhcmserviceprovidername').html(default_opt + cdepartment);
                    $('#phmjserviceprovidername').html(default_opt + cdepartment);
                    $('#phmcmserviceprovidername').html(default_opt + cdepartment);
                    $('#phsjserviceprovidername').html(default_opt + cdepartment);
                    $('#phscmserviceprovidername').html(default_opt + cdepartment);
                    $('#serviceprovider').html(default_opt + cdepartment);

                }
            }
        }
    })

}

//Show/hide service subtable
function servicedetails(e, id, flag, wtype) {
    // alert('test')
    debugger;
    var tr = e.closest('tr');
    if (flag == 'advice') {
        var row = $('#labadvicetable').DataTable().row(tr);
    }
    else if (flag == 'diaorder') {
        var row = $('#labordertable').DataTable().row(tr);

    }
    else if (flag == 'lhorder') {
        var row = $('#lhordertable').DataTable().row(tr);

    }
    else if (flag == 'pkghmcorders') {
        var row = $('#pkhmcordertable').DataTable().row(tr);

    }
    else if (flag == 'pkghscorders') {
        var row = $('#pkhscordertable').DataTable().row(tr);

    }
    else if (flag == 'pkghscadvice') {
        var row = $('#pkhscadvicetable').DataTable().row(tr);

    }
    console.log(row);
    //var row = $('#request_view').DataTable().row(tr);

    if (row.child.isShown()) {
        // This row is already open - close it
        row.child.hide();
        // tr.removeClass('shown');
    }
    else {
        // Open this row
        row.child(getservicedetails(id, wtype)).show();
        //  tr.addClass('shown');
    }
}
//getting service details for subtable
function getservicedetails(id, wtype) {
    debugger;
    div = $('<div/>')
        .addClass('loading')
        .addClass('table_child')
        .addClass('table-responsive');
    var service_data = {
        work_orderid: id,
        flag: wtype,
        spname: "SP_Work_Order_Action",
        Dml_Indicator: 'SD'
    }
    $.ajax({
        async: true,
        type: 'POST',
        url: '/Workorder/Get_Workorder',
        contentType: 'application/json; charset=UTF-8',
        data: JSON.stringify(service_data),
        success: function (data) {
            debugger;
            var data = JSON.parse(data);
            console.log(data);
            if (data.msg == "Success") {
                var data1 = data.data;
                var tr = '', j = 1;

                if (jQuery.isEmptyObject((data1))) {
                }

                else {
                    div.removeClass('loading')

                    var row = 2;
                    var tr, row_data;
                    tr = $('<table class="table table-condensed body-borderless table_bordered">');
                    tr.append('<thead><tr><th>S.No</th><th>Service Code</th><th>Service Name</th><th>Number of Usage</th><th>Reason</th><th>Action</th></tr></thead><tbody>');
                    $.each(data1.Table, function (i, emp) {

                        row_data = '<tr id="t_' + emp.work_order_details_id + '"><td>' + j + '</td><td>' + emp.service_code + '</td><td>' + emp.service_name + '</td><td>' + emp.quantity + '</td><td><textarea id="reason_' + emp.work_order_details_id + '"></textarea></td><td><a id="servicedel_' + emp.work_order_details_id + '" class="btn deleteicon-btn btn-xs" href="javascript:void(0);" onclick=servicedel("' + emp.work_order_details_id + '")><i class="fa fa-trash" aria-hidden="true"></i></a></td></tr>';


                        j = j + 1;
                        tr.append(row_data);
                    })
                    tr.append("</tbody>");

                    div.append(tr);

                }
            }
            else {
                console.log(data);
            }
        }
    });
    return div;
}
//delete request service details
function servicedel1(val, flag, tabs, pkg_id, wrk_ord_id) {
    debugger;
    $('#overalldeletewid').val(val);
    $('#overalldeletewoid').val(wrk_ord_id);
    $('#overalldeletetabs').val(tabs);
}
//function deleteservice(event)
$('#overalldeletebtn').click(function () {


    var val = $('#overalldeletewid').val();
    var woid = $('#overalldeletewoid').val();
    var tabs = $('#overalldeletetabs').val();
    servicedel(val, 1, tabs, '0', woid, 1);
    $('#overalldeletewid').val('');
    $('#overalldeletewoid').val('');
    $('#overalldeletetabs').val('')
})
function servicedel(val, flag, tabs, pkg_id, wrk_ord_id, deleteflag) {
    debugger;
    var reason = '';
    if (deleteflag == 1) {
        reason = $("#deletereason").val();
        if (reason == '') {
            toastr.warning('Please Enter Reason');
            $("#deletereason").focus();
            return;

        }
    }
    else {
        reason = $("#reason_" + val + "").val();
        if (reason == '') {
            toastr.warning('Please Enter Reason');
            $("#reason_" + val + "").focus();
            return;

        }
    }
    var msg = "";
    if (pkg_id == '' || pkg_id == '0') {
        msg = "Are You Sure Do You Want Delete This Service?";
    }
    else if (pkg_id != '' || pkg_id != '0') {
        flag = 4;
        pkg_id = pkg_id;
        wrk_ord_id = wrk_ord_id;
        msg = "Are You Sure Do You Want Delete All Package Services?";
    }

    else if (flag == 3) {
        msg = "Are You Sure Do You Want Delete This Service";
    }
    else if (flag == 1 || flag == 10 || flag == 11 || flag == 12 || flag == 13) {
        msg = "Are You Sure Do You Want Delete All This Service";
    }
    toastr.warning("<button type='button' id='confirmationRevertYes' class='btn btn-warning btn-xs mt20'>Yes<button type='button' id='confirmationRevertNo' class='btn btn-warning btn-xs mt20'>No", msg,
        {
            closeButton: true,
            progressBar: true,
            allowHtml: true,
            timeOut: 20000000,

            onShown: function (toast) {
                $("#confirmationRevertYes").click(function () {
                    debugger;
                    var servicevalues = {
                        work_order_details_id: wrk_ord_id,
                        samplbarcodeid: val,
                        servicename: pkg_id,
                        serviceprovidername: reason,
                        work_orderid: wrk_ord_id,
                        flag: 1,
                        spname: "SP_Work_Order_Action",
                        Dml_Indicator: "DRSD"
                    }

                    $.ajax({
                        async: true,
                        type: 'POST',
                        url: '/Workorder/Get_Workorder',
                        contentType: 'application/json; charset=UTF-8',
                        data: JSON.stringify(servicevalues),
                        success: function (data) {
                            debugger;
                            var data = JSON.parse(data);
                            console.log(data);
                            if (data.msg == "Success") {
                                debugger;
                                var data1 = data.data;
                                if (jQuery.isEmptyObject((data1))) {
                                }
                                else {
                                    if (data1.Table[0].status == "mapped") {

                                        toastr.warning("This Service Already Mapped, So You Can Not Delete This Sevice");
                                        return false;
                                    } else {

                                        toastr.success("Successfully deleted")


                                        $('#t_' + val).remove();
                                        if (tabs == 'phmc') {

                                            $("#spackagehomecancelled").tab('show');
                                            loadpkghomecancelledservice(1);
                                        }
                                        else if (tabs == 'phsc') {

                                            $("#spackagehospitalcancelled").tab('show');
                                            loadpkghospitalcancelledservice(1);
                                        }
                                    }
                                }
                            }
                        }
                    });
                })
            }
        })
}
//lab diagnostics getsample dropdown
function labordersample(val, val1, work_order_id, patientid, tabflag, wtype, pkid, work_order_status, serviceproviderid, patient_id, visit_report_id, branchid, hospitalid, wid) {

    $('#ldcsampletable > tbody').empty();
    PatientSearch(patient_id, 0, branchid, visit_report_id)
    $('#poppatientid').val(patientid);
    $('#popworkorder_id').val(work_order_id);
    $('#pophospitalid').val(hospitalid);
    $('#popbranchid').val(branchid);


    // alert('test')
    debugger;
    var flag;
    $('#masterserviceid').val('');
    if (serviceproviderid == '0' || serviceproviderid == '') {

        $('#csserviceprovidernamelb').hide();
        $('#csserviceprovidername').hide();
        $('#csserviceprovidercontact').hide();
        $('#csserviceprovidercontactlb').hide();


    }
    else {
        $('#csserviceprovidernamelb').show();
        $('#csserviceprovidername').show();
        $('#csserviceprovidercontact').show();
        $('#csserviceprovidercontactlb').show();
    }
    if (tabflag == 'ld') {
        //$('#csserviceprovidernamelb').hide();
        //$('#csserviceprovidername').hide();
        //$('#csserviceprovidercontact').hide();
        //$('#csserviceprovidercontactlb').hide();
        $('#labhometranidr').val(0);
        flag = 1;
    }
    else if (tabflag == 'lh') {
        //$('#csserviceprovidernamelb').show();
        //$('#csserviceprovidername').show();
        //$('#csserviceprovidercontact').show();
        //$('#csserviceprovidercontactlb').show();
        var lid = $('#ldtwork_order_no_' + val1 + '').data('id');
        $('#labhometranidr').val(lid);
        flag = 1;
    }
    else if (tabflag == 'phmc') {
        //$('#csserviceprovidernamelb').show();
        //$('#csserviceprovidername').show();
        //$('#csserviceprovidercontact').show();
        //$('#csserviceprovidercontactlb').show();
        var lid = $('#ldtwork_order_no_' + val1 + '').data('id');
        $('#labhometranidr').val(lid);
        flag = 3;
    }
    else if (tabflag == 'phmsc') {
        //$('#csserviceprovidernamelb').show();
        //$('#csserviceprovidername').show();
        //$('#csserviceprovidercontact').show();
        //$('#csserviceprovidercontactlb').show();
        var lid = $('#ldtwork_order_no_' + val1 + '').data('id');
        $('#labhometranidr').val(lid);
        flag = 2;
    }

    $("#tapflag").val(tabflag);
    var patientname = $("#ldtpatient_username_" + val1 + "").html();
    var ldtpatient_id = $("#ldtpatient_id_" + val1 + "").html();
    var ldtwork_order_no = $("#ldtwork_order_no_" + val1 + "").html();
    var ldtpatient_id = $("#ldtpatient_id_" + val1 + "").html();
    $('#serviceproviderid').val('');
    $('#master_service_id').val('');
    $('#master_service_id').val(pkid);
    $('#work_order_status').val(work_order_status);
    $('#ldcpatientname').val(patientname);
    $('#ldcpatientid').val(ldtpatient_id);
    $('#work_orderid').val(work_order_id);
    $('#serviceproviderid').val(serviceproviderid);
    $('#request_id').val(val);
    $('#patientid').val(patientid);
    $('#work_order_type').val(wtype);
    if (pkid == "") {
        pkid = 0;
    }
    var servicevalues = {
        request_id: val,
        jobsflag: wtype,
        serviceproviderid: serviceproviderid,
        flag: flag,
        barcodeid: pkid,
        work_order_status: work_order_status,
        work_orderid: work_order_id,
        serviceprovidername: wid,
        Dml_Indicator: "LCST",
        spname: "SP_Work_Order_Action",
        departmentid: departmentideader
    }

    $.ajax({
        async: true,
        type: 'POST',
        url: '/Workorder/Get_Workorder',
        contentType: 'application/json; charset=UTF-8',
        data: JSON.stringify(servicevalues),
        success: function (data) {
            debugger;
            var data = JSON.parse(data);
            console.log(data);
            if (data.msg == "Success") {
                var data1 = data.data;
                if (jQuery.isEmptyObject((data1))) {
                    $('#ldcsampletable > tbody').empty();
                }
                else {


                    debugger;


                    var dd = data1.Table.length;
                    $('#ldcdepartment').empty();
                    $('#ldcnosamplecollect').val(dd);
                    var j = 0;
                    $('#ldcsampletable > tbody').empty();
                    var count = 0, value = '';
                    $.each(data1.Table, function (i, emp) {
                        j = i + 1;
                        if (emp.samplbarcodeid != '') {
                            var checked = "checked";
                        }

                        value = value + "<tr class='tr_input number' data-id='" + j + "' id='t_" + j + "'><td>" + j + "</td><td id='twork_order_details_id_" + j + "' hidden>" + emp.work_order_details_id + "</td><td id='tmaster_service_id_" + j + "' hidden>" + emp.master_service_id + "</td><td id='tsamplebarid_" + j + "' class='tsamplebarid_" + emp.work_order_details_id + emp.sample_id + "' hidden>" + emp.samplebarid + "</td><td id='tdepartmentid_" + j + "' hidden>" + emp.sub_category_department_id + "</td><td id='tsampleid_" + j + "' hidden>" + emp.sample_id + "</td><td id='tldcservicename_" + j + "'>" + emp.service_name + "</td><td id='tldctube_" + j + "' value=" + emp.tubecontainerid + " class='ttubecontainer'>" + emp.tubename + "</td><td id='tldcsampletype_" + j + "'>" + emp.name + "</td><td id='tldcdepartment_" + j + "'>" + emp.sub_cd_name + "</td><td id='tldcsamplebadrcode_" + j + "' class='tldcsamplebadrcode_" + emp.work_order_details_id + emp.sample_id + "' data-id=" + emp.barcodeid + ">" + emp.samplbarcodeid + "</td><td><input " + checked + " type='checkbox' id='chk_" + j + "' class='chksampleclass'></td><td><button class='btn btn-primaryuse tldbarcodeid_" + emp.work_order_details_id + emp.sample_id + "' onclick='jobprintbarcode1(this)'  id=" + emp.barcodeid + " data-id=" + emp.barcodeid + " data-id1=" + emp.samplbarcodeid + "><i class='fa fa-print' aria-hidden='true'></i></button></td></tr>";
                    });
                    $('#ldcsampletable > tbody:last').append(value);



                }
            }
            else {
                console.log(data);
            }
        }
    });

}


//lab diagnostics get department dropdown 
$('#ldcdepartment').change(function () {
    var sample_id = $('#ldcdepartment').val();
    getsample(null);

});
function getsample(sample_id) {
    $('#ldcsampletable > tbody').empty();
    debugger;
    var sample_id1 = $('#ldcdepartment').val();
    var servicevalues = {
        sample_id: sample_id1,
        serviceprovidername: $('#masterserviceid').val(),
        servicename: $('#workorderdetailsids').val(),
        hospital_id: $('#HospitalId').val(),
        branchid: $('#Hbranch_id').val(),
        Dml_Indicator: "LCSD",
        spname: "SP_Work_Order_Action",
        departmentid: departmentideader
    }

    $.ajax({
        async: true,
        type: 'POST',
        url: '/Workorder/Get_Workorder',
        contentType: 'application/json; charset=UTF-8',
        data: JSON.stringify(servicevalues),
        success: function (data) {
            debugger;
            var data = JSON.parse(data);
            console.log(data);
            if (data.msg == "Success") {
                var data1 = data.data;
                var tr = '', j = 1;
                if (jQuery.isEmptyObject((data1))) {
                }
                else {
                    debugger;
                    $('#ldcsampletype').empty();
                    var cdepartment;

                    var default_opt = '<option value="0" data-id="">--Select--</option>';
                    $.each(data1.Table, function (i, emp) {
                        cdepartment = cdepartment + '<option value="' + emp.sample_id + '" data-id="' + emp.name + '">' + emp.name + '</option>';
                    });
                    if (data1.Table.length != 1) {
                        $('#ldcsampletype').append(default_opt + cdepartment);
                    }
                    else {
                        $('#ldcsampletype').append(cdepartment);

                    }
                    var j = 0;
                    $('#ldcsampletable > tbody').empty();
                    var value = '';

                    var count = 0;
                    $.each(data1.Table1, function (i, emp) {
                        j = i + 1;
                        if (emp.samplbarcodeid != '') {
                            var checked = "checked";
                        }

                        value = value + "<tr class='tr_input number' data-id='" + j + "' id='t_" + j + "'><td>" + j + "</td><td id='twork_order_details_id_" + j + "' hidden>" + emp.work_order_details_id + "</td><td id='tmaster_service_id_" + j + "' hidden>" + emp.master_service_id + "</td><td id='tsamplebarid_" + j + "' class='tsamplebarid_" + emp.work_order_details_id + emp.sample_id + "' hidden>" + emp.samplebarid + "</td><td id='tdepartmentid_" + j + "' hidden>" + emp.sub_category_department_id + "</td><td id='tsampleid_" + j + "' hidden>" + emp.sample_id + "</td><td id='tldcservicename_" + j + "'>" + emp.service_name + "</td><td id='tldctube_" + j + "' value=" + emp.tubecontainerid + " class='ttubecontainer'>" + emp.tubename + "</td><td id='tldcsampletype_" + j + "'>" + emp.name + "</td><td id='tldcdepartment_" + j + "'>" + emp.sub_cd_name + "</td><td id='tldcsamplebadrcode_" + j + "' class='tldcsamplebadrcode_" + emp.work_order_details_id + emp.sample_id + "' data-id=" + emp.barcodeid + ">" + emp.samplbarcodeid + "</td><td><input " + checked + " type='checkbox' id='chk_" + j + "'></td><td><button class='btn btn-primaryuse  btn-sm btn-add' onclick='jobprintbarcode1(this)' id='tldbarcodeid_" + emp.work_order_details_id + emp.sample_id + "' data-id=" + j + " data-id1=" + emp.samplbarcodeid + " ><i class='fa fa-print' aria-hidden='true'></i></button></td></tr>";
                    });
                    $('#ldcsampletable > tbody:last').append(value);
                }
            }
            else {
                console.log(data);
            }
        }
    });
}
$('#ldctubecontainer').change(function () {
    var tubename = $('#ldctubecontainer').val();
    var tubeid = $('#ldctubecontainer').data('id');
    $('.ttubecontainer').html(tubename);
    $('.ttubecontainer').val(tubeid);
});

$('#ldcgeneratebarcode').click(function () {
    debugger;
    var serviceproviderid = $('#serviceproviderid').val();
    var work_orderid = $('#work_orderid').val();
    var master_service_id = $('#master_service_id').val();
    var work_order_status = $('#work_order_status').val();
    var serviceproviderid = $('#serviceproviderid').val();
    var patientid = $('#patientid').val();
    var ldsamplebarid = $('#ldsamplebarid').val();
    var request_id = $('#request_id').val();
    var created_on = $('#txt_date_time').val();
    var customers = new Array();
    var chkcount = 0;
    var tot_rowM = $('#ldcsampletable >tbody >tr').length;
    if (tot_rowM > 0) {
        var L = 0;
        for (j = 1; j <= tot_rowM; j++) {
            var customer = {};
            var isChecked = $('#chk_' + j).is(":checked");
            if (isChecked) {
                debugger;
                chkcount = chkcount + 1;
                customer.sno = j,
                    customer.work_orderid = work_orderid,
                    customer.serviceproviderid = serviceproviderid,
                    customer.request_id = request_id,
                    customer.work_order_status = work_order_status,
                    customer.departmentid = $('#tdepartmentid_' + j).html(),
                    customer.work_order_details_id = $('#twork_order_details_id_' + j).html(),
                    customer.patientid = patientid,
                    customer.Dml_Indicator = 'LCSB',
                    customer.spname = "SP_Work_Order_Action",
                    customer.master_service_id = $('#tmaster_service_id_' + j).html(),
                    customer.sample_id = $('#tsampleid_' + j).html(),
                    customer.tubecontainerid = ($('#tldctube_' + j).val() == '') ? 0 : $('#tldctube_' + j).val(),
                    customer.created_by = $('#hiddenUser_id').val();
                customer.created_on = created_on
                customers.push(customer);
            }
        }

        $.ajax({
            async: true,
            type: 'POST',
            url: '/Workorder/Samplebarcode_Generate',
            contentType: 'application/json; charset=UTF-8',
            data: JSON.stringify(customers),
            success: function (data) {
                debugger;
                var data = JSON.parse(data);
                console.log(data);
                if (data.msg == "Success") {
                    var data1 = data.data;
                    var tr = '', j = 1;
                    if (jQuery.isEmptyObject((data1))) {
                    }
                    else {
                        $.each(data1.Table1, function (i, emp) {


                            $('.tsamplebarid_' + data1.Table1[i].work_order_details_id + data1.Table1[i].sampleid).val(data1.Table1[i].samplebarid);
                            $('.tldcsamplebadrcode_' + data1.Table1[i].work_order_details_id + data1.Table1[i].sampleid).val(data1.Table1[i].samplbarcodeid);
                            $('.tsamplebarid_' + data1.Table1[i].work_order_details_id + data1.Table1[i].sampleid).html(data1.Table1[i].samplebarid);
                            $('.tldcsamplebadrcode_' + data1.Table1[i].work_order_details_id + data1.Table1[i].sampleid).html(data1.Table1[i].samplbarcodeid);
                            $('.tldcsamplebadrcode_' + data1.Table1[i].work_order_details_id + data1.Table1[i].sampleid).data('id', data1.Table1[i].barcodeid);
                            $('.tldbarcodeid_' + data1.Table1[i].work_order_details_id + data1.Table1[i].sampleid).data('id', data1.Table1[i].barcodeid);
                            $('.tldbarcodeid_' + data1.Table1[i].work_order_details_id + data1.Table1[i].sampleid).data('id1', data1.Table1[i].samplbarcodeid);
                        });
                        toastr.success("Barcode Generated Successfully");
                        jobprintbarcodeall('ldcsampletable');
                        $('#ldcollect_samplepopup .close').click();
                        loadpackagehospitaljobs(1, 'LPKHSCRS', 1, 'pkhscreceivesampletable', 'rs');
                      //  loadpackagehospitaljobs(1, 'LPKHSCPR', 3, 'pkhscpendingapprovaltable', 'pr');
                          $("#spackagehospitalreceivesample").tab('show');
                        if (chkcount = tot_rowM) {
                            tapflag = $("#tapflag").val();
                        }
                    }
                }
                else {
                    console.log(data);
                }

            }
        });
    }
});



//add   collect sample barcode
$('#Add_ldcsample_record').click(function () {
    debugger;
    var samplebadrcode = '';
    var ldcsampletype = $('#ldcsampletype option:selected').data('id');
    //var master_service_id = $('#ldcsampletype option:selected').data('id1');
    var ldcdepartment = $('#ldcdepartment option:selected').data('id');
    var sampleid = $('#ldcsampletype').val();
    var departmentid = $('#ldcdepartment').val();
    var work_orderid = $('#work_orderid').val();
    var master_service_id = $('#master_service_id').val();
    var work_order_status = $('#work_order_status').val();
    var serviceproviderid = $('#serviceproviderid').val();
    if (master_service_id == null) {
        master_service_id = 0;

    }
    var patientid = $('#patientid').val();
    var ldsamplebarid = $('#ldsamplebarid').val();
    var request_id = $('#request_id').val();




    if ($.trim((ldcsampletype)) == "") {
        $('#Pldcsampletype').show();
        $('#Pldcsampletype').fadeOut(8000);
        $('#Pldcsampletype').html('Select Sample Name');
        $('#ldcsampletype').focus();
        return false;
    }
    if ($.trim((ldcdepartment)) == "") {
        $('#Pldcdepartment').show();
        $('#Pldcdepartment').fadeOut(8000);
        $('#Pldcdepartment').html('Select Department Name');
        $('#ldcdepartment').focus();
        return false;
    }

    var paraid = $("#ldsamplebarcode").val();
    if (paraid == "") {


        var servicevalues = {
            Dml_Indicator: "LCSB",
            sample_id: sampleid,
            request_id: request_id,
            work_orderid: work_orderid,
            serviceproviderid: serviceproviderid,
            work_order_status: work_order_status,
            departmentid: departmentid,
            patientid: patientid,
            spname: "SP_Work_Order_Action",
        }
        $.ajax({
            async: true,
            type: 'POST',
            url: '/Workorder/Get_Workorder',
            contentType: 'application/json; charset=UTF-8',
            data: JSON.stringify(servicevalues),
            success: function (data) {
                debugger;

                var data = JSON.parse(data);
                console.log(data);
                if (data.msg == "Success") {
                    var data1 = data.data;
                    if (jQuery.isEmptyObject((data1))) {
                    }
                    else {
                        var data1 = data.data;
                        if (data1.Table[0].status == 'Already here') {
                            toastr.warning('This Sample already Generated');
                            return;
                        }
                        samplebadrcode = data1.Table[0].samplbarcodeid;
                        //var ikey = "0";
                        var rowcount = $('#ldcsampletable >tbody >tr').length;
                        if (rowcount == 0) {
                            var ikey = 1
                        }
                        else {

                            var max = 0;

                            $('.number').each(function () {

                                var value = parseInt($(this).data('id'));

                                max = (value > max) ? value : max;

                            });
                            var ikey = Number(max) + 1;
                        }

                        var value = "<tr class='tr_input number' data-id='" + ikey + "' id='t_" + ikey + "'><td>" + ikey + "</td><td id='tmaster_service_id_" + ikey + "' hidden>" + master_service_id + "</td><td id='tsamplebarid_" + ikey + "' hidden>" + ldsamplebarid + "</td><td id='tdepartmentid_" + ikey + "' hidden>" + departmentid + "</td><td id='tsampleid_" + ikey + "' hidden>" + sampleid + "</td><td id='tldcsampletype_" + ikey + "'>" + ldcsampletype + "</td><td id='tldcdepartment_" + ikey + "'>" + ldcdepartment + "</td><td id='tldcsamplebadrcode_" + ikey + "' data-id=" + emp.barcodeid + ">" + samplebadrcode + "</td><td><button class='btn btn-primaryuse  btn-sm btn-add' onclick='jobprintbarcode1(this)' id='tldbarcodeid_" + ikey + "' data-id=" + ikey + "  data-id1=" + samplebadrcode + " ><i class='fa fa-print' aria-hidden='true'></i></button></td></tr>";

                        $('#ldcsampletable > tbody:last').append(value);
                        $('#ldcsampletype').val('0');
                        $('#ldcdepartment').val('0');
                    }
                }
            }
        });


    }





});
//  edit lab diagnostics sample collect 
function ldcsampleedit(val) {

    debugger;

    var tdepartmentid = $('#tdepartmentid_' + val).html();

    var tsampleid = $('#tsampleid_' + val).html();

    $('#ldcdepartment').val(tdepartmentid);

    $('#ldcsampletype').val(tsampleid);

    $('#rowid').val(val);

    $('#Add_ldcsample_record').hide();
    $('#Update_ldcsample_record').show();
    //getdepartment(tdepartmentid);
}


// delete lab diagnostics sample collect 
function ldcsampledelete(val) {
    debugger;

    var paraid = $("#tsamplebarid_" + val + "").html();
    if (paraid != "") {

        var servicevalues = {
            Dml_Indicator: "DCS",
            samplbarcodeid: paraid,
            spname: "SP_Work_Order_Action"

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

                var data2 = JSON.parse(data);

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

                }
                else {

                    if (data2.msg == "Success") {
                        sessionStorage.removeItem(val);
                        $('#t_' + val).remove();
                    }
                }
            }
        });
    }

    else {
        sessionStorage.removeItem(val);
        $('#t_' + val).remove();


    }
}
// update collect sample barcode

$('#Update_ldcsample_record').click(function () {
    debugger;
    var ldcsampletype = $('#ldcsampletype option:selected').data('id');
    var ldcdepartment = $('#ldcdepartment option:selected').data('id');
    var sampleid = $('#ldcsampletype').val();
    var departmentid = $('#ldcdepartment').val();
    var rowid = $('#rowid').val();
    $('#tldcsampletype_' + rowid).html(ldcsampletype);
    $('#tldcdepartment_' + rowid).html(ldcdepartment);
    $('#tsampleid_' + rowid).html(sampleid);
    $('#tdepartmentid_' + rowid).html(departmentid);
    $('#ldcsampletype').val('0');
    $('#ldcdepartment').val('0');
    $('#Add_ldcsample_record').show();
    $('#Update_ldcsample_record').hide();
});

//update collect sample flag
$('#ldcsamplesubmit').click(function () {



    var rowcount = $('#ldcsampletable >tbody >tr').length;
    if (rowcount == 0) {
        toastr.warning("Please Generate Sample Barcode");
        return false;
    }
    var work_orderid = $('#work_orderid').val();
    var request_id = $('#request_id').val();
    var samplecount = $('#ldcnosamplecollect').val();
    var master_service_id = $('#master_service_id').val();
    var work_order_status = $('#work_order_status').val();
    var labhometranid = $('#labhometranidr').val();
    var flag = $('#work_order_type').val();
    var serviceproviderid = $('#serviceproviderid').val();
    var servicevalues = {
        Dml_Indicator: "UWCS",
        request_id: request_id,
        work_orderid: work_orderid,
        serviceproviderid: serviceproviderid,
        work_order_status: work_order_status,
        sample_id: samplecount,
        spname: "SP_Work_Order_Action",
        samplbarcodeid: (labhometranid == '') ? 0 : labhometranid,
        flag: flag,

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

            var data = JSON.parse(data);
            console.log(data);
            if (data.msg == "Success") {
                var data1 = data.data;
                if (jQuery.isEmptyObject((data1))) {
                }
                else {

                    toastr.success('Sample collect successfully');
                    tapflag = $("#tapflag").val();

                    if (tapflag == 'phmc') {


                        $('#ldcollect_samplepopup .close').click();
                        $("#spackagehomejobs").tab('show');
                        loadpackagehomejobs(1);
                    }
                    else if (tapflag == 'phmsc') {


                        $('#ldcollect_samplepopup .close').click();
                        $("#spackagehospitaljobs").tab('show');
                        loadpackagehospitaljobs(1);
                    }

                }
            }
        }
    });
    $('#labhometranidr').val('');
    $('#work_order_type').val('');
});
var parameterCalculations = {};

//get sample type parameters
var responsedatalabtest = '';
function ldlabresult(requestid, workorderid, samplid, master_service_id, btnflag, tabflag, flag, wtype, samplbarcodeid, hospitalid, branchid, patient_auto_id, patient_id, visit_report_id) {
    debugger;
    $('#ldresultconclusiondiv').hide();
    $('#div_labresult_2').hide();
    $('#div_labresult_1').hide();
    PatientSearch(patient_id, 0, branchid, visit_report_id)
    //if (btnflag == 'ReceiveSample') {
    //    toastr.warning("<button type='button' id='confirmationRevertYes' class='btn btn-warning btn-xs mt20'>Yes<button type='button' id='confirmationRevertNo' class='btn btn-warning btn-xs mt20'>No", 'Are You Sure Do you Receive This Sample',
    //        {
    //            closeButton: true,
    //            progressBar: true,
    //            allowHtml: true,
    //            timeOut: 20000000,

    //            onShown: function (toast) {
    //                $("#confirmationRevertYes").click(function () {
    //                    var readflag = '';
    //                    var edittag = '', indicator = '';
    //                    $('#photolog').empty();
    //                    $('#docpathvalue').val('');
    //                    $('#tapflagad').val(tabflag);
    //                    $('#popworkorder_id').val(workorderid);
    //                    $('#pophospitalid').val(hospitalid);
    //                    $('#popbranchid').val(branchid);
    //                    $('#poppatientid').val(patient_auto_id);
    //                    $('#popsampleid').val(samplbarcodeid);

    //                    var servicevalues = {
    //                        Dml_Indicator: "LLDLP",
    //                        sample_id: samplid,
    //                        barcodeid: wtype,
    //                        samplbarcodeid: samplbarcodeid,
    //                        work_orderid: workorderid,
    //                        jobsflag: btnflag,
    //                        flag: flag,
    //                        spname: "SP_Work_Order_Action",
    //                        UserId: $('#hiddenUser_id').val(),
    //                        created_by: $('#hiddenUser_id').val()
    //                    }
    //                    $.ajax({
    //                        async: true,
    //                        type: 'POST',
    //                        url: '/Workorder/Get_Workorder',
    //                        contentType: 'application/json; charset=UTF-8',
    //                        data: JSON.stringify(servicevalues),
    //                        success: function (data) {
    //                            debugger;

    //                            var data = JSON.parse(data);
    //                            console.log(data);
    //                            if (data.msg == "Success") {
    //                                var data1 = data.data;
    //                                if (jQuery.isEmptyObject((data1))) {
    //                                }
    //                                else {
    //                                    if (btnflag == 'ReceiveSample') {

    //                                        if (data1.Table[0].status == 'Success') {
    //                                            toastr.success('Sample Received Successfully');
    //                                            if (tabflag == 'phmsc') {
    //                                                $("#spackagehospitaljobs").tab('show');
    //                                                loadpackagehospitaljobs(1, "LPKHSCJ", 1, 'pkhscjobtable', 'jo');
    //                                            }
    //                                            else if (tabflag == 'phmc') {
    //                                                $("#spackagehomejobs").tab('show');
    //                                                loadpackagehomejobs(1, "LPKHCJ", 2, 'pkhmcjobtable', 'jo');
    //                                            }

    //                                        }

    //                                    }
    //                                    else if (btnflag == 'AddResults') {
    //                                        readflag = '';
    //                                        $("#ldaddresult").show();
    //                                        $('#ldresultaction').hide();
    //                                        $("#ldaddresult").html('Submit')
    //                                        $("#ldaddresult").val('Submit')
    //                                        $('#btnResultPrint').hide();
    //                                        $('#btnResultSendMail').hide();
    //                                        edittag = '';

    //                                    }
    //                                    else if (btnflag == 'Verify') {
    //                                        $('#ldresultaction').show();
    //                                        $("#ldaddresult").show();
    //                                        readflag = 'readonly';
    //                                        $("#ldaddresult").html('Verified')
    //                                        $("#ldaddresult").val('Verified')
    //                                        $('#btnResultPrint').show();
    //                                        $('#btnResultSendMail').show();
    //                                        edittag = '<button class="btn editicon-btn btn-xs" data-toggle="tooltip" data-placement="bottom" title="Edit"><i class="fa fa-pencil" aria-hidden="true"></i></button>';



    //                                    }
    //                                    else if (btnflag == 'View') {
    //                                        readflag = 'disabled';
    //                                        $("#ldaddresult").hide();
    //                                        edittag = '';
    //                                        $('#ldresultaction').hide();
    //                                        $('#btnResultPrint').show();
    //                                        $('#btnResultSendMail').show();

    //                                    }

    //                                    var b = data1.Table;
    //                                    $('#ldlabParameters_body').empty();
    //                                    //$('#ldresultconclusion').val(b[0].conclusion);

    //                                    tr = '';
    //                                    var servicename =
    //                                    $.each(b, function (i, emp) {


    //                                        if (service_name != emp.doctor_module_name) {
    //                                            Tservice_name = emp.doctor_module_name;
    //                                        }
    //                                        else {
    //                                            Tservice_name = '';
    //                                        }
    //                                        service_name = emp.doctor_module_name;
    //                                        tr = tr + '<tr id="t_' + emp.parameter_id + '"><td id="ldbarcodeid_' + i + '" hidden>' + emp.samplbarcodeid + '</td><td id="ldsampleid_' + i + '" hidden>' + emp.sample_id + '</td><td id="ldresultid_' + i + '" hidden>' + emp.resultid + '</td><td id="ldwork_order_details_id_' + i + '" hidden>' + emp.work_order_details_id + '</td><td id="samplebarid_' + i + '" hidden>' + emp.samplebarid + '</td><td id="master_service_id_' + i + '" hidden>' + emp.master_service_id + '</td><td id="ldparameter_id_' + i + '" hidden>' + emp.parameter_id + '</td><td id="ldrequestid_' + i + '" hidden>' + requestid + '</td><td id="ldworkorderid_' + i + '" hidden>' + workorderid + '</td> <td id="ldservice_name_' + i + '">' + Tservice_name + '</td><td id="ldparameter_name_' + i + '">' + emp.parameter_name + '</td><td><textarea type="text"  ' + readflag + '  class="sm-field"  id="ldobsval_' + i + '" style="width: 321px; height: 70px;" >' + emp.observation + '<textarea></td><td id="ldreference_value_' + i + '"><textarea  style="border:none" style="width: 321px; height: 70px;">' + emp.reference_value + '</textarea></td><td id="unit_' + i + '">' + emp.unit + '</td><td><textarea type="text" id="ldconclusion_' + i + '" >' + emp.conclusion + '</textarea></td>' + edittag + '</tr>';
    //                                    });

    //                                    $('#ldlabParameters_body').html(tr);

    //                                    var str = b[0].document_path;


    //                                    if (str != "" && str != null) {
    //                                        $('#docpathvalue').val(str);
    //                                        var temp = new Array();
    //                                        temp = str.split(",");

    //                                        var strarray = str.split(',');
    //                                        var j = 0;
    //                                        for (var i = 0; i < strarray.length; i++) {
    //                                            j = j + 1;
    //                                            $('#photolog').append('<a href="' + $('#hdnfilepath1').val() + $('#HospitalId').val() + "/" + $('#pkg_branch_id').val() + "/Lab_Documents/" + strarray[i] + '" target="_blank">' + strarray[i] + '' + '/' + '');
    //                                        }
    //                                    }



    //                                }
    //                            }
    //                        }
    //                    });
    //                })
    //            }
    //        })

    //}



    //else {


    var readflag = '';
    var edittag = '', indicator = '';
    $('#photolog').empty();
    $('#docpathvalue').val('');
    $('#popbarcodeid').val('');
    $('#tapflagad').val(tabflag);
    $('#popworkorder_id').val(workorderid);
    $('#pophospitalid').val(hospitalid);

    $('#popbranchid').val(branchid);
    $('#poppatientid').val(patient_auto_id);
    $('#popsampleid').val(samplbarcodeid);

    var servicevalues = {
        Dml_Indicator: "LLDLP",
        sample_id: samplid,
        barcodeid: wtype,
        samplbarcodeid: samplbarcodeid,
        work_orderid: workorderid,
        jobsflag: btnflag,
        spname: "SP_Work_Order_Action",
        flag: flag,
        UserId: $('#hiddenUser_id').val()
    }
    $.ajax({
        async: true,
        type: 'POST',
        url: '/Workorder/Get_Workorder',
        contentType: 'application/json; charset=UTF-8',
        data: JSON.stringify(servicevalues),
        success: function (data) {
            debugger;

            var data = JSON.parse(data);
            console.log(data);
            if (data.msg == "Success") {
                var data1 = data.data;
                if (jQuery.isEmptyObject((data1))) {
                }
                else {

                    if (btnflag == 'AddResults') {
                        readflag = '';
                        readflagconclusion = '';
                        $("#ldaddresult").show();
                        $('#ldresultpr').hide();
                        $('#ldresultaction').hide();
                        $("#ldaddresult").html('Submit')
                        $('#headerresult').html('Add Result')
                        $("#ldaddresult").val('Submit')
                        $('#btnResultPrint').hide();
                        $('#btnResultSendMail').hide();
                        $('#btnResultPrintworksheet').show();

                        edittag = '';
                    }
                    else if (btnflag == 'Verify') {
                        $('#ldresultaction').show();
                        $('#ldresultpr').show();
                        $("#ldaddresult").show();
                        readflag = 'disabled';
                        readflagconclusion = '';
                        $("#ldaddresult").html('Approve')
                        $('#headerresult').html('Pending Approval')
                        $("#ldaddresult").val('Approve')
                        $('#btnResultPrint').show();
                        $('#btnResultSendMail').show();
                        $('#btnResultPrintworksheet').hide();
                        // edittag = '<td id="edit"><i class="fa fa-pencil-square-o" aria-hidden="true"></i></td>';
                    }
                    else if (btnflag == 'View') {
                        $('#headerresult').html('Completed')
                        // readflag = 'disabled';
                        $("#ldaddresult").hide();
                        edittag = '';
                        $('#ldresultaction').hide();
                        $('#ldresultpr').show();
                        readflag = 'disabled';
                        readflagconclusion = 'disabled';
                        $('#btnResultPrintworksheet').hide();
                        $('#btnResultPrint').show();
                        $('#btnResultSendMail').show();



                    }
                    else if (btnflag == 'ReceiveSample') {
                        readflagconclusion = 'disabled';
                        readflag = 'disabled';
                        $("#ldaddresult").show();
                        $('#ldresultpr').hide();
                        $('#ldresultaction').hide();
                        $("#ldaddresult").html('Received')
                        $("#ldaddresult").val('Received')
                        $('#btnResultPrint').hide();
                        $('#btnResultSendMail').hide();
                        $('#btnResultPrintworksheet').hide();

                        edittag = '';
                    }

                    var b = data1.Table;
                    responsedatalabtest=data1.Table;

                    if (b[0].refunitflag == 0) {
                        if ($('#HFormbuilder_id').val() == 1) {

                            $('#lab_service_name').html(b[0].service_name);
                            $('#div_labresult_2').show();
                            $('#div_labresult_1').hide();
                            $('#div_labservice_btn').hide();
                            if (b[0].form_master_data_id != null) {
                                $('#iframe_form').attr('src', 'https://formbuilder.mocerohealth.in/edit-form/' + b[0].form_master_data_id + '')
                            }
                            else {
                                $('#iframe_form').attr('src', 'https://formbuilder.mocerohealth.in/form/' + b[0].form_id + '?work_order_details_id=' + btoa(b[0].work_order_details_id) + '&patientid=' + btoa(b[0].patientid) + '')
                            }
                        }
                        else {
                            $('#div_labresult_2').hide();
                            $('#div_labresult_1').show();
                            $('#div_labservice_btn').show();
                            $('#ldlabParameters_body').empty();
                            //$('#ldresultconclusion').val(b[0].conclusion);

                            tr = '';
                            var j = 0, m = 1, k = 0;
                            var service_name = '', Tservice_name = '', calculation = "", chkbox = '', Aobservation = '', AddTemplate='';
                            $.each(b, function (i, emp) {
                                if (service_name != emp.service_name) {
                                    j = 0;
                                    k = k + 1
                                    Tservice_name = emp.service_name;
                                    chkbox = '<input checked  type="checkbox" data-id1 = ' + k + ' data-id=' + emp.master_service_id + ' id="chks_' + i + '" onchange=resultCheck(' + emp.master_service_id + ',this) checked>';
                                    AddTemplate = '<button data-toggle="modal" data-target="#AddTemplate_popup" class="btn btn-xs btn-submit pull-right mr-10" onclick=AddTemplatePopup(this,"' + emp.work_orderid + '","' + emp.work_order_details_id + '","' + emp.master_service_id + '","' + emp.samplebarid + '","' + emp.sample_id + '","' + emp.samplbarcodeid + '","' + emp.WorkorderTemplateId + '")>Add Template</button>'
                                }
                                else {

                                    Tservice_name = '';
                                    chkbox = '';
                                    Aobservation = '';
                                    AddTemplate = '';
                                }
                                if (emp.calculation != null) {
                                    calculation = "(" + emp.calculation + ")";
                                    parameterCalculations[emp.parameter_name] = emp.calculation;
                                    //parameterValues[emp.parameter_id] = NaN;
                                }
                                else {
                                    calculation = "";
                                }
                                if (btnflag == 'Verify') {
                                    edittag = '<td>' + chkbox + '' + AddTemplate + '</td><td id="edit"> <button class="btn editicon-btn" data-toggle="tooltip" data-placement="bottom" title="Edit" onClick=editlabresult(' + i + ')><i class="fa fa-pencil" aria-hidden="true"></i></button> </i></td>';
                                    Aobservation = '';
                                    $('#ldaddresultreject').addClass('hidden');
                                    $('#ldpendingareject').removeClass('hidden');
                                    $('#ldcompletedreject').addClass('hidden');
                                }
                                else if (btnflag == 'View') {
                                    edittag = '<td>' + chkbox + '' + AddTemplate + '</td>';
                                    if (emp.auditobservation != '') {
                                        Aobservation = '<br> Prevoius Value:' + emp.auditobservation + '';
                                    }
                                    $('#ldaddresultreject').addClass('hidden');
                                    $('#ldpendingareject').addClass('hidden');
                                    $('#ldcompletedreject').removeClass('hidden');
                                }
                                else if (btnflag == 'AddResults') {
                                    edittag = '<td>' + chkbox + '' + AddTemplate + '</td>';
                                    $('#ldaddresultreject').removeClass('hidden');
                                    $('#ldpendingareject').addClass('hidden');
                                    $('#ldcompletedreject').addClass('hidden');
                                }
                                j = Number(j) + Number(m)
                                service_name = emp.service_name;
                                //tr = tr + '<tr id="t_' + emp.parameter_id + '"><td id="ldrsamplbarcodeid_' + i + '"  hidden>' + emp.samplbarcodeid + '</td><td id="ldbarcodeid_' + i + '" hidden>' + emp.barcodeid + '</td><td id="ldsampleid_' + i + '" hidden>' + emp.sample_id + '</td><td id="ldresultid_' + i + '" hidden>' + emp.resultid + '</td><td id="ldwork_order_details_id_' + i + '" hidden>' + emp.work_order_details_id + '</td><td id="samplebarid_' + i + '" hidden>' + emp.samplebarid + '</td><td id="result_chk_' + i + '" hidden class="chk_' + emp.master_service_id + '">1</td><td id="master_service_id_' + i + '" hidden>' + emp.master_service_id + '</td><td id="ldparameter_id_' + i + '" hidden>' + emp.parameter_id + '</td><td id="ldrequestid_' + i + '" hidden>' + requestid + '</td><td id="ldworkorderid_' + i + '" hidden>' + workorderid + '</td> <td id="ldservice_name_' + i + '" data-id=' + j + '>' + Tservice_name + '</td><td id="ldparameter_name_' + i + '">' + emp.parameter_name + '</td><td><input type="text" class="sm-field ' + readflag + '"  id="ldobsval_' + i + '" value=' + emp.observation + '></input>' + Aobservation + '</td><td id="ldreference_value_' + i + '"><textarea  class="sm-field ' + readflag + '"  id="ldreferencevalue_' + i + '" >' + emp.reference_value + '</textarea></td><td id="unit_' + i + '"><input type="text"    class="sm-field ' + readflag + '"  id="ldunitval_' + i + '" value=' + emp.unit + '></input></td><td><textarea tyepe="text"  class="' + readflagconclusion + '"  id="ldconclusion_' + i + '"  style="width: 321px; height: 70px;">' + emp.conclusion + '</textarea></td>' + edittag + '</tr>';
                                tr = tr + '<tr id="t_' + emp.parameter_id + '"><td id="ldrsamplbarcodeid_' + i + '"  hidden>' + emp.samplbarcodeid + '</td><td id="ldbarcodeid_' + i + '" hidden>' + emp.barcodeid + '</td><td id="ldsampleid_' + i + '" hidden>' + emp.sample_id + '</td><td id="ldresultid_' + i + '" hidden>' + emp.resultid + '</td><td id="ldwork_order_details_id_' + i + '" hidden>' + emp.work_order_details_id + '</td><td id="samplebarid_' + i + '" hidden>' + emp.samplebarid + '</td><td id="result_chk_' + i + '" hidden class="chk_' + emp.master_service_id + '">1</td><td id="master_service_id_' + i + '" hidden>' + emp.master_service_id + '</td><td id="ldparameter_id_' + i + '" hidden>' + emp.parameter_id + '</td><td id="ldrequestid_' + i + '" hidden>' + requestid + '</td><td id="ldworkorderid_' + i + '" hidden>' + workorderid + '</td> <td id="ldservice_name_' + i + '" data-id=' + j + '>' + Tservice_name + '</td><td id="ldparameter_name_' + i + '">' + emp.parameter_name + '<br>' + calculation + '</td><td id="ldparameter_nameC_' + i + '" hidden>' + emp.parameter_name + '</td><td><input type="text" data-parameter-name="' + emp.parameter_name + '"  autocomplete="off" class="sm-field ui-autocomplete-input' + readflag + '"  id="ldobsval_' + i + '" value="' + emp.observation + '" onkeyup="AddResultobservation(this,' + emp.parameter_id + ')"></input>' + Aobservation + '</td><td id="ldreference_value_' + i + '"><textarea autocomplete="off" class="sm-field ui-autocomplete-input ' + readflag + '"  id="ldreferencevalue_' + i + '" onkeyup="AddResultReferenceVal(this,' + emp.parameter_id + ')">' + emp.reference_value + '</textarea></td><td id="unit_' + i + '"><input type="text" autocomplete="off" class="sm-field ui-autocomplete-input ' + readflag + '"  id="ldunitval_' + i + '" value=' + emp.unit + ' onkeyup="AddResultUnit(this,' + emp.parameter_id + ')"></input></td><td><textarea tyepe="text"  class="' + readflagconclusion + '"  id="ldconclusion_' + i + '"  style="width: 321px; height: 70px;">' + emp.conclusion + '</textarea></td>' + edittag + '</tr>';

                                /*<input class="form-control ui-autocomplete-input" type="text" id="req_service" name="cpiName" value="" placeholder="Search Service Name" autocomplete="off">*/
                            });

                            $('#ldlabParameters_body').html(tr);
                        }
                    }
                    else {
                        $('#div_labresult_2').hide();
                        $('#div_labresult_1').show();
                        $('#div_labservice_btn').show();

                        $('#ldlabParameters_body').empty();
                        //$('#ldresultconclusion').val(b[0].conclusion);

                        tr = '';
                        var j = 0, m = 1, k = 0;
                        var service_name = '', Tservice_name = '', calculation = '', chkbox = '', Aobservation = '', AddTemplate='';
                        $.each(b, function (i, emp) {
                            if (service_name != emp.service_name) {
                                j = 0;
                                k = k + 1;
                                Tservice_name = emp.service_name;
                                chkbox = '<input checked  type="checkbox" data-id1 =' + k + ' data-id=' + emp.master_service_id + ' id="chks_' + i + '" onchange=resultCheck(' + emp.master_service_id + ',this) checked>';
                                AddTemplate = '<button data-toggle="modal" data-target="#AddTemplate_popup" class="btn btn-xs btn-submit pull-right mr-10" onclick=AddTemplatePopup(this,"' + emp.work_orderid + '","' + emp.work_order_details_id + '","' + emp.master_service_id + '","' + emp.samplebarid + '","' + emp.sample_id + '","' + emp.samplbarcodeid + '","' + emp.WorkorderTemplateId + '")>Add Template</button>'
                            }
                            else {
                                Tservice_name = '';
                                chkbox = '';
                                Aobservation = '';
                                AddTemplate = '';
                            }
                            if (emp.calculation != null)
                            {
                                calculation = "(" + emp.calculation + ")";
                                parameterCalculations[emp.parameter_name] = emp.calculation;
                                //parameterValues[emp.parameter_id] = NaN;
                            }
                            else
                            {
                                calculation = "";
                            }
                            if (btnflag == 'Verify') {
                                edittag = '<td>' + chkbox + ' ' + AddTemplate + '</td><td id="edit"> <button class="btn editicon-btn" data-toggle="tooltip" data-placement="bottom" title="Edit" onClick=editlabresult(' + i + ')><i class="fa fa-pencil" aria-hidden="true"></i></button> </i></td>';
                                Aobservation = '';
                                $('#ldaddresultreject').addClass('hidden');
                                $('#ldpendingareject').removeClass('hidden');
                                $('#ldcompletedreject').addClass('hidden');
                            }
                            else if (btnflag == 'View') {
                                edittag = '<td>' + chkbox + ' ' + AddTemplate + '</td>';
                                if (emp.auditobservation != '') {
                                    Aobservation = '<br> Prevoius Value:' + emp.auditobservation + '';
                                }
                                $('#ldaddresultreject').addClass('hidden');
                                $('#ldpendingareject').addClass('hidden');
                                $('#ldcompletedreject').removeClass('hidden');
                            }
                            else if (btnflag == 'AddResults') {
                                edittag = '<td>' + chkbox + ' '+AddTemplate+'</td>';
                                $('#ldaddresultreject').removeClass('hidden');
                                $('#ldpendingareject').addClass('hidden');
                                $('#ldcompletedreject').addClass('hidden');
                            }
                            j = Number(j) + Number(m)
                            service_name = emp.service_name;
                            //tr = tr + '<tr id="t_' + emp.parameter_id + '"><td id="ldrsamplbarcodeid_' + i + '" hidden>' + emp.samplbarcodeid + '</td><td id="ldbarcodeid_' + i + '" hidden>' + emp.barcodeid + '</td><td id="ldsampleid_' + i + '" hidden>' + emp.sample_id + '</td><td id="ldresultid_' + i + '" hidden>' + emp.resultid + '</td><td id="ldwork_order_details_id_' + i + '" hidden>' + emp.work_order_details_id + '</td><td id="samplebarid_' + i + '" hidden>' + emp.samplebarid + '</td><td id="result_chk_' + i + '" hidden class="chk_' + emp.master_service_id + '">1</td><td id="master_service_id_' + i + '" hidden>' + emp.master_service_id + '</td><td id="ldparameter_id_' + i + '" hidden>' + emp.parameter_id + '</td><td id="ldrequestid_' + i + '" hidden>' + requestid + '</td><td id="ldworkorderid_' + i + '" hidden>' + workorderid + '</td> <td id="ldservice_name_' + i + '" data-id=' + j + '>' + Tservice_name + '</td><td id="ldparameter_name_' + i + '">' + emp.parameter_name + '</td><td><input type="text"    class="sm-field ' + readflag + '"  id="ldobsval_' + i + '" value=' + emp.observation + '></input>' + Aobservation + '</td><td id="ldreference_value_' + i + '"><textarea  class="sm-field ' + readflag + '" id="ldreferencevalue_' + i + '">' + emp.reference_value + '</textarea></td><td id="unit_' + i + '"><input type="text"    class="sm-field ' + readflag + '"  id="ldunitval_' + i + '" value=' + emp.unit + '></input></td><td><textarea tyepe="text"  class="' + readflagconclusion + '"  id="ldconclusion_' + i + '"  style="width: 321px; height: 70px;">' + emp.conclusion + '</textarea></td>' + edittag + '</tr>';
                            tr = tr + '<tr id="t_' + emp.parameter_id + '"><td id="ldrsamplbarcodeid_' + i + '" hidden>' + emp.samplbarcodeid + '</td><td id="ldbarcodeid_' + i + '" hidden>' + emp.barcodeid + '</td><td id="ldsampleid_' + i + '" hidden>' + emp.sample_id + '</td><td id="ldresultid_' + i + '" hidden>' + emp.resultid + '</td><td id="ldwork_order_details_id_' + i + '" hidden>' + emp.work_order_details_id + '</td><td id="samplebarid_' + i + '" hidden>' + emp.samplebarid + '</td><td id="result_chk_' + i + '" hidden class="chk_' + emp.master_service_id + '">1</td><td id="master_service_id_' + i + '" hidden>' + emp.master_service_id + '</td><td id="ldparameter_id_' + i + '" hidden>' + emp.parameter_id + '</td><td id="ldrequestid_' + i + '" hidden>' + requestid + '</td><td id="ldworkorderid_' + i + '" hidden>' + workorderid + '</td> <td id="ldservice_name_' + i + '" data-id=' + j + '>' + Tservice_name + '</td><td id="ldparameter_name_' + i + '">' + emp.parameter_name + '<br>' + calculation + '</td><td id="ldparameter_nameC_' + i + '" hidden>' + emp.parameter_name + '</td><td><input type="text" data-parameter-name="' + emp.parameter_name + '" autocomplete="off" class="sm-field ui-autocomplete-input ' + readflag + '"  id="ldobsval_' + i + '" value="' + emp.observation + '" onkeyup="AddResultobservation(this,' + emp.parameter_id + ')"></input>' + Aobservation + '</td><td id="ldreference_value_' + i + '"><textarea autocomplete="off" class="sm-field ui-autocomplete-input ' + readflag + '" id="ldreferencevalue_' + i + '" onkeyup="AddResultReferenceVal(this,' + emp.parameter_id + ')">' + emp.reference_value + '</textarea></td><td id="unit_' + i + '"><input type="text" autocomplete="off" class="sm-field ui-autocomplete-input ' + readflag + '"  id="ldunitval_' + i + '" value="' + emp.unit + '" onkeyup="AddResultUnit(this,' + emp.parameter_id + ')"></input></td><td><textarea tyepe="text"  class="' + readflagconclusion + '"  id="ldconclusion_' + i + '"  style="width: 321px; height: 70px;">' + emp.conclusion + '</textarea></td>' + edittag + '</tr>';
                        });
                        $('#ldlabParameters_body').html(tr);
                    }
                    var str = b[0].document_path;
                    $('#popbarcodeid').val(b[0].samplbarcodeid);
                    if (str != "" && str != null) {
                        $('#docpathvalue').val(str);
                        var temp = new Array();
                        temp = str.split(",");
                        var strarray = str.split(',');
                        var j = 0;
                        for (var i = 0; i < strarray.length; i++) {
                            j = j + 1;
                            $('#photolog').append('<a href="' + $('#hdnfilepath1').val() + $('#HospitalId').val() + "/" + $('#popbranchid').val() + "/Lab_Documents/" + strarray[i] + '" target="_blank">' + strarray[i] + '' + '/' + '');
                        }
                    }
                }
            }
        }
    });
}

const parameterValues = {};

// Update the event listener for dynamic fields
$('#ldlabParameters_body').on('keyup', 'input[id^="ldobsval_"]', function () {
    debugger;
    var $row = $(this).closest('tr');
    var parameterName = $row.find('td[id^="ldparameter_nameC_"]').text().trim();
    var samplbarcodeid = $row.find('td[id^="ldrsamplbarcodeid_"]').text().trim();
    var value = parseFloat($(this).val().trim());

    // Update the parameter values
    parameterValues[parameterName] = value;

    // Loop through all parameters to handle calculations
    $.each(responsedatalabtest, function (i, emp) {
        if (samplbarcodeid==emp.samplbarcodeid) {

            if (emp.calculation != null && emp.calculation != "") {
                var calculatedValue = calculateFormula(emp.calculation);

                // Find the corresponding dynamic field and update its value with the calculated result
                // var $dynamicField = $('#ldlabParameters_body').find('input[data-parameter-name="' + emp.parameter_name + '"]');
                //  $dynamicField.val(calculatedValue);
                $('#ldlabParameters_body input[data-parameter-name="' + emp.parameter_name + '"]').val(calculatedValue);
                parameterValues[emp.parameter_name] = calculatedValue;
            }

        }
        
    });
});

function calculateFormula(formula) {
    debugger;
    // Split the formula by "=" to separate left-hand side and right-hand side
    var sides = formula.split('=');
    var leftHandSide = sides[0].trim();
    var rightHandSide = sides[1].trim();

    // Replace parameter names with their values in both sides of the equation
    for (var paramName in parameterValues) {
        if (parameterValues.hasOwnProperty(paramName)) {
            var paramValue = parameterValues[paramName];
            var regex = new RegExp('\\b' + paramName + '\\b', 'g');
            leftHandSide = leftHandSide.replace(regex, paramValue);
            rightHandSide = rightHandSide.replace(regex, paramValue);
        }
    }

    // Evaluate the updated formula to get the calculated value
    try {
        var calculatedValue = eval(leftHandSide);
        // Update the corresponding parameter value with the calculated result
        parameterValues[rightHandSide] = calculatedValue;
        return calculatedValue;
    } catch (error) {
        console.error('Error calculating formula:', error);
        return NaN;
    }
}




function AddResultUnit(e,parameterid) {
 
    AutoCompleteAction(e.id, "GWU", parameterid);
}

function AddResultReferenceVal(e, parameterid) {

    AutoCompleteAction(e.id, "GWR", parameterid);
}

function AddResultobservation(e, parameterid) {

    AutoCompleteAction(e.id, "GWO", parameterid);
}


function AutoCompleteAction(Id, flag, parameterid) {
  
    var RowId = Id

    $('#' + RowId + '').autocomplete({
        source: function (request, response) {
            debugger;
            var Indicator = flag;;
            var HospitalId = $('#HospitalId').val();
            var BranchId = $('#popbranchid').val();
            var ParameterId = parameterid
            var spname = "SP_Work_Order_Action"

            $.ajax({
                async: true,
                type: 'POST',
                url: '/Workorder/AutoCompleteService?Dml_Indicator=' + Indicator + '&result=' + $('#' + RowId + '').val() + '&SpName=' + spname + '&branchId=' + BranchId + '&hospitalId=' + HospitalId + '&SampleId=' + ParameterId +'',
                dataType: "json",
                data: {},
                success: function (data) {
                   
                    console.log(data);
                    response($.map(data, function (item) {
                    
                        return { label: item.servicename, value: item.servicename, id: item.resultid};
                    }))
                }
            })
        },
        minLength: 1,
        select: function (event, ui) {
            $('#user_id').val(ui.item.id);
        },
        html: true,
        open: function (event, ui) {
            $(".ui-autocomplete").css("z-index", 1000);

        }
    });
}




//}
function resultCheck(master_service_id, event) {
    debugger;
    var id = event.id
    var chk = (event.checked) ? 1 : 2
    $('#' + id).val(chk)
    $('.chk_' + master_service_id).html(chk);
}
function ldlabrecivesample(requestid, workorderid, samplid, master_service_id, btnflag, tabflag, flag, wtype, samplbarcodeid, hospitalid, branchid, patient_auto_id, patient_id, visit_report_id) {

    debugger;
    $('#photolog').empty();
    $('#docpathvalue').val('');
    $('#popbarcodeid').val('');
    $('#tapflagad').val(tabflag);
    $('#popworkorder_id').val(workorderid);
    $('#pophospitalid').val(hospitalid);
    $('#popbranchid').val(branchid);
    $('#poppatientid').val(patient_auto_id);
    $('#popsampleid').val(samplbarcodeid);
    PatientSearch(patient_id, 0, branchid, visit_report_id)
    var servicevalues = {
        Dml_Indicator: "LRES",
        sample_id: samplid,
        barcodeid: wtype,
        samplbarcodeid: samplbarcodeid,
        work_orderid: workorderid,
        jobsflag: btnflag,
        spname: "SP_Work_Order_Action",
        flag: flag,
        UserId: $('#hiddenUser_id').val()
    }
    $.ajax({
        async: true,
        type: 'POST',
        url: '/Workorder/Get_Workorder',
        contentType: 'application/json; charset=UTF-8',
        data: JSON.stringify(servicevalues),
        success: function (data) {
            debugger;

            var data = JSON.parse(data);
            console.log(data);
            if (data.msg == "Success") {
                var data1 = data.data;
                if (jQuery.isEmptyObject((data1))) {
                }
                else {
                    $('#ldcsampletablerecive > tbody').empty();
                    var count = 0, value = '';
                    $.each(data1.Table, function (i, emp) {
                        j = i + 1;
                        if (emp.samplbarcodeid != '') {
                            var checked = "checked";
                        }

                        value = value + "<tr class='tr_input number' data-id='" + j + "' id='t_" + j + "'><td>" + j + "</td><td id='twork_order_details_id_" + j + "' hidden>" + emp.work_order_details_id + "</td><td id='trmaster_service_id_" + j + "' hidden>" + emp.master_service_id + "</td><td id='tsamplebarid_" + j + "' class='tsamplebarid_" + emp.work_order_details_id + emp.sample_id + "' hidden>" + emp.samplebarid + "</td><td id='tdepartmentid_" + j + "' hidden>" + emp.sub_category_department_id + "</td><td id='tsampleid_" + j + "' hidden>" + emp.sample_id + "</td><td id='tldcservicename_" + j + "'>" + emp.service_name + "</td><td id='tldctube_" + j + "' value=" + emp.tubecontainerid + " class='ttubecontainer'>" + emp.tubename + "</td><td id='tldcsampletype_" + j + "'>" + emp.name + "</td><td id='tldcdepartment_" + j + "'>" + emp.sub_cd_name + "</td><td id='tldcsamplebadrcode_" + j + "' class='tldcsamplebadrcode_" + emp.work_order_details_id + emp.sample_id + "' data-id=" + emp.barcodeid + ">" + emp.samplbarcodeid + "</td><td><input " + checked + " type='checkbox' id='chkrec_" + j + "' class='chksampleclass'></td><td><button class='btn btn-primaryuse tldbarcodeid_" + emp.work_order_details_id + emp.sample_id + "' onclick='jobprintbarcode1(this)'  id=" + emp.barcodeid + " data-id=" + emp.barcodeid + " data-id1=" + emp.samplbarcodeid + "><i class='fa fa-print' aria-hidden='true'></i></button></td></tr>";
                    });
                    $('#ldcsampletablerecive > tbody:last').append(value);
                }
            }
        }
    })

}
function editlabresult(val) {
    $('#ldobsval_' + val + '').removeClass('disabled');
    $('#ldobsval_' + val + '').focus();
}

//print lab result
function jobprint() {

    var tot_rowM = $('#ldlabrsultParameters >tbody >tr').length;
    var barcode = new Array();
    if (tot_rowM > 0) {
        var L = 0;
        for (j = 0; j <= tot_rowM; j++) {
            var customer = {};
            var isChecked = $('#chks_' + j).is(":checked");
            if (isChecked) {
                var barno = $('#chks_' + j).data('id');
                if (barno != 0) {
                    customer.barcodeno = barno;
                    barcode.push(customer);
                }
            }
        }
    }
    let masterserviceid = barcode.map(x => x.barcodeno).join(",");

    var load_data = {
        formid: "108",
        branchid: $('#popbranchid').val(),
        hospitalid: $('#pophospitalid').val(),
        work_order_id: $('#popworkorder_id').val(),
        patientid: $('#poppatientid').val(),
        barcodeid: $('#popsampleid').val(),
        masterserviceid: masterserviceid
    }

    $.ajax({
        async: true,
        type: 'POST',
        url: '/reports/PrintCrystalReport',
        contentType: 'application/json; charset=UTF-8',
        data: JSON.stringify(load_data),
        success: function (data) {
            var byteArray = new Uint8Array(data);
            var blob = new Blob([byteArray], { type: "application/pdf" });
            var link = window.URL.createObjectURL(blob);
            window.open(link, '_blank');

        }
    });

}
//print barcode

function jobprintbarcode1(e) {

    debugger

    var barcodeid = $(e).data('id');
    var popsampleid = $(e).data('id1');
    var load_data = {
        formid: "104",
        branchid: $('#popbranchid').val(),
        hospitalid: $('#pophospitalid').val(),
        work_order_id: $('#popworkorder_id').val(),
        patientid: $('#poppatientid').val(),
        barcodeid: barcodeid,
        samplbarcodeid: popsampleid,
        masterserviceid: 0,
    }

    $.ajax({
        async: true,
        type: 'POST',
        url: '/reports/PrintCrystalReport',
        contentType: 'application/json; charset=UTF-8',
        data: JSON.stringify(load_data),
        success: function (data) {
            var byteArray = new Uint8Array(data);
            var blob = new Blob([byteArray], { type: "application/pdf" });
            var link = window.URL.createObjectURL(blob);
            window.open(link, '_blank');

        }
    });

}
//print work sheet
function jobprintworksheet(e) {

    debugger
    var tot_rowM = $('#ldlabrsultParameters >tbody >tr').length;
    var barcode = new Array();
    if (tot_rowM > 0) {
        var L = 0;
        for (j = 0; j <= tot_rowM; j++) {
            var customer = {};
            var isChecked = $('#chks_' + j).is(":checked");
            if (isChecked) {
                var barno = $('#chks_' + j).data('id');
                if (barno != 0) {
                    customer.barcodeno = barno;
                    barcode.push(customer);
                }
            }
        }
    }
    let masterserviceid = barcode.map(x => x.barcodeno).join(",");

    var load_data = {
        formid: "115",
        branchid: $('#popbranchid').val(),
        hospitalid: $('#pophospitalid').val(),
        work_order_id: $('#popworkorder_id').val(),
        patientid: $('#poppatientid').val(),
        barcodeid: $('#popbarcodeid').val(),
        masterserviceid: masterserviceid
    }

    $.ajax({
        async: true,
        type: 'POST',
        url: '/reports/PrintCrystalReport',
        contentType: 'application/json; charset=UTF-8',
        data: JSON.stringify(load_data),
        success: function (data) {
            var byteArray = new Uint8Array(data);
            var blob = new Blob([byteArray], { type: "application/pdf" });
            var link = window.URL.createObjectURL(blob);
            window.open(link, '_blank');

        }
    });

}

//print barcode

function jobprintbarcode() {
    debugger
    var load_data = {
        formid: "104",
        branchid: $('#popbranchid').val(),
        hospitalid: $('#pophospitalid').val(),
        work_order_id: $('#popworkorder_id').val(),
        patientid: $('#poppatientid').val(),
        barcodeid: $('#popbarcodeid').val(),
        samplbarcodeid: $('#popsampleid').val(),
        masterserviceid: 0,
    }

    $.ajax({
        async: true,
        type: 'POST',
        url: '/reports/PrintCrystalReport',
        contentType: 'application/json; charset=UTF-8',
        data: JSON.stringify(load_data),
        success: function (data) {
            var byteArray = new Uint8Array(data);
            var blob = new Blob([byteArray], { type: "application/pdf" });
            var link = window.URL.createObjectURL(blob);
            window.open(link, '_blank');

        }
    });

}


//print barcode all

function jobprintbarcodeall(tblname) {
    debugger
    var tot_rowM = $('#' + tblname + ' >tbody >tr').length;
    var barcode = new Array();
    if (tot_rowM > 0) {
        var L = 0;
        for (j = 1; j <= tot_rowM; j++) {
            var customer = {};
            var barno = $('#tldcsamplebadrcode_' + j).data('id');
            if (barno != 0) {
                customer.barcodeno = barno;
                barcode.push(customer);
            }
        }
    }
    let barcodeno = barcode.map(x => x.barcodeno).join(",");
    //let barcodeno = '';
    var load_data = {
        formid: "106",
        branchid: $('#popbranchid').val(),
        hospitalid: $('#pophospitalid').val(),
        work_order_id: $('#popworkorder_id').val(),
        patientid: $('#poppatientid').val(),
        barcodeid: barcodeno,
        masterserviceid: 0,
    }

    $.ajax({
        async: true,
        type: 'POST',
        url: '/reports/PrintCrystalReport',
        contentType: 'application/json; charset=UTF-8',
        data: JSON.stringify(load_data),
        success: function (data) {
            var byteArray = new Uint8Array(data);
            var blob = new Blob([byteArray], { type: "application/pdf" });
            var link = window.URL.createObjectURL(blob);
            window.open(link, '_blank');

        }
    });

}
//print barcode all

function jobprintbarcodeallresult(tblname) {
    debugger
    var tot_rowM = $('#' + tblname + ' >tbody >tr').length;
    var barcode = new Array();
    if (tot_rowM > 0) {
        var L = 0;
        for (j = 0; j <= tot_rowM; j++) {
            var customer = {};
            var barno = $('#ldbarcodeid_' + j).html();
            if (barno != 0) {
                customer.barcodeno = barno;
                barcode.push(customer);
            }
        }
    }
    let barcodeno = barcode.map(x => x.barcodeno).join(",");
    //let barcodeno = '';
    var load_data = {
        formid: "106",
        branchid: $('#popbranchid').val(),
        hospitalid: $('#pophospitalid').val(),
        work_order_id: $('#popworkorder_id').val(),
        patientid: $('#poppatientid').val(),
        barcodeid: barcodeno,
        masterserviceid: 0,
    }

    $.ajax({
        async: true,
        type: 'POST',
        url: '/reports/PrintCrystalReport',
        contentType: 'application/json; charset=UTF-8',
        data: JSON.stringify(load_data),
        success: function (data) {
            var byteArray = new Uint8Array(data);
            var blob = new Blob([byteArray], { type: "application/pdf" });
            var link = window.URL.createObjectURL(blob);
            window.open(link, '_blank');

        }
    });

}
//send Mail lab result
function sendmaillabresult() {
    $('#EmailpopupModal').modal("toggle");
    $('#txtMobileNo').val($('.pat_contact').html());
    $('#txtEmailID').val($('.pat_email').html());

}

$('#Send_email_sms').click(function () {
    Send_Eamil_WhatsApp();
    //$('#EmailpopupModal').hide();
    $('#EmailpopupModal').modal('toggle');
});

function Send_Eamil_WhatsApp() {
    debugger;
    var tot_rowM = $('#ldlabrsultParameters >tbody >tr').length;
    var barcode = new Array();
    if (tot_rowM > 0) {
        var L = 0;
        for (j = 0; j <= tot_rowM; j++) {
            var customer = {};
            var isChecked = $('#chks_' + j).is(":checked");
            if (isChecked) {
                var barno = $('#chks_' + j).data('id');
                if (barno != 0) {
                    customer.barcodeno = barno;
                    barcode.push(customer);
                }
            }
        }
    }
    let masterserviceid = barcode.map(x => x.barcodeno).join(",");

    var load_data = {
        //formid: "108",
        formid: "152",
        branchid: $('#popbranchid').val(),
        hospitalid: $('#pophospitalid').val(),
        work_order_id: $('#popworkorder_id').val(),
        patientid: $('#poppatientid').val(),
        barcodeid: $('#popbarcodeid').val(),
        masterserviceid: masterserviceid,
        samplbarcodeid: $('#popsampleid').val(),
    }

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

            var customers = {
                Dml_Indicator: "SMLR",
                branchid: $('#popbranchid').val(),
                hospitalid: $('#pophospitalid').val(),
                work_orderid: $('#popworkorder_id').val(),
                patientid: $('#poppatientid').val(),
                samplbarcodeid: $('#popsampleid').val(),
                spname: "SP_Work_Order_Action",
                patient_phoneno: $('#txtMobileNo').val(),
                patient_email: $('#txtEmailID').val()
            }
            $.ajax({
                async: true,
                type: 'POST',
                url: '/Workorder/Send_Mail',
                contentType: 'application/json; charset=UTF-8',
                data: JSON.stringify(customers),
                success: function (data) {
                    debugger;
                    var data = JSON.parse(data);
                    console.log(data);
                    if (data.msg == "Success") {

                        toastr.success("Message Send Successfully");
                    }
                    else {
                        toastr.warning("Somthing Went Wrong");
                    }
                }

            });
            //var byteArray = new Uint8Array(data);
            //var blob = new Blob([byteArray], { type: "application/pdf" });
            //var link = window.URL.createObjectURL(blob);
            //window.open(link, '_blank');

        }
    });
}

//Add labresult  Lab diagnostics orders
$('#ldaddresult').click(function () {
    debugger;
    $("#ldaddresult").prop('disabled', true);
    var btnval = $("#ldaddresult").val();
    var tabflagad = $('#tapflagad').val();

    var customers = new Array();
    var tabflagad = $('#tapflagad').val();
    var flag = '';

    if (btnval == 'Submit') {
        flag = 1

    }
    else if (btnval == 'Approve') {

        flag = 2
    }
    var master_service_idchk1 = "";
    var tot_rowM = $('#ldlabrsultParameters >tbody >tr').length;
    if (tot_rowM > 0) {
        var jj = 0;
        var k = 0
        for (j = 0; j <= tot_rowM - 1; j++) {
            var obsval = $('#ldobsval_' + j).val();
            var master_service_idchk = $('#master_service_id_' + j).html();
            var service_namedataid = $('#ldservice_name_' + j).data('id');
            if (service_namedataid == 1) {
                if (obsval != "") {
                    jj = 1;
                }

            }

            var isChecked = $('#chks_' + j).is(":checked");
            var chkflag = $('#chks_' + j).data('id1');

            if (chkflag != 'undefined') {
                if (isChecked) {
                    k = 1;
                }
            }
        }

        if (k == 0) {
            toastr.warning("Please Select Any One Check Box");
            $('#ldaddresult').prop('disabled', false);
            return;
        }
        //if (jj == 0) {
        //    toastr.warning("Please Enter Any One Of The  Service  Parameter Values");
        //    $('#ldaddresult').prop('disabled', false);
        //    return;
        //}
        var L = 0, M = 0;
        var jj = 0;
        for (j = 0; j <= tot_rowM - 1; j++) {

            var obsval = $('#ldobsval_' + j).val();
            var master_service_idchk = $('#master_service_id_' + j).html();
            var service_namedataid = $('#ldservice_name_' + j).data('id');

            // var isChecked = $('#chks_' + j).is(":checked");
            var isChecked = $('#result_chk_' + j).html();
            if (isChecked == 1) {


                var chkflag = $('#chks_' + j).data('id1');
                if (chkflag == 1) {
                    chkflag = 2;
                }

                var parameter_name = $('#ldparameter_name_' + j).html();
                if (service_namedataid == 1) {
                    m = 0;
                    if (obsval != "") {
                        m = 1;
                        jj = 1;
                    }
                }
                //command by pidanson fro magna point
                //if (m == 1) {
                //    if (obsval == "") {
                //        toastr.warning("Please Enter Remaining Parameters Value For This Parameter:" + parameter_name + " ");
                //        $('#ldaddresult').prop('disabled', false);
                //        return false;
                //    }
                //}
                //if (jj == 0) {
                //    toastr.warning("Please Enter Any One Of The  Service  Parameter Values");
                //    $('#ldaddresult').prop('disabled', false);
                //    return;
                //}


                var customer = {};
                if ($('#ldobsval_' + j).val() != '') {
                    var resultid = $('#ldresultid_' + j).html();
                    if (resultid == '') {
                        resultid = 0;
                    }


                    customer.parameter_id = $('#ldparameter_id_' + j).html();
                    customer.request_id = 0;
                    customer.document_path = $('#docpathvalue').val();;
                    customer.work_orderid = $('#ldworkorderid_' + j).html();
                    customer.samplbarcodeid = $('#samplebarid_' + j).html();
                    customer.observation = $('#ldobsval_' + j).val();
                    customer.resultid = resultid;
                    customer.conclusion = $('#ldconclusion_' + j).val();
                    customer.unit = $('#ldunitval_' + j).val();
                    customer.referenceval = $('#ldreferencevalue_' + j).val();
                    customer.master_service_id = $('#master_service_id_' + j).html();
                    customer.work_order_details_id = $('#ldwork_order_details_id_' + j).html();
                    customer.Dml_Indicator = "ILDLR";
                    customer.spname = "SP_Work_Order_Action",
                        customer.jobsflag = btnval;
                    customer.flag = flag;
                    customer.sample_id = $('#ldsampleid_' + j).html();
                    customer.barcodeid = $('#ldbarcodeid_' + j).html();
                    customer.created_by = $('#hiddenUser_id').val();
                    customers.push(customer);
                }
            }
        }
    }

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

            var data = JSON.parse(data);
            console.log(data);
            if (data.msg == "Success") {
                var data1 = data.data;
                if (jQuery.isEmptyObject((data1))) {
                    $('#ldaddresult').prop('disabled', false);
                }
                else {
                    if (btnval == 'Submit') {

                        $('#ldaddresult').prop('disabled', false);
                        toastr.success('Results Add Successfully');
                        $('#result_popup .close').click();
                        if (tabflagad == 'phmc') {
                            $("#spackagehomependingapproval").tab('show');
                            loadpackagehomejobs(1, 'LPKHCPR', 3, 'pkhmcpendingapprovaltable', 'pr');
                        }
                        else if (tabflagad == 'phmsc') {
                            $("#spackagehospitalpendingapproval").tab('show');
                            loadpackagehospitaljobs(1, 'LPKHSCPR', 3, 'pkhscpendingapprovaltable', 'pr');

                        }
                    }
                    else if (btnval == 'Approve') {
                        $('#ldaddresult').prop('disabled', false);
                        if (data1.Table1[0].status == 'due') {
                            toastr.warning("Cannot approve. bill is in due");
                            return;
                        }

                        toastr.success('Approved Successfully');
                        $('#result_popup .close').click();
                        $('#tapflagad').val('');
                        $('#photolog').val('');
                        $('#docpathvalue').val('');
                        if (tabflagad == 'phmc') {
                            $('#result_popup .close').click();
                            $("#spackagehomecompleted").tab('show');
                            loadpackagehomecompleted(1);
                        }
                        else if (tabflagad == 'phmsc') {
                            $('#result_popup .close').click();
                            $("#spackagehospitalcompleted").tab('show');
                            loadpackagehospitalcompleted(1);
                        }
                    }




                }
            }
        }
    });

});

$('#ldcrecivedsample').click(function () {
    debugger;
    var tot_rowM = $('#ldcsampletablerecive >tbody >tr').length;
    var barcode = new Array();
    var samplecode = new Array();
    if (tot_rowM > 0) {
        var L = 0;
        var rk = 0;
        for (rk = 0; rk <= tot_rowM; rk++) {
            var customer = {};
            var samplebarcodeid = {};
            var isChecked = $('#chkrec_' + rk).is(":checked");
            if (isChecked) {
                var barno = $('#trmaster_service_id_' + rk).html();
                var sampleno = $('#tldcsamplebadrcode_' + rk).html();
                if (barno != 0) {
                    customer.barcodeno = barno;
                    barcode.push(customer);
                }
                samplebarcodeid.samplecodeno = sampleno;
                samplecode.push(samplebarcodeid);
            }
        }
    }
    let masterserviceid = barcode.map(x => x.barcodeno).join(",");
    let popsampleid = samplecode.map(x => x.samplecodeno).join(",");
    var btnval = $("#ldaddresult").val();
    var tabflagad = $('#tapflagad').val();
    if (masterserviceid != "") {
        toastr.warning("<button type='button' id='confirmationRevertYes' class='btn btn-warning btn-xs mt20'>Yes<button type='button' id='confirmationRevertNo' class='btn btn-warning btn-xs mt20'>No", 'Are You Sure Do you Receive This Sample',
            {
                closeButton: true,
                progressBar: true,
                allowHtml: true,
                timeOut: 20000000,

                onShown: function (toast) {
                    $("#confirmationRevertYes").click(function () {
                        var readflag = '';
                        var edittag = '', indicator = '';
                        $('#photolog').empty();


                        var servicevalues = {
                            Dml_Indicator: "LLDLP",
                            sample_id: 0,
                            barcodeid: 0,
                            samplbarcodeid: popsampleid,
                            work_orderid: $('#popworkorder_id').val(),
                            serviceprovidername: masterserviceid,
                            jobsflag: 'Received',
                            flag: 1,
                            spname: "SP_Work_Order_Action",
                            UserId: $('#hiddenUser_id').val(),
                            created_by: $('#hiddenUser_id').val()
                        }
                        $.ajax({
                            async: true,
                            type: 'POST',
                            url: '/Workorder/Get_Workorder',
                            contentType: 'application/json; charset=UTF-8',
                            data: JSON.stringify(servicevalues),
                            success: function (data) {
                                debugger;

                                var data = JSON.parse(data);
                                console.log(data);
                                if (data.msg == "Success") {
                                    var data1 = data.data;
                                    if (jQuery.isEmptyObject((data1))) {
                                    }
                                    else {


                                        if (data1.Table[0].status == 'Success') {
                                            toastr.success('Sample Received Successfully');
                                            $('#ldrecivie_samplepopup .close').click();
                                            if (tabflagad == 'phmsc') {
                                                $("#spackagehospitaljobs").tab('show');
                                                loadpackagehospitaljobs(1, "LPKHSCJ", 1, 'pkhscjobtable', 'jo');
                                            }
                                            else if (tabflagad == 'phmc') {
                                                $("#spackagehomejobs").tab('show');
                                                loadpackagehomejobs(1, "LPKHCJ", 2, 'pkhmcjobtable', 'jo');
                                            }

                                        }

                                    }
                                }
                            }
                        });
                    })
                }
            })
    }
    else {
        toastr.warning('Please Select Any One Check Box');
    }

});






//open Schedule page

function lhorderschedule(val, val1, work_order_id, patientid, statusflag, pkgflg, stabflag, is_lab, master_service_id, visit_report_id, branch_id, jobsflag, tableid, work_order_status, wid) {

    //alert('test')

    $('#lhassignsericeprovider').show();
    $('#serviceprovider').removeClass('disabled');

    $('#lhscheaddress').html('');
    $('#lhschepatientname').html('');
    $('#work_orderid').val('');
    $('#request_id').val('');
    $('#patientid').val('');
    $('#master_service_id').val('');
    $('#stabflag').val('');
    $('#jobsflag').val('');
    $('#is_package').val('');
    debugger;
    var patientname = '';
    var patientaddress = '';
    var ldtpatient_id = '';
    var ldtwork_order_no = '';
    var ldtpatient_id = '';
    var ldtpackage_name = '';
    var ldtscheduledate = '';
    var ldtscheduletime = '';
    // var is_lab = '';  
    var patientname = $("#" + tableid + " #ldtpatient_username_" + val1 + "").html();
    var patientaddress = $("#" + tableid + " #lhtpaddress_" + val1 + "").html();
    var ldtpatient_id = $("#" + tableid + " #ldtpatient_id_" + val1 + "").html();
    var ldtwork_order_no = $("#" + tableid + " #ldtwork_order_no_" + val1 + "").html();
    var ldtscheduledate = $("#" + tableid + " #ldtscheduledate_" + val1 + "").html();
    var ldtscheduletime = $("#" + tableid + " #ldtscheduletime_" + val1 + "").html();

    //var ldtpatient_id = $("#ldtpatient_id_" + val1 + "").html();
    //var ldtpackage_name = $("#ldtservice_name_" + val1 + "").val();
    //var ldtpackage_name = $("#ldtservice_name_" + val1 + "").html();
    //var is_lab = is_lab;
    if (master_service_id == undefined) {
        master_service_id = 0;
    }
    $('#lhscheaddress').html(patientaddress);
    $('#lhschepatientname').html(patientname);
    $('#work_orderid').val(work_order_id);
    $('#work_order_details_id').val(val);
    $('#patientid').val(patientid);
    $('#master_service_id').val(master_service_id);
    $('#stabflag').val(stabflag + is_lab);
    $('#is_package').val(pkgflg);
    $('#is_lab').val(is_lab);
    $('#tblPatientAppiontment').empty()
    $('#jobsflag').val(jobsflag);
    PatientSearch(patientid, 0, branch_id, visit_report_id)
    //loadserviceprovider(work_order_id, master_service_id, is_lab);

    loadserviceprovider(work_order_id, master_service_id, is_lab, 1, jobsflag, val, ldtscheduledate, ldtscheduletime, work_order_status, statusflag, wid);


}
//load service provider
function loadserviceprovider(work_order_id, master_service_id, is_lab, conclusionflag, jobsflag, work_order_details_id, ldtscheduledate, ldtscheduletime, work_order_status, statusflag, wid) {
    debugger;
    var indicator = '';
    if (conclusionflag == 1) {
        $('#nonlabresultconclusiondiv').hide();
    }
    else {
        $('#nonlabresultconclusiondiv').show();
    }
    if (statusflag == 'Assign') {
        indicator = 'LLHSP'
    }
    else if (statusflag == 'Schedule') {
        indicator = 'LLHSPS'
    }
    var servicevalues = {
        work_orderid: work_order_id,
        samplbarcodeid: wid,
        master_service_id: master_service_id,
        work_order_details_id: work_order_details_id,
        flag: is_lab,
        jobsflag: jobsflag,
        Dml_Indicator: indicator,
        departmentid: ($('#Hdepartment_id').val() == '') ? '' : $('#Hdepartment_id').val(),
        hospital_id: $('#HospitalId').val(),
        scheduledate: ldtscheduledate,
        scheduletime: ldtscheduletime,
        spname: "SP_Work_Order_Action",
        work_order_status: work_order_status
    }
    $.ajax({
        async: true,
        type: 'POST',
        url: '/Workorder/Get_Workorder',
        contentType: 'application/json; charset=UTF-8',
        data: JSON.stringify(servicevalues),
        success: function (data) {
            debugger;
            var data = JSON.parse(data);
            console.log(data);
            if (data.msg == "Success") {
                var data1 = data.data;
                var tr = '', j = 1;

                debugger;

                if (statusflag == 'Assign') {
                    $('#serviceprovider').empty();

                    if (is_lab == 1 || is_lab != 1) {
                        debugger;
                        $('#headercompleted').html('Assign User/Service Provider');
                        $('#sproviderother').hide();
                        $('#sproviderotherlab').show();
                        $('#ldlabassignserviceprovider').show();
                        $('#lhassignsericeprovider').hide();
                        $('#ldlabassignserviceprovider_body').empty();
                        var tr = '';


                        $.each(data1.Table1, function (i, emp) {
                            debugger;
                            i = i + 1;
                            var msid = emp.master_service_id;
                            tr = tr + '<tr><td class="hidden" id="master_service_id_' + msid + '">' + emp.master_service_id + '</td><td id="servicename_' + msid + '">' + emp.service_name + '</td><td id="serviceprovider_' + msid + '"><select  class="form-control serviceproviderlab" id="serviceproviderlab_' + emp.master_service_id + '" ></select></td><td id=lhscheddates_' + msid + '><input type="text" class="form-control pull-right c_dateformat1" style="width:145px;" id="lhscheddate_' + msid + '" value="' + emp.scheduledate + '"></td><td class="disp_if w100" id= lhschdFTimes_' + msid + '><div class="bootstrap-timepicker" id=""><div class="form-group disp_if" style="align-items:center;"><label class="">Start:</label><input type="text" class="mr-5 ml-5 form-control wk-width lhschdFTimeStart" id="lhschdFTimeStart_' + msid + '" value="' + emp.scheduletime + '"></div></div><div class="bootstrap-timepicker" id=""><div class="form-group disp_if" style="align-items:center;"><label class="">End:</label><input type="text" class="ml-5 mr-5 form-control wk-width timepicker" disabled id="lhschdFTimeEnd_' + msid + '" value="' + emp.scheduletime + '"> <input type="text" class="form-control hidden" id="slotendtimemintues_' + msid + '" value=""></div></div><h id="stottimes_' + msid + '"></h> <a href="#" class="dropdown-toggle btn btn-info-dots btn-xs" data-toggle="dropdown" aria-expanded="true"> <span class="fa fa-eye mt10" data-toggle="tooltip" data-placement="bottom" title="Other Options" style="color:black;" aria-hidden="true"></span><span class="sr-only">Options</span></a><div class="dropdown-menu info-dropdown1 pull-right" id=""> <div class="text-left" id="listslotallocation_' + msid + '">Slot List</div></div></td><td><button class="btn btn-primaryuse btn-xs" id="ldassignedbutton_' + msid + '" onclick=labassignprovider("' + emp.master_service_id + '","' + work_order_id + '","' + emp.work_order_details_id + '","' + emp.labhometranid + '","' + i + '")>Assign</button></td></tr>';

                        });

                        $('#ldlabassignserviceprovider_body').html(tr);

                        $.each(data1.Table1, function (i, emp) {
                            debugger;
                            i = i + 1;
                            var msid = emp.master_service_id;
                            //tr = tr + '<tr><td class="hidden" id="master_service_id_' + i + '">' + emp.master_service_id + '</td><td id="servicename_' + i + '">' + emp.service_name + '</td><td id="serviceprovider_' + i + '"><select  class="form-control serviceproviderlab" id="serviceproviderlab_' + emp.master_service_id + '" ></select></td><td id= lhscheddates_' + i + '><input type="text" class="form-control pull-right visiteddate c_dateformat" style="width:145px;" id="lhscheddate_' + i + '" value="' + emp.scheduledate + '"></td><td id= lhschdFTimes_' + i + '><input type="text" class="form-control timepicker" id="lhschdFTime_' + i + '" value="' + emp.scheduletime + '"></td><td><button class="btn btn-primaryuse btn-xs" onclick=labassignprovider("' + emp.master_service_id + '","' + work_order_id + '","' + emp.work_order_details_id + '","' + emp.labhometranid + '","' + i + '")>Assign</button></td></tr>'

                            var default_opt = '<option value="0" data-id="">--Select--</option>';
                            var cdepartment;
                            $.each(data1.Table2, function (i, emp1) {
                                debugger;

                                if (msid == emp1.master_service_id) {
                                    cdepartment = cdepartment + '<option value="' + emp1.labtranid + '" data-id="' + emp1.lab_name + '">' + emp1.lab_name + '</option>';
                                }
                            });

                            $('#serviceproviderlab_' + emp.master_service_id + '').append(default_opt + cdepartment);
                        });


                        $('.c_dateformat1').datepicker('destroy').datepicker({
                            format: 'dd/mm/yyyy',
                            autoclose: true,
                            todayHighlight: true,
                            startDate: 'today'
                        });
                        $('.visiteddate').datepicker({
                            autoclose: true,
                            todayHighlight: true,
                            endDate: new Date()
                        });
                        $('.timepicker').timepicker({
                            showInputs: false
                        });
                        $('.lhschdFTimeStart').timepicker({
                            showInputs: false
                        });

                    }
                }
                else {
                    $.each(data1.Table, function (i, emp) {
                        debugger;
                        i = i + 1;
                        var msid = emp.master_service_id;
                        tr = tr + '<tr><td class="hidden" id="smaster_service_id_' + i + '">' + emp.master_service_id + '</td><td class="hidden" id="swork_order_details_id' + i + '">' + emp.work_order_details_id + '</td><td id="sservicename_' + i + '">' + emp.service_name + '</td><td id=slhscheddates_' + i + '><input type="text" class="form-control c_dateformat1"  id="slhscheddate_' + i + '" value="' + emp.scheduledate + '"></td><td  id="slhschdFTimes_' + i + '"><div class="bootstrap-timepicker" id=""><input type="text" class="mr-5 ml-5 form-control wk-width lhschdFTime" id="slhschdFTime_' + i + '"></div></td><td><input checked  type="checkbox" id="chks_' + i + '"></td></tr>';

                    });

                    $('#ldlabpopupschuleduletable_body').html(tr);
                    $('.c_dateformat1').datepicker('destroy').datepicker({
                        format: 'dd/mm/yyyy',
                        autoclose: true,
                        todayHighlight: true,
                        startDate: 'today'
                    });

                    $('.timepicker').timepicker({
                        showInputs: false
                    });
                    $('.lhschdFTime').timepicker({
                        showInputs: false
                    });
                }

            }
        }
    })

}

//Lab Home collection add schedule 
$('#lhschesubmit').click(function () {
    var stabflag = $('#stabflag').val();
    //if ($('#lhschedate').val() == '') {
    //    toastr.warning("Please select scheduledate");
    //    return;
    //}
    //if ($('#lhschFTime').val() == '') {
    //    toastr.warning("Please select slot time");
    //    return;

    //}
    var customers = new Array();
    var chkcount = 0;
    var tot_rowM = $('#ldlabpopupschuleduletable >tbody >tr').length;
    if (tot_rowM > 0) {
        var L = 0;
        for (j = 1; j <= tot_rowM; j++) {
            var customer = {};
            var isChecked = $('#chks_' + j).is(":checked");
            if (isChecked) {
                debugger;
                chkcount = chkcount + 1;
                customer.sno = j,
                    customer.work_orderid = $('#work_orderid').val(),
                    customer.scheduledate = $('#slhscheddate_' + j).val(),
                    customer.flag = $('#is_package').val(),
                    customer.master_service_id = $('#smaster_service_id_' + j).html(),
                    customer.scheduletime = $('#slhschdFTime_' + j).val(),
                    customer.work_order_details_id = $('#swork_order_details_id' + j).html(),
                    customer.patientid = $('#patientid').val(),
                    customer.Dml_Indicator = 'ILHSCH',
                    customer.spname = "SP_Work_Order_Action",
                    customer.created_by = $('#hiddenUser_id').val();
                customers.push(customer);
            }
        }

        //var servicevalues = {
        //    Dml_Indicator: 'ILHSCH',
        //    work_order_details_id: $('#work_order_details_id').val(),
        //    work_orderid: $('#work_orderid').val(),
        //    master_service_id: $('#master_service_id').val(),
        //    flag: $('#is_package').val(),
        //    is_lab: $('#is_lab').val(),
        //    work_orderid: $('#work_orderid').val(),
        //    patientid: $('#patientid').val(),
        //    scheduledate: $('#lhschedate').val(),
        //    scheduletime: $('#lhschFTime').val(),
        //    jobsflag: $('#jobsflag').val(),
        //}
        $.ajax({
            async: true,
            type: 'POST',
            url: '/Workorder/Schedule_insert',
            contentType: 'application/json; charset=UTF-8',
            data: JSON.stringify(customers),
            success: function (data) {
                debugger;

                var data = JSON.parse(data);
                console.log(data);
                if (data.msg == "Success") {
                    //var data1 = data.data;
                    if (jQuery.isEmptyObject((data))) {


                    }
                    else {

                        toastr.success('Scheduled Successfully');
                        $('#Schedule .close').click();
                        if (stabflag == 'phmc1' || stabflag == 'phmc2') {

                            loadpackagehomeunassigned(1);
                            $("#spackagehomeunassigned").tab('show');
                        }
                        else if (stabflag == 'phmsc1' || stabflag == 'phmsc2') {

                            loadpackagehospitalunassigned(1);
                            $("#spackagehospitalunassigned").tab('show');
                        }


                    }
                }
            }

        })
    }
})
function labassignprovider(master_service_id, work_order_id, work_order_details_id, labhometranid, val) {
    debugger;
    var rowcount = $('#ldlabassignserviceprovider >tbody >tr').length;
    var stabflag = $('#stabflag').val();
    if ($('#serviceprovider_' + master_service_id + ' option:selected').val() == '' || $('#serviceprovider_' + master_service_id + ' option:selected').val() == '0') {
        toastr.warning('Please select the service  provider');
        return;
    }
    if ($('#lhscheddate_' + master_service_id + '').val() == '') {
        toastr.warning("Please select scheduledate");
        return;
    }
    if ($('#lhschdFTime_' + master_service_id + '').val() == '') {
        toastr.warning("Please select slot time");
        return;

    }
    var servicevalues = {
        Dml_Indicator: 'ULHSCHP',
        work_order_details_id: work_order_details_id,
        is_lab: 1,
        work_orderid: work_order_id,
        master_service_id: master_service_id,
        serviceprovidername: $('#serviceprovider_' + master_service_id + ' option:selected').data('id'),
        serviceproviderid: $('#serviceprovider_' + master_service_id + ' option:selected').val(),
        patientid: $('#patientid').val(),
        scheduledate: $('#lhscheddate_' + master_service_id + '').val(),
        scheduletime: $('#lhschdFTimeStart_' + master_service_id + '').val() + '-' + $('#lhschdFTimeEnd_' + master_service_id + '').val(),
        samplbarcodeid: (labhometranid == "null") ? 0 : labhometranid,
        spname: "SP_Work_Order_Action",
        jobsflag: 1
    }
    $.ajax({
        async: true,
        type: 'POST',
        url: '/Workorder/Get_Workorder',
        contentType: 'application/json; charset=UTF-8',
        data: JSON.stringify(servicevalues),
        success: function (data) {
            debugger;
            var data = JSON.parse(data);
            console.log(data);
            if (data.msg == "Success") {
                var data1 = data.data;
                if (jQuery.isEmptyObject((data1))) {
                }
                else {
                    if (data1.Table1[0].status == 'success') {
                        toastr.success('Service Provider Assigned Successfully');

                        $('#ldassignedbutton_' + master_service_id + '').html('Assigned')

                        if (rowcount == val) {
                            $('#Assign .close').click();
                            if (stabflag == 'phmc1') {
                                $("#spackagehomecollectsamples").tab('show');
                                loadpackagehomecollectsamples(1);
                            }
                            else if (stabflag == 'phmsc1') {
                                $("#spackagehospitalcollectsamples").tab('show');
                                loadpackagehospitalcollectsamples(1);
                            }
                            else if (stabflag == 'phmsc2') {
                                $("#spackagehospitaljobs").tab('show');
                                loadpackagehospitaljobs(1, "LPKHSCJ", 2, 'pkhscjobtable', 'jo');
                            }
                            else if (stabflag == 'phmc2') {
                                $("#spackagehomejobs").tab('show');
                                //loadpackagehomejobs(1, "LPKHCJ", 2, 'pkhscjobtable', 'jo');
                                loadpackagehomejobs(1, "LPKHCJ", 2, 'pkhmcjobtable', 'jo');
                            }
                        }
                    }
                    else {
                        toastr.warning("<button type='button' id='confirmationRevertYes' class='btn btn-warning btn-xs mt20'>Yes<button type='button' id='confirmationRevertNo' class='btn btn-warning btn-xs mt20'>No", 'Are You Sure This Service Provider Already Alloted In Same Time',
                            {
                                closeButton: true,
                                progressBar: true,
                                allowHtml: true,
                                timeOut: 20000000,

                                onShown: function (toast) {
                                    $("#confirmationRevertYes").click(function () {
                                        var servicevalues = {
                                            Dml_Indicator: 'ULHSCHP',
                                            work_order_details_id: work_order_details_id,
                                            is_lab: 1,
                                            work_orderid: work_order_id,
                                            master_service_id: master_service_id,
                                            serviceprovidername: $('#serviceprovider_' + master_service_id + ' option:selected').data('id'),
                                            serviceproviderid: $('#serviceprovider_' + master_service_id + ' option:selected').val(),
                                            patientid: $('#patientid').val(),
                                            scheduledate: $('#lhscheddate_' + master_service_id + '').val(),
                                            scheduletime: $('#lhschdFTimeStart_' + master_service_id + '').val() + '-' + $('#lhschdFTimeEnd_' + master_service_id + '').val(),
                                            samplbarcodeid: (labhometranid == "null") ? 0 : labhometranid,
                                            spname: "SP_Work_Order_Action",
                                            jobsflag: 2
                                        }
                                        $.ajax({
                                            async: true,
                                            type: 'POST',
                                            url: '/Workorder/Get_Workorder',
                                            contentType: 'application/json; charset=UTF-8',
                                            data: JSON.stringify(servicevalues),
                                            success: function (data) {
                                                debugger;
                                                var data = JSON.parse(data);
                                                console.log(data);
                                                if (data.msg == "Success") {
                                                    var data1 = data.data;
                                                    if (jQuery.isEmptyObject((data1))) {
                                                    }
                                                    else {
                                                        if (data1.Table[0].status == 'success') {
                                                            toastr.success('Service Provider Assigned Successfully');
                                                            $('#ldassignedbutton_' + master_service_id + '').html('Assigned')
                                                            if (rowcount == val) {
                                                                $('#Assign .close').click();
                                                                if (stabflag == 'phmc1') {
                                                                    $("#spackagehomecollectsamples").tab('show');
                                                                    loadpackagehomecollectsamples(1);
                                                                }
                                                                else if (stabflag == 'phmsc1') {
                                                                    $("#spackagehospitalcollectsamples").tab('show');
                                                                    loadpackagehospitalcollectsamples(1);
                                                                }
                                                                else if (stabflag == 'phmsc2') {
                                                                    $("#spackagehospitaljobs").tab('show');
                                                                    loadpackagehospitaljobs(1, "LPKHSCJ", 2, 'pkhscjobtable', 'jo');
                                                                }
                                                                else if (stabflag == 'phmc2') {
                                                                    $("#spackagehomejobs").tab('show');
                                                                    //loadpackagehomejobs(1, "LPKHCJ", 2, 'pkhscjobtable', 'jo');
                                                                    loadpackagehomejobs(1, "LPKHCJ", 2, 'pkhmcjobtable', 'jo');
                                                                }
                                                            }
                                                        }
                                                    }
                                                }
                                            }
                                        })


                                    })
                                }
                            })
                        return;
                    }

                }
            }
            $('#serviceeditflag').val(0);
        }
    })
}


$(document).on('change', '.c_dateformat1', function (e) {
    debugger;
    // $('#timeslot').show()
    //var master_service_id = $('#master_service_id').val();

    var val = $(this).attr("id").toString();

    var array = val.split("_")
    var master_service_id = array[1];

    var serviceproviderid = $('#serviceproviderlab_' + master_service_id + '').val()

    var scheduledate = $('#lhscheddate_' + master_service_id + '').val();
    //var scheduledate = moment(scheduledate).format('DD/MM/YYYY')
    $('#stottimes_' + master_service_id + '').html('')
    $('#lhschdFTime_' + master_service_id + '').val('');
    //var scheduledate = $(this).val();
    if (master_service_id != 0) {
        var servicevalues = {
            master_service_id: master_service_id,
            serviceproviderid: serviceproviderid,
            scheduledate: scheduledate,
            hospital_id: $('#HospitalId').val(),
            Dml_Indicator: "LASS",
            spname: "SP_Work_Order_Action",
        }
        $.ajax({
            async: true,
            type: 'POST',
            url: '/Workorder/Get_Workorder',
            contentType: 'application/json; charset=UTF-8',
            data: JSON.stringify(servicevalues),
            success: function (data) {
                debugger;
                var data = JSON.parse(data);
                console.log(data);

                if (data.msg == "Success") {
                    var data1 = data.data;
                    var tr = '', j = 1;
                    if (jQuery.isEmptyObject((data1.Table[0]))) {
                        $('#lhschFTime').show()
                        $('#lhschesubmit').show()
                        $('.c_dateformat1').datepicker('destroy').datepicker({
                            format: 'dd/mm/yyyy',
                            autoclose: true,
                            todayHighlight: true,
                            startDate: 'today'
                        });
                        $('.visiteddate').datepicker({
                            autoclose: true,
                            todayHighlight: true,
                            endDate: new Date()
                        });
                        $('.timepicker').timepicker({
                            showInputs: false
                        });
                    }
                    else {
                        debugger;

                        if (data1.Table.length != 0) {
                            if (data1.Table[0].status == 'noslot') {
                                $('#listslotallocation_' + master_service_id + '').html('');
                                $('#listslotallocation_' + master_service_id + '').html('Slot List');
                                if (data1.Table[0].status == 'error') {
                                    return;
                                }
                                var PatientAppiontment = '';

                                $('#lhschdFTimeStart_' + master_service_id + '').val(data1.Table1[0].slotstarttime)
                                $('#lhschdFTimeEnd_' + master_service_id + '').val(data1.Table1[0].slotendtime)
                                $('#stottimes_' + master_service_id + '').html('There Is No Slot This Service')
                                var listval = '';
                                for (var i = 0; i < data1.Table2.length; i++) {
                                    listval += '<p>' + data1.Table2[i].slotlist + '</p>';
                                }
                                $('#listslotallocation_' + master_service_id + '').append(listval);
                                $('#slotendtimemintues_' + master_service_id + '').val(data1.Table3[0].slotendtimemintues)
                            }
                            else {
                                $('#listslotallocation_' + master_service_id + '').html('');
                                $('#listslotallocation_' + master_service_id + '').html('Slot List');
                                if (data1.Table[0].status == 'error') {
                                    return;
                                }
                                var PatientAppiontment = '';

                                $('#lhschdFTimeStart_' + master_service_id + '').val(data1.Table1[0].slotstarttime)
                                $('#lhschdFTimeEnd_' + master_service_id + '').val(data1.Table1[0].slotendtime)
                                $('#stottimes_' + master_service_id + '').html('Start Time:' + data1.Table1[0].slot_start_time + '  End Time:' + data1.Table1[0].slot_end_time + '')
                                var listval = '';
                                for (var i = 0; i < data1.Table2.length; i++) {
                                    listval += '<p>' + data1.Table2[i].slotlist + '</p>';
                                }
                                $('#listslotallocation_' + master_service_id + '').append(listval);
                                $('#slotendtimemintues_' + master_service_id + '').val(data1.Table3[0].slotendtimemintues)
                            }
                        }
                        else {
                            //$('#slotendtimemintues').val(data1.Table2[0].slotendtimemintues)
                            //var slotendtimemintues = data1.Table2[0].slotendtimemintues;
                            //var d = new Date(dateTime);
                            //d.setMinutes(d.getMinutes() + slotendtimemintues);
                            //$('#lhschdFTimeEnd_' + master_service_id + '').timepicker({
                            //    minuteStep: slotendtimemintues
                            //});
                        }



                    }

                }
            }
        })
    }
    else {


    }
})

$(document).on('change', '.serviceproviderlab', function (e) {
    debugger;
    // $('#timeslot').show()
    //var master_service_id = $('#master_service_id').val();

    var val = $(this).attr("id").toString();
    var serviceproviderid = $(this).val();
    var array = val.split("_")
    var master_service_id = array[1];

    //var scheduledate = $('#lhscheddate_' + master_service_id + '').val()
    var scheduledate = $('#lhscheddate_' + master_service_id + '').val();
    //var scheduledate = moment(scheduledate).format('DD/MM/YYYY')
    $('#stottimes_' + master_service_id + '').html('')
    $('#lhschdFTime_' + master_service_id + '').val('');
    //var scheduledate = $(this).val();
    if (master_service_id != 0) {
        var servicevalues = {
            master_service_id: master_service_id,
            serviceproviderid: serviceproviderid,
            scheduledate: scheduledate,
            hospital_id: $('#HospitalId').val(),
            Dml_Indicator: "LASS",
            spname: "SP_Work_Order_Action",
        }
        $.ajax({
            async: true,
            type: 'POST',
            url: '/Workorder/Get_Workorder',
            contentType: 'application/json; charset=UTF-8',
            data: JSON.stringify(servicevalues),
            success: function (data) {
                debugger;
                var data = JSON.parse(data);
                console.log(data);

                if (data.msg == "Success") {
                    var data1 = data.data;
                    var tr = '', j = 1;
                    if (jQuery.isEmptyObject((data1.Table[0]))) {
                        $('#lhschFTime').show()
                        $('#lhschesubmit').show()
                        $('.c_dateformat1').datepicker('destroy').datepicker({
                            format: 'dd/mm/yyyy',
                            autoclose: true,
                            todayHighlight: true,
                            startDate: 'today'
                        });
                        $('.visiteddate').datepicker({
                            autoclose: true,
                            todayHighlight: true,
                            endDate: new Date()
                        });
                        $('.timepicker').timepicker({
                            showInputs: false
                        });
                    }
                    else {
                        debugger;
                        if (data1.Table.length != 0) {
                            if (data1.Table[0].status == 'noslot') {
                                $('#listslotallocation_' + master_service_id + '').html('');
                                $('#listslotallocation_' + master_service_id + '').html('Slot List');
                                if (data1.Table[0].status == 'error') {
                                    return;
                                }
                                var PatientAppiontment = '';

                                $('#lhschdFTimeStart_' + master_service_id + '').val(data1.Table1[0].slotstarttime)
                                $('#lhschdFTimeEnd_' + master_service_id + '').val(data1.Table1[0].slotendtime)
                                $('#stottimes_' + master_service_id + '').html('There Is No Slot This Service')
                                var listval = '';
                                for (var i = 0; i < data1.Table2.length; i++) {
                                    listval += '<p>' + data1.Table2[i].slotlist + '</p>';
                                }
                                $('#listslotallocation_' + master_service_id + '').append(listval);
                                $('#slotendtimemintues_' + master_service_id + '').val(data1.Table3[0].slotendtimemintues)
                            }
                            else {
                                $('#listslotallocation_' + master_service_id + '').html('');
                                $('#listslotallocation_' + master_service_id + '').html('Slot List');
                                if (data1.Table[0].status == 'error') {
                                    return;
                                }
                                var PatientAppiontment = '';

                                $('#lhschdFTimeStart_' + master_service_id + '').val(data1.Table1[0].slotstarttime)
                                $('#lhschdFTimeEnd_' + master_service_id + '').val(data1.Table1[0].slotendtime)
                                $('#stottimes_' + master_service_id + '').html('Start Time:' + data1.Table1[0].slot_start_time + '  End Time:' + data1.Table1[0].slot_end_time + '')
                                var listval = '';
                                for (var i = 0; i < data1.Table2.length; i++) {
                                    listval += '<p>' + data1.Table2[i].slotlist + '</p>';
                                }
                                $('#listslotallocation_' + master_service_id + '').append(listval);
                                $('#slotendtimemintues_' + master_service_id + '').val(data1.Table3[0].slotendtimemintues)
                            }
                        }
                        else {
                            //$('#slotendtimemintues').val(data1.Table2[0].slotendtimemintues)
                            //var slotendtimemintues = data1.Table2[0].slotendtimemintues;
                            //var d = new Date(dateTime);
                            //d.setMinutes(d.getMinutes() + slotendtimemintues);
                            //$('#lhschdFTimeEnd_' + master_service_id + '').timepicker({
                            //    minuteStep: slotendtimemintues
                            //});
                        }



                    }

                }
            }
        })
    }
    else {


    }
})
$(document).on('change', '.lhschdFTimeStart', function (e) {
    debugger;
    var val = $(this).attr("id").toString();
    var serviceproviderid = $(this).val();
    var array = val.split("_")
    var master_service_id = array[1];
    var slotendtimemintues = $('#slotendtimemintues_' + master_service_id + '').val();

    var getValue = $('#lhschdFTimeStart_' + master_service_id + '').val();

    var newtime = moment(getValue, 'hh:mm A')
        .add(slotendtimemintues, 'minutes')
        .format("hh:mm A");
    $('#lhschdFTimeEnd_' + master_service_id + '').timepicker('setTime', newtime);

    $('#lhschdFTimeEnd_' + master_service_id + '').val(newtime);
})
function addMinutes(time, minsToAdd) {
    function D(J) { return (J < 10 ? '0' : '') + J; };
    var piece = time.split(':');
    var mins = piece[0] * 60 + +piece[1] + +minsToAdd;

    return D(mins % (24 * 60) / 60 | 0) + ':' + D(mins % 60);
}


function slotinsert() {
    //alert('test')
    var slottime = $("#slottimeid").data('id');
    //alert(slottime)
    //var stabflag = $('#stabflag').val();
    var stabflag = $('#stabflag').val();
    if ($('#lhschedate').val() == '') {
        toastr.warning("Please select scheduledate");
        return;
    }
    if (slottime == '') {
        toastr.warning("Please select slot time");
        return;

    }

    debugger;
    var servicevalues = {
        Dml_Indicator: 'ILHSCH',
        work_order_details_id: $('#work_order_details_id').val(),
        work_orderid: $('#work_orderid').val(),
        master_service_id: $('#master_service_id').val(),
        flag: $('#is_package').val(),
        is_lab: $('#is_lab').val(),
        work_orderid: $('#work_orderid').val(),
        patientid: $('#patientid').val(),
        scheduledate: $('#lhschedate').val(),
        scheduletime: slottime,
        jobsflag: $('#jobsflag').val(),
        spname: "SP_Work_Order_Action",
    }
    $.ajax({
        async: true,
        type: 'POST',
        url: '/Workorder/Get_Workorder',
        contentType: 'application/json; charset=UTF-8',
        data: JSON.stringify(servicevalues),
        success: function (data) {
            debugger;

            var data = JSON.parse(data);
            console.log(data);
            if (data.msg == "Success") {
                var data1 = data.data;
                if (jQuery.isEmptyObject((data1))) {


                }
                else {

                    toastr.success('Scheduled Successfully');
                    $('#Schedule .close').click();
                    if (stabflag == 'phmc') {

                        loadpackagehomeunassigned(1);
                        $("#spackagehomeunassigned").tab('show');
                    }
                    else if (stabflag == 'phmsc') {

                        loadpackagehospitalunassigned(1);
                        $("#spackagehospitalunassigned").tab('show');
                    }


                }
            }
        }
    })

}


//Lab Home collection Assign service provider 
$('#lhassignsericeprovider').click(function () {

    debugger;
    var stabflag = $('#stabflag').val();
    var labhometranid = $('#labhometranid').val();

    var serviceeditflag = $('#serviceeditflag').val();
    var Dml_Indicator = '';
    var request_id = $('#request_id').val();
    if ($('#serviceprovider option:selected').val() == '' || $('#serviceprovider option:selected').val() == '0') {
        toastr.warning("Please Select The Service Provider");
        return;
    }

    if (serviceeditflag == '1') {
        Dml_Indicator = 'ELHSCHP';
    }
    else if (serviceeditflag == '3') {
        Dml_Indicator = 'CPKG';
    }
    else {
        Dml_Indicator = 'ULHSCHP';
    }
    if (labhometranid == '') {
        labhometranid = 0;
    }


    var servicevalues = {
        Dml_Indicator: Dml_Indicator,
        work_order_details_id: ($('#work_order_details_id').val() == '') ? 0 : $('#work_order_details_id').val(),
        is_lab: ($('#is_lab').val() == '') ? 0 : $('#is_lab').val(),
        work_orderid: $('#work_orderid').val(),
        master_service_id: $('#master_service_id').val(),
        serviceprovidername: $('#serviceprovider option:selected').data('id'),
        serviceproviderid: $('#serviceprovider').val(),
        patientid: $('#patientid').val(),
        scheduledate: $('#lhscheddate').val(),
        scheduletime: $('#lhschdFTime').val(),
        servicename: $('#nonlabresultconclusion').val(),
        created_by: $('#hiddenUser_id').val(),
        samplbarcodeid: labhometranid,
        spname: "SP_Work_Order_Action",
    }
    $.ajax({
        async: true,
        type: 'POST',
        url: '/Workorder/Get_Workorder',
        contentType: 'application/json; charset=UTF-8',
        data: JSON.stringify(servicevalues),
        success: function (data) {
            debugger;

            var data = JSON.parse(data);
            console.log(data);
            if (data.msg == "Success") {
                var data1 = data.data;
                if (jQuery.isEmptyObject((data1))) {
                }
                else {


                    $('#Assign .close').click();
                    if (stabflag == 'phmc') {
                        $('#stabflag').val('');
                        if (Dml_Indicator == 'CPKG') {
                            toastr.success('Completed Successfully');
                            $("#spackagehomecompleted").tab('show');
                            loadpackagehomecompleted(1);
                        }
                        else if (Dml_Indicator == 'ELHSCHP') {
                            toastr.success('Updated Successfully');
                            $('#stabflag').val('');
                            $("#spackagehomejobs").tab('show');
                            loadpackagehomejobs(1);
                        }
                        else {
                            toastr.success('Service Provider Assigned Successfully');
                            $('#stabflag').val('');
                            $("#spackagehomejobs").tab('show');
                            loadpackagehomejobs(1);
                        }

                    }
                    else if (stabflag == 'phmsc') {
                        if (Dml_Indicator == 'CPKG') {
                            toastr.success('Completed Successfully');
                            $('#stabflag').val('');
                            $("#spackagehospitalcompleted").tab('show');
                            loadpackagehospitalcompleted(1);

                        }
                        else if (Dml_Indicator == 'ELHSCHP') {
                            toastr.success('Updated Successfully');
                            $('#stabflag').val('');
                            $("#spackagehospitaljobs").tab('show');
                            loadpackagehospitaljobs(1);

                        }
                        else {
                            toastr.success('Service Provider Assigned Successfully');
                            $('#stabflag').val('');
                            $("#spackagehospitaljobs").tab('show');
                            loadpackagehospitaljobs(1);
                        }
                    }

                }
            }
            $('#serviceeditflag').val(0);
            $('#work_order_details_id').val(0);


        }
    })
})






//start package home care


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

    loadpackagehomeunscheduled(1);
    $('.asidefilterclass').addClass('hidden');
    $('#asidepkhmcunscheduledtable').removeClass('hidden');
    $('.groupclass').addClass('hidden');
    $('#asidepkhmcunscheduledtablegroupclass').removeClass('hidden');
    $('.Filterclass').addClass('hidden');
    $('#asidepkhmcunscheduledtableFilterclass').removeClass('hidden');
})
//#start package home care unscheduled
$('#spackagehomeunscheduled').click(function () {
    loadpackagehomeunscheduled(1);
    $('.asidefilterclass').addClass('hidden');
    $('#asidepkhmcunscheduledtable').removeClass('hidden');
    $('.groupclass').addClass('hidden');
    $('#asidepkhmcunscheduledtablegroupclass').removeClass('hidden');
    $('.Filterclass').addClass('hidden');
    $('#asidepkhmcunscheduledtableFilterclass').removeClass('hidden');
})
$('#phmunscheduledbtnreportfilter').click(function () {
    loadpackagehomeunscheduled(2);
})
$('#phmunscheduledbtnreportclear').click(function () {
    var hospitalid = $('#HospitalId').val();
    $('#phmounscheduledno').val('');
    $('#phmounscheduledtodate').val('');
    $('#phmounscheduleddate').val('');
    Branchdetails(hospitalid);
    loadpackagehomeunscheduled(1);
})
function loadpackagehomeunscheduled(flag) {


    var servicevalues = {
        Dml_Indicator: "LPKHCUNS",
        flag: flag,
        orderdate: $('#phmounscheduleddate').val(),
        ordertodate: $('#phmounscheduledtodate').val(),
        orderno: $('#phmounscheduledno').val(),
        jobsflag: $('#phmoschedulestatus').val(),
        branchid: $('#pkghmobranch_id').val(),
        departmentid: ($('#Hdepartment_id').val() == '') ? '' : $('#Hdepartment_id').val(),
        UserId: useridheder,
        spname: "SP_Work_Order_Home_UNS",


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

            var data = JSON.parse(data);
            console.log(data);
            if (data.msg == "Success") {
                var data1 = data.data;
                if (jQuery.isEmptyObject((data1))) {
                    tr = '';
                    $('#pkhmcunscheduledtablebody').html(tr);
                }
                else {

                    var b = data1.Table;
                    $('#pkhmcunscheduledtablebody').empty();
                    $('#pkhmcunscheduledtable').dataTable().fnClearTable();
                    //$('#pkhmcunscheduledtable').dataTable().fnDraw();
                    $('#pkhmcunscheduledtable').dataTable().fnDestroy();
                    tr = '';
                    var popupflagid, popupflag, onclickflag, sflg = '', status_color = '';

                    $.each(b, function (i, emp) {
                        popupflag = emp.btnflag;
                        if (emp.scheduletime == '00:01') {
                            stime = '';
                        }
                        else {
                            stime = emp.scheduletime;
                        }
                        if (emp.patientprefertime == '00:01') {
                            ptime = '';
                        }
                        else {
                            ptime = emp.patientprefertime;
                        }

                        if (emp.Bill_status == "Paid") {
                            status_color = "<span style='background-color: green !important;color:white;font-size:10px;padding:3px;border-radius:4px;'>paid</span>";
                        }
                        else if (emp.Bill_status == "Due") {
                            status_color = "<span style='background-color: red !important;color:white;font-size:10px;padding:3px;border-radius:4px;'>Due</span>";
                        }
                        else if (emp.Bill_status == "Partial Due") {
                            status_color = "<span style='background-color: orange !important;color:white;font-size:10px;padding:3px;border-radius:4px;'>Partial paid</span>";
                        }
                        else {
                            status_color = '';
                        }


                        if (emp.is_lab == 2) {

                            tr = tr + '<tr id="t_' + emp.work_order_id + '"><td><div class="col-md-12 padding0"><div class="disp_if"><button style="cursor:pointer;font-size:8px;" data-toggle="modal" data-target="#' + popupflag + '" class="btn-primaryuse btn-xs" onclick=lhorderschedule("' + emp.work_order_details_id + '","' + i + '","' + emp.work_order_id + '","' + emp.patientid + '","' + emp.btnflag + '",1,"phmc",' + emp.is_lab + ',' + emp.master_service_id + ',"' + emp.visit_report_id + '","' + emp.branch_id + '",2,"pkhmcunscheduledtable","' + emp.work_order_status + '","' + emp.wid + '")>' + emp.btnflag + '</button><a href="#" class="dropdown-toggle btn btn-info-dots btn-xs" data-toggle="dropdown" aria-expanded="true"><span class="fa fa-ellipsis-h" data-toggle="tooltip" data-placement="bottom" title="Other Options" style="color:black;" aria-hidden="true"></span><span class="sr-only">Options</span></a><div class="dropdown-menu info-dropdown-workorder" id=""><a  class="btn btn-delete btn-xs mr-10" data-toggle="modal" data-target="#delete_reason_popup"  onclick=servicedel1("' + emp.work_order_details_id + '",2,"phmc","' + emp.package_id + '","' + emp.work_order_id + '")><i class="fa fa-trash-o mr-10" aria-hidden="true"></i>Delete</a></div></div></td><td class="tbl-name" id="ldtpatient_id_' + i + '">' + '<a data-toggle="modal" style="cursor: pointer;" data-target="#myModalPatientSearchDetails" onclick=\'billing_details(\"' + emp.patient_id + '\",\"' + emp.patient_username + '\",\"' + emp.phone_number_1 + '\",this)\'>' + emp.patient_username + " " + status_color + '</a>' + '<Span class="tbl_pno"><br>' + emp.patient_id + '</span></td><td id="ldtphone_number_1_' + i + '">' + emp.phone_number_1 + '<Span class="tbl_pno"><br>' + emp.paddress + '</span></td><td>' + emp.visit_type_name + '</td><td id="ldtservice_name_' + i + '" value=' + emp.master_service_id + ' data-id=' + emp.master_service_id + ' data1-id=' + emp.is_lab + '>' + '<span class="tbl-name">' + emp.service_name + '</span><Span class="tbl_wpkg"><br>' + (($.trim(emp.package_name) != '') ? emp.package_name + ' / ' + emp.package_id : emp.package_id) + '</span></td><td>' + emp.package_purchased_date + '</td><td>' + emp.branch_name + '</td><td id="ldtvisit_report_id_' + i + '">' + (($.trim(emp.patientpreferdate) != '') ? emp.patientpreferdate + ' ' + ptime : ptime) + '</td><td id="ldtvisit_report_id_' + i + '">' + (($.trim(emp.scheduledate) != '') ? emp.scheduledate + ' ' + stime : stime) + '</td><td id="ldtvisit_report_id_' + i + '">' + emp.serviceprovidername + '</td><td id="ldtwork_order_no_' + i + '" data-id1=' + emp.is_lab + '>' + emp.work_order_no + '</td></tr>';
                        }
                        else if (emp.is_lab == 1) {
                            if (emp.btnflag == 'Schedule' || emp.btnflag == 'Assign') {
                                tr = tr + '<tr id="t_' + emp.work_order_id + '"><td><div class="col-md-12 padding0"><div class="disp_if"><button style="cursor:pointer;font-size:8px;" data-toggle="modal" data-target="#' + popupflag + '" class="btn-primaryuse btn-xs" onclick=lhorderschedule("' + emp.work_order_details_id + '","' + i + '","' + emp.work_order_id + '","' + emp.patientid + '","' + emp.btnflag + '",1,"phmc",' + emp.is_lab + ',' + emp.master_service_id + ',"' + emp.visit_report_id + '","' + emp.branch_id + '",2,"pkhmcunscheduledtable","' + emp.work_order_status + '","' + emp.wid + '")>' + emp.btnflag + '</button><a href="#" class="dropdown-toggle btn btn-info-dots btn-xs" data-toggle="dropdown" aria-expanded="true"><span class="fa fa-ellipsis-h" data-toggle="tooltip" data-placement="bottom" title="Other Options" style="color:black;" aria-hidden="true"></span><span class="sr-only">Options</span></a><div class="dropdown-menu info-dropdown-workorder" id=""><a  class="btn btn-delete btn-xs mr-10"  data-toggle="modal" data-target="#delete_reason_popup" onclick=servicedel1("' + emp.wid + '",2,"phmc","' + emp.package_id + '","' + emp.work_order_id + '")><i class="fa fa-trash-o mr-10" aria-hidden="true"></i>Delete</a></div></div></td><td class="tbl-name" id="ldtpatient_id_' + i + '">' + '<a data-toggle="modal" style="cursor: pointer;" data-target="#myModalPatientSearchDetails" onclick=\'billing_details(\"' + emp.patient_id + '\",\"' + emp.patient_username + '\",\"' + emp.phone_number_1 + '\",this)\'>' + emp.patient_username + " " + status_color + '</a>' + '<Span class="tbl_pno"><br>' + emp.patient_id + '</span></td><td id="ldtphone_number_1_' + i + '">' + emp.phone_number_1 + '<Span class="tbl_pno"><br>' + emp.paddress + '</span></td><td>' + emp.visit_type_name + '</td><td class="details-control" ' + sflg + ' onclick=servicedetailspackage(this,"' + emp.work_order_id + '","pkghmcunsched",' + emp.package_auto_id + ',"' + emp.wid + '",1);>' + emp.service_count + '</span><Span class="tbl_wpkg"><br>' + (($.trim(emp.package_name) != '') ? emp.package_name + ' / ' + emp.package_id : emp.package_id) + '</span><i class="fa fa-angle-double-down table-arrow-size pull-right"></i></td><td>' + emp.package_purchased_date + '</td><td>' + emp.branch_name + '</td><td id="ldtvisit_report_id_' + i + '">' + (($.trim(emp.patientpreferdate) != '') ? emp.patientpreferdate + ' ' + ptime : ptime) + '</td><td id="ldtvisit_report_id_' + i + '">' + (($.trim(emp.scheduledate) != '') ? emp.scheduledate + ' ' + stime : stime) + '</td><td id="ldtvisit_report_id_' + i + '">' + emp.serviceprovidername + '</td><td id="ldtwork_order_no_' + i + '" data-id1=' + emp.is_lab + '>' + emp.work_order_no + '</td></tr>';

                            }
                            else {
                                if (emp.btnflag == 'Schedule' || emp.btnflag == 'Assign') {
                                    tr = tr + '<tr id="t_' + emp.work_order_id + '"><td><div class="col-md-12 padding0"><div class="disp_if"><button style="cursor:pointer;font-size:8px;" data-toggle="modal" data-target="#' + popupflag + '" class="btn-primaryuse btn-xs" onclick=lhorderschedule("' + emp.work_order_details_id + '","' + i + '","' + emp.work_order_id + '","' + emp.patientid + '","' + emp.btnflag + '",1,"phmc",' + emp.is_lab + ',' + emp.master_service_id + ',"' + emp.visit_report_id + '","' + emp.branch_id + '",2,"pkhmcunscheduledtable","' + emp.work_order_status + '","' + emp.wid + '")>' + emp.btnflag + '</button><a href="#" class="dropdown-toggle btn btn-info-dots btn-xs" data-toggle="dropdown" aria-expanded="true"><span class="fa fa-ellipsis-h" data-toggle="tooltip" data-placement="bottom" title="Other Options" style="color:black;" aria-hidden="true"></span><span class="sr-only">Options</span></a><div class="dropdown-menu info-dropdown-workorder" id=""><a  class="btn btn-delete btn-xs mr-10" data-toggle="modal" data-target="#delete_reason_popup" onclick=servicedel1("' + emp.wid + '",2,"phmc","' + emp.package_id + '","' + emp.work_order_id + '")><i class="fa fa-trash-o mr-10" aria-hidden="true"></i>Delete</a></div></div><td class="tbl-name" id="ldtpatient_id_' + i + '">' + '<a data-toggle="modal" style="cursor: pointer;" data-target="#myModalPatientSearchDetails" onclick=\'billing_details(\"' + emp.patient_id + '\",\"' + emp.patient_username + '\",\"' + emp.phone_number_1 + '\",this)\'>' + emp.patient_username + " " + status_color + '</a>' + '<Span class="tbl_pno"><br>' + emp.patient_id + '</span></td><td id="ldtphone_number_1_' + i + '">' + emp.phone_number_1 + '<Span class="tbl_pno"><br>' + emp.paddress + '</span></td><td>' + emp.visit_type_name + '</td><td class="details-control" ' + sflg + ' onclick=servicedetailspackage(this,"' + emp.work_order_id + '","pkghmcunsched",' + emp.package_auto_id + ',""' + emp.wid + '"",1);>' + emp.service_count + '</span><Span class="tbl_wpkg"><br>' + (($.trim(emp.package_name) != '') ? emp.package_name + ' / ' + emp.package_id : emp.package_id) + '</span><i class="fa fa-angle-double-down table-arrow-size pull-right"></i></td><td>' + emp.package_purchased_date + '</td><td>' + emp.branch_name + '</td><td id="ldtvisit_report_id_' + i + '">' + (($.trim(emp.patientpreferdate) != '') ? emp.patientpreferdate + ' ' + ptime : ptime) + '</td><td id="ldtvisit_report_id_' + i + '">' + (($.trim(emp.scheduledate) != '') ? emp.scheduledate + ' ' + stime : stime) + '</td><td id="ldtvisit_report_id_' + i + '">' + emp.serviceprovidername + '</td><td id="ldtwork_order_no_' + i + '" data-id1=' + emp.is_lab + '>' + emp.work_order_no + '</td></tr>';

                                }
                                else {
                                    tr = tr + '<tr id="t_' + emp.work_order_id + '"><td><div class="col-md-12 padding0"><div class="disp_if">' + emp.btnflag + '<a href="#" class="dropdown-toggle btn btn-info-dots btn-xs" data-toggle="dropdown" aria-expanded="true"><span class="fa fa-ellipsis-h" data-toggle="tooltip" data-placement="bottom" title="Other Options" style="color:black;" aria-hidden="true"></span><span class="sr-only">Options</span></a><div class="dropdown-menu info-dropdown-workorder" id=""><a  class="btn btn-delete btn-xs mr-10" data-toggle="modal" data-target="#delete_reason_popup" onclick=servicedel1("' + emp.wid + '",2,"phmc","' + emp.package_id + '","' + emp.work_order_id + '")><i class="fa fa-trash-o mr-10" aria-hidden="true"></i>Delete</a></div></div></td><td class="tbl-name" id="ldtpatient_id_' + i + '">' + '<a data-toggle="modal" style="cursor: pointer;" data-target="#myModalPatientSearchDetails" onclick=\'billing_details(\"' + emp.patient_id + '\",\"' + emp.patient_username + '\",\"' + emp.phone_number_1 + '\",this)\'>' + emp.patient_username + " " + status_color + '</a>' + '<Span class="tbl_pno"><br>' + emp.patient_id + '</span></td><td id="ldtphone_number_1_' + i + '">' + emp.phone_number_1 + '<Span class="tbl_pno"><br>' + emp.paddress + '</span></td><td>' + emp.visit_type_name + '</td><td class="details-control" ' + sflg + ' onclick=servicedetailspackage(this,"' + emp.work_order_id + '","pkghmcunsched",' + emp.package_auto_id + ',"' + emp.wid + '",1);>' + emp.service_count + '</span><Span class="tbl_wpkg"><br>' + (($.trim(emp.package_name) != '') ? emp.package_name + ' / ' + emp.package_id : emp.package_id) + '</span><i class="fa fa-angle-double-down table-arrow-size pull-right"></i></td><td>' + emp.package_purchased_date + '</td><td>' + emp.branch_name + '</td><td id="ldtvisit_report_id_' + i + '">' + (($.trim(emp.patientpreferdate) != '') ? emp.patientpreferdate + ' ' + ptime : ptime) + '</td><td id="ldtvisit_report_id_' + i + '">' + (($.trim(emp.scheduledate) != '') ? emp.scheduledate + ' ' + stime : stime) + '</td><td id="ldtvisit_report_id_' + i + '">' + emp.serviceprovidername + '</td><td id="ldtwork_order_no_' + i + '" data-id=' + emp.labhometranid + '>' + emp.work_order_no + '</td></tr>';

                                }
                            }
                        }


                    });

                    $('#pkhmcunscheduledtablebody').html(tr);
                    //$('#pkhmcunscheduledtable').DataTable();
                    datatable('pkhmcunscheduledtable');


                }
            }
        }
    });
}
//# end package home care unscheduled



//#start package home care unassgined
$('#spackagehomeunassigned').click(function () {
    loadpackagehomeunassigned(1);
    $('.asidefilterclass').addClass('hidden');
    $('#asidepkhmcunassignedtable').removeClass('hidden');
    $('.groupclass').addClass('hidden');
    $('#asidepkhmcunassignedtablegroupclass').removeClass('hidden');
    $('.Filterclass').addClass('hidden');
    $('#asidepkhmcunassignedtableFilterclass').removeClass('hidden');
})
$('#phmunassignedbtnreportfilter').click(function () {
    loadpackagehomeunassigned(2);
})
$('#phmunassignedbtnreportclear').click(function () {
    var hospitalid = $('#HospitalId').val();
    $('#phmounassignedno').val('');
    $('#phmounassigneddate').val('');
    $('#phmounassignedtodate').val('');
    Branchdetails(hospitalid);
    loadpackagehomeunassigned(1);
})
function loadpackagehomeunassigned(flag) {

    debugger;
    var servicevalues = {
        Dml_Indicator: "LPKHCUNA",
        flag: flag,
        orderdate: $('#phmounassigneddate').val(),
        ordertodate: $('#phmounassignedtodate').val(),
        orderno: $('#phmounassignedno').val(),
        branchid: $('#pkghmunassignedbranch_id').val(),
        departmentid: ($('#Hdepartment_id').val() == '') ? '' : $('#Hdepartment_id').val(),
        UserId: useridheder,
        spname: "SP_Work_Order_Home_Assign",
    }
    $.ajax({
        async: true,
        type: 'POST',
        url: '/Workorder/Get_Workorder',
        contentType: 'application/json; charset=UTF-8',
        data: JSON.stringify(servicevalues),
        success: function (data) {
            debugger;

            var data = JSON.parse(data);
            console.log(data);
            if (data.msg == "Success") {
                var data1 = data.data;
                if (jQuery.isEmptyObject((data1))) {
                    tr = '';
                    $('#pkhmcunassignedtablebody').html(tr);
                }
                else {

                    var b = data1.Table;
                    $('#pkhmcunassignedtablebody').empty();
                    $('#pkhmcunassignedtable').dataTable().fnClearTable();
                    // $('#pkhmcunassignedtable').dataTable().fnDraw();
                    $('#pkhmcunassignedtable').dataTable().fnDestroy();
                    tr = '';
                    var popupflagid, popupflag, onclickflag, sflg = '', status_color = '';

                    $.each(b, function (i, emp) {
                        popupflag = emp.btnflag;
                        if (emp.scheduletime == '00:01') {
                            stime = '';
                        }
                        else {
                            stime = emp.scheduletime;
                        }
                        if (emp.patientprefertime == '00:01') {
                            ptime = '';
                        }
                        else {
                            ptime = emp.patientprefertime;
                        }

                        if (emp.Bill_status == "Paid") {
                            status_color = "<span style='background-color: green !important;color:white;font-size:10px;padding:3px;border-radius:4px;'>paid</span>";
                        }
                        else if (emp.Bill_status == "Due") {
                            status_color = "<span style='background-color: red !important;color:white;font-size:10px;padding:3px;border-radius:4px;'>Due</span>";
                        }
                        else if (emp.Bill_status == "Partial Due") {
                            status_color = "<span style='background-color: orange !important;color:white;font-size:10px;padding:3px;border-radius:4px;'>Partial paid</span>";
                        }
                        else {
                            status_color = '';
                        }

                        if (emp.is_lab == 2) {

                            tr = tr + '<tr id="t_' + emp.work_order_id + '"><td class="col-sm-1"><button style="cursor:pointer;font-size:8px;" data-toggle="modal" data-target="#' + popupflag + '" class="btn-primaryuse btn-xs" onclick=lhorderschedule("' + emp.work_order_details_id + '","' + i + '","' + emp.work_order_id + '","' + emp.patientid + '","' + emp.btnflag + '",1,"phmc",' + emp.is_lab + ',' + emp.master_service_id + ',"' + emp.visit_report_id + '","' + emp.branch_id + '",2,"pkhmcunassignedtable","' + emp.work_order_status + '","' + emp.wid + '")>' + emp.btnflag + '</button></td><td class="tbl-name" id="ldtpatient_id_' + i + '">' + '<a data-toggle="modal" style="cursor: pointer;" data-target="#myModalPatientSearchDetails" onclick=\'billing_details(\"' + emp.patient_id + '\",\"' + emp.patient_username + '\",\"' + emp.phone_number_1 + '\",this)\'>' + emp.patient_username + " " + status_color + '</a>' + '<Span class="tbl_pno"><br>' + emp.patient_id + '</span></td><td id="ldtphone_number_1_' + i + '">' + emp.phone_number_1 + '<Span class="tbl_pno"><br>' + emp.paddress + '</span></td><td>' + emp.visit_type_name + '</td><td id="ldtservice_name_' + i + '" value=' + emp.master_service_id + ' data-id=' + emp.master_service_id + ' data1-id=' + emp.is_lab + '>' + '<span class="tbl-name">' + emp.service_name + '</span><Span class="tbl_wpkg"><br>' + (($.trim(emp.package_name) != '') ? emp.package_name + ' / ' + emp.package_id : emp.package_id) + '</span></td><td>' + emp.package_purchased_date + '</td><td>' + emp.branch_name + '</td><td id="ldtvisit_report_id_' + i + '">' + (($.trim(emp.patientpreferdate) != '') ? emp.patientpreferdate + ' ' + ptime : ptime) + '</td><td id="ldtvisit_report_id_' + i + '">' + (($.trim(emp.scheduledate) != '') ? emp.scheduledate + ' ' + stime : stime) + '</td><td id="ldtvisit_report_id_' + i + '">' + emp.serviceprovidername + '</td><td id="ldtwork_order_no_' + i + '" data-id1=' + emp.is_lab + '>' + emp.work_order_no + '</td></tr>';

                        }
                        else if (emp.is_lab == 1) {
                            if (emp.btnflag == 'Schedule' || emp.btnflag == 'Assign') {
                                tr = tr + '<tr id="t_' + emp.work_order_id + '"><td><button style="cursor:pointer;font-size:8px;" data-toggle="modal" data-target="#' + popupflag + '" class="btn btn-primaryuse btn-xs" onclick=lhorderschedule("' + emp.work_order_details_id + '","' + i + '","' + emp.work_order_id + '","' + emp.patientid + '","' + emp.btnflag + '",1,"phmc",' + emp.is_lab + ',' + emp.master_service_id + ',"' + emp.visit_report_id + '","' + emp.branch_id + '",2,"pkhmcunassignedtable","' + emp.work_order_status + '","' + emp.wid + '")>' + emp.btnflag + '</button></td><td class="tbl-name" id="ldtpatient_id_' + i + '">' + '<a data-toggle="modal" style="cursor: pointer;" data-target="#myModalPatientSearchDetails" onclick=\'billing_details(\"' + emp.patient_id + '\",\"' + emp.patient_username + '\",\"' + emp.phone_number_1 + '\",this)\'>' + emp.patient_username + " " + status_color + '</a>' + '<Span class="tbl_pno"><br>' + emp.patient_id + '</span></td><td id="ldtphone_number_1_' + i + '">' + emp.phone_number_1 + '<Span class="tbl_pno"><br>' + emp.paddress + '</span></td><td>' + emp.visit_type_name + '</td><td class="details-control" ' + sflg + ' onclick=servicedetailspackage(this,"' + emp.work_order_id + '","pkghmcunass",' + emp.package_auto_id + ',"' + emp.wid + '",2);>' + emp.service_count + '</span><Span class="tbl_wpkg"><br>' + (($.trim(emp.package_name) != '') ? emp.package_name + ' / ' + emp.package_id : emp.package_id) + '</span><i class="fa fa-angle-double-down table-arrow-size pull-right"></i></td><td>' + emp.package_purchased_date + '</td><td>' + emp.branch_name + '</td><td id="ldtvisit_report_id_' + i + '">' + (($.trim(emp.patientpreferdate) != '') ? emp.patientpreferdate + ' ' + ptime : ptime) + '</td><td id="ldtvisit_report_id_' + i + '">' + (($.trim(emp.scheduledate) != '') ? emp.scheduledate + ' ' + stime : stime) + '</td><td id="ldtvisit_report_id_' + i + '">' + emp.serviceprovidername + '</td><td id="ldtwork_order_no_' + i + '" data-id1=' + emp.is_lab + '>' + emp.work_order_no + '</td></tr>';

                            }
                            else {
                                // tr = tr + '<tr id="t_' + emp.work_order_id + '"><td id="ldtwork_order_no_' + i + '">' + emp.work_order_no + '</td><td id="ldtpackage_id_' + i + '">' + emp.package_id + '</td><td id="ldtpackage_name_' + i + '">' + emp.package_name + '</td><td id="ldtservice_name_' + i + '" data-id=' + emp.master_service_id + ' data1-id=' + emp.is_lab + '>' + emp.service_name + '</td><td></td><td id="ldtpatient_id_' + i + '">' + emp.patient_id + '</td><td id="ldtpatient_username_' + i + '">' + emp.patient_username + '</td><td id="ldtphone_number_1_' + i + '">' + emp.phone_number_1 + '</td><td id="ldtpaddress_' + i + '">' + emp.paddress + '</td><td></td><td></td><td id="ldttotal_amount_' + i + '">' + emp.total_amount + '</td><td class="details-control" ' + sflg + ' onclick=servicedetailspackage(this,"' + emp.request_id + '","pkghmcorders");>' + emp.service_count + '<i class="fa fa-angle-double-down table-arrow-size pull-right"></i></td><td><button style="cursor:pointer;" data-toggle="modal" data-target="#' + popupflag + '" class="btn btn-primaryuse btn-xs" onclick=labordersample("' + emp.request_id + '","' + i + '","' + emp.work_order_id + '","' + emp.patientid + '","' + emp.btnflag + '",1,"phmc")>' + emp.btnflag + '</button></tr>';

                                if (emp.btnflag == 'Schedule' || emp.btnflag == 'Assign') {
                                    tr = tr + '<tr id="t_' + emp.work_order_id + '"><td><button style="cursor:pointer;font-size:8px;" data-toggle="modal" data-target="#' + popupflag + '" class="btn btn-primaryuse btn-xs" onclick=lhorderschedule("' + emp.work_order_details_id + '","' + i + '","' + emp.work_order_id + '","' + emp.patientid + '","' + emp.btnflag + '",1,"phmc",' + emp.is_lab + ',' + emp.master_service_id + ',"' + emp.visit_report_id + '","' + emp.branch_id + '",2,"pkhmcunassignedtable","' + emp.work_order_status + '","' + emp.wid + '")>' + emp.btnflag + '</button></td><td class="tbl-name" id="ldtpatient_id_' + i + '">' + '<a data-toggle="modal" style="cursor: pointer;" data-target="#myModalPatientSearchDetails" onclick=\'billing_details(\"' + emp.patient_id + '\",\"' + emp.patient_username + '\",\"' + emp.phone_number_1 + '\",this)\'>' + emp.patient_username + " " + status_color + '</a>' + '<Span class="tbl_pno"><br>' + emp.patient_id + '</span></td><td id="ldtphone_number_1_' + i + '">' + emp.phone_number_1 + '<Span class="tbl_pno"><br>' + emp.paddress + '</span></td><td>' + emp.visit_type_name + '</td><td class="details-control" ' + sflg + ' onclick=servicedetailspackage(this,"' + emp.work_order_id + '","pkghmcunass",' + emp.package_auto_id + ',"' + emp.wid + '",2);>' + emp.service_count + '</span><Span class="tbl_wpkg"><br>' + (($.trim(emp.package_name) != '') ? emp.package_name + ' / ' + emp.package_id : emp.package_id) + '</span><i class="fa fa-angle-double-down table-arrow-size pull-right"></i></td><td>' + emp.package_purchased_date + '</td><td>' + emp.branch_name + '</td><td id="ldtvisit_report_id_' + i + '">' + (($.trim(emp.patientpreferdate) != '') ? emp.patientpreferdate + ' ' + ptime : ptime) + '</td><td id="ldtvisit_report_id_' + i + '">' + (($.trim(emp.scheduledate) != '') ? emp.scheduledate + ' ' + stime : stime) + '</td><td id="ldtvisit_report_id_' + i + '">' + emp.serviceprovidername + '</td><td id="ldtwork_order_no_' + i + '" data-id1=' + emp.is_lab + '>' + emp.work_order_no + '</td></tr>';

                                }
                                else {
                                    tr = tr + '<tr id="t_' + emp.work_order_id + '"><td><button style="cursor:pointer;font-size:8px;" data-toggle="modal" data-target="#ldcollect_samplepopup" class="btn btn-primaryuse btn-xs" onclick=labordersample("' + emp.work_order_details_id + '","' + i + '","' + emp.work_order_id + '","' + emp.patientid + '","phmc",3,"' + emp.package_auto_id + '",' + emp.work_order_status + ',' + emp.serviceproviderid + ',"' + emp.patient_id + '","' + emp.visit_report_id + '","' + emp.branch_id + '","' + emp.hospitalid + '","' + emp.wid + '")>' + emp.btnflag + '</button></td><td class="tbl-name" id="ldtpatient_id_' + i + '">' + '<a data-toggle="modal" style="cursor: pointer;" data-target="#myModalPatientSearchDetails" onclick=\'billing_details(\"' + emp.patient_id + '\",\"' + emp.patient_username + '\",\"' + emp.phone_number_1 + '\",this)\'>' + emp.patient_username + " " + status_color + '</a>' + '<Span class="tbl_pno"><br>' + emp.patient_id + '</span></td><td id="ldtphone_number_1_' + i + '">' + emp.phone_number_1 + '<Span class="tbl_pno"><br>' + emp.paddress + '</span></td><td>' + emp.visit_type_name + '</td><td class="details-control" ' + sflg + ' onclick=servicedetailspackage(this,"' + emp.work_order_id + '","pkghmcunass",' + emp.package_auto_id + ',"' + emp.wid + '",2);>' + emp.service_count + '</span><Span class="tbl_wpkg"><br>' + (($.trim(emp.package_name) != '') ? emp.package_name + ' / ' + emp.package_id : emp.package_id) + '</span><i class="fa fa-angle-double-down table-arrow-size pull-right"></i></td><td>' + emp.package_purchased_date + '</td><td>' + emp.branch_name + '</td><td id="ldtvisit_report_id_' + i + '">' + (($.trim(emp.patientpreferdate) != '') ? emp.patientpreferdate + ' ' + ptime : ptime) + '</td><td id="ldtvisit_report_id_' + i + '">' + (($.trim(emp.scheduledate) != '') ? emp.scheduledate + ' ' + stime : stime) + '</td><td id="ldtvisit_report_id_' + i + '">' + emp.serviceprovidername + '</td><td id="ldtwork_order_no_' + i + '" data-id=' + emp.labhometranid + '>' + emp.work_order_no + '</td></tr>';

                                }
                            }
                        }


                    });

                    $('#pkhmcunassignedtablebody').html(tr);

                    datatable('pkhmcunassignedtable');


                }
            }
        }
    });
}

//# end package home care unassigned


//#start package home care unassgined
$('#spackagehomecollectsamples').click(function () {
    loadpackagehomecollectsamples(1);
    $('.asidefilterclass').addClass('hidden');
    $('#asidepkhmccollectsamplestable').removeClass('hidden');
    $('.groupclass').addClass('hidden');
    $('#asidepkhmccollectsamplestablegroupclass').removeClass('hidden');
    $('.Filterclass').addClass('hidden');
    $('#asidepkhmccollectsamplestableFilterclass').removeClass('hidden');
})
$('#phmcollectsamplesbtnreportfilter').click(function () {
    loadpackagehomecollectsamples(2);
})
$('#phmcollectsamplesbtnreportclear').click(function () {
    var hospitalid = $('#HospitalId').val();
    $('#phmocollectsamplesno').val('');
    $('#phmocollectsamplesdate').val('');
    $('#phmocollectsamplestodate').val('');
    Branchdetails(hospitalid);
    loadpackagehomecollectsamples(1);
})
function loadpackagehomecollectsamples(flag) {

    debugger;
    var servicevalues = {
        Dml_Indicator: "LPKHCS",
        flag: flag,
        orderdate: $('#phmocollectsamplesdate').val(),
        ordertodate: $('#phmocollectsamplestodate').val(),
        orderno: $('#phmocollectsamplesno').val(),
        serviceproviderid: $('#phmocollectsamplesserviceprovidername').val(),
        branchid: $('#pkghmcollectsamplesbranch_id').val(),
        departmentid: ($('#Hdepartment_id').val() == '') ? '' : $('#Hdepartment_id').val(),
        UserId: useridheder,
        spname: "SP_Work_Order_Home_CS",
    }
    $.ajax({
        async: true,
        type: 'POST',
        url: '/Workorder/Get_Workorder',
        contentType: 'application/json; charset=UTF-8',
        data: JSON.stringify(servicevalues),
        success: function (data) {
            debugger;

            var data = JSON.parse(data);
            console.log(data);
            if (data.msg == "Success") {
                var data1 = data.data;
                if (jQuery.isEmptyObject((data1))) {
                    tr = '';
                    $('#pkhmccollectsamplestablebody').html(tr);
                }
                else {

                    var b = data1.Table;
                    $('#pkhmccollectsamplestablebody').empty();
                    $('#pkhmccollectsamplestable').dataTable().fnClearTable();
                    // $('#pkhmccollectsamplestable').dataTable().fnDraw();
                    $('#pkhmccollectsamplestable').dataTable().fnDestroy();
                    tr = '';
                    var popupflagid, popupflag, onclickflag, sflg = '', status_color = '';

                    $.each(b, function (i, emp) {
                        popupflag = emp.btnflag;

                        if (emp.scheduletime == '00:01') {
                            stime = '';
                        }
                        else {
                            stime = emp.scheduletime;
                        }
                        if (emp.patientprefertime == '00:01') {
                            ptime = '';
                        }
                        else {
                            ptime = emp.patientprefertime;
                        }

                        if (emp.Bill_status == "Paid") {
                            status_color = "<span style='background-color: green !important;color:white;font-size:10px;padding:3px;border-radius:4px;'>paid</span>";
                        }
                        else if (emp.Bill_status == "Due") {
                            status_color = "<span style='background-color: red !important;color:white;font-size:10px;padding:3px;border-radius:4px;'>Due</span>";
                        }
                        else if (emp.Bill_status == "Partial Due") {
                            status_color = "<span style='background-color: orange !important;color:white;font-size:10px;padding:3px;border-radius:4px;'>Partial paid</span>";
                        }
                        else {
                            status_color = '';
                        }

                        if (emp.is_lab == 2) {

                            tr = tr + '<tr id="t_' + emp.work_order_id + '"><td class="col-sm-1 disp_if"><i class="fa fa-close mr-10" cursor: pointer; data-toggle="tooltip" title="Click to Reject!" style="font-size:24px;color:red" onclick=rejection("' + emp.work_order_details_id + '","' + emp.work_order_id + '","' + emp.patientid + '",' + emp.is_lab + ',' + emp.master_service_id + ',"' + emp.visit_report_id + '",' + emp.serviceproviderid + ',"' + emp.wid + '",2)></i><button style="cursor:pointer;font-size:8px;" data-toggle="modal" data-target="#' + popupflag + '" class="btn-primaryuse btn-xs" onclick=lhorderschedule("' + emp.work_order_details_id + '","' + i + '","' + emp.work_order_id + '","' + emp.patientid + '","' + emp.btnflag + '",1,"phmc",' + emp.is_lab + ',' + emp.master_service_id + ',"' + emp.visit_report_id + '","' + emp.branch_id + '",2,"pkhmccollectsamplestable","' + emp.work_order_status + '","' + emp.wid + '")>' + emp.btnflag + '</button></td><td class="tbl-name" id="ldtpatient_id_' + i + '">' + '<a data-toggle="modal" style="cursor: pointer;" data-target="#myModalPatientSearchDetails" onclick=\'billing_details(\"' + emp.patient_id + '\",\"' + emp.patient_username + '\",\"' + emp.phone_number_1 + '\",this)\'>' + emp.patient_username + " " + status_color + '</a>' + '<Span class="tbl_pno"><br>' + emp.patient_id + '</span></td><td id="ldtphone_number_1_' + i + '">' + emp.phone_number_1 + '<Span class="tbl_pno"><br>' + emp.paddress + '</span></td><td>' + emp.visit_type_name + '</td><td id="ldtservice_name_' + i + '" value=' + emp.master_service_id + ' data-id=' + emp.master_service_id + ' data1-id=' + emp.is_lab + '>' + '<span class="tbl-name">' + emp.service_name + '</span><Span class="tbl_wpkg"><br>' + (($.trim(emp.package_name) != '') ? emp.package_name + ' / ' + emp.package_id : emp.package_id) + '</span></td><td>' + emp.package_purchased_date + '</td><td>' + emp.branch_name + '</td><td id="ldtvisit_report_id_' + i + '">' + (($.trim(emp.patientpreferdate) != '') ? emp.patientpreferdate + ' ' + ptime : ptime) + '</td><td id="ldtvisit_report_id_' + i + '">' + (($.trim(emp.scheduledate) != '') ? emp.scheduledate + ' ' + stime : stime) + '</td><td id="ldtvisit_report_id_' + i + '">' + emp.serviceprovidername + '</td><td id="ldtwork_order_no_' + i + '" data-id1=' + emp.is_lab + '>' + emp.work_order_no + '</td></tr>';

                        }
                        else if (emp.is_lab == 1) {
                            if (emp.btnflag == 'Schedule' || emp.btnflag == 'Assign') {
                                tr = tr + '<tr id="t_' + emp.work_order_id + '"><td class="disp_if"><i class="fa fa-close mr-10" data-toggle="tooltip" title="Click to Reject!" cursor: pointer; style="font-size:24px;color:red" onclick=rejection("' + emp.work_order_details_id + '","' + emp.work_order_id + '","' + emp.patientid + '",' + emp.is_lab + ',' + emp.master_service_id + ',"' + emp.visit_report_id + '",' + emp.serviceproviderid + ',"' + emp.wid + '",2)></i><button style="cursor:pointer;font-size:8px;" data-toggle="modal" data-target="#' + popupflag + '" class="btn btn-primaryuse btn-xs" onclick=lhorderschedule("' + emp.work_order_details_id + '","' + i + '","' + emp.work_order_id + '","' + emp.patientid + '","' + emp.btnflag + '",1,"phmc",' + emp.is_lab + ',' + emp.master_service_id + ',"' + emp.visit_report_id + '","' + emp.branch_id + '",2,"pkhmccollectsamplestable","' + emp.work_order_status + '","' + emp.wid + '")>' + emp.btnflag + '</button></td><td class="tbl-name" id="ldtpatient_id_' + i + '">' + '<a data-toggle="modal" style="cursor: pointer;" data-target="#myModalPatientSearchDetails" onclick=\'billing_details(\"' + emp.patient_id + '\",\"' + emp.patient_username + '\",\"' + emp.phone_number_1 + '\",this)\'>' + emp.patient_username + " " + status_color + '</a>' + '<Span class="tbl_pno"><br>' + emp.patient_id + '</span></td><td id="ldtphone_number_1_' + i + '">' + emp.phone_number_1 + '<Span class="tbl_pno"><br>' + emp.paddress + '</span></td><td>' + emp.visit_type_name + '</td><td class="details-control" ' + sflg + ' onclick=servicedetailspackage(this,"' + emp.work_order_id + '","pkghmccs",' + emp.package_auto_id + ',"' + emp.wid + '",1);>' + emp.service_count + '</span><Span class="tbl_wpkg"><br>' + (($.trim(emp.package_name) != '') ? emp.package_name + ' / ' + emp.package_id : emp.package_id) + '</span><i class="fa fa-angle-double-down table-arrow-size pull-right"></i></td><td>' + emp.package_purchased_date + '</td><td>' + emp.branch_name + '</td><td id="ldtvisit_report_id_' + i + '">' + (($.trim(emp.patientpreferdate) != '') ? emp.patientpreferdate + ' ' + ptime : ptime) + '</td><td id="ldtvisit_report_id_' + i + '">' + (($.trim(emp.scheduledate) != '') ? emp.scheduledate + ' ' + stime : stime) + '</td><td id="ldtvisit_report_id_' + i + '">' + emp.serviceprovidername + '</td><td id="ldtwork_order_no_' + i + '" data-id1=' + emp.is_lab + '>' + emp.work_order_no + '</td></tr>';

                            }
                            else {
                                // tr = tr + '<tr id="t_' + emp.work_order_id + '"><td id="ldtwork_order_no_' + i + '">' + emp.work_order_no + '</td><td id="ldtpackage_id_' + i + '">' + emp.package_id + '</td><td id="ldtpackage_name_' + i + '">' + emp.package_name + '</td><td id="ldtservice_name_' + i + '" data-id=' + emp.master_service_id + ' data1-id=' + emp.is_lab + '>' + emp.service_name + '</td><td></td><td id="ldtpatient_id_' + i + '">' + emp.patient_id + '</td><td id="ldtpatient_username_' + i + '">' + emp.patient_username + '</td><td id="ldtphone_number_1_' + i + '">' + emp.phone_number_1 + '</td><td id="ldtpaddress_' + i + '">' + emp.paddress + '</td><td></td><td></td><td id="ldttotal_amount_' + i + '">' + emp.total_amount + '</td><td class="details-control" ' + sflg + ' onclick=servicedetailspackage(this,"' + emp.request_id + '","pkghmcorders");>' + emp.service_count + '<i class="fa fa-angle-double-down table-arrow-size pull-right"></i></td><td><button style="cursor:pointer;" data-toggle="modal" data-target="#' + popupflag + '" class="btn btn-primaryuse btn-xs" onclick=labordersample("' + emp.request_id + '","' + i + '","' + emp.work_order_id + '","' + emp.patientid + '","' + emp.btnflag + '",1,"phmc")>' + emp.btnflag + '</button></tr>';

                                if (emp.btnflag == 'Schedule' || emp.btnflag == 'Assign') {
                                    tr = tr + '<tr id="t_' + emp.work_order_id + '"><td class="disp_if"><i class="fa fa-close mr-10" data-toggle="tooltip" title="Click to Reject!" cursor: pointer;  style="font-size:24px;color:red" onclick=rejection("' + emp.work_order_details_id + '","' + emp.work_order_id + '","' + emp.patientid + '",' + emp.is_lab + ',' + emp.master_service_id + ',"' + emp.visit_report_id + '",' + emp.serviceproviderid + ',"' + emp.wid + '",2)></i><button style="cursor:pointer;font-size:8px;" data-toggle="modal" data-target="#' + popupflag + '" class="btn btn-primaryuse btn-xs" onclick=lhorderschedule("' + emp.work_order_details_id + '","' + i + '","' + emp.work_order_id + '","' + emp.patientid + '","' + emp.btnflag + '",1,"phmc",' + emp.is_lab + ',' + emp.master_service_id + ',"' + emp.visit_report_id + '","' + emp.branch_id + '",2,"pkhmccollectsamplestable","' + emp.work_order_status + '","' + emp.wid + '")>' + emp.btnflag + '</button></td><td class="tbl-name" id="ldtpatient_id_' + i + '">' + '<a data-toggle="modal" style="cursor: pointer;" data-target="#myModalPatientSearchDetails" onclick=\'billing_details(\"' + emp.patient_id + '\",\"' + emp.patient_username + '\",\"' + emp.phone_number_1 + '\",this)\'>' + emp.patient_username + " " + status_color + '</a>' + '<Span class="tbl_pno"><br>' + emp.patient_id + '</span></td><td id="ldtphone_number_1_' + i + '">' + emp.phone_number_1 + '<Span class="tbl_pno"><br>' + emp.paddress + '</span></td><td>' + emp.visit_type_name + '</td><td class="details-control" ' + sflg + ' onclick=servicedetailspackage(this,"' + emp.work_order_id + '","pkghmccs",' + emp.package_auto_id + ',"' + emp.wid + '",1);>' + emp.service_count + '</span><Span class="tbl_wpkg"><br>' + (($.trim(emp.package_name) != '') ? emp.package_name + ' / ' + emp.package_id : emp.package_id) + '</span><i class="fa fa-angle-double-down table-arrow-size pull-right"></i></td><td>' + emp.package_purchased_date + '</td><td>' + emp.branch_name + '</td><td id="ldtvisit_report_id_' + i + '">' + (($.trim(emp.patientpreferdate) != '') ? emp.patientpreferdate + ' ' + ptime : ptime) + '</td><td id="ldtvisit_report_id_' + i + '">' + (($.trim(emp.scheduledate) != '') ? emp.scheduledate + ' ' + stime : stime) + '</td><td id="ldtvisit_report_id_' + i + '">' + emp.serviceprovidername + '</td><td id="ldtwork_order_no_' + i + '" data-id1=' + emp.is_lab + '>' + emp.work_order_no + '</td></tr>';

                                }
                                else {
                                    tr = tr + '<tr id="t_' + emp.work_order_id + '"><td class="disp_if"><i class="fa fa-close mr-10" data-toggle="tooltip" title="Click to Reject!" cursor: pointer; style="font-size:24px;color:red" onclick=rejection("' + emp.work_order_details_id + '","' + emp.work_order_id + '","' + emp.patientid + '",' + emp.is_lab + ',' + emp.master_service_id + ',"' + emp.visit_report_id + '",' + emp.serviceproviderid + ',"' + emp.wid + '",2)></i><button style="cursor:pointer;font-size:8px;" data-toggle="modal" data-target="#ldcollect_samplepopup" class="btn btn-primaryuse btn-xs" onclick=labordersample("' + emp.work_order_details_id + '","' + i + '","' + emp.work_order_id + '","' + emp.patientid + '","phmc",3,"' + emp.package_auto_id + '",' + emp.work_order_status + ',' + emp.serviceproviderid + ',"' + emp.patient_id + '","' + emp.visit_report_id + '","' + emp.branch_id + '","' + emp.hospitalid + '","' + emp.wid + '")>' + emp.btnflag + '</button></td><td class="tbl-name" id="ldtpatient_id_' + i + '">' + '<a data-toggle="modal" style="cursor: pointer;" data-target="#myModalPatientSearchDetails" onclick=\'billing_details(\"' + emp.patient_id + '\",\"' + emp.patient_username + '\",\"' + emp.phone_number_1 + '\",this)\'>' + emp.patient_username + " " + status_color + '</a>' + '<Span class="tbl_pno"><br>' + emp.patient_id + '</span></td><td id="ldtphone_number_1_' + i + '">' + emp.phone_number_1 + '<Span class="tbl_pno"><br>' + emp.paddress + '</span></td><td>' + emp.visit_type_name + '</td><td class="details-control" ' + sflg + ' onclick=servicedetailspackage(this,"' + emp.work_order_id + '","pkghmccs",' + emp.package_auto_id + ',"' + emp.wid + '",1);>' + emp.service_count + '</span><Span class="tbl_wpkg"><br>' + (($.trim(emp.package_name) != '') ? emp.package_name + ' / ' + emp.package_id : emp.package_id) + '</span><i class="fa fa-angle-double-down table-arrow-size pull-right"></i></td><td>' + emp.package_purchased_date + '</td><td>' + emp.branch_name + '</td><td id="ldtvisit_report_id_' + i + '">' + (($.trim(emp.patientpreferdate) != '') ? emp.patientpreferdate + ' ' + ptime : ptime) + '</td><td id="ldtvisit_report_id_' + i + '">' + (($.trim(emp.scheduledate) != '') ? emp.scheduledate + ' ' + stime : stime) + '</td><td id="ldtvisit_report_id_' + i + '">' + emp.serviceprovidername + '</td><td id="ldtwork_order_no_' + i + '" data-id=' + emp.labhometranid + '>' + emp.work_order_no + '</td></tr>';

                                }
                            }
                        }


                    });

                    $('#pkhmccollectsamplestablebody').html(tr);
                    //$('#pkhmccollectsamplestable').DataTable();
                    datatable('pkhmccollectsamplestable');


                }
            }
        }
    });
}

//# end package home care collectsamples

function rejection(work_order_details_id, work_order_id, patientid, is_lab, master_service_id, visit_report_id, serviceproviderid, wid, tabflag) {

    msg = "Are You Sure Do You Want Reject";
    toastr.warning("<button type='button' id='confirmationRevertYes' class='btn btn-warning btn-xs mt20'>Yes<button type='button' id='confirmationRevertNo' class='btn btn-warning btn-xs mt20'>No", msg,
        {
            closeButton: true,
            progressBar: true,
            allowHtml: true,
            timeOut: 20000000,

            onShown: function (toast) {
                $("#confirmationRevertYes").click(function () {
                    debugger;
                    var servicevalues = {
                        Dml_Indicator: "SREJ",
                        samplbarcodeid: wid,
                        work_order_details_id: work_order_details_id,
                        work_orderid: work_order_id,
                        serviceproviderid: serviceproviderid,
                        is_lab: is_lab,
                        spname: "SP_Work_Order_Action",
                        flag: tabflag
                    }
                    $.ajax({
                        async: true,
                        type: 'POST',
                        url: '/Workorder/Get_Workorder',
                        contentType: 'application/json; charset=UTF-8',
                        data: JSON.stringify(servicevalues),
                        success: function (data) {
                            debugger;
                            var data = JSON.parse(data);
                            if (data.msg == "Success") {
                                toastr.success("Rejected Successfully");
                            }
                        }
                    })
                });
            }
        });
}



$('#spackagehomeorders').click(function () {
    loadpackagehomeorders(1);

    $('.asidefilterclass').addClass('hidden');
    $('#asidepkhmcordertable').removeClass('hidden');
    $('.groupclass').addClass('hidden');
    $('#asidepkhmcordertablegroupclass').removeClass('hidden');
    $('.Filterclass').addClass('hidden');
    $('#asidepkhmcordertableFilterclass').removeClass('hidden');
})
$('#phmorderbtnreportfilter').click(function () {
    loadpackagehomeorders(2);
})
$('#phmorderbtnreportclear').click(function () {
    var hospitalid = $('#HospitalId').val();
    $('#phmallorderno').val('');
    $('#phmoschedulestatus').val('');
    $('#phmallorderdate').val('');
    $('#phmallordertodate').val('');
    Branchdetails(hospitalid);
    loadpackagehomeorders(1);
})
function loadpackagehomeorders(flag) {

    debugger;
    var servicevalues = {
        Dml_Indicator: "LPKHCO",
        flag: flag,
        orderdate: $('#phmallorderdate').val(),
        ordertodate: $('#phmallordertodate').val(),
        orderno: $('#phmallorderno').val(),
        jobsflag: $('#phmoschedulestatus').val(),
        serviceproviderid: $('#phmallorderserviceprovidername').val(),
        branchid: $('#pkghmallordersbranch_id').val(),
        departmentid: ($('#Hdepartment_id').val() == '') ? '' : $('#Hdepartment_id').val(),
        UserId: useridheder,
        spname: "SP_Work_Order_Home_order",
    }
    $.ajax({
        async: true,
        type: 'POST',
        url: '/Workorder/Get_Workorder',
        contentType: 'application/json; charset=UTF-8',
        data: JSON.stringify(servicevalues),
        success: function (data) {
            debugger;

            var data = JSON.parse(data);
            console.log(data);
            if (data.msg == "Success") {
                var data1 = data.data;
                if (jQuery.isEmptyObject((data1))) {
                    tr = '';
                    $('#pkhmcordertablebody').html(tr);
                }
                else {

                    var b = data1.Table;
                    $('#pkhmcordertablebody').empty();
                    $('#pkhmcordertable').dataTable().fnClearTable();
                    // $('#pkhmcordertable').dataTable().fnDraw();
                    $('#pkhmcordertable').dataTable().fnDestroy();
                    tr = '';
                    var popupflagid, popupflag, onclickflag, sflg = '';

                    $.each(b, function (i, emp) {
                        popupflag = emp.btnflag;
                        if (emp.scheduletime == '00:01') {
                            stime = '';
                        }
                        else {
                            stime = emp.scheduletime;
                        }
                        if (emp.patientprefertime == '00:01') {
                            ptime = '';
                        }
                        else {
                            ptime = emp.patientprefertime;
                        }

                        if (emp.is_lab == 2) {

                            tr = tr + '<tr id="t_' + emp.work_order_id + '"><td>' + emp.btnflag + '</td><td class="tbl-name" id="ldtpatient_id_' + i + '">' + '<a data-toggle="modal" style="cursor: pointer;" data-target="#myModalPatientSearchDetails" onclick=\'billing_details(\"' + emp.patient_id + '\",\"' + emp.patient_username + '\",\"' + emp.phone_number_1 + '\",this)\'>' + emp.patient_username + '</a>' + '<Span class="tbl_pno"><br>' + emp.patient_id + '</span></td><td id="ldtphone_number_1_' + i + '">' + emp.phone_number_1 + '<Span class="tbl_pno"><br>' + emp.paddress + '</span></td><td>' + emp.visit_type_name + '</td><td id="ldtservice_name_' + i + '" value=' + emp.master_service_id + ' data-id=' + emp.master_service_id + ' data1-id=' + emp.is_lab + '>' + '<span class="tbl-name">' + emp.service_name + '</span><Span class="tbl_wpkg"><br>' + (($.trim(emp.package_name) != '') ? emp.package_name + ' / ' + emp.package_id : emp.package_id) + '</span></td><td>' + emp.package_purchased_date + '</td><td>' + emp.branch_name + '</td><td id="ldtvisit_report_id_' + i + '">' + (($.trim(emp.patientpreferdate) != '') ? emp.patientpreferdate + ' ' + ptime : ptime) + '</td><td id="ldtvisit_report_id_' + i + '">' + (($.trim(emp.scheduledate) != '') ? emp.scheduledate + ' ' + stime : stime) + '</td><td id="ldtvisit_report_id_' + i + '">' + emp.serviceprovidername + '</td><td id="ldtwork_order_no_' + i + '" data-id1=' + emp.is_lab + '>' + emp.work_order_no + '</td></tr>';

                        }
                        else if (emp.is_lab == 1) {
                            tr = tr + '<tr id="t_' + emp.work_order_id + '"><td>' + emp.btnflag + '</td><td class="tbl-name" id="ldtpatient_id_' + i + '">' + '<a data-toggle="modal" style="cursor: pointer;" data-target="#myModalPatientSearchDetails" onclick=\'billing_details(\"' + emp.patient_id + '\",\"' + emp.patient_username + '\",\"' + emp.phone_number_1 + '\",this)\'>' + emp.patient_username + '</a>' + '<Span class="tbl_pno"><br>' + emp.patient_id + '</span></td><td id="ldtphone_number_1_' + i + '">' + emp.phone_number_1 + '<Span class="tbl_pno"><br>' + emp.paddress + '</span></td><td>' + emp.visit_type_name + '</td><td id="ldtservice_name_' + i + '" value=' + emp.master_service_id + '  data-id=' + emp.master_service_id + ' data1-id=' + emp.is_lab + ' >' + '<span class="tbl-name">' + emp.service_name + '</span><Span class="tbl_wpkg"><br>' + (($.trim(emp.package_name) != '') ? emp.package_name + ' / ' + emp.package_id : emp.package_id) + '</span></td><td>' + emp.package_purchased_date + '</td><td>' + emp.branch_name + '</td><td id="ldtvisit_report_id_' + i + '">' + (($.trim(emp.patientpreferdate) != '') ? emp.patientpreferdate + ' ' + ptime : ptime) + '</td><td id="ldtvisit_report_id_' + i + '">' + (($.trim(emp.scheduledate) != '') ? emp.scheduledate + ' ' + stime : stime) + '</td><td id="ldtvisit_report_id_' + i + '">' + emp.serviceprovidername + '</td><td id="ldtwork_order_no_' + i + '" data-id=' + emp.labhometranid + '>' + emp.work_order_no + '</td></tr>';

                        }

                    });

                    $('#pkhmcordertablebody').html(tr);
                    datatable('pkhmcordertable');

                }
            }
        }
    });
}




// service provider assign edit
function pkgjobsdetails(work_orderid, master_service_id, flag, flag1, work_order_details_id, patient_id, branchid, visit_report_id) {
    debugger;
    // getserviceprovider(work_orderid);
    $('#nonlabresultconclusiondiv').show();
    $('#ldlabassignserviceprovider').hide();
    $('#sproviderother').show();
    $('#work_order_details_id').val(work_order_details_id);
    $('#work_order_id').val(work_orderid);
    //loadserviceprovider(work_orderid, master_service_id,2,2);
    PatientSearch(patient_id, 0, branchid, visit_report_id)
    var servicevalues = {
        work_orderid: work_orderid,
        master_service_id: master_service_id,
        work_order_details_id: work_order_details_id,
        Dml_Indicator: "LSP",
        spname: "SP_Work_Order_Action",
    }
    $.ajax({
        async: true,
        type: 'POST',
        url: '/Workorder/Get_Workorder',
        contentType: 'application/json; charset=UTF-8',
        data: JSON.stringify(servicevalues),
        success: function (data) {
            debugger;
            var data = JSON.parse(data);
            console.log(data);
            if (data.msg == "Success") {
                var data1 = data.data;
                var tr = '', j = 1;
                if (jQuery.isEmptyObject((data1))) {
                }
                else {
                    debugger;
                    if (flag1 == 'E') {

                        $('#lhscheddate').val(data1.Table[0].scheduledate);
                        $('#labhometranid').val(data1.Table[0].labhometranid);
                        $('#lhschdFTime').val(data1.Table[0].scheduletime);
                        $('#nonlabresultconclusion').val(data1.Table[0].conclusion);
                        $('#nonlabresultconclusion').removeClass('disabled');
                        $('#serviceprovider').html(data1.Table[0].first_name);
                        $('#serviceprovider').empty();
                        $('#serviceprovider').addClass('disabled');
                        var cdepartment = '<option value="' + data1.Table[0].serviceproviderid + '" data-id="' + data1.Table[0].first_name + '">' + data1.Table[0].first_name + '</option>';
                        $('#serviceprovider').append(cdepartment);
                        $('#serviceprovider').val(data1.Table[0].serviceproviderid);
                        $('#serviceeditflag').val(1);
                        $('#lhscheddate').removeClass('disabled');
                        $('#lhschdFTime').removeClass('disabled');
                        $('#serviceprovider').addClass('disabled');
                        $('#stabflag').val(flag);
                        $('#lhassignsericeprovider').show();
                        $('#headercompleted').html('Completed');


                    }
                    else if (flag1 == 'D') {
                        $('#lhscheddate').val(data1.Table[0].scheduledate);
                        $('#labhometranid').val(data1.Table[0].labhometranid);
                        $('#lhschdFTime').val(data1.Table[0].scheduletime);
                        $('#nonlabresultconclusion').val(data1.Table[0].conclusion);
                        $('#nonlabresultconclusion').val(data1.Table[0].conclusion);
                        $('#nonlabresultconclusion').addClass('disabled');
                        $('#serviceprovider').empty();
                        $('#serviceprovider').addClass('disabled');
                        var cdepartment = '<option value="' + data1.Table[0].serviceproviderid + '" data-id="' + data1.Table[0].first_name + '">' + data1.Table[0].first_name + '</option>';
                        $('#serviceprovider').append(cdepartment);
                        $('#serviceprovider').val(data1.Table[0].serviceproviderid);
                        $('#lhscheddate').addClass('disabled');
                        $('#lhschdFTime').addClass('disabled');
                        $('#serviceprovider').addClass('disabled');
                        $('#lhassignsericeprovider').hide();
                        $('#headercompleted').html('Completed');
                    }
                    else if (flag1 == 'C') {
                        $('#stabflag').val(flag);
                        $('#lhscheddate').val(data1.Table[0].scheduledate);
                        $('#labhometranid').val(data1.Table[0].labhometranid);
                        $('#lhschdFTime').val(data1.Table[0].scheduletime);
                        $('#serviceeditflag').val(3);
                        $('#nonlabresultconclusion').val(data1.Table[0].conclusion);
                        $('#nonlabresultconclusion').removeClass('disabled');
                        $('#serviceprovider').empty();
                        $('#serviceprovider').addClass('disabled');
                        var cdepartment = '<option value="' + data1.Table[0].serviceproviderid + '" data-id="' + data1.Table[0].first_name + '">' + data1.Table[0].first_name + '</option>';
                        $('#serviceprovider').append(cdepartment);
                        $('#serviceprovider').val(data1.Table[0].serviceproviderid);
                        $('#lhscheddate').addClass('disabled');
                        $('#lhschdFTime').addClass('disabled');
                        $('#serviceprovider').addClass('disabled');
                        $('#lhassignsericeprovider').show();
                        $('#headercompleted').html('Completed');
                    }
                }

            }
        }
    })

}






//load package home care jobs
$('#spackagehomejobs').click(function () {
    loadpackagehomejobs(1, "LPKHCJ", 2, 'pkhmcjobtable', 'jo');
    $('.asidefilterclass').addClass('hidden');
    $('#asidepkhmcjobtable').removeClass('hidden');
    $('.groupclass').addClass('hidden');
    $('#asidepkhmcjobtablegroupclass').removeClass('hidden');
    $('.Filterclass').addClass('hidden');
    $('#asidepkhmcjobtableFilterclass').removeClass('hidden');
})


//load package home care receive sample
$('#spackagehomereceivesample').click(function () {
    loadpackagehomejobs(1, 'LPKHCRS', 1, 'pkhmcreceivesampletable', 'rs');
    $('.asidefilterclass').addClass('hidden');
    $('#asidepkhmcreceivesampletable').removeClass('hidden');
    $('.groupclass').addClass('hidden');
    $('#asidepkhmcreceivesampletablegroupclass').removeClass('hidden');
    $('.Filterclass').addClass('hidden');
    $('#asidepkhmcreceivesampletableFilterclass').removeClass('hidden');
})

//load package home care Pending Approval
$('#spackagehomependingapproval').click(function () {
    loadpackagehomejobs(1, 'LPKHCPR', 3, 'pkhmcpendingapprovaltable', 'pr');
    $('.asidefilterclass').addClass('hidden');
    $('#asidepkhmcpendingapprovaltable').removeClass('hidden');
    $('.groupclass').addClass('hidden');
    $('#asidepkhmcpendingapprovaltablegroupclass').removeClass('hidden');
    $('.Filterclass').addClass('hidden');
    $('#asidepkhmcpendingapprovaltableFilterclass').removeClass('hidden');
})
$('#phmjobbtnreportfilter').click(function () {
    loadpackagehomejobs(2, "LPKHCJ", 2, 'pkhmcjobtable', 'jo');
})
$('#phmprbtnreportfilter').click(function () {
    loadpackagehomejobs(2, 'LPKHCPR', 3, 'pkhmcpendingapprovaltable', 'pr');
})
$('#phmrsbtnreportfilter').click(function () {
    loadpackagehomejobs(2, 'LPKHCRS', 1, 'pkhmcreceivesampletable', 'rs');
})
$('#phmjobbtnreportclear').click(function () {
    var hospitalid = $('#HospitalId').val();
    $('#phmjorderno').val('');
    $('#phmjsampleid').val('');
    $('#phmjschedulestatus').val('');
    $('#phmjorderdate').val('');
    $('#phmjordertodate').val('');
    Branchdetails(hospitalid);
    getserviceprovider(0);
    loadpackagehomejobs(1, "LPKHCJ", 2, 'pkhmcjobtable', 'jo');
})
$('#phmrsbbtnreportclear').click(function () {
    var hospitalid = $('#HospitalId').val();
    $('#phmrsorderno').val('');
    $('#phmrssampleid').val('');
    $('#phmrsschedulestatus').val('');
    $('#phmrsorderdate').val('');
    $('#phmrsordertodate').val('');
    Branchdetails(hospitalid);
    getserviceprovider(0);
    loadpackagehomejobs(1, 'LPKHCRS', 1, 'pkhmcreceivesampletable', 'rs');
})
$('#phmprbtnreportclear').click(function () {
    var hospitalid = $('#HospitalId').val();
    $('#phmprorderno').val('');
    $('#phmprsampleid').val('');
    $('#phmprschedulestatus').val('');
    $('#phmprorderdate').val('');
    $('#phmprordertodate').val('');
    Branchdetails(hospitalid);
    getserviceprovider(0);
    loadpackagehomejobs(1, 'LPKHCPR', 3, 'pkhmcpendingapprovaltable', 'pr');
})
function loadpackagehomejobs(flag, indicator, wstatus, tblname, filtername) {
    if (indicator == 'LPKHCRS') {
        spname = "SP_Work_Order_Home_RS"
    }
    else if (indicator == 'LPKHCJ') {
        spname = "SP_Work_Order_Home_JOBS"
    }
    else if (indicator == 'LPKHCPR') {
        spname = "SP_Work_Order_Home_PR"
    }
    debugger;
    var servicevalues = {
        Dml_Indicator: indicator,
        flag: flag,
        samplbarcodeid: $('#phm' + filtername + 'sampleid').val(),
        orderdate: $('#phm' + filtername + 'orderdate').val(),
        ordertodate: $('#phm' + filtername + 'ordertodate').val(),
        orderno: $('#phm' + filtername + 'orderno').val(),
        jobsflag: $('#phm' + filtername + 'schedulestatus').val(),
        branchid: $('#pkghm' + filtername + 'branch_id').val(),
        serviceproviderid: $('#pkghm' + filtername + 'serviceprovidername').val(),
        work_order_status: wstatus,
        departmentid: ($('#Hdepartment_id').val() == '') ? '' : $('#Hdepartment_id').val(),
        UserId: useridheder,
        spname: spname,
    }
    $.ajax({
        async: true,
        type: 'POST',
        url: '/Workorder/Get_Workorder',
        contentType: 'application/json; charset=UTF-8',
        data: JSON.stringify(servicevalues),
        success: function (data) {
            debugger;

            var data = JSON.parse(data);
            console.log(data);
            if (data.msg == "Success") {
                var data1 = data.data;
                if (jQuery.isEmptyObject((data1.Table))) {
                    tr = '';
                    $('#' + tblname + 'body').html(tr);
                }
                else {

                    var b = data1.Table;
                    $('#' + tblname + 'body').empty();
                    $('#' + tblname + '').dataTable().fnClearTable();
                    $('#' + tblname + '').dataTable().fnDraw();
                    $('#' + tblname + '').dataTable().fnDestroy();
                    tr = '';
                    var popupflagid, popupflag, onclickflag, sflg = '', status_color = '';

                    $.each(b, function (i, emp) {
                        popupflag = emp.btnflag;
                        if (emp.scheduletime == '00:01') {
                            stime = '';
                        }
                        else {
                            stime = emp.scheduletime;
                        }

                        if (emp.Bill_status == "Paid") {
                            status_color = "<span style='background-color: green !important;color:white;font-size:10px;padding:3px;border-radius:4px;'>paid</span>";
                        }
                        else if (emp.Bill_status == "Due") {
                            status_color = "<span style='background-color: red !important;color:white;font-size:10px;padding:3px;border-radius:4px;'>Due</span>";
                        }
                        else if (emp.Bill_status == "Partial Due") {
                            status_color = "<span style='background-color: orange !important;color:white;font-size:10px;padding:3px;border-radius:4px;'>Partial paid</span>";
                        }
                        else {
                            status_color = '';
                        }


                        if (emp.is_lab == 2) {

                            tr = tr + '<tr id="t_' + emp.work_order_id + '"><td><div class="col-md-12 padding0"><div class="disp_if"><button style="cursor:pointer;" data-toggle="modal" data-target="#Assign" class="btn-primaryuse btn-xs" onclick=pkgjobsdetails("' + emp.work_order_id + '","' + emp.master_service_id + '","phmsc","C",' + emp.work_order_details_id + ',"' + emp.patient_id + '",' + emp.branch_id + ',"' + emp.visit_report_id + '")>Completed</button><a href="#" class="dropdown-toggle btn btn-info-dots btn-xs" data-toggle="dropdown" aria-expanded="true"><span class="fa fa-ellipsis-h" data-toggle="tooltip" data-placement="bottom" title="Other Options" style="color:black;" aria-hidden="true"></span><span class="sr-only">Options</span></a><div class="dropdown-menu info-dropdown-workorder" id=""><p style="text-align-last:start"; ><button style="cursor:pointer;" data-toggle="modal" data-target="#Assign" class="btn-primaryuse btn-xs" onclick=pkgjobsdetails("' + emp.work_order_id + '","' + emp.master_service_id + '","phmc","E",' + emp.work_order_details_id + ',"' + emp.patient_id + '",' + emp.branch_id + ',"' + emp.visit_report_id + '")>Edit</button> </p><p style="text-align-last:start"; > <button style="cursor:pointer;" data-toggle="modal" data-target="#Assign" class="btn-primaryuse btn-xs" onclick=pkgjobsdetails("' + emp.work_order_id + '","' + emp.master_service_id + '","phmc","D",' + emp.work_order_details_id + ',"' + emp.patient_id + '",' + emp.branch_id + ',"' + emp.visit_report_id + '")>Details</button></p><p class="btn btn-xs btn-delete" style="text-align-last:start"; data-toggle="tooltip" title="Click to Reject!" cursor: pointer; onclick=rejection("' + emp.work_order_details_id + '","' + emp.work_order_id + '","' + emp.patientid + '",' + emp.is_lab + ',' + emp.master_service_id + ',"' + emp.visit_report_id + '",' + emp.serviceproviderid + ',"' + emp.wid + '",2)><i class="fa fa-ban"></i></p></div></div></td><td id="ldsamplbarcodeid_' + i + '">' + emp.samplbarcodeid + '</td><td class="tbl-name" id="ldtpatient_id_' + i + '">' + '<a data-toggle="modal" style="cursor: pointer;" data-target="#myModalPatientSearchDetails" onclick=\'billing_details(\"' + emp.patient_id + '\",\"' + emp.patient_username + '\",\"' + emp.phone_number_1 + '\",this)\'>' + emp.patient_username + " " + status_color + '</a>' + '<Span class="tbl_pno"><br>' + emp.patient_id + '</span></td><td id="ldtphone_number_1_' + i + '">' + emp.phone_number_1 + '<Span class="tbl_pno"><br>' + emp.paddress + '</span></td><td>' + emp.visit_type_name + '</td><td id="ldtservice_name_' + i + '" data-id=' + emp.master_service_id + ' data1-id=' + emp.is_lab + '>' + '<span class="tbl-name">' + emp.service_name + '</span><Span class="tbl_wpkg"><br>' + (($.trim(emp.package_name) != '') ? emp.package_name + ' / ' + emp.package_id : emp.package_id) + '</span></td><td>' + emp.package_purchased_date + '</td><td>' + emp.branch_name + '</td><td id="ldtvisit_report_id_' + i + '">' + (($.trim(emp.scheduledate) != '') ? emp.scheduledate + ' ' + stime : stime) + '</td><td id="ldtvisit_report_id_' + i + '">' + emp.serviceprovidername + '</td><td id="ldtwork_order_no_' + i + '">' + emp.work_order_no + '</td></tr>';

                        }
                        else if (emp.is_lab == 1) {
                            if (emp.btnflag == 'Receive Sample') {
                                tr = tr + '<tr id="t_' + emp.work_order_id + '"><td><div class="col-md-12 padding0"><div class="disp_if"><button style="cursor:pointer;font-size:7px;" data-toggle="modal" data-target="#ldrecivie_samplepopup" class="btn btn-primaryuse btn-xs" onclick=ldlabrecivesample("' + emp.request_id + '","' + emp.work_order_id + '","' + emp.sampleid + '","' + emp.master_service_id + '","' + emp.statusflag + '","phmc","2",3,"' + emp.samplbarcodeid + '","' + emp.hospitalid + '","' + emp.branch_id + '","' + emp.patientid + '","' + emp.patient_id + '","' + emp.visit_report_id + '")>' + emp.btnflag + '</button><a href="#" class="dropdown-toggle btn btn-info-dots btn-xs" data-toggle="dropdown" aria-expanded="true"><span class="fa fa-ellipsis-h" data-toggle="tooltip" data-placement="bottom" title="Other Options" style="color:black;" aria-hidden="true"></span><span class="sr-only">Options</span></a><div class="dropdown-menu info-dropdown-workorder" id=""><a style="text-align-last:start";"cursor:pointer;" class="btn btn-xs" data-toggle="modal" data-target="#previous_results_modal"  onclick=Patient_PreviousResult(' + emp.patientid + ')><i class="fa fa-eye mr-10"></i> Previous Results </a></div></div></td><td id="ldsamplbarcodeid_' + i + '">' + emp.samplbarcodeid + '</td><td class="tbl-name" id="ldtpatient_id_' + i + '">' + '<a data-toggle="modal" style="cursor: pointer;" data-target="#myModalPatientSearchDetails" onclick=\'billing_details(\"' + emp.patient_id + '\",\"' + emp.patient_username + '\",\"' + emp.phone_number_1 + '\",this)\'>' + emp.patient_username + " " + status_color + '</a>' + '<Span class="tbl_pno"><br>' + emp.patient_id + '</span></td><td id="ldtphone_number_1_' + i + '">' + emp.phone_number_1 + '<Span class="tbl_pno"><br>' + emp.paddress + '</span></td><td>' + emp.visit_type_name + '</td><td class="details-control" ' + sflg + ' onclick=servicedetailspackage(this,"' + emp.work_order_id + '","' + tblname + '","' + emp.package_auto_id + '","' + emp.wid + '",2);>' + emp.service_count + '</span><Span class="tbl_wpkg"><br>' + (($.trim(emp.package_name) != '') ? emp.package_name + ' / ' + emp.package_id : emp.package_id) + '</span><i class="fa fa-angle-double-down table-arrow-size pull-right"></i></td><td>' + emp.package_purchased_date + '</td><td>' + emp.branch_name + '</td><td id="ldtvisit_report_id_' + i + '">' + (($.trim(emp.scheduledate) != '') ? emp.scheduledate + ' ' + stime : stime) + '</td><td id="ldtvisit_report_id_' + i + '">' + emp.serviceprovidername + '</td><td id="ldtwork_order_no_' + i + '" data-id1=' + emp.is_lab + '>' + emp.work_order_no + '</td></tr>';

                            }
                            else {
                                tr = tr + '<tr id="t_' + emp.work_order_id + '"><td><div class="col-md-12 padding0"><div class="disp_if"><button style="cursor:pointer;font-size:8px;" data-toggle="modal" data-target="#result_popup" class="btn btn-primaryuse btn-xs" onclick=ldlabresult("' + emp.request_id + '","' + emp.work_order_id + '","' + emp.sampleid + '","' + emp.master_service_id + '","' + emp.statusflag + '","phmc","2",3,"' + emp.samplbarcodeid + '","' + emp.hospitalid + '","' + emp.branch_id + '","' + emp.patientid + '","' + emp.patient_id + '","' + emp.visit_report_id + '")>' + emp.btnflag + '</button><a href="#" class="dropdown-toggle btn btn-info-dots btn-xs" data-toggle="dropdown" aria-expanded="true"><span class="fa fa-ellipsis-h" data-toggle="tooltip" data-placement="bottom" title="Other Options" style="color:black;" aria-hidden="true"></span><span class="sr-only">Options</span></a><div class="dropdown-menu info-dropdown-workorder" id=""><a style="text-align-last:start";"cursor:pointer;" class="btn btn-xs" data-toggle="modal" data-target="#previous_results_modal" onclick=Patient_PreviousResult(' + emp.patientid + ')><i class="fa fa-eye mr-10"></i> Previous Results </a></div></div></td><td id="ldsamplbarcodeid_' + i + '">' + emp.samplbarcodeid + '</td><td class="tbl-name" id="ldtpatient_id_' + i + '">' + '<a data-toggle="modal" style="cursor: pointer;" data-target="#myModalPatientSearchDetails" onclick=\'billing_details(\"' + emp.patient_id + '\",\"' + emp.patient_username + '\",\"' + emp.phone_number_1 + '\",this)\'>' + emp.patient_username + " " + status_color + '</a>' + '<Span class="tbl_pno"><br>' + emp.patient_id + '</span></td><td id="ldtphone_number_1_' + i + '">' + emp.phone_number_1 + '<Span class="tbl_pno"><br>' + emp.paddress + '</span></td><td>' + emp.visit_type_name + '</td><td class="details-control" ' + sflg + ' onclick=servicedetailspackage(this,"' + emp.work_order_id + '","' + tblname + '","' + emp.package_auto_id + '","' + emp.wid + '",2);>' + emp.service_count + '</span><Span class="tbl_wpkg"><br>' + (($.trim(emp.package_name) != '') ? emp.package_name + ' / ' + emp.package_id : emp.package_id) + '</span><i class="fa fa-angle-double-down table-arrow-size pull-right"></i></td><td>' + emp.package_purchased_date + '</td><td>' + emp.branch_name + '</td><td id="ldtvisit_report_id_' + i + '">' + (($.trim(emp.scheduledate) != '') ? emp.scheduledate + ' ' + stime : stime) + '</td><td id="ldtvisit_report_id_' + i + '">' + emp.serviceprovidername + '</td><td id="ldtwork_order_no_' + i + '">' + emp.work_order_no + '</td></tr>';

                            }
                        }


                    });

                    $('#' + tblname + 'body').html(tr);
                    datatable(tblname);

                }
            }
        }
    });
}

//load package home care compeleted
$('#spackagehomecompleted').click(function () {
    loadpackagehomecompleted(1);
    $('.asidefilterclass').addClass('hidden');
    $('#asidepkhmccompletedtable').removeClass('hidden');
    $('.groupclass').addClass('hidden');
    $('#asidepkhmccompletedtablegroupclass').removeClass('hidden');
    $('.Filterclass').addClass('hidden');
    $('#asidepkhmccompletedtableFilterclass').removeClass('hidden');
})
$('#phmcmbtnreportfilter').click(function () {
    loadpackagehomecompleted(2);
})

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

    var hospitalid = $('#HospitalId').val();
    $('#phmcmorderno').val('');
    $('#phmcmsampleid').val('');
    $('#phmcmorderdate').val('');
    $('#phmcmordertodate').val('');
    Branchdetails(hospitalid);
    getserviceprovider(0);
    loadpackagehomecompleted(1);
})
function loadpackagehomecompleted(flag) {

    debugger;
    var servicevalues = {
        Dml_Indicator: "LPKHCCM",
        flag: flag,
        samplbarcodeid: $('#phmcmsampleid').val(),
        orderdate: $('#phmcmorderdate').val(),
        ordertodate: $('#phmcmordertodate').val(),
        orderno: $('#phmcmorderno').val(),
        serviceprovidername: $('#phmcmserviceprovidername').val(),
        branchid: $('#pkghmcbranch_id').val(),
        departmentid: ($('#Hdepartment_id').val() == '') ? '' : $('#Hdepartment_id').val(),
        UserId: useridheder,
        spname: "SP_Work_Order_Home_CM",
    }
    $.ajax({
        async: true,
        type: 'POST',
        url: '/Workorder/Get_Workorder',
        contentType: 'application/json; charset=UTF-8',
        data: JSON.stringify(servicevalues),
        success: function (data) {
            debugger;

            var data = JSON.parse(data);
            console.log(data);
            if (data.msg == "Success") {

                var data1 = data.data;
                if (jQuery.isEmptyObject((data1))) {
                    tr = '';
                    $('#pkhmccompletedablebody').html(tr);
                }
                else {

                    var b = data1.Table;
                    $('#pkhmccompletedtablebody').empty();
                    $('#pkhmccompletedtable').dataTable().fnClearTable();
                    // $('#pkhmccompletedtable').dataTable().fnDraw();
                    $('#pkhmccompletedtable').dataTable().fnDestroy();
                    tr = '';
                    var popupflagid, popupflag, onclickflag, sflg = '', comp_view = '', status_color = '';

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

                        var revert = '';
                        popupflag = emp.btnflag;
                        if (emp.scheduletime == '00:01') {
                            stime = '';
                        }
                        else {
                            stime = emp.scheduletime;
                        }

                        if (emp.Bill_status == "Paid") {
                            status_color = "<span style='background-color: green !important;color:white;font-size:10px;padding:3px;border-radius:4px;'>paid</span>";
                        }
                        else if (emp.Bill_status == "Due") {
                            status_color = "<span style='background-color: red !important;color:white;font-size:10px;padding:3px;border-radius:4px;'>Due</span>";
                        }
                        else if (emp.Bill_status == "Partial Due") {
                            status_color = "<span style='background-color: orange !important;color:white;font-size:10px;padding:3px;border-radius:4px;'>Partial paid</span>";
                        }
                        else {
                            status_color = '';
                        }


                        if (popupflag = 'View') {
                            comp_view = '<i class="fa fa-eye"></i>'
                        }
                        if (emp.is_lab == 2) {

                            tr = tr + '<tr id="t_' + emp.work_order_id + '"><td class="col-sm-1 disp_if"><button style="cursor:pointer;font-size:8px;" data-toggle="modal" data-target="#Assign" class="btn btn-eye btn-xs" title="View" onclick=pkgjobsdetails("' + emp.work_order_id + '","' + emp.master_service_id + '","phmc","D",' + emp.work_order_details_id + ',"' + emp.patient_id + '",' + emp.branch_id + ',"' + emp.visit_report_id + '")>' + comp_view + '</button></td><td id="ldsamplbarcodeid_' + i + '">' + emp.samplbarcodeid + '</td><td class="tbl-name" id="ldtpatient_id_' + i + '">' + '<a data-toggle="modal" style="cursor: pointer;" data-target="#myModalPatientSearchDetails" onclick=\'billing_details(\"' + emp.patient_id + '\",\"' + emp.patient_username + '\",\"' + emp.phone_number_1 + '\",this)\'>' + emp.patient_username + " " + status_color + '</a>' + '<Span class="tbl_pno"><br>' + emp.patient_id + '</span></td><td id="ldtphone_number_1_' + i + '">' + emp.phone_number_1 + '<Span class="tbl_pno"><br>' + emp.paddress + '</span></td><td>' + emp.visit_type_name + '</td><td id="ldtservice_name_' + i + '" data-id=' + emp.master_service_id + ' data1-id=' + emp.is_lab + '>' + '<span class="tbl-name">' + emp.service_name + '</span><Span class="tbl_wpkg"><br>' + (($.trim(emp.package_name) != '') ? emp.package_name + ' / ' + emp.package_id : emp.package_id) + '</span></td><td>' + emp.package_purchased_date + '</td><td>' + emp.branch_name + '</td><td id="ldtvisit_report_id_' + i + '">' + (($.trim(emp.scheduledate) != '') ? emp.scheduledate + ' ' + stime : stime) + '</td><td id="ldtvisit_report_id_' + i + '">' + emp.serviceprovidername + '</td><td id="ldtwork_order_no_' + i + '">' + emp.work_order_no + '</td></tr>';

                        }
                        else if (emp.is_lab == 1) {
                            revert = '<button style="cursor:pointer;" class="btn btn-eye btn-xs" title="Home Care Revert"  data-toggle="modal" data-target="#reject_reason_popup" onclick=WorkOrder_revert("' + emp.samplbarcodeid + '","phmc")><i class="fa fa-ban fa-sm" aria-hidden="true"></i></button>';
                            if (emp.btnflag == 'Schedule' || emp.btnflag == 'Assign') {
                                tr = tr + '<tr id="t_' + emp.work_order_id + '"><td class="disp_if"><button style="cursor:pointer;font-size:8px;" data-toggle="modal" data-target="#' + popupflag + '" class="btn btn-eye btn-xs" title="View" onclick=lhorderschedule("' + emp.work_order_details_id + '","' + i + '","' + emp.work_order_id + '","' + emp.patientid + '","' + emp.btnflag + '",1,"phmc",' + emp.is_lab + ',' + emp.master_service_id + ',"' + emp.visit_report_id + '","' + emp.branch_id + '",2,"pkhmccompletedtable","' + emp.work_order_status + '","' + emp.wid + '")>' + comp_view + " " + revert + '</button></td><td id="ldsamplbarcodeid_' + i + '">' + emp.samplbarcodeid + '</td><td class="tbl-name" id="ldtpatient_id_' + i + '">' + '<a data-toggle="modal" style="cursor: pointer;" data-target="#myModalPatientSearchDetails" onclick=\'billing_details(\"' + emp.patient_id + '\",\"' + emp.patient_username + '\",\"' + emp.phone_number_1 + '\",this)\'>' + emp.patient_username + " " + status_color + '</a>' + '<Span class="tbl_pno"><br>' + emp.patient_id + '</span></td><td id="ldtphone_number_1_' + i + '">' + emp.phone_number_1 + '<Span class="tbl_pno"><br>' + emp.paddress + '</span></td><td>' + emp.visit_type_name + '</td><td class="details-control" ' + sflg + ' onclick=servicedetailspackage(this,"' + emp.work_order_id + '","' + tblname + '","' + emp.package_auto_id + '","' + emp.wid + '",2);>' + emp.service_count + '</span><Span class="tbl_wpkg"><br>' + (($.trim(emp.package_name) != '') ? emp.package_name + ' / ' + emp.package_id : emp.package_id) + '</span><i class="fa fa-angle-double-down table-arrow-size pull-right"></i></td><td>' + emp.package_purchased_date + '</td><td>' + emp.branch_name + '</td><td id="ldtvisit_report_id_' + i + '">' + (($.trim(emp.scheduledate) != '') ? emp.scheduledate + ' ' + stime : stime) + '</td><td id="ldtvisit_report_id_' + i + '">' + emp.serviceprovidername + '</td><td id="ldtwork_order_no_' + i + '">' + emp.work_order_no + '</td></tr>';

                            }
                            else {
                                tr = tr + '<tr id="t_' + emp.work_order_id + '"><td class="disp_if"><button style="cursor:pointer;font-size:8px;" data-toggle="modal" data-target="#result_popup" class="btn btn-eye btn-xs" title="View" onclick=ldlabresult("' + emp.work_order_details_id + '","' + emp.work_order_id + '","' + emp.sampleid + '","' + emp.master_service_id + '","' + emp.btnflag + '","phmc","2",3,"' + emp.samplbarcodeid + '","' + emp.hospitalid + '","' + emp.branch_id + '","' + emp.patientid + '","' + emp.patient_id + '","' + emp.visit_report_id + '")>' + comp_view + " " + revert + '</button></td><td id="ldsamplbarcodeid_' + i + '">' + emp.samplbarcodeid + '</td><td class="tbl-name" id="ldtpatient_id_' + i + '">' + '<a data-toggle="modal" style="cursor: pointer;" data-target="#myModalPatientSearchDetails" onclick=\'billing_details(\"' + emp.patient_id + '\",\"' + emp.patient_username + '\",\"' + emp.phone_number_1 + '\",this)\'>' + emp.patient_username + " " + status_color + '</a>' + '<Span class="tbl_pno"><br>' + emp.patient_id + '</span></td><td id="ldtphone_number_1_' + i + '">' + emp.phone_number_1 + '<Span class="tbl_pno"><br>' + emp.paddress + '</span></td><td>' + emp.visit_type_name + '</td><td class="details-control" ' + sflg + ' onclick=servicedetailspackage(this,"' + emp.work_order_id + '","' + 'pkhmccompletedtable' + '","' + emp.package_auto_id + '","' + emp.wid + '",2);>' + emp.service_count + '</span><Span class="tbl_wpkg"><br>' + (($.trim(emp.package_name) != '') ? emp.package_name + ' / ' + emp.package_id : emp.package_id) + '</span><i class="fa fa-angle-double-down table-arrow-size pull-right"></i></td><td>' + emp.package_purchased_date + '</td><td>' + emp.branch_name + '</td><td id="ldtvisit_report_id_' + i + '">' + (($.trim(emp.scheduledate) != '') ? emp.scheduledate + ' ' + stime : stime) + '</td><td id="ldtvisit_report_id_' + i + '">' + emp.serviceprovidername + '</td><td id="ldtwork_order_no_' + i + '">' + emp.work_order_no + '</td></tr>';

                            }

                        }


                    });

                    $('#pkhmccompletedtablebody').html(tr);
                    var revertrights = data1.Table1;
                    if (revertrights[0].status == 0) {
                        $('.revert').addClass('hidden');
                    }
                    //$('#pkhmccompletedtable').DataTable();
                    datatable('pkhmccompletedtable');

                }
            }
        }
    });
}





//# Start package Home care turn around time
$('#spackagehometurnaroundtime').click(function () {
    loadpackagehometat(1, "LPKHCTAT", 2, 'pkhmcturnaroundtimetable', 'tat');
    $('.asidefilterclass').addClass('hidden');
    $('#asidepkhmcturnaroundtimetable').removeClass('hidden');
    $('.groupclass').addClass('hidden');
    $('#asidepkhmcturnaroundtimetablegroupclass').removeClass('hidden');
    $('.Filterclass').addClass('hidden');
    $('#asidepkhmcturnaroundtimetableFilterclass').removeClass('hidden');
});

$('#phmtatbtnreportfilter').click(function () {
    loadpackagehometat(2, "LPKHCTAT", 1, 'pkhmcturnaroundtimetable', 'tat');
})
$('#phmtatbtnreportclear').click(function () {
    var hospitalid = $('#HospitalId').val();
    $('#phmtatrderno').val('');
    $('#phmtatampleid').val('');
    $('#phmtatchedulestatus').val('');
    $('#phmtatrderdate').val('');
    $('#phmtatrdertodate').val('');
    Branchdetails(hospitalid);
    getserviceprovider(0);
    loadpackagehometat(1, "LPKHCTAT", 1, 'pkhmcturnaroundtimetable', 'tat');
})
function loadpackagehometat(flag, indicator, wstatus, tblname, filtername) {

    debugger;
    var servicevalues = {
        Dml_Indicator: indicator,
        flag: flag,
        samplbarcodeid: $('#phm' + filtername + 'sampleid').val(),
        orderdate: $('#phm' + filtername + 'orderdate').val(),
        ordertodate: $('#phm' + filtername + 'ordertodate').val(),
        orderno: $('#phm' + filtername + 'orderno').val(),
        jobsflag: $('#phm' + filtername + 'schedulestatus').val(),
        branchid: $('#pkghm' + filtername + 'branch_id').val(),
        // serviceprovidername: $('#phm' + filtername + 'serviceprovidername').val(),
        work_order_status: wstatus,
        departmentid: ($('#Hdepartment_id').val() == '') ? '' : $('#Hdepartment_id').val(),
        UserId: useridheder,
        spname: "SP_Work_Order_Home_TAT",
    }
    $.ajax({
        async: true,
        type: 'POST',
        url: '/Workorder/Get_Workorder',
        contentType: 'application/json; charset=UTF-8',
        data: JSON.stringify(servicevalues),
        success: function (data) {
            debugger;

            var data = JSON.parse(data);
            console.log(data);
            if (data.msg == "Success") {
                var data1 = data.data;
                if (jQuery.isEmptyObject((data1))) {
                    tr = '';
                    $('#' + tblname + 'body').html(tr);
                }
                else {

                    var b = data1.Table;
                    $('#' + tblname + 'body').empty();
                    $('#' + tblname + '').dataTable().fnClearTable();
                    $('#' + tblname + '').dataTable().fnDraw();
                    $('#' + tblname + '').dataTable().fnDestroy();
                    tr = '';
                    var popupflagid, popupflag, onclickflag, sflg = '', color = '';

                    $.each(b, function (i, emp) {
                        popupflag = emp.btnflag;
                        if (emp.color == "red") {
                            color = 'tabletxtcolorred';
                        }
                        else if (emp.color == "green") {
                            color = 'tabletxtcolorgreen'
                        }
                        if (emp.is_lab == 2) {

                            tr = tr + '<tr id="t_' + emp.work_order_id + '" class="' + color + '"><td id="ldtwork_order_no_' + i + '" class="' + color + '">' + emp.work_order_no + '</td><td class="' + color + '">' + emp.samplbarcodeid + '</td><td id="ldtpatient_id_' + i + '" class="' + color + '">' + emp.patient_id + '/' + '<a data-toggle="modal" style="cursor: pointer;" data-target="#myModalPatientSearchDetails" onclick=\'billing_details(\"' + emp.patient_id + '\",\"' + emp.patient_username + '\",\"' + emp.phone_number_1 + '\",this)\'>' + emp.patient_username + '</a>' + '</td><td id="ldtphone_number_1_' + i + '" class="' + color + '">' + emp.phone_number_1 + '-' + emp.paddress + '</td><td id="ldtservice_name_' + i + '" data-id=' + emp.master_service_id + ' data1-id=' + emp.is_lab + ' class="' + color + '">' + emp.service_name + '</td><td id="ldtpackage_id_' + i + '"  class="' + color + '">' + emp.package_id + '</td><td id="ldtpackage_name_' + i + '" class="' + color + '">' + emp.package_name + '</td><td class="' + color + '">' + emp.branch_name + '</td><td id="ldtvisit_report_id_' + i + '" class="' + color + '">' + emp.schdulewaittime + '</td><td id="ldtvisit_report_id_' + i + '" class="' + color + '">' + emp.Assignwaittime + '</td><td id="ldtvisit_report_id_' + i + '" class="' + color + '">' + emp.collectsamplewaittime + '</td><td id="ldtvisit_report_id_' + i + '" class="' + color + '">' + emp.receivedwaittime + '</td><td id="ldsamplbarcodeid_' + i + '" class="' + color + '">' + emp.Addresultwaittime + '</td><td class="' + color + '">' + emp.verifiedwaittime + '</td><td class="' + color + '">' + emp.completedwaittime + '</td><td class="' + color + '">' + emp.Duration + '</td><td class="' + color + '">' + emp.delaytime + '</td></tr>';
                        }
                        else if (emp.is_lab == 1) {

                            tr = tr + '<tr id="t_' + emp.work_order_id + '"  class="' + color + '"><td id="ldtwork_order_no_' + i + '" class="' + color + '">' + emp.work_order_no + '</td><td class="' + color + '">' + emp.samplbarcodeid + '</td><td id="ldtpatient_id_' + i + '" class="' + color + '">' + emp.patient_id + '/' + '<a data-toggle="modal" style="cursor: pointer;" data-target="#myModalPatientSearchDetails" onclick=\'billing_details(\"' + emp.patient_id + '\",\"' + emp.patient_username + '\",\"' + emp.phone_number_1 + '\",this)\'>' + emp.patient_username + '</a>' + '</td><td id="ldtphone_number_1_' + i + '" class="' + color + '">' + emp.phone_number_1 + '-' + emp.paddress + '</td><td id="ldtservice_name_' + i + '" data-id=' + emp.master_service_id + ' data1-id=' + emp.is_lab + ' class="' + color + '">' + emp.service_name + '</td><td id="ldtpackage_id_' + i + '" class="' + color + '">' + emp.package_id + '</td><td id="ldtpackage_name_' + i + '" class="' + color + '">' + emp.package_name + '</td><td class="' + color + '">' + emp.branch_name + '</td><td id="ldtvisit_report_id_' + i + '" class="' + color + '">' + emp.schdulewaittime + '</td><td id="ldtvisit_report_id_' + i + '" class="' + color + '">' + emp.Assignwaittime + '</td><td id="ldtvisit_report_id_' + i + '" class="' + color + '">' + emp.collectsamplewaittime + '</td><td id="ldtvisit_report_id_' + i + '" class="' + color + '">' + emp.receivedwaittime + '</td><td id="ldsamplbarcodeid_' + i + '" class="' + color + '">' + emp.Addresultwaittime + '</td><td class="' + color + '">' + emp.verifiedwaittime + '</td><td class="' + color + '">' + emp.completedwaittime + '</td><td class="' + color + '">' + emp.Duration + '</td><td class="' + color + '">' + emp.delaytime + '</td></tr>';

                        }


                    });

                    $('#' + tblname + 'body').html(tr);
                    datatable(tblname);

                }
            }
        }
    });
}
//# end package Home care turn around time


//load package home care cancelled 
$('#spackagehomecancelled').click(function () {
    loadpkghomecancelledservice(1);

    $('.asidefilterclass').addClass('hidden');
    $('#asidepkhmccancelledtable').removeClass('hidden');
    $('.groupclass').addClass('hidden');
    $('#asidepkhmccancelledtablegroupclass').removeClass('hidden');
    $('.Filterclass').addClass('hidden');
    $('#asidepkhmccancelledtableFilterclass').removeClass('hidden');
});
$('#phmcnbtnreportfilter').click(function () {
    loadpkghomecancelledservice(2);
});
$('#phmcnbtnreportclear').click(function () {
    var hospitalid = $('#HospitalId').val();
    $('#phmcnorderno').val('');
    $('#phmcnorderdate').val('');
    $('#phmcnordertodate').val('');
    Branchdetails(hospitalid);
    loadpkghomecancelledservice(1);
});
function loadpkghomecancelledservice(flag) {


    var servicevalues = {
        Dml_Indicator: "LPKHCCAN",
        flag: flag,
        orderdate: $('#phmcnorderdate').val(),
        ordertodate: $('#phmcnordertodate').val(),
        orderno: $('#phmcnorderno').val(),
        branchid: $('#pkghmcnbranch_id').val(),
        departmentid: ($('#Hdepartment_id').val() == '') ? '' : $('#Hdepartment_id').val(),
        UserId: useridheder,
        spname: "SP_Work_Order_Home_CN",
    }
    $.ajax({
        async: true,
        type: 'POST',
        url: '/Workorder/Get_Workorder',
        contentType: 'application/json; charset=UTF-8',
        data: JSON.stringify(servicevalues),
        success: function (data) {
            debugger;

            var data = JSON.parse(data);
            console.log(data);
            if (data.msg == "Success") {
                var data1 = data.data;
                if (jQuery.isEmptyObject((data1))) {
                    tr = '';
                    $('#pkhmccancelledtablebody').html(tr);
                }
                else {

                    var b = data1.Table;
                    $('#pkhmccancelledtablebody').empty();
                    $('#pkhmccancelledtable').dataTable().fnClearTable();
                    $('#pkhmccancelledtable').dataTable().fnDestroy();
                    tr = '';
                    var status_color = '';
                    var actions
                    $.each(b, function (i, emp) {

                        if (emp.Bill_status == "Paid") {
                            status_color = "<span style='background-color: green !important;color:white;font-size:10px;padding:3px;border-radius:4px;'>paid</span>";
                        }
                        else if (emp.Bill_status == "Due") {
                            status_color = "<span style='background-color: red !important;color:white;font-size:10px;padding:3px;border-radius:4px;'>Due</span>";
                        }
                        else if (emp.Bill_status == "Partial Due") {
                            status_color = "<span style='background-color: orange !important;color:white;font-size:10px;padding:3px;border-radius:4px;'>Partial paid</span>";
                        }
                        else {
                            status_color = '';
                        }

                        if (emp.refundflag == '1') {
                            if (emp.visit_type == '2') {

                                actions = '<a style="cursor:pointer;" onclick=iprefund() class="btn btn-edit btn-xs" title="Refund"><i class="fa fa-undo"></i></a>';
                            }
                            else {
                                actions = '<a style="cursor:pointer;" href="/BillingMaster/refund?Patient_Id=' + emp.patientid + "&Work_order_detailsid=" + emp.work_order_details_id + "&Billcode=" + emp.billing_no + "&refund_code=" + emp.billing_refund_code + "&billing_type=" + emp.billing_type + "&Branch_id=" + emp.branch_id + '"" class="btn btn-edit btn-xs" title="Refund"><i class="fa fa-undo" aria-hidden="true"></i></a>';
                            }
                        }
                        else {
                            actions = 'Refunded'
                        }
                        tr = tr + '<tr id="t_' + emp.work_order_id + '"><td>' + actions + '</td><td id="ldtwork_order_no_' + i + '">' + emp.work_order_no + '</td><td id="ldtcreated_on_' + i + '">' + emp.created_on + '</td><td class="tbl-name" id="ldtpatient_id_' + i + '">' + '<a data-toggle="modal" style="cursor: pointer;" data-target="#myModalPatientSearchDetails" onclick=\'billing_details(\"' + emp.patient_id + '\",\"' + emp.patient_username + '\",\"' + emp.phone_number_1 + '\",this)\'>' + emp.patient_username + " " + status_color + '</a>' + '<Span class="tbl_pno"><br>' + emp.patient_id + '</span></td><td id="ldtphone_number_1_' + i + '">' + emp.phone_number_1 + '<Span class="tbl_pno"><br>' + emp.paddress + '</span></td><td>' + emp.visit_type_name + '</td><td id="ldtpatient_id_' + i + '">' + '<span class="tbl-name">' + emp.service_name + '</span><Span class="tbl_wpkg"><br>' + (($.trim(emp.package_name) != '') ? emp.package_name + ' / ' + emp.package_id : emp.package_id) + '</span></td><td id="ldtdoctorname_' + i + '">' + emp.doctorname + '</td><td id="ldtvisit_report_id_' + i + '">' + emp.visit_report_id + '</td><td>' + emp.branch_name + '</td><td>' + emp.reason + '</td></tr>';

                    });

                    $('#pkhmccancelledtablebody').html(tr);
                    //  $('#pkhmccancelledtable').DataTable();
                    datatable('pkhmccancelledtable');

                }
            }
        }
    });
}
function iprefund() {
    toastr.warning('This is IP service,so you can not refund');
    return;
}
//end package home care


//#start package hospital care



//# Start package hospital care unscheduled
$('#spackagehospitalunscheduled').click(function () {
    debugger;
    loadpackagehospitalunscheduled(1);
    $('.asidefilterclass').addClass('hidden');
    $('#asidehsunscheduled').removeClass('hidden');
    $('.groupclass').addClass('hidden');
    $('#asidehsunscheduledgroupclass').removeClass('hidden');
    $('.Filterclass').addClass('hidden');
    $('#asidehsunscheduledFilterclass').removeClass('hidden');


});
$('#phsunscheduledbtnreportfilter').click(function () {
    loadpackagehospitalunscheduled(2);
})
$('#phsunscheduledbtnreportclear').click(function () {
    var hospitalid = $('#HospitalId').val();
    $('#phsunscheduledorderno').val('');
    $('#phsunscheduleddate').val('');
    $('#phsunscheduledtodate').val('');
    Branchdetails(hospitalid);
    loadpackagehospitalunscheduled(1);
})
var table = '';
function loadpackagehospitalunscheduled(flag) {

    debugger;
    var branch_id = '';
    if (parseInt($('#hiddenRole_id').val()) == 6) {
        branch_id = $('#HospitalBranchID').val();
    }
    else {
        branch_id = $('#pkghsunscheduledbranch_id').val();
    }

    var servicevalues = {
        Dml_Indicator: "LPKHSCUNS",
        flag: flag,
        orderdate: $('#phsunscheduleddate').val(),
        ordertodate: $('#phsunscheduledtodate').val(),
        orderno: $('#phsunscheduledorderno').val(),
        //branchid: $('#pkghsunscheduledbranch_id').val(),
        branchid: branch_id,
        departmentid: ($('#Hdepartment_id').val() == '') ? '' : $('#Hdepartment_id').val(),
        UserId: useridheder,
        spname: "SP_Work_Order_Hospital",
    }
    $.ajax({
        async: true,
        type: 'POST',
        url: '/Workorder/Get_Workorder',
        contentType: 'application/json; charset=UTF-8',
        data: JSON.stringify(servicevalues),
        success: function (data) {
            debugger;

            var data = JSON.parse(data);
            console.log(data);
            if (data.msg == "Success") {
                var data1 = data.data;
                if (jQuery.isEmptyObject((data1))) {
                    tr = '';
                    $('#pkhscunscheduledtablebody').html(tr);
                }
                else {

                    var b = data1.Table;
                    $('#pkhscunscheduledtablebody').empty();
                    $('#pkhscunscheduledtable').dataTable().fnClearTable();
                    //$('#pkhscunscheduledtable').dataTable().fnDraw();
                    $('#pkhscunscheduledtable').dataTable().fnDestroy();
                    tr = '';
                    var popupflagid, popupflag, onclickflag, sflg = '', deleteflag = '',status_color='';

                    $.each(b, function (i, emp) {
                        popupflag = emp.btnflag;
                        
                        if (emp.scheduletime == '00:01') {
                            stime = '';
                        }
                        else {
                            stime = emp.scheduletime;
                        }
                        if (emp.patientprefertime == '00:01') {
                            ptime = '';
                        }
                        else {
                            ptime = emp.patientprefertime;
                        }

                        if (emp.Bill_status == "Paid") {
                            status_color = "<span style='background-color: green !important;color:white;font-size:10px;padding:3px;border-radius:4px;'>paid</span>";
                        }
                        else if (emp.Bill_status == "Due") {
                            status_color = "<span style='background-color: red !important;color:white;font-size:10px;padding:3px;border-radius:4px;'>Due</span>";
                        }
                        else if (emp.Bill_status == "Partial Due") {
                            status_color = "<span style='background-color: orange !important;color:white;font-size:10px;padding:3px;border-radius:4px;'>Partial paid</span>";
                        }
                        else {
                            status_color = '';
                        }

                        if (emp.is_lab == 2) {

                            if (emp.btnflag == 'expired') {
                                tr = tr + '<tr id="t_' + emp.work_order_id + '"><td><div class="col-md-12 padding0"><div class="disp_if">' + emp.btnflag + ' <a href="#" class="dropdown-toggle btn btn-info-dots btn-xs" data-toggle="dropdown" aria-expanded="true"><span class="fa fa-ellipsis-h" data-toggle="tooltip" data-placement="bottom" title="Other Options" style="color:black;" aria-hidden="true"></span><span class="sr-only">Options</span></a><div class="dropdown-menu info-dropdown-workorder" id=""><a style="text-align-last:start"; class="btn btn-delete btn-xs mr-10" data-toggle="modal" data-target="#delete_reason_popup" onclick=servicedel1("' + emp.work_order_details_id + '",2,"phsc","' + emp.package_id + '","' + emp.work_order_id + '")><i class="fa fa-trash-o mr-10" aria-hidden="true"></i>Delete</a></div></div></td><td class="tbl-name" id="ldtpatient_username_' + i + '">' + '<a data-toggle="modal" style="cursor: pointer;" data-target="#myModalPatientSearchDetails" onclick=\'billing_details(\"' + emp.patient_id + '\",\"' + emp.patient_username + '\",\"' + emp.phone_number_1 + '\",this)\'>' + emp.patient_username + ' ' + status_color + '</a>' + '<Span class="tbl_pno"><br>' + emp.patient_id + '</span></td><td id="ldtphone_number_1_' + i + '">' + emp.phone_number_1 + '<Span class="tbl_pno"><br>' + emp.paddress + '</span></td><td>' + emp.visit_type_name + '</td><td id="ldtservice_name_' + i + '" data-id=' + emp.master_service_id + ' data1-id=' + emp.is_lab + '>' + '<span class="tbl-name">' + emp.service_name + '</span><Span class="tbl_wpkg"><br>' + (($.trim(emp.package_name) != '') ? emp.package_name + ' / ' + emp.package_id : emp.package_id) + '</span></td><td>' + emp.doctorname + '</td><td>' + emp.package_purchased_date + '</td><td>' + emp.branch_name + '</td><td id="ldtvisit_report_id_' + i + '">' + (($.trim(emp.patientpreferdate) != '') ? emp.patientpreferdate + ' ' + ptime : ptime) + '</td><td id="ldtvisit_report_id_' + i + '">' + (($.trim(emp.scheduledate) != '') ? emp.scheduledate + ' ' + stime : stime) + '</td><td id="ldtvisit_report_id_' + i + '">' + emp.serviceprovidername + '</td><td id="ldtwork_order_no_' + i + '" data-id1=' + emp.is_lab + '>' + emp.work_order_no + '</td></tr>';
                            }
                            else {
                                tr = tr + '<tr id="t_' + emp.work_order_id + '"><td><div class="col-md-12 padding0"><div class="disp_if"><button style="cursor:pointer;font-size:8px;" data-toggle="modal" data-target="#' + popupflag + '" class="btn-primaryuse btn-xs" onclick=lhorderschedule("' + emp.work_order_details_id + '","' + i + '","' + emp.work_order_id + '","' + emp.patientid + '","' + emp.btnflag + '",1,"phmsc",' + emp.is_lab + ',' + emp.master_service_id + ',"' + emp.visit_report_id + '","' + emp.branch_id + '",1,"pkhscunscheduledtable","' + emp.work_order_status + '","' + emp.wid + '")>' + emp.btnflag + '</button> <a href="#" class="dropdown-toggle btn btn-info-dots btn-xs" data-toggle="dropdown" aria-expanded="true"><span class="fa fa-ellipsis-h" data-toggle="tooltip" data-placement="bottom" title="Other Options" style="color:black;" aria-hidden="true"></span><span class="sr-only">Options</span></a><div class="dropdown-menu info-dropdown-workorder" id=""><a  style="text-align-last:start"; class="btn btn-delete btn-xs mr-10" data-toggle="modal" data-target="#delete_reason_popup" onclick=servicedel1("' + emp.work_order_details_id + '",2,"phsc","' + emp.package_id + '","' + emp.work_order_id + '")><i class="fa fa-trash-o mr-10" aria-hidden="true"></i>Delete</a></div></div></td><td class="tbl-name" id="ldtpatient_username_' + i + '">' + '<a data-toggle="modal" style="cursor: pointer;" data-target="#myModalPatientSearchDetails" onclick=\'billing_details(\"' + emp.patient_id + '\",\"' + emp.patient_username + '\",\"' + emp.phone_number_1 + '\",this)\'>' + emp.patient_username + " " + status_color + '</a>' + '<Span class="tbl_pno"><br>' + emp.patient_id + '</span></td><td id="ldtphone_number_1_' + i + '">' + emp.phone_number_1 + '<Span class="tbl_pno"><br>' + emp.paddress + '</span></td><td>' + emp.visit_type_name + '</td><td id="ldtservice_name_' + i + '" data-id=' + emp.master_service_id + ' data1-id=' + emp.is_lab + '>' + '<span class="tbl-name">' + emp.service_name + '</span><Span class="tbl_wpkg"><br>' + (($.trim(emp.package_name) != '') ? emp.package_name + ' / ' + emp.package_id : emp.package_id) + '</span></td><td>' + emp.doctorname + '</td><td>' + emp.package_purchased_date + '</td><td>' + emp.branch_name + '</td><td id="ldtvisit_report_id_' + i + '">' + (($.trim(emp.patientpreferdate) != '') ? emp.patientpreferdate + ' ' + ptime : ptime) + '</td><td id="ldtvisit_report_id_' + i + '">' + (($.trim(emp.scheduledate) != '') ? emp.scheduledate + ' ' + stime : stime) + '</td><td id="ldtvisit_report_id_' + i + '">' + emp.serviceprovidername + '</td><td id="ldtwork_order_no_' + i + '" data-id1=' + emp.is_lab + '>' + emp.work_order_no + '</td></tr>';
                            }
                        }
                        else if (emp.is_lab == 1) {
                            if (emp.btnflag == 'Schedule' || emp.btnflag == 'Assign') {
                                if (emp.is_internal == 1) {
                                    deleteflag = 10
                                }
                                else {
                                    deleteflag = 12
                                }
                                tr = tr + '<tr id="t_' + emp.work_order_id + '"><td><div class="col-md-12 padding0"><div class="disp_if"><button style="cursor:pointer;font-size:8px;" data-toggle="modal" data-target="#' + popupflag + '" class="btn btn-primaryuse btn-xs" onclick=lhorderschedule("' + emp.work_order_details_id + '","' + i + '","' + emp.work_order_id + '","' + emp.patientid + '","' + emp.btnflag + '",1,"phmsc",' + emp.is_lab + ',' + emp.master_service_id + ',"' + emp.visit_report_id + '","' + emp.branch_id + '",1,"pkhscunscheduledtable","' + emp.work_order_status + '","' + emp.wid + '")>' + emp.btnflag + '</button><a href="#" class="dropdown-toggle btn btn-info-dots btn-xs" data-toggle="dropdown" aria-expanded="true"><span class="fa fa-ellipsis-h" data-toggle="tooltip" data-placement="bottom" title="Other Options" style="color:black;" aria-hidden="true"></span><span class="sr-only">Options</span></a><div class="dropdown-menu info-dropdown-workorder" id=""><a  style="text-align-last:start"; class="btn btn-delete btn-xs mr-10" data-toggle="modal"  data-target="#delete_reason_popup" onclick=servicedel1("' + emp.wid + '",2,"phsc","' + emp.package_id + '","' + emp.work_order_id + '")><i class="fa fa-trash-o mr-10" aria-hidden="true"></i>Delete</a></div></div></td><td class="tbl-name" id="ldtpatient_username_' + i + '">' + '<a data-toggle="modal" style="cursor: pointer;" data-target="#myModalPatientSearchDetails" onclick=\'billing_details(\"' + emp.patient_id + '\",\"' + emp.patient_username + '\",\"' + emp.phone_number_1 + '\",this)\'>' + emp.patient_username + " " + status_color + '</a>' + '<Span class="tbl_pno"><br>' + emp.patient_id + '</span></td><td id="ldtphone_number_1_' + i + '">' + emp.phone_number_1 + '<Span class="tbl_pno"><br>' + emp.paddress + '</span></td><td>' + emp.visit_type_name + '</td><td class="details-control" ' + sflg + ' onclick=servicedetailspackage(this,"' + emp.work_order_id + '","pkghscunsched",' + emp.package_auto_id + ',"' + emp.wid + '",1);>' + emp.service_count + '<Span class="tbl_wpkg"><br>' + (($.trim(emp.package_name) != '') ? emp.package_name + ' / ' + emp.package_id : emp.package_id) + '</span><i class="fa fa-angle-double-down table-arrow-size pull-right"></i></td><td>' + emp.doctorname + '</td><td>' + emp.package_purchased_date + '</td><td>' + emp.branch_name + '</td><td id="ldtvisit_report_id_' + i + '">' + (($.trim(emp.patientpreferdate) != '') ? emp.patientpreferdate + ' ' + ptime : ptime) + '</td><td id="ldtvisit_report_id_' + i + '">' + (($.trim(emp.scheduledate) != '') ? emp.scheduledate + ' ' + stime : stime) + '</td><td id="ldtvisit_report_id_' + i + '">' + emp.serviceprovidername + '</td><td id="ldtwork_order_no_' + i + '" data-id1=' + emp.is_lab + '>' + emp.work_order_no + '</td></tr>';

                            }

                        }


                    });

                    $('#pkhscunscheduledtablebody').html(tr);
                    // $('#pkhscordertable').DataTable();

                    datatable('pkhscunscheduledtable');
                    //$('#pkhscunscheduledtable').DataTable({
                    //    "autoWidth": false,
                    //    // Other DataTable options and configurations...
                    //});


                }
            }
        }
    });
}

//# End package hospital care unscheduled





//# Start package hospital care unassigned
$('#spackagehospitalunassigned').click(function () {
    loadpackagehospitalunassigned(1);
    $('.asidefilterclass').addClass('hidden');
    $('#asidehsunassigned').removeClass('hidden');
    $('.groupclass').addClass('hidden');
    $('#asidehsunassignedgroupclass').removeClass('hidden');
    $('.Filterclass').addClass('hidden');
    $('#asidehsunassignedFilterclass').removeClass('hidden');
});
$('#phsunassignedbtnreportfilter').click(function () {
    loadpackagehospitalunassigned(2);
})
$('#phsunassignedbtnreportclear').click(function () {
    var hospitalid = $('#HospitalId').val();
    $('#phsunassignedorderno').val('');
    $('#phsoorderdate').val('');
    $('#phsoordertodate').val('');
    $('#phsunassigneddate').val('');
    $('#phsunassignedtodate').val('');

    Branchdetails(hospitalid);
    loadpackagehospitalunassigned(1);
})
var table = '';

function loadpackagehospitalunassigned(flag) {

    debugger;
    var servicevalues = {
        Dml_Indicator: "LPKHSCUNAS",
        flag: flag,
        orderdate: $('#phsunassigneddate').val(),
        ordertodate: $('#phsunassignedtodate').val(),
        orderno: $('#phsunassignedorderno').val(),
        branchid: $('#pkghsunassignedbranch_id').val(),
        departmentid: ($('#Hdepartment_id').val() == '') ? '' : $('#Hdepartment_id').val(),
        UserId: useridheder,
        spname: "SP_Work_Order_Hospital_assign",
    }
    $.ajax({
        async: true,
        type: 'POST',
        url: '/Workorder/Get_Workorder',
        contentType: 'application/json; charset=UTF-8',
        data: JSON.stringify(servicevalues),
        success: function (data) {
            debugger;

            var data = JSON.parse(data);
            console.log(data);
            if (data.msg == "Success") {
                var data1 = data.data;
                if (jQuery.isEmptyObject((data1))) {
                    tr = '';
                    $('#pkhscunassignedtablebody').html(tr);
                }
                else {

                    var b = data1.Table;
                    $('#pkhscunassignedtablebody').empty();
                    $('#pkhscunassignedtable').dataTable().fnClearTable();
                    $('#pkhscunassignedtable').dataTable().fnDraw();
                    $('#pkhscunassignedtable').dataTable().fnDestroy();
                    tr = '';
                    var popupflagid, popupflag, onclickflag, sflg = '';

                    $.each(b, function (i, emp) {
                        popupflag = emp.btnflag;
                        if (emp.scheduletime == '00:01') {
                            stime = '';
                        }
                        else {
                            stime = emp.scheduletime;
                        }
                        if (emp.patientprefertime == '00:01') {
                            ptime = '';
                        }
                        else {
                            ptime = emp.patientprefertime;
                        }

                        if (emp.Bill_status == "Paid") {
                            status_color = "<span style='background-color: green !important;color:white;font-size:10px;padding:3px;border-radius:4px;'>paid</span>";
                        }
                        else if (emp.Bill_status == "Due") {
                            status_color = "<span style='background-color: red !important;color:white;font-size:10px;padding:3px;border-radius:4px;'>Due</span>";
                        }
                        else if (emp.Bill_status == "Partial Due") {
                            status_color = "<span style='background-color: orange !important;color:white;font-size:10px;padding:3px;border-radius:4px;'>Partial paid</span>";
                        }
                        else {
                            status_color = '';
                        }

                        if (emp.is_lab == 2) {

                            tr = tr + '<tr id="t_' + emp.work_order_id + '"><td class="col-sm-1 disp_if"><button style="cursor:pointer;font-size:8px;" data-toggle="modal" data-target="#' + popupflag + '" class="btn-primaryuse btn-xs" onclick=lhorderschedule("' + emp.work_order_details_id + '","' + i + '","' + emp.work_order_id + '","' + emp.patientid + '","' + emp.btnflag + '",1,"phmsc",' + emp.is_lab + ',' + emp.master_service_id + ',"' + emp.visit_report_id + '","' + emp.branch_id + '",1,"pkhscunassignedtable","' + emp.work_order_status + '","' + emp.wid + '")>' + emp.btnflag + '</button></td><td class="tbl-name" id="ldtpatient_username_' + i + '">' + '<a data-toggle="modal" style="cursor: pointer;" data-target="#myModalPatientSearchDetails" onclick=\'billing_details(\"' + emp.patient_id + '\",\"' + emp.patient_username + '\",\"' + emp.phone_number_1 + '\",this)\'>' + emp.patient_username + " " + status_color + '</a>' + '<span<Span class="tbl_pno"><br>' + emp.patient_id + '</span></td><td id="ldtphone_number_1_' + i + '">' + emp.phone_number_1 + '<Span class="tbl_pno"><br>' + emp.paddress + '</span></td><td>' + emp.visit_type_name + '</td><td id="ldtservice_name_' + i + '" data-id=' + emp.master_service_id + ' data1-id=' + emp.is_lab + '>' + '<span class="tbl-name">' + emp.service_name + '</span><Span class="tbl_wpkg"><br>' + (($.trim(emp.package_name) != '') ? emp.package_name + ' / ' + emp.package_id : emp.package_id) + '</span></td><td>' + emp.doctorname + '</td><td>' + emp.package_purchased_date + '</td><td>' + emp.branch_name + '</td><td id="ldtvisit_report_id_' + i + '">' + (($.trim(emp.patientpreferdate) != '') ? emp.patientpreferdate + ' ' + ptime : ptime) + '</td><td id="ldtscheduledate_' + i + '">' + (($.trim(emp.scheduledate) != '') ? emp.scheduledate + ' ' + stime : stime) + '</td><td id="ldtvisit_report_id_' + i + '">' + emp.serviceprovidername + '</td><td id="ldtwork_order_no_' + i + '" data-id1=' + emp.is_lab + '>' + emp.work_order_no + '</td></tr>';

                        }
                        else if (emp.is_lab == 1) {
                            if (emp.btnflag == 'Schedule' || emp.btnflag == 'Assign') {
                                if (emp.patientpreferdate != '') {
                                    tr = tr + '<tr id="t_' + emp.work_order_id + '"><td class="disp_if"><button style="cursor:pointer;font-size:8px;" data-toggle="modal" data-target="#' + popupflag + '" class="btn btn-primaryuse btn-xs" onclick=lhorderschedule("' + emp.work_order_details_id + '","' + i + '","' + emp.work_order_id + '","' + emp.patientid + '","' + emp.btnflag + '",1,"phmsc",' + emp.is_lab + ',' + emp.master_service_id + ',"' + emp.visit_report_id + '","' + emp.branch_id + '",1,"pkhscunassignedtable","' + emp.work_order_status + '","' + emp.wid + '")>' + emp.btnflag + '</button></td><td class="tbl-name" id="ldtpatient_username_' + i + '">' + '<a data-toggle="modal" style="cursor: pointer;" data-target="#myModalPatientSearchDetails" onclick=\'billing_details(\"' + emp.patient_id + '\",\"' + emp.patient_username + '\",\"' + emp.phone_number_1 + '\",this)\'>' + emp.patient_username + " " + status_color + '</a>' + '<span class="tbl_pno"><br>' + emp.patient_id + '</span></td><td id="ldtphone_number_1_' + i + '">' + emp.phone_number_1 + '<Span class="tbl_pno"><br>' + emp.paddress + '</span></td><td>' + emp.visit_type_name + '</td><td class="details-control" ' + sflg + '   onclick=servicedetailspackage(this,"' + emp.work_order_id + '","pkghscunass",' + emp.package_auto_id + ',"' + emp.wid + '",2);>' + emp.service_count + '<Span class="tbl_wpkg"><br>' + (($.trim(emp.package_name) != '') ? emp.package_name + ' / ' + emp.package_id : emp.package_id) + '</span><i class="fa fa-angle-double-down table-arrow-size pull-right"></i></td><td>' + emp.doctorname + '</td><td>' + emp.package_purchased_date + '</td><td>' + emp.branch_name + '</td><td id="ldtvisit_report_id_' + i + '">' + (($.trim(emp.patientpreferdate) != '') ? emp.patientpreferdate + ' ' + ptime : ptime) + '</td><td id="ldtscheduledate_' + i + '">' + (($.trim(emp.scheduledate) != '') ? emp.scheduledate + ' ' + stime : stime) + '</td><td id="ldtvisit_report_id_' + i + '">' + emp.serviceprovidername + '</td><td id="ldtwork_order_no_' + i + '" data-id1=' + emp.is_lab + '>' + emp.work_order_no + '</td></tr>';
                                }
                                else {
                                    tr = tr + '<tr id="t_' + emp.work_order_id + '"><td><div class="col-md-12 padding0"><div class="disp_if"><button style="cursor:pointer;font-size:8px;" data-toggle="modal" data-target="#' + popupflag + '" class="btn btn-primaryuse btn-xs" onclick=lhorderschedule("' + emp.work_order_details_id + '","' + i + '","' + emp.work_order_id + '","' + emp.patientid + '","' + emp.btnflag + '",1,"phmsc",' + emp.is_lab + ',' + emp.master_service_id + ',"' + emp.visit_report_id + '","' + emp.branch_id + '",1,"pkhscunassignedtable","' + emp.work_order_status + '","' + emp.wid + '")>' + emp.btnflag + '</button><a href="#" class="dropdown-toggle btn btn-info-dots btn-xs" data-toggle="dropdown" aria-expanded="true"><span class="fa fa-ellipsis-h" data-toggle="tooltip" data-placement="bottom" title="Other Options" style="color:black;" aria-hidden="true"></span><span class="sr-only">Options</span></a><div class="dropdown-menu info-dropdown-workorder" id=""><a  style="text-align-last:start"; class="btn btn-delete btn-xs mr-10" data-toggle="modal" data-target="#delete_reason_popup" onclick=servicedel1("' + emp.wid + '",13,"phsc","' + emp.package_id + '","' + emp.work_order_id + '")><i class="fa fa-trash mr-10" aria-hidden="true"></i>Delete</a></div></div></td><td class="tbl-name" id="ldtpatient_username_' + i + '">' + '<a data-toggle="modal" style="cursor: pointer;" data-target="#myModalPatientSearchDetails" onclick=\'billing_details(\"' + emp.patient_id + '\",\"' + emp.patient_username + '\",\"' + emp.phone_number_1 + '\",this)\'>' + emp.patient_username + " " + status_color + '</a>' + '<span class="tbl_pno"><br>' + emp.patient_id + '</span></td><td id="ldtphone_number_1_' + i + '">' + emp.phone_number_1 + '<Span class="tbl_pno"><br>' + emp.paddress + '</span></td><td>' + emp.visit_type_name + '</td><td class="details-control" ' + sflg + ' onclick=servicedetailspackage(this,"' + emp.work_order_id + '","pkghscunass",' + emp.package_auto_id + ',"' + emp.wid + '",2);>' + emp.service_count + '<Span class="tbl_wpkg"><br>' + (($.trim(emp.package_name) != '') ? emp.package_name + ' / ' + emp.package_id : emp.package_id) + '</span><i class="fa fa-angle-double-down table-arrow-size pull-right"></i></td><td>' + emp.doctorname + '</td><td>' + emp.package_purchased_date + '</td><td>' + emp.branch_name + '</td><td id="ldtvisit_report_id_' + i + '">' + (($.trim(emp.patientpreferdate) != '') ? emp.patientpreferdate + ' ' + ptime : ptime) + '</td><td id="ldtscheduledate_' + i + '">' + (($.trim(emp.scheduledate) != '') ? emp.scheduledate + ' ' + stime : stime) + '</td><td id="ldtvisit_report_id_' + i + '">' + emp.serviceprovidername + '</td><td id="ldtwork_order_no_' + i + '" data-id1=' + emp.is_lab + '>' + emp.work_order_no + '</td></tr>'

                                }
                            }

                        }


                    });

                    $('#pkhscunassignedtablebody').html(tr);
                    datatable('pkhscunassignedtable');
                }
            }
        }
    });
}

//# End package hospital care unassigned




//# Start package hospital care collectsamples
$('#spackagehospitalcollectsamples').click(function () {
    loadpackagehospitalcollectsamples(1);
    $('.asidefilterclass').addClass('hidden');
    $('#asidepkhsccollectsamplestable').removeClass('hidden');
    $('.groupclass').addClass('hidden');
    $('#asidepkhsccollectsamplestablegroupclass').removeClass('hidden');
    $('.Filterclass').addClass('hidden');
    $('#asidepkhsccollectsamplestableFilterclass').removeClass('hidden');
});
$('#phscollectsamplesbtnreportfilter').click(function () {
    loadpackagehospitalcollectsamples(2);
})
$('#phscollectsamplesbtnreportclear').click(function () {
    var hospitalid = $('#HospitalId').val();
    $('#phscollectsamplesorderno').val('');
    $('#phscollectsamplesdate').val('');
    $('#phscollectsamplestodate').val('');
    Branchdetails(hospitalid);
    loadpackagehospitalcollectsamples(1);
})
var table = '';
function loadpackagehospitalcollectsamples(flag) {

    debugger;
    var servicevalues = {
        Dml_Indicator: "LPKHSCS",
        flag: flag,
        orderdate: $('#phscollectsamplesdate').val(),
        orderdate: $('#phscollectsamplestodate').val(),
        orderno: $('#phscollectsamplesorderno').val(),
        branchid: $('#pkghscollectsamplesbranch_id').val(),
        serviceproviderid: $('#phscollectsamplesserviceprovidername').val(),
        departmentid: ($('#Hdepartment_id').val() == '') ? '' : $('#Hdepartment_id').val(),
        UserId: useridheder,
        spname: "SP_Work_Order_Hospital_CS",
    }
    $.ajax({
        async: true,
        type: 'POST',
        url: '/Workorder/Get_Workorder',
        contentType: 'application/json; charset=UTF-8',
        data: JSON.stringify(servicevalues),
        success: function (data) {
            debugger;

            var data = JSON.parse(data);
            console.log(data);
            if (data.msg == "Success") {
                var data1 = data.data;
                if (jQuery.isEmptyObject((data1))) {
                    tr = '';
                    $('#pkhsccollectsamplestablebody').html(tr);
                }
                else {

                    var b = data1.Table;
                    $('#pkhsccollectsamplestablebody').empty();
                    $('#pkhsccollectsamplestable').dataTable().fnClearTable();
                    $('#pkhsccollectsamplestable').dataTable().fnDraw();
                    $('#pkhsccollectsamplestable').dataTable().fnDestroy();
                    tr = '';
                    var popupflagid, popupflag, onclickflag, sflg = '', status_color = '';
                    var stime = '', ptime = '';
                    $.each(b, function (i, emp) {
                        popupflag = emp.btnflag;
                        if (emp.scheduletime == '00:01') {
                            stime = '';
                        }
                        else {
                            stime = emp.scheduletime;
                        }
                        if (emp.patientprefertime == '00:01') {
                            ptime = '';
                        }
                        else {
                            ptime = emp.patientprefertime;
                        }

                        if (emp.Bill_status == "Paid") {
                            status_color = "<span style='background-color: green !important;color:white;font-size:10px;padding:3px;border-radius:4px;'>paid</span>";
                        }
                        else if (emp.Bill_status == "Due") {
                            status_color = "<span style='background-color: red !important;color:white;font-size:10px;padding:3px;border-radius:4px;'>Due</span>";
                        }
                        else if (emp.Bill_status == "Partial Due") {
                            status_color = "<span style='background-color: orange !important;color:white;font-size:10px;padding:3px;border-radius:4px;'>Partial paid</span>";
                        }
                        else {
                            status_color = '';
                        }

                        if (emp.serviceproviderid == '0') {

                            var tag = '';
                            var other_info = '<div class="col-md-12 padding0"><div class="disp_if"><button style="cursor:pointer;font-size:8px;" data-toggle="modal" data-target="#ldcollect_samplepopup" class="btn btn-primaryuse btn-xs" onclick=labordersample("' + emp.work_order_details_id + '","' + i + '","' + emp.work_order_id + '","' + emp.patientid + '","phmsc",4,"' + emp.package_auto_id + '",' + emp.work_order_status + ',' + emp.serviceproviderid + ',"' + emp.patient_id + '","' + emp.visit_report_id + '","' + emp.branch_id + '","' + emp.hospitalid + '","' + emp.wid + '")>' + emp.btnflag + '</button> <a href="#" class="dropdown-toggle btn btn-info-dots btn-xs" data-toggle="dropdown" aria-expanded="true"><span class="fa fa-ellipsis-h" data-toggle="tooltip" data-placement="bottom" title="Other Options" style="color:black;" aria-hidden="true"></span><span class="sr-only">Options</span></a><div class="dropdown-menu info-dropdown-workorder" id=""><p style="text-align-last:start";> <a class="btn btn-delete btn-xs mr-10" title="Delete" data-toggle="modal" data-target="#delete_reason_popup" onclick=servicedel1("' + emp.wid + '",11,"phsc","' + emp.package_id + '","' + emp.work_order_id + '")><i class="fa fa-trash-o mr-10" aria-hidden="true"></i> Delete</a> </p><p style="text-align-last:start";>' + tag + '</p></ul></div></div>';
                            // var other_info = '<div class="col-md-12 padding0"><div class="disp_if">' + edit + ' <a href="#" class="dropdown-toggle btn btn-info-dots btn-xs" data-toggle="dropdown" aria-expanded="true"><span class="fa fa-ellipsis-h" data-toggle="tooltip" data-placement="bottom" title="Other Options" style="color:black;" aria-hidden="true"></span><span class="sr-only">Options</span></a><div class="dropdown-menu info-dropdown" id=""><li class="text-left">' + print + '</li></ul></div></div>';
                        }
                        else {


                            var tag = '<a id="reject_' + i + '" class="btn btn-delete btn-xs" data-toggle="tooltip" title="Click to Reject" cursor: pointer; style="font-size:12px;color:red" onclick=rejection("' + emp.work_order_details_id + '","' + emp.work_order_id + '","' + emp.patientid + '",' + emp.is_lab + ',' + emp.master_service_id + ',"' + emp.visit_report_id + '",' + emp.serviceproviderid + ',"' + emp.wid + '",1)><i class="fa fa-ban mr-10"></i>Reject</a>';
                            var other_info = '<div class="col-md-12 padding0"><div class="disp_if"><button style="cursor:pointer;font-size:8px;" data-toggle="modal" data-target="#ldcollect_samplepopup" class="btn btn-primaryuse btn-xs" onclick=labordersample("' + emp.work_order_details_id + '","' + i + '","' + emp.work_order_id + '","' + emp.patientid + '","phmsc",4,"' + emp.package_auto_id + '",' + emp.work_order_status + ',' + emp.serviceproviderid + ',"' + emp.patient_id + '","' + emp.visit_report_id + '","' + emp.branch_id + '","' + emp.hospitalid + '","' + emp.wid + '")>' + emp.btnflag + '</button> <a href="#" class="dropdown-toggle btn btn-info-dots btn-xs" data-toggle="dropdown" aria-expanded="true"><span class="fa fa-ellipsis-h" data-toggle="tooltip" data-placement="bottom" title="Other Options" style="color:black;" aria-hidden="true"></span><span class="sr-only">Options</span></a><div class="dropdown-menu info-dropdown-workorder" id=""><p style="text-align-last:start";> <a class="btn btn-delete btn-xs mr-10" title="Delete" data-toggle="modal" data-target="#delete_reason_popup" onclick=servicedel1("' + emp.wid + '",11,"phsc","' + emp.package_id + '","' + emp.work_order_id + '")><i class="fa fa-trash-o mr-10" aria-hidden="true"></i> Delete</a> </p><p style="text-align-last:start";>' + tag + '</p></ul></div></div>';

                        }
                        if (emp.is_lab == 1) {
                            if (emp.btnflag == 'Collect Sample' || emp.btnflag == 'Assign') {
                                tr = tr + '<tr id="t_' + emp.work_order_id + '"><td> ' + other_info + '</td><td class="tbl-name" id="ldtpatient_id_' + i + '">' + '<a data-toggle="modal" style="cursor: pointer;" data-target="#myModalPatientSearchDetails" onclick=\'billing_details(\"' + emp.patient_id + '\",\"' + emp.patient_username + '\",\"' + emp.phone_number_1 + '\",this)\'>' + emp.patient_username + " " + status_color +'</a>' + '<Span class="tbl_pno"><br>' + emp.patient_id + '</span></td><td id="ldtphone_number_1_' + i + '">' + emp.phone_number_1 + '<Span class="tbl_pno"><br>' + emp.paddress + '</span></td><td>' + emp.visit_type_name + '</td><td class="details-control" ' + sflg + ' onclick=servicedetailspackage(this,"' + emp.work_order_id + '","pkghsccs",' + emp.package_auto_id + ',"' + emp.wid + '",1);>' + '<span class="tbl-name">' + emp.service_count + '</span><Span class="tbl_wpkg"><br>' + (($.trim(emp.package_name) != '') ? emp.package_name + ' / ' + emp.package_id : emp.package_id) + '</span><i class="fa fa-angle-double-down table-arrow-size pull-right"></i></td><td>' + emp.doctorname + '</td><td>' + emp.package_purchased_date + '</td><td>' + emp.branch_name + '</td><td id="ldtvisit_report_id_' + i + '">' + (($.trim(emp.patientpreferdate) != '') ? emp.patientpreferdate + ' ' + ptime : ptime) + '</td><td id="ldtvisit_report_id_' + i + '">' + (($.trim(emp.scheduledate) != '') ? emp.scheduledate + ' ' + stime : stime) + '</td><td id="ldtvisit_report_id_' + i + '">' + emp.serviceprovidername + '</td><td id="ldtwork_order_no_' + i + '" data-id1=' + emp.is_lab + '>' + emp.work_order_no + '</td></tr>';
                            }
                        }
                    });

                    $('#pkhsccollectsamplestablebody').html(tr);
                    // $('#pkhscordertable').DataTable();
                    datatable('pkhsccollectsamplestable');

                }
            }
        }
    });
}

//# End package hospital care collectsamples






//# Start package hospital care orders
$('#spackagehospitalorders').click(function () {
    loadpackagehospitalorders(1);
    $('.asidefilterclass').addClass('hidden');
    $('#asidepkhscordertable').removeClass('hidden');
    $('.groupclass').addClass('hidden');
    $('#asidepkhscordertablegroupclass').removeClass('hidden');
    $('.Filterclass').addClass('hidden');
    $('#asidepkhscordertableFilterclass').removeClass('hidden');
});
$('#phsorderbtnreportfilter').click(function () {
    loadpackagehospitalorders(2);
})
$('#phsorderbtnreportclear').click(function () {
    var hospitalid = $('#HospitalId').val();
    $('#phsoorderno').val('');
    $('#phsoschedulestatus').val('');
    $('#phsoorderdate').val('');
    $('#phsoordertodate').val('');
    Branchdetails(hospitalid);
    loadpackagehospitalorders(1);
})
var table = '';
function loadpackagehospitalorders(flag) {

    debugger;
    var servicevalues = {
        Dml_Indicator: "LPKHSCO",
        flag: flag,
        orderdate: $('#phsoorderdate').val(),
        ordertodate: $('#phsoordertodate').val(),
        orderno: $('#phsoorderno').val(),
        jobsflag: $('#phsoschedulestatus').val(),
        branchid: $('#pkghsobranch_id').val(),
        serviceproviderid: $('#phsorderserviceprovidername').val(),
        departmentid: ($('#Hdepartment_id').val() == '') ? '' : $('#Hdepartment_id').val(),
        UserId: useridheder,
        spname: "SP_Work_Order_Hospital_order",
    }
    $.ajax({
        async: true,
        type: 'POST',
        url: '/Workorder/Get_Workorder',
        contentType: 'application/json; charset=UTF-8',
        data: JSON.stringify(servicevalues),
        success: function (data) {
            debugger;

            var data = JSON.parse(data);
            console.log(data);
            if (data.msg == "Success") {
                var data1 = data.data;
                if (jQuery.isEmptyObject((data1))) {
                    tr = '';
                    $('#pkhscordertablebody').html(tr);
                }
                else {

                    var b = data1.Table;
                    $('#pkhscordertablebody').empty();
                    $('#pkhscordertable').dataTable().fnClearTable();
                    //$('#pkhscordertable').dataTable().fnDraw();
                    $('#pkhscordertable').dataTable().fnDestroy();
                    tr = '';
                    var popupflagid, popupflag, onclickflag, sflg = '';

                    $.each(b, function (i, emp) {
                        popupflag = emp.btnflag;
                        if (emp.scheduletime == '00:01') {
                            stime = '';
                        }
                        else {
                            stime = emp.scheduletime;
                        }
                        if (emp.patientprefertime == '00:01') {
                            ptime = '';
                        }
                        else {
                            ptime = emp.patientprefertime;
                        }

                        //if (emp.is_lab == 2) {

                        tr = tr + '<tr id="t_' + emp.work_order_id + '"><td>' + emp.btnflag + '</td><td class="tbl-name" id="ldtpatient_id_' + i + '">' + '<a data-toggle="modal" style="cursor: pointer;" data-target="#myModalPatientSearchDetails" onclick=\'billing_details(\"' + emp.patient_id + '\",\"' + emp.patient_username + '\",\"' + emp.phone_number_1 + '\",this)\'>' + emp.patient_username + '</a>' + '<Span class="tbl_pno"><br>' + emp.patient_id + '</span></td><td id="ldtphone_number_1_' + i + '">' + emp.phone_number_1 + '<Span class="tbl_pno"><br>' + emp.paddress + '</span></td><td>' + emp.visit_type_name + '</td><td id="ldtpackage_name_' + i + '">' + '<span class="tbl-name">' + emp.service_name + '</span><Span class="tbl_wpkg"><br>' + (($.trim(emp.package_name) != '') ? emp.package_name + ' / ' + emp.package_id : emp.package_id) + '</span></td><td>' + emp.doctorname + '</td><td>' + emp.package_purchased_date + '</td><td>' + emp.branch_name + '</td><td id="ldtvisit_report_id_' + i + '">' + (($.trim(emp.patientpreferdate) != '') ? emp.patientpreferdate + ' ' + ptime : ptime) + '</td><td id="ldtvisit_report_id_' + i + '">' + (($.trim(emp.scheduledate) != '') ? emp.scheduledate + ' ' + stime : stime) + '</td><td id="ldtvisit_report_id_' + i + '">' + emp.serviceprovidername + '</td><td id="ldtwork_order_no_' + i + '" data-id1=' + emp.is_lab + '>' + emp.work_order_no + '</td></tr>';

                        //}
                        //else if (emp.is_lab == 1) {

                        //    tr = tr + '<tr id="t_' + emp.work_order_id + '"><td>' + emp.btnflag + '</td><td id="ldtwork_order_no_' + i + '" data-id=' + emp.labhometranid + '>' + emp.work_order_no + '</td><td id="ldtpatient_id_' + i + '">' + emp.patient_id + '</td><td id="ldtpatient_username_' + i + '">' + emp.patient_username + '</td><td id="ldtphone_number_1_' + i + '">' + (($.trim(emp.paddress) != '') ? emp.paddress + '/' + emp.phone_number_1 : emp.phone_number_1) + '</td><td id="ldtpackage_id_' + i + '">' + emp.package_id + '</td><td id="ldtpackage_name_' + i + '">' + emp.package_name + '</td><td class="details-control" ' + sflg + ' onclick=servicedetailspackage(this,"' + emp.work_order_id + '","pkhscordertable","' + emp.package_auto_id + '","' + emp.wid + '",2);>' + emp.service_count + '<i class="fa fa-angle-double-down table-arrow-size pull-right"></i></td><td>' + emp.doctorname + '</td><td id="ldtvisit_report_id_' + i + '">' + emp.patientpreferdate + '</td><td id="ldtvisit_report_id_' + i + '">' + emp.patientprefertime + '</td><td id="ldtvisit_report_id_' + i + '">' + emp.scheduledate + '</td><td id="ldtvisit_report_id_' + i + '">' + emp.scheduletime + '</td><td id="ldtvisit_report_id_' + i + '">' + emp.serviceprovidername + '</td><td>' + emp.package_purchased_date + '</td><td>' + emp.branch_name + '</td></tr>';
                        //}



                    });

                    $('#pkhscordertablebody').html(tr);

                    datatable('pkhscordertable');

                }
            }
        }
    });
}

//# end package hospital care orders






//load package hospital care jobs
$('#spackagehospitaljobs').click(function () {
    loadpackagehospitaljobs(1, "LPKHSCJ", 2, 'pkhscjobtable', 'jo');
    $('.asidefilterclass').addClass('hidden');
    $('#asidepkhscjobtable').removeClass('hidden');
    $('.groupclass').addClass('hidden');
    $('#asidepkhscjobtablegroupclass').removeClass('hidden');
    $('.Filterclass').addClass('hidden');
    $('#asidepkhscjobtableFilterclass').removeClass('hidden');
})


//load package hospital care receive sample
$('#spackagehospitalreceivesample').click(function () {
    loadpackagehospitaljobs(1, 'LPKHSCRS', 1, 'pkhscreceivesampletable', 'rs');
    $('.asidefilterclass').addClass('hidden');
    $('#asidepkhscreceivesampletable').removeClass('hidden');
    $('.groupclass').addClass('hidden');
    $('#asidepkhscreceivesampletablegroupclass').removeClass('hidden');
    $('.Filterclass').addClass('hidden');
    $('#asidepkhscreceivesampletableFilterclass').removeClass('hidden');
})

//load package hospital care Pending Approval
$('#spackagehospitalpendingapproval').click(function () {
    loadpackagehospitaljobs(1, 'LPKHSCPR', 3, 'pkhscpendingapprovaltable', 'pr');
    $('.asidefilterclass').addClass('hidden');
    $('#asidepkhscpendingapprovaltable').removeClass('hidden');
    $('.groupclass').addClass('hidden');
    $('#asidepkhscpendingapprovaltablegroupclass').removeClass('hidden');
    $('.Filterclass').addClass('hidden');
    $('#asidepkhscpendingapprovaltableFilterclass').removeClass('hidden');
})
$('#phsjobbtnreportfilter').click(function () {
    loadpackagehospitaljobs(2, "LPKHSCJ", 2, 'pkhscjobtable', 'jo');
})
$('#phsprbtnreportfilter').click(function () {
    loadpackagehospitaljobs(2, 'LPKHSCPR', 3, 'pkhscpendingapprovaltable', 'pr');
})
$('#phsrsbtnreportfilter').click(function () {
    loadpackagehospitaljobs(2, 'LPKHSCRS', 1, 'pkhscreceivesampletable', 'rs');
})
$('#phsjobbtnreportclear').click(function () {
    var hospitalid = $('#HospitalId').val();
    $('#phsjorderno').val('');
    $('#phsjsampleid').val('');
    $('#phsjschedulestatus').val('');
    $('#phsjoorderdate').val('');
    $('#phsjoordertodate').val('');
    $('#phsjoorderno').val('');
    $('#phsjosampleid').val('');
    Branchdetails(hospitalid);
    getserviceprovider(0);
    loadpackagehospitaljobs(1, "LPKHSCJ", 2, 'pkhscjobtable', 'jo');
})

$('#phsrsbtnreportclear').click(function () {
    var hospitalid = $('#HospitalId').val();
    $('#phsrsorderno').val('');
    $('#phsrssampleid').val('');
    $('#phsrsschedulestatus').val('');
    $('#phsrsorderdate').val('');
    $('#phsrsordertodate').val('');
    Branchdetails(hospitalid);
    getserviceprovider(0);
    loadpackagehospitaljobs(1, 'LPKHSCRS', 1, 'pkhscreceivesampletable', 'rs');
})
$('#phsprbtnreportclear').click(function () {
    var hospitalid = $('#HospitalId').val();
    $('#phsprorderno').val('');
    $('#phsprsampleid').val('');
    $('#phsprschedulestatus').val('');
    $('#phsprorderdate').val('');
    $('#phsprordertodate').val('');
    $('#phsprorderno').val('');
    $('#phsprsampleid').val('');
    Branchdetails(hospitalid);
    getserviceprovider(0);
    loadpackagehospitaljobs(1, 'LPKHSCPR', 3, 'pkhscpendingapprovaltable', 'pr');
})
function loadpackagehospitaljobs(flag, indicator, wstatus, tblname, filtername) {
    var spname = "";
    debugger;
    if (indicator == 'LPKHSCRS') {
        spname = "SP_Work_Order_Hospital_RS"
    }
    else if (indicator == 'LPKHSCJ') {
        spname = "SP_Work_Order_Hospital_JOBS"
    }
    else if (indicator == 'LPKHSCPR') {
        spname = "SP_Work_Order_Hospital_PR"
    }
    var servicevalues = {
        Dml_Indicator: indicator,
        flag: flag,
        samplbarcodeid: $('#phs' + filtername + 'sampleid').val(),
        orderdate: $('#phs' + filtername + 'orderdate').val(),
        ordertodate: $('#phs' + filtername + 'ordertodate').val(),
        orderno: $('#phs' + filtername + 'orderno').val(),
        jobsflag: $('#phs' + filtername + 'schedulestatus').val(),
        serviceproviderid: $('#phs' + filtername + 'serviceprovidername').val(),
        branchid: $('#pkghs' + filtername + 'branch_id').val(),
        work_order_status: wstatus,
        departmentid: ($('#Hdepartment_id').val() == '') ? '' : $('#Hdepartment_id').val(),
        UserId: useridheder,
        spname: spname

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

            var data = JSON.parse(data);
            console.log(data);
            if (data.msg == "Success") {
                var data1 = data.data;
                if (jQuery.isEmptyObject((data1))) {
                    tr = '';
                    $('#' + tblname + 'body').html(tr);
                }
                else {

                    var b = data1.Table;
                    $('#' + tblname + 'body').empty();
                    $('#' + tblname + '').dataTable().fnClearTable();
                    $('#' + tblname + '').dataTable().fnDraw();
                    $('#' + tblname + '').dataTable().fnDestroy();
                    tr = '';
                    var popupflagid, popupflag, onclickflag, sflg = '', status_color = '';

                    var stime = '', ptime = '';
                    $.each(b, function (i, emp) {
                        popupflag = emp.btnflag;
                        if (emp.scheduletime == '00:01') {
                            stime = '';
                        }
                        else {
                            stime = emp.scheduletime;
                        }
                        if (emp.patientprefertime == '00:01') {
                            ptime = '';
                        }
                        else {
                            ptime = emp.patientprefertime;
                        }

                        if (emp.Bill_status == "Paid") {
                            status_color = "<span style='background-color: green !important;color:white;font-size:10px;padding:3px;border-radius:4px;'>paid</span>";
                        }
                        else if (emp.Bill_status == "Due") {
                            status_color = "<span style='background-color: red !important;color:white;font-size:10px;padding:3px;border-radius:4px;'>Due</span>";
                        }
                        else if (emp.Bill_status == "Partial Due") {
                            status_color = "<span style='background-color: orange !important;color:white;font-size:10px;padding:3px;border-radius:4px;'>Partial paid</span>";
                        }
                        else {
                            status_color = '';
                        }


                        if (emp.serviceproviderid == '0') {

                            var tag = '';

                        }
                        else {

                            var tag = '<p id="reject_' + i + '" class="btn btn-delete btn-xs" data-toggle="tooltip" title="Click to Reject!" cursor: pointer;  onclick=rejection("' + emp.work_order_details_id + '","' + emp.work_order_id + '","' + emp.patientid + '",' + emp.is_lab + ',' + emp.master_service_id + ',"' + emp.visit_report_id + '",' + emp.serviceproviderid + ',"' + emp.wid + '",1)><i class="fa fa-ban mr-10" aria-hidden="true"></i>Reject</p>';

                        }
                        if (emp.is_lab == 2) {

                            tr = tr + '<tr id="t_' + emp.work_order_id + '"><td><div class="col-md-12 padding0"><div class="disp_if"><button style="cursor:pointer;" data-toggle="modal" data-target="#Assign" class="btn btn-primaryuse btn-xs" onclick=pkgjobsdetails("' + emp.work_order_id + '","' + emp.master_service_id + '","phmsc","C",' + emp.work_order_details_id + ',"' + emp.patient_id + '",' + emp.branch_id + ',"' + emp.visit_report_id + '")>Completed</button><a href="#" class="dropdown-toggle btn btn-info-dots btn-xs" data-toggle="dropdown" aria-expanded="true"><span class="fa fa-ellipsis-h" data-toggle="tooltip" data-placement="bottom" title="Other Options" style="color:black;" aria-hidden="true"></span><span class="sr-only">Options</span></a><div class="dropdown-menu info-dropdown-workorder" id=""><p style="text-align-last:start"; ><button style="cursor:pointer;" data-toggle="modal" data-target="#Assign" class="btn btn-edit btn-xs" onclick=pkgjobsdetails("' + emp.work_order_id + '","' + emp.master_service_id + '","phmsc","E",' + emp.work_order_details_id + ',"' + emp.patient_id + '",' + emp.branch_id + ',"' + emp.visit_report_id + '")><i class="fa fa-pencil mr-10"></i> Edit</button> </p><p style="text-align-last:start"; > <button style="cursor:pointer;" data-toggle="modal" data-target="#Assign" class="btn btn-eye btn-xs" onclick=pkgjobsdetails("' + emp.work_order_id + '","' + emp.master_service_id + '","phmsc","D",' + emp.work_order_details_id + ',"' + emp.patient_id + '",' + emp.branch_id + ',"' + emp.visit_report_id + '")><i class="fa fa-eye mr-10"></i>View</button></p>' + tag + '</div></div></td><td id="ldsamplbarcodeid_' + i + '">' + emp.samplbarcodeid + '</td><td class="tbl-name" id="ldtpatient_id_' + i + '">' + emp.patient_username + " " + status_color + '<Span class="tbl_pno"><br>' + emp.patient_id + '</span></td><td id="ldtphone_number_1_' + i + '">' + emp.phone_number_1 + '<Span class="tbl_pno"><br>' + emp.paddress + '</span></td><td>' + emp.visit_type_name + '</td><td id="ldtservice_name_' + i + '" data-id=' + emp.master_service_id + ' data1-id=' + emp.is_lab + '>' + '<span class="tbl-name">' + emp.service_name + '</span><Span class="tbl_wpkg"><br>' + (($.trim(emp.package_name) != '') ? emp.package_name + ' / ' + emp.package_id : emp.package_id) + '</span></td><td>' + emp.doctorname + '</td><td>' + emp.package_purchased_date + '</td><td>' + emp.branch_name + '</td><td id="ldtvisit_report_id_' + i + '">' + (($.trim(emp.patientpreferdate) != '') ? emp.patientpreferdate + ' ' + ptime : ptime) + '</td><td id="ldtvisit_report_id_' + i + '">' + (($.trim(emp.scheduledate) != '') ? emp.scheduledate + ' ' + stime : stime) + '</td><td id="ldtvisit_report_id_' + i + '">' + emp.serviceprovidername + '</td><td id="ldtwork_order_no_' + i + '">' + emp.work_order_no + '</td></tr>';
                        }
                        else if (emp.is_lab == 1) {
                            if (tblname == 'pkhscreceivesampletable') {
                                var taglab = '<p id="reject_' + i + '" class="btn btn-delete btn-xs title="Click to Reject!" cursor: pointer; data-toggle="modal" data-target="#reject_reason_popup"  onclick=rejectionlabtest("' + emp.work_order_details_id + '","' + emp.work_order_id + '","' + emp.patientid + '",' + emp.is_lab + ',' + emp.master_service_id + ',"' + emp.visit_report_id + '",' + emp.serviceproviderid + ',"' + emp.wid + '",1,"' + emp.samplbarcodeid + '","phmsc")><i class="fa fa-ban mr-10" aria-hidden="true"></i>Reject</p>';
                            }
                            else if (tblname == 'pkhscjobtable') {
                                var taglab = '<p id="reject_' + i + '" class="btn btn-delete btn-xs"  title="Click to Reject!" cursor: pointer;  data-toggle="modal" data-target="#reject_reason_popup" onclick=rejectionlabtest("' + emp.work_order_details_id + '","' + emp.work_order_id + '","' + emp.patientid + '",' + emp.is_lab + ',' + emp.master_service_id + ',"' + emp.visit_report_id + '",' + emp.serviceproviderid + ',"' + emp.wid + '",1,"' + emp.samplbarcodeid + '","phmsc")><i class="fa fa-ban mr-10" aria-hidden="true"></i>Reject</p>';

                            }
                            else if (tblname == 'pkhscpendingapprovaltable') {
                                var taglab = '<p id="reject_' + i + '" class="btn btn-delete btn-xs"  title="Click to Reject!" cursor: pointer; data-toggle="modal" data-target="#reject_reason_popup"  onclick=rejectionlabtest("' + emp.work_order_details_id + '","' + emp.work_order_id + '","' + emp.patientid + '",' + emp.is_lab + ',' + emp.master_service_id + ',"' + emp.visit_report_id + '",' + emp.serviceproviderid + ',"' + emp.wid + '",2,"' + emp.samplbarcodeid + '","phmscP")><i class="fa fa-ban mr-10" aria-hidden="true"></i>Reject</p>';

                            }
                            if (emp.btnflag == 'Receive Sample') {

                                tr = tr + '<tr id="t_' + emp.work_order_id + '"><td><div class="col-md-12 padding0"><div class="disp_if"><button style="cursor:pointer;font-size:7px;" data-toggle="modal" data-target="#ldrecivie_samplepopup" class="btn btn-primaryuse btn-xs" onclick=ldlabrecivesample("' + emp.work_order_details_id + '","' + emp.work_order_id + '","' + emp.sampleid + '","' + emp.master_service_id + '","' + emp.statusflag + '","phmsc","2",4,"' + emp.samplbarcodeid + '","' + emp.hospitalid + '","' + emp.branch_id + '","' + emp.patientid + '","' + emp.patient_id + '","' + emp.visit_report_id + '")>' + emp.btnflag + '</button><a href="#" class="dropdown-toggle btn btn-info-dots btn-xs" data-toggle="dropdown" aria-expanded="true"><span class="fa fa-ellipsis-h" data-toggle="tooltip" data-placement="bottom" title="Other Options" style="color:black;" "cursor:pointer;" aria-hidden="true"></span><span class="sr-only">Options</span></a><div class="dropdown-menu info-dropdown-workorder" id=""><a style="text-align-last:start"; class="btn btn-xs" data-toggle="modal" data-target="#previous_results_modal" onclick=Patient_PreviousResult(' + emp.patientid + ')><i class="fa fa-eye mr-10"></i> Previous Results</a> ' + taglab + '</div></div> </td><td id="ldsamplbarcodeid_' + i + '">' + emp.samplbarcodeid + '</td><td class="tbl-name" id="ldtpatient_id_' + i + '">' + '<a data-toggle="modal" style="cursor: pointer;" data-target="#myModalPatientSearchDetails" onclick=\'billing_details(\"' + emp.patient_id + '\",\"' + emp.patient_username + '\",\"' + emp.phone_number_1 + '\",this)\'>' + emp.patient_username + " " + status_color + '</a>' + '<Span class="tbl_pno"><br>' + emp.patient_id + '</span></td><td id="ldtphone_number_1_' + i + '">' + emp.phone_number_1 + '<Span class="tbl_pno"><br>' + emp.paddress + '</span></td><td>' + emp.visit_type_name + '</td><td class="details-control" ' + sflg + ' onclick=servicedetailspackage(this,"' + emp.work_order_id + '","' + tblname + '","' + emp.package_auto_id + '","' + emp.wid + '",2);>' + '<span class="tbl-name">' + emp.service_count + '</span><Span class="tbl_wpkg"><br>' + (($.trim(emp.package_name) != '') ? emp.package_name + ' / ' + emp.package_id : emp.package_id) + '</span><i class="fa fa-angle-double-down table-arrow-size pull-right"></i></td><td>' + emp.doctorname + '</td><td>' + emp.package_purchased_date + '</td><td>' + emp.branch_name + '</td><td id="ldtvisit_report_id_' + i + '">' + (($.trim(emp.patientpreferdate) != '') ? emp.patientpreferdate + ' ' + ptime : ptime) + '</td><td id="ldtvisit_report_id_' + i + '">' + (($.trim(emp.scheduledate) != '') ? emp.scheduledate + ' ' + stime : stime) + '</td><td id="ldtvisit_report_id_' + i + '">' + emp.serviceprovidername + '</td><td id="ldtwork_order_no_' + i + '" data-id1=' + emp.is_lab + '>' + emp.work_order_no + '</td></tr>';
                            }
                            else {

                                tr = tr + '<tr id="t_' + emp.work_order_id + '"><td><div class="col-md-12 padding0"><div class="disp_if"><button style="cursor:pointer; font-size:7px;" data-toggle="modal" data-target="#result_popup" class="btn btn-primaryuse btn-xs" onclick=ldlabresult("' + emp.work_order_details_id + '","' + emp.work_order_id + '","' + emp.sampleid + '","' + emp.master_service_id + '","' + emp.statusflag + '","phmsc","2",4,"' + emp.samplbarcodeid + '","' + emp.hospitalid + '","' + emp.branch_id + '","' + emp.patientid + '","' + emp.patient_id + '","' + emp.visit_report_id + '")>' + emp.btnflag + '</button><a href="#" class="dropdown-toggle btn btn-info-dots btn-xs" data-toggle="dropdown" aria-expanded="true"><span class="fa fa-ellipsis-h" data-toggle="tooltip" data-placement="bottom" title="Other Options" style="color:black;" "cursor:pointer;" aria-hidden="true"></span><span class="sr-only">Options</span></a><div class="dropdown-menu info-dropdown-workorder" id=""><a style="text-align-last:start"; class="btn btn-xs" data-toggle="modal" data-target="#previous_results_modal" onclick=Patient_PreviousResult(' + emp.patientid + ')><i class="fa fa-eye mr-10"></i> Previous Results</a>' + taglab + ' </div></div> </td><td id="ldsamplbarcodeid_' + i + '">' + emp.samplbarcodeid + '</td><td class="tbl-name" id="ldtpatient_id_' + i + '">' + '<a data-toggle="modal" style="cursor: pointer;" data-target="#myModalPatientSearchDetails" onclick=\'billing_details(\"' + emp.patient_id + '\",\"' + emp.patient_username + '\",\"' + emp.phone_number_1 + '\",this)\'>' + emp.patient_username + " " + status_color + '</a>' + '<Span class="tbl_pno"><br>' + emp.patient_id + '</span></td><td id="ldtphone_number_1_' + i + '">' + emp.phone_number_1 + '<Span class="tbl_pno"><br>' + emp.paddress + '</span></td><td>' + emp.visit_type_name + '</td><td class="details-control" ' + sflg + ' onclick=servicedetailspackage(this,"' + emp.work_order_id + '","' + tblname + '","' + emp.package_auto_id + '","' + emp.wid + '",2);>' + '<span class="tbl-name">' + emp.service_count + '</span><Span class="tbl_wpkg"><br>' + (($.trim(emp.package_name) != '') ? emp.package_name + ' / ' + emp.package_id : emp.package_id) + '</span><i class="fa fa-angle-double-down table-arrow-size pull-right"></i></td><td>' + emp.doctorname + '</td><td>' + emp.package_purchased_date + '</td><td>' + emp.branch_name + '</td><td id="ldtvisit_report_id_' + i + '">' + (($.trim(emp.patientpreferdate) != '') ? emp.patientpreferdate + ' ' + ptime : ptime) + '</td><td id="ldtvisit_report_id_' + i + '">' + (($.trim(emp.scheduledate) != '') ? emp.scheduledate + ' ' + stime : stime) + '</td><td id="ldtvisit_report_id_' + i + '">' + emp.serviceprovidername + '</td><td id="ldtwork_order_no_' + i + '" data-id1=' + emp.is_lab + '>' + emp.work_order_no + '</td></tr>';
                            }
                        }

                    });

                    $('#' + tblname + 'body').html(tr);
                    datatable(tblname);


                }
            }
        }
    });
}

//load package hospital care compeleted
$('#spackagehospitalcompleted').click(function () {
    loadpackagehospitalcompleted(1);
    $('.asidefilterclass').addClass('hidden');
    $('#asidepkhsccompletedtable').removeClass('hidden');
    $('.groupclass').addClass('hidden');
    $('#asidepkhsccompletedtablegroupclass').removeClass('hidden');
    $('.Filterclass').addClass('hidden');
    $('#asidepkhsccompletedtableFilterclass').removeClass('hidden');
})
$('#phscmbtnreportfilter').click(function () {
    loadpackagehospitalcompleted(2);
})
$('#phscmbtnreportclear').click(function () {
    var hospitalid = $('#HospitalId').val();
    $('#phscmorderno').val('');
    $('#phscmsampleid').val('');
    $('#phscmorderdate').val('');
    $('#phscmordertodate').val('');
    Branchdetails(hospitalid);
    getserviceprovider(0);
    loadpackagehospitalcompleted(1);
})
function loadpackagehospitalcompleted(flag) {

    debugger;
    var servicevalues = {
        Dml_Indicator: "LPKHSCCM",
        flag: flag,
        samplbarcodeid: $('#phscmsampleid').val(),
        orderdate: $('#phscmorderdate').val(),
        ordertodate: $('#phscmordertodate').val(),
        orderno: $('#phscmorderno').val(),
        serviceprovidername: $('#phscmserviceprovidername').val(),
        branchid: $('#pkghscbranch_id').val(),
        departmentid: ($('#Hdepartment_id').val() == '') ? '' : $('#Hdepartment_id').val(),
        UserId: useridheder,
        spname: "SP_Work_Order_Hospital_CM",
    }
    $.ajax({
        async: true,
        type: 'POST',
        url: '/Workorder/Get_Workorder',
        contentType: 'application/json; charset=UTF-8',
        data: JSON.stringify(servicevalues),
        success: function (data) {
            debugger;

            var data = JSON.parse(data);
            console.log(data);
            if (data.msg == "Success") {
                var revert = '';
                var data1 = data.data;
                if (jQuery.isEmptyObject((data1))) {
                    tr = '';
                    $('#pkhsccompletedablebody').html(tr);
                }
                else {

                    var b = data1.Table;
                    $('#pkhsccompletedtablebody').empty();
                    $('#pkhsccompletedtable').dataTable().fnClearTable();
                    $('#pkhsccompletedtable').dataTable().fnDraw();
                    $('#pkhsccompletedtable').dataTable().fnDestroy();
                    tr = '';
                    var popupflagid, popupflag, onclickflag, sflg = '', comp_view = '', status_color = '';

                    $.each(b, function (i, emp) {
                        popupflag = emp.btnflag;
                        if (emp.scheduletime == '00:01') {
                            stime = '';
                        }
                        else {
                            stime = emp.scheduletime;
                        }

                        if (emp.Bill_status == "Paid") {
                            status_color = "<span style='background-color: green !important;color:white;font-size:10px;padding:3px;border-radius:4px;'>paid</span>";
                        }
                        else if (emp.Bill_status == "Due") {
                            status_color = "<span style='background-color: red !important;color:white;font-size:10px;padding:3px;border-radius:4px;'>Due</span>";
                        }
                        else if (emp.Bill_status == "Partial Due") {
                            status_color = "<span style='background-color: orange !important;color:white;font-size:10px;padding:3px;border-radius:4px;'>Partial paid</span>";
                        }
                        else {
                            status_color = '';
                        }


                        if (popupflag = 'View') {
                            comp_view = '<i class="fa fa-eye"></i>'
                        }

                        if (emp.is_lab == 2) {

                            tr = tr + '<tr id="t_' + emp.work_order_id + '"><td class="col-sm-1"><button style="cursor:pointer;" data-toggle="modal" data-target="#Assign" class="btn btn-eye btn-xs" title="View" onclick=pkgjobsdetails("' + emp.work_order_id + '","' + emp.master_service_id + '","phmc","D",' + emp.work_order_details_id + ',"' + emp.patient_id + '",' + emp.branch_id + ',"' + emp.visit_report_id + '")>' + comp_view + '</button> </td><td id="ldsamplbarcodeid_' + i + '">' + emp.samplbarcodeid + '</td><td class="tbl-name" id="ldtpatient_id_' + i + '">' + '<a data-toggle="modal" style="cursor: pointer;" data-target="#myModalPatientSearchDetails" onclick=\'billing_details(\"' + emp.patient_id + '\",\"' + emp.patient_username + '\",\"' + emp.phone_number_1 + '\",this)\'>' + emp.patient_username + " " + status_color + '</a>' + '<Span class="tbl_pno"><br>' + emp.patient_id + '</span></td><td id="ldtphone_number_1_' + i + '">' + emp.phone_number_1 + '<Span class="tbl_pno"><br>' + emp.paddress + '</span></td><td>' + emp.visit_type_name + '</td><td id="ldtservice_name_' + i + '" data-id=' + emp.master_service_id + ' data1-id=' + emp.is_lab + '>' + '<span class="tbl-name">' + emp.service_name + '</span><Span class="tbl_wpkg"><br>' + (($.trim(emp.package_name) != '') ? emp.package_name + ' / ' + emp.package_id : emp.package_id) + '</span></td><td>' + emp.package_purchased_date + '</td><td>' + emp.branch_name + '</td><td id="ldtvisit_report_id_' + i + '">' + (($.trim(emp.scheduledate) != '') ? emp.scheduledate + ' ' + stime : stime) + '</td><td id="ldtvisit_report_id_' + i + '">' + emp.serviceprovidername + '</td><td id="ldtwork_order_no_' + i + '">' + emp.work_order_no + '</td></tr>';
                        }
                        else if (emp.is_lab == 1) {

                            revert = '<button style="cursor:pointer;" class="btn btn-eye btn-xs revert" title="Hospital Care Revert"  data-toggle="modal" data-target="#reject_reason_popup"  onclick=WorkOrder_revert("' + emp.samplbarcodeid + '","phmsc")><i class="fa fa-ban fa-sm" aria-hidden="true"></i></button>';

                            tr = tr + '<tr id="t_' + emp.work_order_id + '"><td><button style="cursor:pointer;font-size:7px;" data-toggle="modal" data-target="#result_popup" class="btn btn-eye btn-xs" title="View" onclick=ldlabresult("' + emp.work_order_details_id + '","' + emp.work_order_id + '","' + emp.sampleid + '","' + emp.master_service_id + '","' + emp.btnflag + '","phmsc","2",4,"' + emp.samplbarcodeid + '","' + emp.hospitalid + '","' + emp.branch_id + '","' + emp.patientid + '","' + emp.patient_id + '","' + emp.visit_report_id + '")>' + comp_view + '</button>' + " " + revert + '</td><td id="ldsamplbarcodeid_' + i + '">' + emp.samplbarcodeid + '</td><td class="tbl-name" id="ldtpatient_id_' + i + '">' + '<a data-toggle="modal" style="cursor: pointer;" data-target="#myModalPatientSearchDetails" onclick=\'billing_details(\"' + emp.patient_id + '\",\"' + emp.patient_username + '\",\"' + emp.phone_number_1 + '\",this)\'>' + emp.patient_username + " " + status_color + '</a>' + '<Span class="tbl_pno"><br>' + emp.patient_id + '</span></td><td id="ldtphone_number_1_' + i + '">' + emp.phone_number_1 + '<Span class="tbl_pno"><br>' + emp.paddress + '</span></td><td>' + emp.visit_type_name + '</td><td class="details-control" ' + sflg + ' onclick=servicedetailspackage(this,"' + emp.work_order_id + '","pkhsccompletedtable","' + emp.package_auto_id + '","' + emp.wid + '",2);>' + emp.service_count + '</span><Span class="tbl_wpkg"><br>' + (($.trim(emp.package_name) != '') ? emp.package_name + ' / ' + emp.package_id : emp.package_id) + '</span><i class="fa fa-angle-double-down table-arrow-size pull-right"></i></td><td>' + emp.package_purchased_date + '</td><td>' + emp.branch_name + '</td><td id="ldtvisit_report_id_' + i + '">' + (($.trim(emp.scheduledate) != '') ? emp.scheduledate + ' ' + stime : stime) + '</td><td id="ldtvisit_report_id_' + i + '">' + emp.serviceprovidername + '</td><td id="ldtwork_order_no_' + i + '">' + emp.work_order_no + '</td></tr>';
                        }
                    });

                    $('#pkhsccompletedtablebody').html(tr);
                    var revertrights = data1.Table1;
                    if (revertrights[0].status == 0) {
                        $('.revert').addClass('hidden');
                    }
                    datatable('pkhsccompletedtable');


                }
            }
        }
    });
}
//load package hospital care cancelled 
$('#spackagehospitalcancelled').click(function () {

    loadpkghospitalcancelledservice(1);
    $('.asidefilterclass').addClass('hidden');
    $('#asidepkhsccancelledtable').removeClass('hidden');
    $('.groupclass').addClass('hidden');
    $('#asidepkhsccancelledtablegroupclass').removeClass('hidden');
    $('.Filterclass').addClass('hidden');
    $('#asidepkhsccancelledtableFilterclass').removeClass('hidden');
});
$('#phscnbtnreportfilter').click(function () {

    loadpkghospitalcancelledservice(2);
});
$('#phscnbtnreportclear').click(function () {
    var hospitalid = $('#HospitalId').val();
    $('#phscnorderno').val('');
    $('#phscnorderdate').val('');
    $('#phscnordertodate').val('');
    Branchdetails(hospitalid);
    loadpkghospitalcancelledservice(1);
});
function loadpkghospitalcancelledservice(flag) {


    var servicevalues = {
        Dml_Indicator: "LPKHSCCAN",
        flag: flag,
        orderdate: $('#phscnorderdate').val(),
        ordertodate: $('#phscnordertodate').val(),
        orderno: $('#phscnorderno').val(),
        branchid: $('#pkghscnbranch_id').val(),
        departmentid: ($('#Hdepartment_id').val() == '') ? '' : $('#Hdepartment_id').val(),
        UserId: useridheder,
        spname: "SP_Work_Order_Hospital_CN",
    }
    $.ajax({
        async: true,
        type: 'POST',
        url: '/Workorder/Get_Workorder',
        contentType: 'application/json; charset=UTF-8',
        data: JSON.stringify(servicevalues),
        success: function (data) {
            debugger;

            var data = JSON.parse(data);
            console.log(data);
            if (data.msg == "Success") {
                var data1 = data.data;
                if (jQuery.isEmptyObject((data1))) {
                    tr = '';
                    $('#pkhsccancelledtablebody').html(tr);
                }
                else {

                    var b = data1.Table;
                    $('#pkhsccancelledtablebody').empty();
                    $('#pkhsccancelledtable').dataTable().fnClearTable();
                    $('#pkhsccancelledtable').dataTable().fnDraw();
                    $('#pkhsccancelledtable').dataTable().fnDestroy();
                    tr = '';
                    var status_color = '';
                    $.each(b, function (i, emp) {

                        if (emp.Bill_status == "Paid") {
                            status_color = "<span style='background-color: green !important;color:white;font-size:10px;padding:3px;border-radius:4px;'>paid</span>";
                        }
                        else if (emp.Bill_status == "Due") {
                            status_color = "<span style='background-color: red !important;color:white;font-size:10px;padding:3px;border-radius:4px;'>Due</span>";
                        }
                        else if (emp.Bill_status == "Partial Due") {
                            status_color = "<span style='background-color: orange !important;color:white;font-size:10px;padding:3px;border-radius:4px;'>Partial paid</span>";
                        }
                        else {
                            status_color = '';
                        }

                        if (emp.refundflag == '1') {
                            if (emp.visit_type == '2') {

                                actions = '<a style="cursor:pointer;" onclick=iprefund() class="btn btn-edit btn-xs" title="Refund"><i class="fa fa-undo"></i></a>';
                            }
                            else {
                                actions = '<a style="cursor:pointer;" href="/BillingMaster/refund?Patient_Id=' + emp.patientid + "&Work_order_detailsid=" + emp.work_order_details_id + "&Billcode=" + emp.billing_no + "&refund_code=" + emp.billing_refund_code + "&billing_type=" + emp.billing_type + "&Branch_id=" + emp.branch_id + '"" class="btn btn-edit btn-xs" title="Refund"><i class="fa fa-undo"></i></a>';
                            }
                        }
                        else {
                            actions = 'Refunded'
                        }
                        tr = tr + '<tr id="t_' + emp.work_order_id + '"><td>' + actions + '</td><td id="ldtwork_order_no_' + i + '">' + emp.work_order_no + '</td><td id="ldtcreated_on_' + i + '">' + emp.created_on + '</td><td class="tbl-name" id="ldtpatient_id_' + i + '">' + '<a data-toggle="modal" style="cursor: pointer;" data-target="#myModalPatientSearchDetails" onclick=\'billing_details(\"' + emp.patient_id + '\",\"' + emp.patient_username + '\",\"' + emp.phone_number_1 + '\",this)\'>' + emp.patient_username + " " + status_color + '</a>' + '<Span class="tbl_pno"><br>' + emp.patient_id + '</span></td><td id="ldtphone_number_1_' + i + '">' + emp.phone_number_1 + '<Span class="tbl_pno"><br>' + emp.paddress + '</span></td><td>' + emp.visit_type_name + '</td><td id="ldtpatient_id_' + i + '">' + '<span class="tbl-name">' + emp.service_name + '</span><Span class="tbl_wpkg"><br>' + (($.trim(emp.package_name) != '') ? emp.package_name + ' / ' + emp.package_id : emp.package_id) + '</span></td><td id="ldtdoctorname_' + i + '">' + emp.doctorname + '</td><td id="ldtvisit_report_id_' + i + '">' + emp.visit_report_id + '</td><td>' + emp.branch_name + '</td><td>' + emp.reason + '</td></tr>';

                    });

                    $('#pkhsccancelledtablebody').html(tr);
                    // $('#pkhsccancelledtable').DataTable();
                    datatable('pkhsccancelledtable');


                }
            }
        }
    });
}

//# Start package hospital care turn around time
$('#spackagehospitalturnaroundtime').click(function () {
    loadpackagehspitaltat(1, "LPKHSCTAT", 2, 'pkhscturnaroundtimetable', 'tat');
    $('.asidefilterclass').addClass('hidden');
    $('#asidepkhscturnaroundtime').removeClass('hidden');
    $('.groupclass').addClass('hidden');
    $('#asidepkhscturnaroundtimegroupclass').removeClass('hidden');
    $('.Filterclass').addClass('hidden');
    $('#asidepkhscturnaroundtimeFilterclass').removeClass('hidden');
});

$('#phstatbtnreportfilter').click(function () {
    loadpackagehspitaltat(2, "LPKHSCTAT", 1, 'pkhscturnaroundtimetable', 'tat');
})
$('#phstatbtnreportclear').click(function () {
    var hospitalid = $('#HospitalId').val();
    $('#phstatrderno').val('');
    $('#phstatampleid').val('');
    $('#phstatchedulestatus').val('');
    $('#phstatrderdate').val('');
    $('#phstatrdertodate').val('');
    $('#phstatsampleid').val('');
    $('#phstatorderno').val('');

    $('#phstatorderdate').val('');
    $('#phstatordertodate').val('');

    Branchdetails(hospitalid);
    getserviceprovider(0);
    loadpackagehspitaltat(1, "LPKHSCTAT", 1, 'pkhscturnaroundtimetable', 'tat');
})
function loadpackagehspitaltat(flag, indicator, wstatus, tblname, filtername) {

    debugger;
    var servicevalues = {
        Dml_Indicator: indicator,
        flag: flag,
        samplbarcodeid: $('#phs' + filtername + 'sampleid').val(),
        orderdate: $('#phs' + filtername + 'orderdate').val(),
        ordertodate: $('#phs' + filtername + 'ordertodate').val(),
        orderno: $('#phs' + filtername + 'orderno').val(),
        jobsflag: $('#phs' + filtername + 'schedulestatus').val(),
        branchid: $('#pkghs' + filtername + 'branch_id').val(),
        //serviceprovidername: $('#pkhs' + filtername + 'serviceprovidername').val(),
        work_order_status: wstatus,
        departmentid: ($('#Hdepartment_id').val() == '') ? '' : $('#Hdepartment_id').val(),
        UserId: useridheder,
        spname: "SP_Work_Order_Hospital_TAT",
    }
    $.ajax({
        async: true,
        type: 'POST',
        url: '/Workorder/Get_Workorder',
        contentType: 'application/json; charset=UTF-8',
        data: JSON.stringify(servicevalues),
        success: function (data) {
            debugger;

            var data = JSON.parse(data);
            console.log(data);
            if (data.msg == "Success") {
                var data1 = data.data;
                if (jQuery.isEmptyObject((data1))) {
                    tr = '';
                    $('#' + tblname + 'body').html(tr);
                }
                else {

                    var b = data1.Table;
                    $('#' + tblname + 'body').empty();
                    $('#' + tblname + '').dataTable().fnClearTable();
                    $('#' + tblname + '').dataTable().fnDraw();
                    $('#' + tblname + '').dataTable().fnDestroy();
                    tr = '';
                    var popupflagid, popupflag, onclickflag, sflg = '';

                    $.each(b, function (i, emp) {
                        popupflag = emp.btnflag;
                        if (emp.color == "red") {
                            color = 'tabletxtcolorred';
                        }
                        else if (emp.color == "green") {
                            color = 'tabletxtcolorgreen'
                        }

                        if (emp.is_lab == 2) {

                            tr = tr + '<tr id="t_' + emp.work_order_id + '"><td id="ldtwork_order_no_' + i + '"  class="' + color + '">' + emp.work_order_no + '</td><td class="' + color + '">' + emp.samplbarcodeid + '</td><td id="ldtpatient_id_' + i + '" class="' + color + '">' + emp.patient_id + '/' + '<a data-toggle="modal" style="cursor: pointer;" data-target="#myModalPatientSearchDetails" onclick=\'billing_details(\"' + emp.patient_id + '\",\"' + emp.patient_username + '\",\"' + emp.phone_number_1 + '\",this)\'>' + emp.patient_username + '</a>' + '</td><td id="ldtphone_number_1_' + i + '" class="' + color + '">' + emp.phone_number_1 + '-' + emp.paddress + '</td><td id="ldtservice_name_' + i + '" data-id=' + emp.master_service_id + ' data1-id=' + emp.is_lab + ' class="' + color + '">' + emp.service_name + '</td><td id="ldtpackage_id_' + i + '" class="' + color + '">' + emp.package_id + '</td><td id="ldtpackage_name_' + i + '" class="' + color + '">' + emp.package_name + '</td><td class="' + color + '">' + emp.branch_name + '</td><td id="ldtvisit_report_id_' + i + '" class="' + color + '">' + emp.schdulewaittime + '</td><td id="ldtvisit_report_id_' + i + '" class="' + color + '">' + emp.Assignwaittime + '</td><td id="ldtvisit_report_id_' + i + '" class="' + color + '">' + emp.collectsamplewaittime + '</td><td id="ldtvisit_report_id_' + i + '" class="' + color + '">' + emp.receivedwaittime + '</td><td id="ldsamplbarcodeid_' + i + '" class="' + color + '">' + emp.Addresultwaittime + '</td><td class="' + color + '">' + emp.verifiedwaittime + '</td><td class="' + color + '">' + emp.completedwaittime + '</td><td class="' + color + '">' + emp.Duration + '</td><td class="' + color + '">' + emp.delaytime + '</td></tr>';
                        }
                        else if (emp.is_lab == 1) {

                            tr = tr + '<tr id="t_' + emp.work_order_id + '"><td id="ldtwork_order_no_' + i + '" class="' + color + '">' + emp.work_order_no + '</td><td class="' + color + '"> ' + emp.samplbarcodeid + '</td><td id="ldtpatient_id_' + i + '" class="' + color + '">' + emp.patient_id + '/' + '<a data-toggle="modal" style="cursor: pointer;" data-target="#myModalPatientSearchDetails" onclick=\'billing_details(\"' + emp.patient_id + '\",\"' + emp.patient_username + '\",\"' + emp.phone_number_1 + '\",this)\'>' + emp.patient_username + '</a>' + '</td><td id="ldtphone_number_1_' + i + '" class="' + color + '">' + emp.phone_number_1 + '-' + emp.paddress + '</td><td id="ldtservice_name_' + i + '" data-id=' + emp.master_service_id + ' data1-id=' + emp.is_lab + ' class="' + color + '">' + emp.service_name + '</td><td id="ldtpackage_id_' + i + '" class="' + color + '">' + emp.package_id + '</td><td id="ldtpackage_name_' + i + '" class="' + color + '">' + emp.package_name + '</td><td class="' + color + '">' + emp.branch_name + '</td><td id="ldtvisit_report_id_' + i + '" class="' + color + '">' + emp.schdulewaittime + '</td><td id="ldtvisit_report_id_' + i + '" class="' + color + '">' + emp.Assignwaittime + '</td><td id="ldtvisit_report_id_' + i + '" class="' + color + '">' + emp.collectsamplewaittime + '</td><td id="ldtvisit_report_id_' + i + '" class="' + color + '">' + emp.receivedwaittime + '</td><td id="ldsamplbarcodeid_' + i + '" class="' + color + '">' + emp.Addresultwaittime + '</td><td class="' + color + '">' + emp.verifiedwaittime + '</td><td class="' + color + '">' + emp.completedwaittime + '</td><td class="' + color + '">' + emp.Duration + '</td><td class="' + color + '">' + emp.delaytime + '</td></tr>';

                        }


                    });

                    $('#' + tblname + 'body').html(tr);
                    datatable(tblname);

                }
            }
        }
    });
}
//# end package hospital care turn around time



//end package hospital care

//Show/hide service subtable
function servicedetailspackage(e, id, flag, pkid, wid, deleteflag) {
    // alert('test')
    debugger;
    var flag1 = "", jobsfllag = "";

    var tr = e.closest('tr');
    if (flag == 'pkghmcorders') {

        flag1 = "phmc";
        jobsflag = 4;
        var row = $('#pkhmcordertable').DataTable().row(tr);
    }
    else if (flag == 'pkghmcunsched') {
        var row = $('#pkhmcunscheduledtable').DataTable().row(tr);
        jobsflag = 4;
    }
    else if (flag == 'pkghmccs') {
        var row = $('#pkhmccollectsamplestable').DataTable().row(tr);
        jobsflag = 4;
    }
    else if (flag == 'pkghmcunass') {
        var row = $('#pkhmcunassignedtable').DataTable().row(tr);
        jobsflag = 5;
    }
    else if (flag == 'diaorder') {
        var row = $('#labordertable').DataTable().row(tr);
        jobsflag = 2;
    }
    else if (flag == 'lhorder') {
        var row = $('#lhordertable').DataTable().row(tr);

    }
    else if (flag == 'pkghsccs') {
        flag1 = "phsc";
        var row = $('#pkhsccollectsamplestable').DataTable().row(tr);
        jobsflag = 1;
    }
    else if (flag == 'pkghscunsched') {
        flag1 = "phsc";
        var row = $('#pkhscunscheduledtable').DataTable().row(tr);
        jobsflag = 2;
    }
    else if (flag == 'pkghscunass') {
        flag1 = "phsc";
        var row = $('#pkhscunassignedtable').DataTable().row(tr);
        jobsflag = 3;
    }
    else if (flag == 'pkghscorders') {

        flag1 = "phsc";
        var row = $('#pkhscordertable').DataTable().row(tr);
        jobsflag = 1;
    }
    else if (flag == 'pkghscadvice') {
        var row = $('#pkhscadvicetable').DataTable().row(tr);
        jobsflag = 1;
    }
    else if (flag == 'pkhscjobtable') {
        var row = $('#pkhscjobtable').DataTable().row(tr);
        jobsflag = 6;
    }
    else if (flag == 'pkhscreceivesampletable') {
        var row = $('#pkhscreceivesampletable').DataTable().row(tr);
        jobsflag = 6;
    }
    else if (flag == 'pkhscpendingapprovaltable') {
        var row = $('#pkhscpendingapprovaltable').DataTable().row(tr);
        jobsflag = 6;
    }
    else if (flag == 'pkhsccompletedtable') {
        var row = $('#pkhsccompletedtable').DataTable().row(tr);
        jobsflag = 6;
    }
    else if (flag == 'pkhscordertable') {
        var row = $('#pkhscordertable').DataTable().row(tr);
        jobsflag = 6;
    }
    else if (flag == 'pkhmcordertable') {
        var row = $('#pkhmcordertable').DataTable().row(tr);
        jobsflag = 6;
    }
    else if (flag == 'pkhmcjobtable') {
        var row = $('#pkhmcjobtable').DataTable().row(tr);
        jobsflag = 7;
    }
    else if (flag == 'pkhmcreceivesampletable') {
        var row = $('#pkhmcreceivesampletable').DataTable().row(tr);
        jobsflag = 7;
    }
    else if (flag == 'pkhmcpendingapprovaltable') {
        var row = $('#pkhmcpendingapprovaltable').DataTable().row(tr);
        jobsflag = 7;
    }
    else if (flag == 'pkhmccompletedtable') {
        var row = $('#pkhmccompletedtable').DataTable().row(tr);
        jobsflag = 7;
    }

    console.log(row);
    //var row = $('#request_view').DataTable().row(tr);

    if (row.child.isShown()) {
        // This row is already open - close it
        row.child.hide();
        // tr.removeClass('shown');
    }
    else {
        // Open this row
        row.child(getservicedetailspackage(id, wid, pkid, deleteflag, flag1)).show();
        //  tr.addClass('shown');
    }
}
//getting service details for subtable
function getservicedetailspackage(id, wid, pkid, deleteflag, flag1) {
    debugger;
    div = $('<div/>')
        .addClass('loading')
        .addClass('table_child')
        .addClass('table-responsive');
    var service_data = {
        work_orderid: id,
        //flag: wtype,
        //jobsflag: jobsflag,
        //barcodeid: (pkid=='') ? 0 : pkid,
        samplbarcodeid: wid,
        //serviceproviderid: spid,
        Dml_Indicator: 'SDP',
        spname: "SP_Work_Order_Action",
        //work_order_status: (work_order_status=='') ? 0 : work_order_status ,
        //scheduledate: (patientpreferdate == undefined) ? 0 : patientpreferdate,
        //departmentid: departmentideader
    }
    $.ajax({
        async: true,
        type: 'POST',
        url: '/Workorder/Get_Workorder',
        contentType: 'application/json; charset=UTF-8',
        data: JSON.stringify(service_data),
        success: function (data) {
            debugger;
            var data = JSON.parse(data);
            console.log(data);
            if (data.msg == "Success") {
                var data1 = data.data;
                var tr = '', j = 1;

                if (jQuery.isEmptyObject((data1))) {
                }

                else {
                    div.removeClass('loading')

                    var row = 2;
                    var tr, row_data;
                    tr = $('<table class="table table-bordered table-hover dt-responsive">');
                    if (deleteflag == '1') {
                        if (pkid == 0) {
                            tr.append('<thead><tr class="info"><th>S.No</th><th>Service Code</th><th>Service Name</th><th>Number of Usage</th><th>Reason</th><th>Delete</th></tr></thead><tbody>');
                            $.each(data1.Table, function (i, emp) {

                                row_data = '<tr id="t_' + emp.work_order_details_id + '"><td>' + j + '</td><td>' + emp.service_code + '</td><td>' + emp.service_name + '</td><td>' + emp.quantity + '</td><td><textarea id="reason_' + emp.work_order_details_id + '"></textarea></td><td><a id="servicedel_' + emp.work_order_details_id + '" class="btn deleteicon-btn btn-xs" href="javascript:void(0);" onclick=servicedel("' + emp.work_order_details_id + '",3,"' + flag1 + '","' + emp.package_id + '","' + id + '")><i class="fa fa-trash" aria-hidden="true"></i></a></td></tr>';

                                j = j + 1;
                                tr.append(row_data);
                            })
                        }

                        else {
                            tr.append('<thead><tr class="info"><th>S.No</th><th>Service Code</th><th>Service Name</th><th>Number of Usage</th></tr></thead><tbody>');
                            $.each(data1.Table, function (i, emp) {
                                row_data = '<tr id="t_' + emp.work_order_details_id + '"><td>' + j + '</td><td>' + emp.service_code + '</td><td>' + emp.service_name + '</td><td>' + emp.quantity + '</td></tr>';
                                j = j + 1;
                                tr.append(row_data);
                            })
                        }
                    }
                    else {
                        tr.append('<thead><tr class="info"><th>S.No</th><th>Service Code</th><th>Service Name</th><th>Number of Usage</th></tr></thead><tbody>');
                        $.each(data1.Table, function (i, emp) {
                            row_data = '<tr id="t_' + emp.work_order_details_id + '"><td>' + j + '</td><td>' + emp.service_code + '</td><td>' + emp.service_name + '</td><td>' + emp.quantity + '</td></tr>';
                            j = j + 1;
                            tr.append(row_data);
                        })
                    }
                    tr.append("</tbody>");

                    div.append(tr);

                }
            }
            else {
                console.log(data);
            }
        }
    });
    return div;
}
$('#pkghsabranch_id').change(function () {
    var val = $('#pkghsabranch_id').val();
    LoadDoctor(val);
})

//Calls the file Upload function 
var PayerDocumentsCount = 0;
$('#fileToUpload').change(function () {
    debugger;
    packageimageupload();

});

//To Upload Image
function packageimageupload() {
    debugger;
    //$('#docpathvalue').val('');
    //$('#photolog').va('')
    var uploadpath = $('#fileToUpload').val();
    var fileExtension = uploadpath.substring(uploadpath.lastIndexOf(".") + 1, uploadpath.length);
    //if (fileExtension == "pdf" || fileExtension == "doc" || fileExtension == "PDF" || fileExtension == "DOC") {
    //}
    //else {
    //    $('#PReferraldocuments').show();
    //    $('#PReferraldocuments').fadeOut(8000);
    //    $('#PReferraldocuments').html('Please upload file having extensions .pdf/.doc only.');
    //    $('#fileToUpload').val("");
    //    $('#fileToUpload').focus();
    //    return false;
    //}

    if (window.FormData !== undefined) {
        debugger;
        var fileUpload = $("#fileToUpload").get(0);
        var files = fileUpload.files;
        var fileData = new FormData();
        fileData.append($('#txtPatientName').val(), '');
        var files = fileUpload.files;
        if (files[0].size > 5e+6) {
            //alert("up to 5 MB per file!");
            toastr.warning('up to 5 MB per file!');
            return false;
        };
        var filePath = fileUpload.value;

        // Allowing file type
        var allowedExtensions =
            /(\.jpg|\.jpeg|\.pdf)$/i;

        if (!allowedExtensions.exec(filePath)) {
            toastr.warning('Invalid File Type');
            fileInput.value = '';
            return false;
        }
        var id;
        if (fileExtension == "pdf" || fileExtension == "PDF") {
            id = "1";
        }
        else {
            id = "2";
        }
        fileData.append(id, '');
        for (var i = 0; i < files.length; i++) {
            fileData.append(files[i].name, files[i]);
        }


        $.ajax({
            url: '/Workorder/UploadIDProof?branch_id=' + $('#popbranchid').val(),
            type: "POST",
            contentType: false,
            processData: false,
            data: fileData,
            success: function (result) {
                debugger;
                $.each(result, function (i, emp) {
                    debugger;
                    var pathName = ($.trim($('#docpathvalue').val()));
                    if (pathName !== "") {
                        pathName = pathName + "," + result.img;
                    }
                    else {
                        pathName = result.img;
                    }
                    console.log(pathName);
                    $('#docpathvalue').val(pathName);
                    $('#photolog').text('');
                    $('#photolog').append('<a href="' + $('#hdnfilepath1').val() + $('#HospitalId').val() + "/" + $('#popbranchid').val() + "/Lab_Documents/" + pathName + '" target="_blank">' + pathName + '</a>');
                });
            }
        });
    }
}
//previous  lab result 
function Patient_PreviousResult(patientid) {
    $('#Previous_results_table_body').empty();
    var servicevalues = {
        Dml_Indicator: 'PRH',
        patientid: patientid,
        spname: "SP_Work_Order_Action",

    }
    $.ajax({
        async: true,
        type: 'POST',
        url: '/Workorder/Get_Workorder',
        contentType: 'application/json; charset=UTF-8',
        data: JSON.stringify(servicevalues),
        success: function (data) {
            debugger;
            $('#Previous_results_table_body').empty();
            var data = JSON.parse(data);
            console.log(data);
            if (data.msg == "Success") {
                var data1 = data.data;
                if (jQuery.isEmptyObject((data1))) {


                }
                else {
                    var tr = '';
                    $('#Previous_results_table_body').empty();
                    $('#previous_results_iptable').dataTable().fnClearTable();
                    $('#previous_results_iptable').dataTable().fnDraw();
                    $('#previous_results_iptable').dataTable().fnDestroy();
                    $.each(data1.Table, function (i, emp) {
                        tr = tr + '<tr><td>' + emp.patient_name + '</td><td>' + emp.visitdate + '</td><td>' + emp.visit_type + '</td><td>' + emp.display_visit_report + '</td><td>' + emp.work_order_no + '</td><td onclick=jobprintpreviousresult(this,"' + emp.visit_reportid + '","' + emp.work_order_id + '","' + emp.hospitalid + '","' + emp.branch_id + '","' + emp.patientid + '")><i class="fa fa-eye"></i></td></tr>';
                    });

                    $('#Previous_results_table_body').html(tr);

                    datatable('previous_results_iptable')
                }
            }
        }
    });
}
function jobprintpreviousresult(e, visit_reportid, work_order_id, hospitalid, branch_id, patientid) {

    var load_data = {
        formid: "109",
        branchid: branch_id,
        hospitalid: hospitalid,
        work_order_id: work_order_id,
        patientid: patientid,
        barcodeid: 0,
        masterserviceid: 0,
        visit_reportid: visit_reportid
    }

    $.ajax({
        async: true,
        type: 'POST',
        url: '/reports/PrintCrystalReport',
        contentType: 'application/json; charset=UTF-8',
        data: JSON.stringify(load_data),
        success: function (data) {
            var byteArray = new Uint8Array(data);
            var blob = new Blob([byteArray], { type: "application/pdf" });
            var link = window.URL.createObjectURL(blob);
            window.open(link, '_blank');

        }
    });
}


$('#chkallbar').change(function (event) {
    debugger;
    if (this.checked) {
        $('.chksampleclass').prop("checked", true);
        //$(".chksampleclass").checked = true;
    }
    else {
        $('.chksampleclass').prop("checked", false);
    }

})
$('#chkallbarrec').change(function (event) {
    debugger;
    if (this.checked) {
        $('.chksampleclass').prop("checked", true);
        //$(".chksampleclass").checked = true;
    }
    else {
        $('.chksampleclass').prop("checked", false);
    }

})

$('#pkghsrsbranch_id').change(function () {
    debugger;
    var branch_id = $('#pkghsrsbranch_id').val();
    ServiceProviderdetails(branch_id)
})
$('#pkghscollectsamplesbranch_id').change(function () {
    debugger;
    var branch_id = $('#pkghscollectsamplesbranch_id').val();
    ServiceProviderdetails(branch_id)
})
$('#pkghsjobranch_id').change(function () {
    debugger;
    var branch_id = $('#pkghsjobranch_id').val();
    ServiceProviderdetails(branch_id)
})
$('#pkghscbranch_id').change(function () {
    debugger;
    var branch_id = $('#pkghscbranch_id').val();
    ServiceProviderdetails(branch_id)
})
$('#pkghstatbranch_id').change(function () {
    debugger;
    var branch_id = $('#pkghstatbranch_id').val();
    ServiceProviderdetails(branch_id)
})

function ServiceProviderdetails(branch_id) {
    $('.phsrsserviceprovidername').empty();
    debugger;
    var ServiceProvider = {
        spname: "SP_Work_Order_Action",
        branchid: branch_id,
        Dml_Indicator: 'WOSP'
    }
    $.ajax({
        async: true,
        type: 'POST',
        url: '/Workorder/Get_Workorder',
        contentType: 'application/json; charset=UTF-8',
        data: JSON.stringify(ServiceProvider),
        success: function (data) {

            var data1 = JSON.parse(data);
            if (data1.msg == "Success") {
                var data1 = data1.data;
                console.log(data1);
                if (jQuery.isEmptyObject((data1))) {
                }
                else {
                    debugger;
                    var SubDepartment = '';
                    var default_opt = '<option value="0">--Select--</option>';
                    $.each(data1.Table, function (i, emp) {
                        SubDepartment = SubDepartment + '<option value="' + emp.labtranid + '">' + emp.lab_name + '</option>';
                    });
                    if (data1.Table.length == 1) {
                        $('.phsrsserviceprovidername').append(SubDepartment);
                        //$('#phsjoserviceprovidername').append(SubDepartment);
                        //$('#phscmserviceprovidername').append(SubDepartment);
                        //$('#phstatserviceprovidername').append(SubDepartment);
                    }
                    else {
                        $('.phsrsserviceprovidername').append(default_opt + SubDepartment);
                        //$('#phsjoserviceprovidername').append(default_opt + SubDepartment);
                        //$('#phscmserviceprovidername').append(default_opt + SubDepartment);
                        //$('#phstatserviceprovidername').append(default_opt + SubDepartment);
                    }
                }
            }
            else {
                console.log(data1);
            }

        }
    });
}


$('#Completed_print').click(function () {
    debugger;
    var work_order_detail_id = $('#work_order_details_id').val()
    var work_orderid = $('#work_order_id').val()

    var load_data = {
        formid: '135',
        hospitalid: $('#HospitalId').val(),
        work_order_id: work_orderid,
        work_order_details_id: work_order_detail_id,
    }
    $.ajax({
        async: true,
        type: 'POST',
        url: '/reports/PrintCrystalReport',
        contentType: 'application/json; charset=UTF-8',
        responseType: 'arraybuffer',
        data: JSON.stringify(load_data),
        success: function (data) {
            debugger;
            console.log(data);
            //var arrrayBuffer = base64ToArrayBuffer(data);
            var byteArray = new Uint8Array(data);
            var blob = new Blob([byteArray], { type: "application/pdf" });
            var link = window.URL.createObjectURL(blob);
            //window.open(link, '_blank');   // to open in new window

            iframe = document.createElement('iframe');
            document.body.appendChild(iframe);

            iframe.style.display = 'none';

            iframe.src = link;
            iframe.onload = function () {
                setTimeout(function () {
                    iframe.focus();
                    iframe.contentWindow.print();
                }, 1);
            };
        }
    });
})


$('#ldaddresultreject').click(function () {
    debugger;
    var tot_rowM = $('#ldlabrsultParameters >tbody >tr').length;
    var barcode = new Array();
    var samplecode = new Array();
    if (tot_rowM > 0) {
        var L = 0;
        var rk = 0;
        for (rk = 0; rk <= tot_rowM; rk++) {
            var customer = {};
            var samplebarcodeid = {};
            var isChecked = $('#chks_' + rk).is(":checked");
            if (isChecked) {

                var val = $('#ldobsval_' + rk).val();
                if (val != '') {
                    toastr.warning('The result value already entered,so you cannot reject this sample');

                    return;
                }
                var barno = $('#master_service_id_' + rk).html();
                var sampleno = $('#samplebarid_' + rk).html();
                if (barno != 0) {
                    customer.barcodeno = barno;
                    barcode.push(customer);
                }
                samplebarcodeid.samplecodeno = sampleno;
                samplecode.push(samplebarcodeid);
            }
        }
    }
    let masterserviceid = barcode.map(x => x.barcodeno).join(",");
    let popsampleid = samplecode.map(x => x.samplecodeno).join(",");
    var btnval = $("#ldaddresult").val();
    var tabflagad = $('#tapflagad').val();
    if (masterserviceid != "") {
        $('#rejsamplebarcodeid').val(popsampleid);
        $('#rejserviceproviderid').val(masterserviceid);
        $('#rejdmlflag').val('LLDLP');
        $('#rejtabflag1').val('Rejectresult');
        $('#rejtabflag').val('phmsc');
        $('#reject_reason_popup').modal('toggle');
    }
    else {
        toastr.warning('Please Select Any One Check Box')
    }
});




$('#ldpendingareject').click(function () {
    debugger;
    var tot_rowM = $('#ldlabrsultParameters >tbody >tr').length;
    var barcode = new Array();
    var samplecode = new Array();
    if (tot_rowM > 0) {
        var L = 0;
        var rk = 0;
        for (rk = 0; rk <= tot_rowM; rk++) {
            var customer = {};
            var samplebarcodeid = {};
            var isChecked = $('#chks_' + rk).is(":checked");
            if (isChecked) {
                var barno = $('#master_service_id_' + rk).html();
                var sampleno = $('#samplebarid_' + rk).html();
                if (barno != 0) {
                    customer.barcodeno = barno;
                    barcode.push(customer);
                }
                samplebarcodeid.samplecodeno = sampleno;
                samplecode.push(samplebarcodeid);
            }
        }
    }
    let masterserviceid = barcode.map(x => x.barcodeno).join(",");
    let popsampleid = samplecode.map(x => x.samplecodeno).join(",");
    var btnval = $("#ldaddresult").val();
    var tabflagad = $('#tapflagad').val();

    $('#rejsamplebarcodeid').val(popsampleid);
    $('#rejserviceproviderid').val(masterserviceid);
    $('#rejdmlflag').val('LLDLP');
    $('#rejtabflag').val('phmsc');
    $('#rejtabflag1').val('Rejectpending');
    $('#reject_reason_popup').modal('toggle');
});

$('#ldcompletedreject').click(function () {
    debugger;
    var tot_rowM = $('#ldlabrsultParameters >tbody >tr').length;
    var barcode = new Array();
    var samplecode = new Array();
    if (tot_rowM > 0) {
        var L = 0;
        var rk = 0;
        for (rk = 0; rk <= tot_rowM; rk++) {
            var customer = {};
            var samplebarcodeid = {};
            var isChecked = $('#chks_' + rk).is(":checked");
            if (isChecked) {
                var barno = $('#master_service_id_' + rk).html();
                var sampleno = $('#samplebarid_' + rk).html();
                if (barno != 0) {
                    customer.barcodeno = barno;
                    barcode.push(customer);
                }
                samplebarcodeid.samplecodeno = sampleno;
                samplecode.push(samplebarcodeid);
            }
        }
    }
    let masterserviceid = barcode.map(x => x.barcodeno).join(",");
    let popsampleid = samplecode.map(x => x.samplecodeno).join(",");
    var btnval = $("#ldaddresult").val();
    var tabflagad = $('#tapflagad').val();
    $('#rejsamplebarcodeid').val(popsampleid);
    $('#rejserviceproviderid').val(masterserviceid);
    $('#rejdmlflag').val('LLDLP');
    $('#rejtabflag').val('phmsc');
    $('#rejtabflag1').val('Rejectcompleted');

    $('#reject_reason_popup').modal('toggle');

});


$('#ldcrjectsample').click(function () {
    debugger;
    var tot_rowM = $('#ldcsampletablerecive >tbody >tr').length;
    var barcode = new Array();
    var samplecode = new Array();
    if (tot_rowM > 0) {
        var L = 0;
        var rk = 0;
        for (rk = 0; rk <= tot_rowM; rk++) {
            var customer = {};
            var samplebarcodeid = {};
            var isChecked = $('#chkrec_' + rk).is(":checked");
            if (isChecked) {
                var barno = $('#trmaster_service_id_' + rk).html();
                var sampleno = $('#tldcsamplebadrcode_' + rk).html();
                if (barno != 0) {
                    customer.barcodeno = barno;
                    barcode.push(customer);
                }
                samplebarcodeid.samplecodeno = sampleno;
                samplecode.push(samplebarcodeid);
            }
        }
    }

    let masterserviceid = barcode.map(x => x.barcodeno).join(",");
    let popsampleid = samplecode.map(x => x.samplecodeno).join(",");
    var btnval = $("#ldaddresult").val();
    var tabflagad = $('#tapflagad').val();
    if (masterserviceid != "") {
        $('#rejsamplebarcodeid').val(popsampleid);
        $('#rejserviceproviderid').val(masterserviceid);
        $('#rejdmlflag').val('LLDLP');
        $('#rejtabflag').val('phmsc');
        $('#rejtabflag1').val('Reject');
        $('#reject_reason_popup').modal('toggle');
    }
    else {
        toastr.warning('Please Select Any One Check Box');
    }


});
function rejectionlabtest(work_order_details_id, work_order_id, patientid, is_lab, master_service_id, visit_report_id, serviceproviderid, wid, tabflag, samplebarcodeid, tflag) {
    debugger;
    $('#rejsamplebarcodeid').val(samplebarcodeid);
    $('#rejwork_order_details_id').val(work_order_details_id);
    $('#rejwork_order_id').val(work_order_id);
    $('#rejis_lab').val(is_lab);
    $('#rejserviceproviderid').val(serviceproviderid);
    $('#rejjobflag').val(tabflag);
    $('#rejtabflag').val(tflag);
    $('#rejwid').val(wid);
    $('#rejdmlflag').val('RLT');

}
function WorkOrder_revert(samplbarcodeid, tabflagad) {
    debugger;
    $('#rejsamplebarcodeid').val(samplbarcodeid);
    $('#rejtabflag').val(tabflagad);
    $('#rejdmlflag').val('WORVT');
    $('#rejserviceproviderid').val('0');
    //$('#reject_reason_popup').modal('toggle');

}
$('#rejectbtn').click(function () {
    {
        reason = $("#rejectreason").val();
        if (reason == '' || reason == "0") {
            toastr.warning('Please select reason');
            $("#deletereason").focus()
            return;

        }


        var tabflagad = $('#rejtabflag').val();
        debugger;
        var rejdmlflag = $('#rejdmlflag').val();
        var rejserviceproviderid = $('#rejserviceproviderid').val();
        if (rejdmlflag == 'RLT') {
            msg = "Are You Sure Do You Want Reject";
            toastr.warning("<button type='button' id='confirmationRevertYes' class='btn btn-warning btn-xs mt20'>Yes<button type='button' id='confirmationRevertNo' class='btn btn-warning btn-xs mt20'>No", msg,
                {
                    closeButton: true,
                    progressBar: true,
                    allowHtml: true,
                    timeOut: 20000000,

                    onShown: function (toast) {
                        $("#confirmationRevertYes").click(function () {
                            debugger;
                            var servicevalues = {
                                Dml_Indicator: $('#rejdmlflag').val(),
                                samplbarcodeid: $('#rejsamplebarcodeid').val(),
                                work_order_details_id: $('#rejwork_order_details_id').val(),
                                work_orderid: $('#rejwork_order_id').val(),
                                serviceproviderid: rejserviceproviderid,
                                is_lab: $('#rejis_lab').val(),
                                spname: "SP_Work_Order_Action",
                                flag: $('#rejjobflag').val(),
                                serviceprovidername: $('#rejwid').val(),
                                UserId: $('#hiddenUser_id').val(),
                                created_by: $('#hiddenUser_id').val(),
                                servicename: $('#rejectreason option:selected').data('id'),
                                request_id: $('#rejectreason').val(),

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

                                        toastr.success("Sample Rejected Successfully");
                                        //$('#reject_reason_popup').hide();
                                        $('#reject_reason_popup').modal('toggle');
                                        getrejectreason();
                                        if (tabflagad == 'phmsc') {
                                            $("#spackagehospitalcollectsamples").tab('show');
                                            loadpackagehospitalcollectsamples(1);
                                        }
                                        else if (tabflagad == 'phmscP') {
                                            $("#spackagehospitaljobs").tab('show');
                                            loadpackagehospitaljobs(1, "LPKHSCJ", 1, 'pkhscjobtable', 'jo');
                                        }
                                        else if (tabflagad == 'phmc') {
                                            $("#spackagehomecollectsamples").tab('show');
                                            loadpackagehomecollectsamples(1);
                                        }
                                    }
                                }
                            })
                        });
                    }
                });
        }
        else if (rejdmlflag == 'LLDLP') {


            $('#rejsamplebarcodeid').val();
            $('#rejserviceproviderid').val();

            toastr.warning("<button type='button' id='confirmationRevertYes' class='btn btn-warning btn-xs mt20'>Yes<button type='button' id='confirmationRevertNo' class='btn btn-warning btn-xs mt20'>No", 'Are You Sure Do you Reject This Sample',
                {
                    closeButton: true,
                    progressBar: true,
                    allowHtml: true,
                    timeOut: 20000000,

                    onShown: function (toast) {
                        $("#confirmationRevertYes").click(function () {
                            var readflag = '';
                            var edittag = '', indicator = '';
                            $('#photolog').empty();


                            var servicevalues = {
                                Dml_Indicator: $('#rejdmlflag').val(),
                                sample_id: 0,
                                barcodeid: 0,
                                samplbarcodeid: $('#rejsamplebarcodeid').val(),
                                work_orderid: $('#popworkorder_id').val(),
                                serviceprovidername: rejserviceproviderid,
                                jobsflag: $('#rejtabflag1').val(),
                                flag: 1,
                                spname: "SP_Work_Order_Action",
                                UserId: $('#hiddenUser_id').val(),
                                created_by: $('#hiddenUser_id').val(),
                                servicename: $('#rejectreason option:selected').data('id'),
                                request_id: $('#rejectreason').val(),
                            }
                            $.ajax({
                                async: true,
                                type: 'POST',
                                url: '/Workorder/Get_Workorder',
                                contentType: 'application/json; charset=UTF-8',
                                data: JSON.stringify(servicevalues),
                                success: function (data) {
                                    debugger;

                                    var data = JSON.parse(data);
                                    console.log(data);
                                    if (data.msg == "Success") {
                                        var data1 = data.data;
                                        if (jQuery.isEmptyObject((data1))) {
                                        }
                                        else {


                                            if (data1.Table[0].status == 'Success') {

                                                toastr.success('Sample Rejected Successfully');
                                                //$('#reject_reason_popup').hide();
                                                $('#reject_reason_popup').modal('toggle');
                                                getrejectreason();

                                                if ($('#rejtabflag1').val() == 'Reject' || $('#rejtabflag1').val() == 'Rejectresult') {
                                                    $('#ldrecivie_samplepopup .close').click();
                                                    $('#result_popup .close').click();


                                                    if (tabflagad == 'phmsc') {
                                                        $("#spackagehospitalcollectsamples").tab('show');
                                                        loadpackagehospitalcollectsamples(1);
                                                    }
                                                    else if (tabflagad == 'phmc') {
                                                        $("#spackagehomecollectsamples").tab('show');
                                                        loadpackagehomecollectsamples(1);
                                                    }
                                                }

                                                else if ($('#rejtabflag1').val() == 'Rejectpending') {
                                                    $('#result_popup .close').click();
                                                    if (tabflagad == 'phmsc') {
                                                        $("#spackagehospitaljobs").tab('show');

                                                        loadpackagehospitaljobs(1, 'LPKHSCRS', 1, 'pkhscreceivesampletable', 'rs');
                                                    }
                                                    else if (tabflagad == 'phmc') {
                                                        $("#spackagehomejobs").tab('show');

                                                        loadpackagehomejobs(1, 'LPKHCRS', 1, 'pkhmcreceivesampletable', 'rs');
                                                    }
                                                }
                                                else if ($('#rejtabflag1').val() == 'Rejectcompleted') {
                                                    $('#result_popup .close').click();
                                                    if (tabflagad == 'phmsc') {
                                                        $("#spackagehospitalpendingapproval").tab('show');
                                                        loadpackagehospitaljobs(1, 'LPKHSCPR', 3, 'pkhscpendingapprovaltable', 'pr');
                                                    }
                                                    else if (tabflagad == 'phmc') {
                                                        $("#spackagehomependingapproval").tab('show');

                                                        loadpackagehomejobs(1, 'LPKHCPR', 3, 'pkhmcpendingapprovaltable', 'pr');
                                                    }
                                                }

                                            }


                                        }
                                    }
                                }
                            });
                        })
                    }
                })

        }
        else if (rejdmlflag == 'WORVT') {

            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>", 'Are You sure,You want to Revert.?',
                {
                    closeButton: true,
                    progressBar: true,
                    allowHtml: true,
                    timeOut: 0,

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


                            var servicevalues = {
                                Dml_Indicator: "WORVT",
                                samplbarcodeid: $('#rejsamplebarcodeid').val(),
                                spname: "SP_Work_Order_Action",
                                UserId: $('#hiddenUser_id').val(),
                                created_by: $('#hiddenUser_id').val(),
                                servicename: $('#rejectreason option:selected').data('id'),
                                request_id: $('#rejectreason').val(),
                            }
                            $.ajax({
                                async: true,
                                type: 'POST',
                                url: '/Workorder/Get_Workorder',
                                contentType: 'application/json; charset=UTF-8',
                                data: JSON.stringify(servicevalues),
                                success: function (data) {
                                    debugger;

                                    var data = JSON.parse(data);
                                    console.log(data);
                                    if (data.msg == "Success") {
                                        var data1 = data.data;
                                        if (jQuery.isEmptyObject((data1))) {

                                        }
                                        else {

                                            toastr.success('Revert Successfully.');
                                            $('#reject_reason_popup').modal('toggle');
                                            getrejectreason();
                                            if (tabflagad == 'phmc') {
                                                $("#spackagehomependingapproval").tab('show');
                                                loadpackagehomejobs(1, 'LPKHCPR', 3, 'pkhmcpendingapprovaltable', 'pr');
                                            }
                                            else if (tabflagad == 'phmsc') {
                                                $("#spackagehospitalpendingapproval").tab('show');
                                                loadpackagehospitaljobs(1, 'LPKHSCPR', 3, 'pkhscpendingapprovaltable', 'pr');

                                            }
                                        }
                                    }
                                }
                            });
                        });
                    }
                });
        }
    }


})




// added by nandhini for patient search view pop ------start----

function billing_details(patient_id, Pname, Phoneno, event) {
    debugger;
    $('#patientsearchpopuptabs li').removeClass('active');
    $('#Paid').removeClass('in active');
    $('#visit').removeClass('in active');
    $('#labs').removeClass('in active');

    $('#bills_tab').addClass('active');
    $('#bills').addClass('in active');

    if ($('#hiddenRole_id').val() == "1" || $('#hiddenRole_id').val() == "5") {
        $('#divcasesheet_view').show();
    }
    else {
        $('#divcasesheet_view').hide();
    }

    if ($('#hiddenRole_id').val() == "2") {
        $("#SelBranchSearchPopup").val($("#SelBranchSearchPopup option:first").val());
    }
    else {
        $("#SelBranchSearchPopup").val($('#HospitalBranchID').val());
        $("#SelBranchSearchPopup").attr('disabled', true);
    }

    $('#Hpatient_id').empty();
    $('#Hpatient_id').val(patient_id)
    $('#patient_name').empty();
    $('#patient_name').append(Pname)
    $('#phone_no').empty();
    $('#phone_no').append(Phoneno);

    LoadOPBillsTab();

}

$('#SelBranchSearchPopup').change(function () {
    LoadOPBillsTab();
    billing_details_home();
    billing_details_diag();
    billing_paid_table();
    billing_paid_table_home();
    billing_paid_table_diag();
});

function LoadOPBillsTab() {
    var branch = ($('#hiddenRole_id').val() == "2") ? $('#SelBranchSearchPopup').val() : $('#HospitalBranchID').val();
    var patient_id = $('#Hpatient_id').val();

    debugger;
    $('#shade_slot').show();
    var DoctorData = {
        dml_indicator: "PBV",
        hospital_id: $('#HospitalId').val(),
        branch_id: branch,
        patient_id: patient_id
    }
    $.ajax({
        async: true,
        type: 'POST',
        url: '/Billing/IP_OP_Billings',
        contentType: 'application/json; charset=UTF-8',
        data: JSON.stringify(DoctorData),
        success: function (data) {


            var data1 = JSON.parse(data)
            console.log(data1);
            $('#noof_visit').empty();
            $('#noof_visit').append(data1.data.Table2[0].visit_count)
            $('#first_visit').empty();
            $('#first_visit').append(data1.data.Table1[0].visit)
            $('#shade_slot').hide();
            debugger;
            if (data1.msg == "Success") {
                debugger;
                if (jQuery.isEmptyObject((data1.data))) {
                }
                else {
                    debugger;
                    var data1 = data1.data;
                    var row_data = "", Discharge = "", bill_due = '', refund = "";


                    if (data1.Table.length > 0) {

                        $('#patient_billing_view_body').empty();
                        $('#patient_billing_view').dataTable().fnClearTable();
                        $('#patient_billing_view').dataTable().fnDraw();
                        $('#patient_billing_view').dataTable().fnDestroy();

                        for (var i = 0; i < data1.Table.length; i++) {
                            bill_due = '';
                            var visit_type = data1.Table[i].visit_type;
                            var is_insurance = data1.Table[i].is_entity;
                            var type = '', IP_GatewayPass = '', Mobile = '';
                            if (visit_type == 1 || visit_type == 5 || visit_type == 6) {
                                type = '<span class="label label-used">OP</span>'
                            }
                            if (visit_type == 2) {
                                type = '<span class="label label-info">IP</span>'
                            }
                            if (visit_type == 1 && is_insurance == 1) {
                                type = '<span class="label label-used">OP ' + data1.Table[i].claim_status + '</span>'
                            }
                            if (visit_type == 2 && is_insurance == 1) {
                                type = '<span class="label label-info">IP ' + data1.Table[i].claim_status + '</span>'
                            }
                            if (visit_type == 3) {
                                type = '<span class="label label-warning">Homecare</span>'
                            }
                            if (visit_type == 4) {
                                type = '<span class="label label-primary">Diagnostics</span>'
                            }
                            if (visit_type == 7) {
                                type = '<span class="label label-primary">Daycare</span>'
                            }
                            if (visit_type == 8) {
                                type = '<span class="label label-primary">Emergency Registration</span>'
                            }
                            if (data1.Table[i].visit_type == 2 && data1.Table[i].ip_visit_report_status == 1 && parseFloat(data1.Table[i].due_amount) == 0) {
                                //Discharge = '<a onclick=IPDischarge("' + data1.Table[i].visit_report_id + '",' + data1.Table[i].due_amount + ')>Discharge</a>';
                                Discharge = '<a   onclick=discharge_reason("' + data1.Table[i].visit_report_id + '",' + data1.Table[i].due_amount + ',' + data1.Table[i].branch_id + ')>Discharge</a>';
                            }
                            else if (data1.Table[i].visit_type == 2 && data1.Table[i].ip_visit_report_status == 2) {
                                Discharge = '';
                                Discharge = '<button  data-toggle="tooltip" data-placement="bottom" title="IP Gate Pass Print" type="button" class="btn btn-print btn-xs mr-5" onclick=IP_GatewayPass("' + data1.Table[i].visit_report_id + '",' + data1.Table[i].hospitalid + ',' + data1.Table[i].branch_id + ')>IP Gate Pass Print</button>';
                            }
                            else {
                                Discharge = '';
                                //IP_GatewayPass = '<button  data-toggle="tooltip" data-placement="bottom" title="Draft Summary Prinrt" type="button" class="btn btn-print btn-xs mr-5" onclick=IP_GatewayPass("' + data1.Table[i].visit_report_id + '",' + data1.Table[i].hospitalid + ',' + data1.Table[i].branch_id + ')>IP Gateway Pass</button>';
                            }
                            var status = '<span class="label label-success" style="margin-left: 8px;">Paid</span>';
                            if (parseFloat(data1.Table[i].due_amount) > 0) {
                                bill_due = '<a class="btn_r" style="cursor:pointer;" data-id="B_F1" data-type="role_rights_function"  data-name="/BillingMaster/billing_receipt?Billing_no=' + data1.Table[i].billing_no + ' " data-nav="redirect">Due Payment</a>';
                                status = '<span class="label label-danger" style="margin-left: 8px;">Due Payment</span>';
                            }


                            var netamount = data1.Table[i].total_net_amount   //- data1.Table[i].total_discount_amount;
                            var claim_amount = parseFloat(data1.Table[i].approved_amount) + parseFloat(data1.Table[i].mou_discount) + parseFloat(data1.Table[i].co_pay) + parseFloat(data1.Table[i].other_discount);

                            //  var edit = '<button type="button" class="btn btn-edit btn-xs mr-5" data-id="B_E1" data-type="role_rights_edit" data-nav="" data-name="" onclick=requestedit(' + data1.Table[i].billing_no + ',' + data1.Table[i].branch_id + ',"' + data1.Table[i].visit_report_id + '",' + data1.Table[i].due_amount + ',this)><i class="fa fa-pencil" aria-hidden="true"></i></button>';
                            // var Del = '<button type="button" class="btn btn-delete btn-xs mr-5" data-id="B_D1" data-type="role_rights_delete" data-nav="" data-name="" onclick=requestdelete(' + data1.Table[i].billing_no + ',this)><i class="fa fa-trash-o" aria-hidden="true"></i></button>';
                            //var Del = '';
                            //   var view = '<button type="button" class="btn btn-blue btn-xs mr-5" data-id="B_V1" data-type="role_rights_view" data-nav="" data-name="" onclick=bill_preview(' + data1.Table[i].billing_no + ',' + data1.Table[i].patientid + ',' + data1.Table[i].hospitalid + ',' + data1.Table[i].branch_id + ',' + data1.Table[i].visit_type + ',this)><i class="fa fa fa-eye" aria-hidden="true"></i></button>';
                            var ipprint = '';
                            var ipdetails = '';
                            var a5print = '';
                            var a4print = '';
                            var reportPrintButtons = '';
                            var claim = '';
                            if (data1.Table[i].is_entity == '1') {
                                claim = '<a class="btn_r btn-blue" style="cursor:pointer;" data-id="B_F1" data-type="role_rights_function"  data-name="/BillingMaster/index?billcopyno=' + data1.Table[i].billing_copy_no + '&Patient_Id=' + data1.Table[i].patient_id + '&Branch_id=' + data1.Table[i].branch_id + ' " data-nav="redirect">Edit Insurance Bill</a>'
                            }
                            if (data1.Table[i].visit_type == 2) {
                                ipprint = '<button type="button" class="btn btn-blue btn-xs mr-5" data-id="B_F1" data-type="role_rights_function" data-nav="" data-name="" onclick=ip_bill_report(' + data1.Table[i].billing_no + ',' + data1.Table[i].patientid + ',' + data1.Table[i].hospitalid + ',' + data1.Table[i].branch_id + ',' + data1.Table[i].visit_type + ',this)><i class="fa fa fa-print" aria-hidden="true"></i> IP Summary </button>';
                                ipdetails = '<button type="button" class="btn btn-blue btn-xs mr-5" data-id="B_F1" data-type="role_rights_function" data-nav="" data-name="" onclick=ip_detail_report(' + data1.Table[i].billing_no + ',' + data1.Table[i].patientid + ',' + data1.Table[i].hospitalid + ',' + data1.Table[i].branch_id + ',' + data1.Table[i].visit_type + ',this)><i class="fa fa fa-print" aria-hidden="true"></i> IP Details </button>';
                                reportPrintButtons = '<li class="text-left">' + ipprint + '</li><li class="text-left">' + ipdetails + '</li>';

                            }
                            else {
                                print = '<button type="button" class="btn btn-blue btn-xs mr-5" data-id="B_F1" data-type="role_rights_function" data-nav="" data-name="" onclick=bill_report(' + data1.Table[i].billing_no + ',' + data1.Table[i].patientid + ',' + data1.Table[i].hospitalid + ',' + data1.Table[i].branch_id + ',' + '1' + ',this)><i class="fa fa fa-print" aria-hidden="true"></i> A4 Print </button>';
                                print1 = '<button type="button" class="btn btn-blue btn-xs mr-5" data-id="B_F1" data-type="role_rights_function" data-nav="" data-name="" onclick=bill_report(' + data1.Table[i].billing_no + ',' + data1.Table[i].patientid + ',' + data1.Table[i].hospitalid + ',' + data1.Table[i].branch_id + ',' + '2' + ',this)><i class="fa fa fa-print" aria-hidden="true"></i> A5 Print </button>';
                                reportPrintButtons = '<li class="text-left">' + print + '</li><li class="text-left">' + print1 + '</li>'
                            }

                            if (data1.Table[i].due_amount > 0) {
                                refund = '';
                            }
                            else {
                                refund = '<a class="btn_r btn-blue" style="cursor:pointer;" data-id="B_F1" data-type="role_rights_function"  data-name="/BillingMaster/refund?Billcode=' + data1.Table[i].billing_no + '&Patient_Id=' + data1.Table[i].patient_id + '&billing_type=4&Branch_id=' + data1.Table[i].branch_id + ' " data-nav="redirect">Refund</a>';
                            }

                            if (data1.Table[i].billing_channel == 2) {
                                Mobile = '<i class="fa fa-mobile icon-design ml-10 mr-10" style="color:blue;font-size:20px;" title="APP BILL" aria-hidden="true"></i>';
                            }
                            else {
                                Mobile = '';
                            }

                            //var refund = '<a class="btn_r" style="cursor:pointer;" data-id="B_F1" data-type="role_rights_function"  data-name="/BillingMaster/refund?Billcode=' + data1.Table[i].billing_no + '&Patient_Id=' + data1.Table[i].patient_id + '&billing_type=4&Branch_id=' + data1.Table[i].branch_id + ' " data-nav="redirect">Refund</a>';

                            other_info = '<div class="col-md-12 padding0"><div class="disp_if"><a href="#" class="dropdown-toggle btn btn-info-dots btn-xs" data-toggle="dropdown" aria-expanded="true"><span class="fa fa-ellipsis-h" data-toggle="tooltip" data-placement="bottom" title="Other Options" style="color:black;" aria-hidden="true"></span><span class="sr-only">Options</span></a><div class="dropdown-menu info-dropdown-workorder" id="">' + reportPrintButtons + '</ul></div></div>';

                            //row_data = row_data + '<tr id=reqv' + i + '><td>' + (i + 1) + '</td><td>' + data1.Table[i].billing_code + '</td><td>' + data1.Table[i].visit_report_id + '</td><td>' + data1.Table[i].total_amount + '</td><td>' + data1.Table[i].due_amount + '</td><td>' + data1.Table[i].received_amount + '</td><td class="details-control" id=service' + i + ' onclick=billingdetails(this,"' + data1.Table[i].billing_no + '");>' + data1.Table[i].billing_no + '<i class="fa fa-angle-double-down ml-20"></i></td><td><button type="button" class="btn btn-primaryuse btn-xs mr-5" onclick=requestedit(' + data1.Table[i].billing_no + ')><i class="fa fa-pencil-square-o" aria-hidden="true"></i></button><button type="button" class="btn btn-danger btn-xs mr-5" onclick=requestdelete(' + data1.Table[i].billing_no + ')><i class="fa fa-trash" aria-hidden="true"></i></button></td></tr>'
                            if (data1.Table[i].payment_type == 0 || data1.Table[i].payment_type == 2 || parseFloat(data1.Table[i].due_amount) == 0) {
                                row_data = row_data + '<tr id=reqv' + i + ' ><td onclick=billingdetails(this,"' + data1.Table[i].billing_no + '")>' + (i + 1) + " " + Mobile + '</td><td>' + data1.Table[i].created_on + '</td><td class="details-control" id=service' + i + ' onclick=billingdetails(this,"' + data1.Table[i].billing_no + '") style=" width: 10% !important;">' + data1.Table[i].billing_code + '</td><td onclick=billingdetails(this,"' + data1.Table[i].billing_no + '")>' + type + '</td><td onclick=billingdetails(this,"' + data1.Table[i].billing_no + '")>' + data1.Table[i].total_amount + '</td><td>' + data1.Table[i].total_discount_amount + '</td><td onclick=billingdetails(this,"' + data1.Table[i].billing_no + '")>₹ ' + netamount + '</td><td onclick=billingdetails(this,"' + data1.Table[i].billing_no + '")> ₹ ' + data1.Table[i].advance_amount + '</td><td onclick=billingdetails(this,"' + data1.Table[i].billing_no + '")>₹ ' + claim_amount + '</td><td onclick=billingdetails(this,"' + data1.Table[i].billing_no + '")> ₹' + data1.Table[i].received_amount + '</td><td onclick=billingdetails(this,"' + data1.Table[i].billing_no + '")> ₹' + data1.Table[i].due_amount + '</td><td>' + status + '</td><td>' + other_info + '</td></tr>'
                            }
                            else {
                                //row_data = row_data + '<tr id=reqv' + i + ' ><td onclick=billingdetails(this,"' + data1.Table[i].billing_no + '")>' + (i + 1) + '</td><td onclick=billingdetails(this,"' + data1.Table[i].billing_no + '")>' + data1.Table[i].branch_id + '</td><td>' + data1.Table[i].created_on + '</td><td class="details-control" id=service' + i + ' onclick=billingdetails(this,"' + data1.Table[i].billing_no + '") style=" width: 10% !important;">' + data1.Table[i].billing_code + '<i class="fa fa-angle-double-down ml-20"></i></td><td onclick=billingdetails(this,"' + data1.Table[i].billing_no + '")>' + data1.Table[i].patient_id + '</td><td onclick=billingdetails(this,"' + data1.Table[i].billing_no + '")>' + data1.Table[i].patient_name + '</td><td onclick=billingdetails(this,"' + data1.Table[i].billing_no + '")>' + data1.Table[i].total_amount + '</td><td onclick=billingdetails(this,"' + data1.Table[i].billing_no + '")>' + data1.Table[i].total_discount_amount + '</td><td onclick=billingdetails(this,"' + data1.Table[i].billing_no + '")>' + netamount + '</td><td onclick=billingdetails(this,"' + data1.Table[i].billing_no + '")>' + data1.Table[i].received_amount + '</td><td onclick=billingdetails(this,"' + data1.Table[i].billing_no + '")>' + data1.Table[i].due_amount + '</td><td><button type="button" class="btn btn-primaryuse btn-xs mr-5" onclick=lookup("' + data1.Table[i].cc_invoiceid + '","' + data1.Table[i].sms_invoice_no + '","' + data1.Table[i].cc_date + '")>Check Status</button><button type="button" class="btn btn-primaryuse btn-xs mr-5" onclick=resent("' + data1.Table[i].cc_invoiceid + '","' + data1.Table[i].tiny_url + '","' + data1.Table[i].phone_number + '","'+data1.Table[i].total_net_amount+'")>Resend link</button></td></tr>'
                                row_data = row_data + '<tr id=reqv' + i + ' ><td onclick=billingdetails(this,"' + data1.Table[i].billing_no + '")>' + (i + 1) + " " + Mobile + '</td><td>' + data1.Table[i].created_on + '</td><td class="details-control" id=service' + i + ' onclick=billingdetails(this,"' + data1.Table[i].billing_no + '") style=" width: 10% !important;">' + data1.Table[i].billing_code + '</td><td onclick=billingdetails(this,"' + data1.Table[i].billing_no + '")>' + type + '</td><td onclick=billingdetails(this,"' + data1.Table[i].billing_no + '")>' + data1.Table[i].total_amount + '</td><td>' + data1.Table[i].total_discount_amount + '</td><td onclick=billingdetails(this,"' + data1.Table[i].billing_no + '")> ₹ ' + netamount + '</td><td onclick=billingdetails(this,"' + data1.Table[i].billing_no + '")> ₹ ' + data1.Table[i].advance_amount + '</td><td onclick=billingdetails(this,"' + data1.Table[i].billing_no + '")> ₹ ' + claim_amount + '</td><td onclick=billingdetails(this,"' + data1.Table[i].billing_no + '")> ₹ ' + data1.Table[i].received_amount + '</td><td onclick=billingdetails(this,"' + data1.Table[i].billing_no + '")> ₹ ' + data1.Table[i].due_amount + '</td><td>' + status + '</td><td class="disp_if">' + other_info + '<button type="button" class="btn btn-primaryuse btn-xs mr-5" onclick=lookup("' + data1.Table[i].cc_invoiceid + '","' + data1.Table[i].sms_invoice_no + '","' + data1.Table[i].cc_date + '")>Check Status</button></td></tr>'

                            }
                        }
                        $('#patient_billing_view_body').html(row_data);
                        //  $('#patient_billing_view').DataTable();
                        datatable("patient_billing_view");
                        // datatable('tbl_billing', 'billing_view', 'Legal');
                    }
                    else {
                        console.log(data1);
                        //   $('#patient_billing_view').DataTable();
                        $('#patient_billing_view_body').empty();
                        $('#patient_billing_view').dataTable().fnClearTable();
                        $('#patient_billing_view').dataTable().fnDraw();
                        $('#patient_billing_view').dataTable().fnDestroy();
                        datatable("patient_billing_view");
                        // datatable('tbl_billing', 'billing_view', 'Legal');
                    }
                }
            }
            else {
                console.log(data1);
                $('#patient_billing_view_body').empty();
                $('#patient_billing_view').dataTable().fnClearTable();
                $('#patient_billing_view').dataTable().fnDraw();
                $('#patient_billing_view').dataTable().fnDestroy();
                //   $('#patient_billing_view').DataTable();
                datatable("patient_billing_view");

                // datatable('tbl_billing', 'billing_view', 'Legal');
            }
        }
    });
}

$('#billhome_tab').click(function () {
    debugger;
    billing_details_home();
})

function billing_details_home() {
    debugger;
    var branch = ($('#hiddenRole_id').val() == "2") ? $('#SelBranchSearchPopup').val() : $('#HospitalBranchID').val();
    var patient_id = $('#Hpatient_id').val();

    debugger;
    $('#shade_slot').show();
    var DoctorData = {
        dml_indicator: "PBVH",
        hospital_id: $('#HospitalId').val(),
        branch_id: branch,
        patient_id: patient_id
    }
    $.ajax({
        async: true,
        type: 'POST',
        url: '/Billing/IP_OP_Billings',
        contentType: 'application/json; charset=UTF-8',
        data: JSON.stringify(DoctorData),
        success: function (data) {
            $('#billing_view_home_body').empty();
            $('#billing_view_home').dataTable().fnClearTable();
            $('#billing_view_home').dataTable().fnDraw();
            $('#billing_view_home').dataTable().fnDestroy();

            var data1 = JSON.parse(data)
            console.log(data1);
            $('#shade_slot').hide();
            debugger;
            if (data1.msg == "Success") {
                debugger;
                if (jQuery.isEmptyObject((data1.data))) {
                }
                else {
                    debugger;
                    var data1 = data1.data;
                    var row_data = "", Discharge = "", bill_due = '', refund = "";


                    if (data1.Table.length > 0) {

                        $('#billing_view_home_body').empty();
                        $('#billing_view_home').dataTable().fnClearTable();
                        $('#billing_view_home').dataTable().fnDraw();
                        $('#billing_view_home').dataTable().fnDestroy();

                        for (var i = 0; i < data1.Table.length; i++) {
                            bill_due = '';
                            var visit_type = data1.Table[i].visit_type;
                            var is_insurance = data1.Table[i].is_entity;
                            var type = '', IP_GatewayPass = '', Mobile = '';
                            if (visit_type == 1 || visit_type == 5 || visit_type == 6) {
                                type = '<span class="label label-used">OP</span>'
                            }
                            if (visit_type == 2) {
                                type = '<span class="label label-info">IP</span>'
                            }
                            if (visit_type == 1 && is_insurance == 1) {
                                type = '<span class="label label-used">OP ' + data1.Table[i].claim_status + '</span>'
                            }
                            if (visit_type == 2 && is_insurance == 1) {
                                type = '<span class="label label-info">IP ' + data1.Table[i].claim_status + '</span>'
                            }
                            if (visit_type == 3) {
                                type = '<span class="label label-warning">Homecare</span>'
                            }
                            if (visit_type == 4) {
                                type = '<span class="label label-primary">Diagnostics</span>'
                            }
                            if (visit_type == 7) {
                                type = '<span class="label label-primary">Daycare</span>'
                            }
                            if (visit_type == 8) {
                                type = '<span class="label label-primary">Emergency Registration</span>'
                            }
                            if (data1.Table[i].visit_type == 2 && data1.Table[i].ip_visit_report_status == 1 && parseFloat(data1.Table[i].due_amount) == 0) {
                                //Discharge = '<a onclick=IPDischarge("' + data1.Table[i].visit_report_id + '",' + data1.Table[i].due_amount + ')>Discharge</a>';
                                Discharge = '<a   onclick=discharge_reason("' + data1.Table[i].visit_report_id + '",' + data1.Table[i].due_amount + ',' + data1.Table[i].branch_id + ')>Discharge</a>';
                            }
                            else if (data1.Table[i].visit_type == 2 && data1.Table[i].ip_visit_report_status == 2) {
                                Discharge = '';
                                Discharge = '<button  data-toggle="tooltip" data-placement="bottom" title="IP Gate Pass Print" type="button" class="btn btn-print btn-xs mr-5" onclick=IP_GatewayPass("' + data1.Table[i].visit_report_id + '",' + data1.Table[i].hospitalid + ',' + data1.Table[i].branch_id + ')>IP Gate Pass Print</button>';
                            }
                            else {
                                Discharge = '';
                                //IP_GatewayPass = '<button  data-toggle="tooltip" data-placement="bottom" title="Draft Summary Prinrt" type="button" class="btn btn-print btn-xs mr-5" onclick=IP_GatewayPass("' + data1.Table[i].visit_report_id + '",' + data1.Table[i].hospitalid + ',' + data1.Table[i].branch_id + ')>IP Gateway Pass</button>';
                            }
                            var status = '<span class="label label-success" style="margin-left: 8px;">Paid</span>';
                            if (parseFloat(data1.Table[i].due_amount) > 0) {
                                bill_due = '<a class="btn_r" style="cursor:pointer;" data-id="B_F1" data-type="role_rights_function"  data-name="/BillingMaster/billing_receipt?Billing_no=' + data1.Table[i].billing_no + ' " data-nav="redirect">Due Payment</a>';
                                status = '<span class="label label-danger" style="margin-left: 8px;">Due Payment</span>';
                            }


                            var netamount = data1.Table[i].total_net_amount   //- data1.Table[i].total_discount_amount;
                            var claim_amount = parseFloat(data1.Table[i].approved_amount) + parseFloat(data1.Table[i].mou_discount) + parseFloat(data1.Table[i].co_pay) + parseFloat(data1.Table[i].other_discount);

                            //  var edit = '<button type="button" class="btn btn-edit btn-xs mr-5" data-id="B_E1" data-type="role_rights_edit" data-nav="" data-name="" onclick=requestedit(' + data1.Table[i].billing_no + ',' + data1.Table[i].branch_id + ',"' + data1.Table[i].visit_report_id + '",' + data1.Table[i].due_amount + ',this)><i class="fa fa-pencil" aria-hidden="true"></i></button>';
                            // var Del = '<button type="button" class="btn btn-delete btn-xs mr-5" data-id="B_D1" data-type="role_rights_delete" data-nav="" data-name="" onclick=requestdelete(' + data1.Table[i].billing_no + ',this)><i class="fa fa-trash-o" aria-hidden="true"></i></button>';
                            //var Del = '';
                            var view = '<button type="button" class="btn btn-blue btn-xs mr-5" data-id="B_V1" data-type="role_rights_view" data-nav="" data-name="" onclick=bill_preview(' + data1.Table[i].billing_no + ',' + data1.Table[i].patientid + ',' + data1.Table[i].hospitalid + ',' + data1.Table[i].branch_id + ',' + data1.Table[i].visit_type + ',this)><i class="fa fa fa-eye" aria-hidden="true"></i></button>';
                            var ipprint = '';
                            var ipdetails = '';
                            var a5print = '';
                            var a4print = '';
                            var reportPrintButtons = '';
                            var claim = '';
                            if (data1.Table[i].is_entity == '1') {
                                claim = '<a class="btn_r btn-blue" style="cursor:pointer;" data-id="B_F1" data-type="role_rights_function"  data-name="/BillingMaster/index?billcopyno=' + data1.Table[i].billing_copy_no + '&Patient_Id=' + data1.Table[i].patient_id + '&Branch_id=' + data1.Table[i].branch_id + ' " data-nav="redirect">Edit Insurance Bill</a>'
                            }
                            if (data1.Table[i].visit_type == 2) {
                                ipprint = '<button type="button" class="btn btn-blue btn-xs mr-5" data-id="B_F1" data-type="role_rights_function" data-nav="" data-name="" onclick=ip_bill_report(' + data1.Table[i].billing_no + ',' + data1.Table[i].patientid + ',' + data1.Table[i].hospitalid + ',' + data1.Table[i].branch_id + ',' + data1.Table[i].visit_type + ',this)><i class="fa fa fa-print" aria-hidden="true"></i> IP Summary </button>';
                                ipdetails = '<button type="button" class="btn btn-blue btn-xs mr-5" data-id="B_F1" data-type="role_rights_function" data-nav="" data-name="" onclick=ip_detail_report(' + data1.Table[i].billing_no + ',' + data1.Table[i].patientid + ',' + data1.Table[i].hospitalid + ',' + data1.Table[i].branch_id + ',' + data1.Table[i].visit_type + ',this)><i class="fa fa fa-print" aria-hidden="true"></i> IP Details </button>';
                                reportPrintButtons = '<li class="text-left">' + ipprint + '</li><li class="text-left">' + ipdetails + '</li>';

                            }
                            else {
                                print = '<button type="button" class="btn btn-blue btn-xs mr-5" data-id="B_F1" data-type="role_rights_function" data-nav="" data-name="" onclick=bill_report(' + data1.Table[i].billing_no + ',' + data1.Table[i].patientid + ',' + data1.Table[i].hospitalid + ',' + data1.Table[i].branch_id + ',' + '1' + ',this)><i class="fa fa fa-print" aria-hidden="true"></i> A4 Print </button>';
                                print1 = '<button type="button" class="btn btn-blue btn-xs mr-5" data-id="B_F1" data-type="role_rights_function" data-nav="" data-name="" onclick=bill_report(' + data1.Table[i].billing_no + ',' + data1.Table[i].patientid + ',' + data1.Table[i].hospitalid + ',' + data1.Table[i].branch_id + ',' + '2' + ',this)><i class="fa fa fa-print" aria-hidden="true"></i> A5 Print </button>';
                                reportPrintButtons = '<li class="text-left">' + print + '</li><li class="text-left">' + print1 + '</li>'
                            }

                            if (data1.Table[i].due_amount > 0) {
                                refund = '';
                            }
                            else {
                                refund = '<a class="btn_r btn-blue" style="cursor:pointer;" data-id="B_F1" data-type="role_rights_function"  data-name="/BillingMaster/refund?Billcode=' + data1.Table[i].billing_no + '&Patient_Id=' + data1.Table[i].patient_id + '&billing_type=4&Branch_id=' + data1.Table[i].branch_id + ' " data-nav="redirect">Refund</a>';
                            }

                            if (data1.Table[i].billing_channel == 2) {
                                Mobile = '<i class="fa fa-mobile icon-design ml-10 mr-10" style="color:blue;font-size:20px;" title="APP BILL" aria-hidden="true"></i>';
                            }
                            else {
                                Mobile = '';
                            }

                            //var refund = '<a class="btn_r" style="cursor:pointer;" data-id="B_F1" data-type="role_rights_function"  data-name="/BillingMaster/refund?Billcode=' + data1.Table[i].billing_no + '&Patient_Id=' + data1.Table[i].patient_id + '&billing_type=4&Branch_id=' + data1.Table[i].branch_id + ' " data-nav="redirect">Refund</a>';

                            other_info = '<div class="col-md-12 padding0"><div class="disp_if"><a href="#" class="dropdown-toggle btn btn-info-dots btn-xs" data-toggle="dropdown" aria-expanded="true"><span class="fa fa-ellipsis-h" data-toggle="tooltip" data-placement="bottom" title="Other Options" style="color:black;" aria-hidden="true"></span><span class="sr-only">Options</span></a><div class="dropdown-menu info-dropdown-workorder" id="">' + reportPrintButtons + '</ul></div></div>';

                            //row_data = row_data + '<tr id=reqv' + i + '><td>' + (i + 1) + '</td><td>' + data1.Table[i].billing_code + '</td><td>' + data1.Table[i].visit_report_id + '</td><td>' + data1.Table[i].total_amount + '</td><td>' + data1.Table[i].due_amount + '</td><td>' + data1.Table[i].received_amount + '</td><td class="details-control" id=service' + i + ' onclick=billingdetails(this,"' + data1.Table[i].billing_no + '");>' + data1.Table[i].billing_no + '<i class="fa fa-angle-double-down ml-20"></i></td><td><button type="button" class="btn btn-primaryuse btn-xs mr-5" onclick=requestedit(' + data1.Table[i].billing_no + ')><i class="fa fa-pencil-square-o" aria-hidden="true"></i></button><button type="button" class="btn btn-danger btn-xs mr-5" onclick=requestdelete(' + data1.Table[i].billing_no + ')><i class="fa fa-trash" aria-hidden="true"></i></button></td></tr>'
                            if (data1.Table[i].payment_type == 0 || data1.Table[i].payment_type == 2 || parseFloat(data1.Table[i].due_amount) == 0) {
                                row_data = row_data + '<tr id=reqv' + i + ' ><td onclick=billingdetails(this,"' + data1.Table[i].billing_no + '")>' + (i + 1) + " " + Mobile + '</td><td>' + data1.Table[i].created_on + '</td><td class="details-control" id=service' + i + ' onclick=billingdetails(this,"' + data1.Table[i].billing_no + '") style=" width: 10% !important;">' + data1.Table[i].billing_code + '</td><td onclick=billingdetails(this,"' + data1.Table[i].billing_no + '")>' + type + '</td><td onclick=billingdetails(this,"' + data1.Table[i].billing_no + '")>' + data1.Table[i].total_amount + '</td><td>' + data1.Table[i].total_discount_amount + '</td><td onclick=billingdetails(this,"' + data1.Table[i].billing_no + '")>₹ ' + netamount + '</td><td onclick=billingdetails(this,"' + data1.Table[i].billing_no + '")> ₹ ' + data1.Table[i].advance_amount + '</td><td onclick=billingdetails(this,"' + data1.Table[i].billing_no + '")>₹ ' + claim_amount + '</td><td onclick=billingdetails(this,"' + data1.Table[i].billing_no + '")> ₹' + data1.Table[i].received_amount + '</td><td onclick=billingdetails(this,"' + data1.Table[i].billing_no + '")> ₹' + data1.Table[i].due_amount + '</td><td>' + status + '</td><td>' + other_info + '</td></tr>'
                            }
                            else {
                                //row_data = row_data + '<tr id=reqv' + i + ' ><td onclick=billingdetails(this,"' + data1.Table[i].billing_no + '")>' + (i + 1) + '</td><td onclick=billingdetails(this,"' + data1.Table[i].billing_no + '")>' + data1.Table[i].branch_id + '</td><td>' + data1.Table[i].created_on + '</td><td class="details-control" id=service' + i + ' onclick=billingdetails(this,"' + data1.Table[i].billing_no + '") style=" width: 10% !important;">' + data1.Table[i].billing_code + '<i class="fa fa-angle-double-down ml-20"></i></td><td onclick=billingdetails(this,"' + data1.Table[i].billing_no + '")>' + data1.Table[i].patient_id + '</td><td onclick=billingdetails(this,"' + data1.Table[i].billing_no + '")>' + data1.Table[i].patient_name + '</td><td onclick=billingdetails(this,"' + data1.Table[i].billing_no + '")>' + data1.Table[i].total_amount + '</td><td onclick=billingdetails(this,"' + data1.Table[i].billing_no + '")>' + data1.Table[i].total_discount_amount + '</td><td onclick=billingdetails(this,"' + data1.Table[i].billing_no + '")>' + netamount + '</td><td onclick=billingdetails(this,"' + data1.Table[i].billing_no + '")>' + data1.Table[i].received_amount + '</td><td onclick=billingdetails(this,"' + data1.Table[i].billing_no + '")>' + data1.Table[i].due_amount + '</td><td><button type="button" class="btn btn-primaryuse btn-xs mr-5" onclick=lookup("' + data1.Table[i].cc_invoiceid + '","' + data1.Table[i].sms_invoice_no + '","' + data1.Table[i].cc_date + '")>Check Status</button><button type="button" class="btn btn-primaryuse btn-xs mr-5" onclick=resent("' + data1.Table[i].cc_invoiceid + '","' + data1.Table[i].tiny_url + '","' + data1.Table[i].phone_number + '","'+data1.Table[i].total_net_amount+'")>Resend link</button></td></tr>'
                                row_data = row_data + '<tr id=reqv' + i + ' ><td onclick=billingdetails(this,"' + data1.Table[i].billing_no + '")>' + (i + 1) + " " + Mobile + '</td><td>' + data1.Table[i].created_on + '</td><td class="details-control" id=service' + i + ' onclick=billingdetails(this,"' + data1.Table[i].billing_no + '") style=" width: 10% !important;">' + data1.Table[i].billing_code + '</td><td onclick=billingdetails(this,"' + data1.Table[i].billing_no + '")>' + type + '</td><td onclick=billingdetails(this,"' + data1.Table[i].billing_no + '")>' + data1.Table[i].total_amount + '</td><td>' + data1.Table[i].total_discount_amount + '</td><td onclick=billingdetails(this,"' + data1.Table[i].billing_no + '")> ₹ ' + netamount + '</td><td onclick=billingdetails(this,"' + data1.Table[i].billing_no + '")> ₹ ' + data1.Table[i].advance_amount + '</td><td onclick=billingdetails(this,"' + data1.Table[i].billing_no + '")> ₹ ' + claim_amount + '</td><td onclick=billingdetails(this,"' + data1.Table[i].billing_no + '")> ₹ ' + data1.Table[i].received_amount + '</td><td onclick=billingdetails(this,"' + data1.Table[i].billing_no + '")> ₹ ' + data1.Table[i].due_amount + '</td><td>' + status + '</td><td class="disp_if">' + other_info + '<button type="button" class="btn btn-primaryuse btn-xs mr-5" onclick=lookup("' + data1.Table[i].cc_invoiceid + '","' + data1.Table[i].sms_invoice_no + '","' + data1.Table[i].cc_date + '")>Check Status</button></td></tr>'

                            }
                        }
                        $('#billing_view_home_body').html(row_data);
                        //  $('#billing_view_home').DataTable();
                        datatable("billing_view_home");
                        // datatable('tbl_billing', 'billing_view', 'Legal');
                    }
                    else {
                        console.log(data1);
                        //  $('#billing_view_home').DataTable();
                        datatable("billing_view_home");
                        // datatable('tbl_billing', 'billing_view', 'Legal');
                    }
                }
            }
            else {
                console.log(data1);
                //  $('#billing_view_home').DataTable();
                datatable("billing_view_home");
                // datatable('tbl_billing', 'billing_view', 'Legal');
            }
        }
    });
}

$('#billdiag_tab').click(function () {
    debugger;
    billing_details_diag();
})

function billing_details_diag() {
    debugger;
    var branch = ($('#hiddenRole_id').val() == "2") ? $('#SelBranchSearchPopup').val() : $('#HospitalBranchID').val();
    var patient_id = $('#Hpatient_id').val();

    debugger;
    $('#shade_slot').show();
    var DoctorData = {
        dml_indicator: "PBVD",
        hospital_id: $('#HospitalId').val(),
        branch_id: branch,
        patient_id: patient_id
    }
    $.ajax({
        async: true,
        type: 'POST',
        url: '/Billing/IP_OP_Billings',
        contentType: 'application/json; charset=UTF-8',
        data: JSON.stringify(DoctorData),
        success: function (data) {
            $('#billing_view_diag_body').empty();
            $('#billing_view_diag').dataTable().fnClearTable();
            $('#billing_view_diag').dataTable().fnDraw();
            $('#billing_view_diag').dataTable().fnDestroy();

            var data1 = JSON.parse(data)
            console.log(data1);
            $('#shade_slot').hide();
            debugger;
            if (data1.msg == "Success") {
                debugger;
                if (jQuery.isEmptyObject((data1.data))) {
                }
                else {
                    debugger;
                    var data1 = data1.data;
                    var row_data = "", Discharge = "", bill_due = '', refund = "";


                    if (data1.Table.length > 0) {

                        $('#billing_view_diag_body').empty();
                        $('#billing_view_diag').dataTable().fnClearTable();
                        $('#billing_view_diag').dataTable().fnDraw();
                        $('#billing_view_diag').dataTable().fnDestroy();

                        for (var i = 0; i < data1.Table.length; i++) {
                            bill_due = '';
                            var visit_type = data1.Table[i].visit_type;
                            var is_insurance = data1.Table[i].is_entity;
                            var type = '', IP_GatewayPass = '', Mobile = '';
                            if (visit_type == 1 || visit_type == 5 || visit_type == 6) {
                                type = '<span class="label label-used">OP</span>'
                            }
                            if (visit_type == 2) {
                                type = '<span class="label label-info">IP</span>'
                            }
                            if (visit_type == 1 && is_insurance == 1) {
                                type = '<span class="label label-used">OP ' + data1.Table[i].claim_status + '</span>'
                            }
                            if (visit_type == 2 && is_insurance == 1) {
                                type = '<span class="label label-info">IP ' + data1.Table[i].claim_status + '</span>'
                            }
                            if (visit_type == 3) {
                                type = '<span class="label label-warning">Homecare</span>'
                            }
                            if (visit_type == 4) {
                                type = '<span class="label label-primary">Diagnostics</span>'
                            }
                            if (visit_type == 7) {
                                type = '<span class="label label-primary">Daycare</span>'
                            }
                            if (visit_type == 8) {
                                type = '<span class="label label-primary">Emergency Registration</span>'
                            }
                            if (data1.Table[i].visit_type == 2 && data1.Table[i].ip_visit_report_status == 1 && parseFloat(data1.Table[i].due_amount) == 0) {
                                //Discharge = '<a onclick=IPDischarge("' + data1.Table[i].visit_report_id + '",' + data1.Table[i].due_amount + ')>Discharge</a>';
                                Discharge = '<a   onclick=discharge_reason("' + data1.Table[i].visit_report_id + '",' + data1.Table[i].due_amount + ',' + data1.Table[i].branch_id + ')>Discharge</a>';
                            }
                            else if (data1.Table[i].visit_type == 2 && data1.Table[i].ip_visit_report_status == 2) {
                                Discharge = '';
                                Discharge = '<button  data-toggle="tooltip" data-placement="bottom" title="IP Gate Pass Print" type="button" class="btn btn-print btn-xs mr-5" onclick=IP_GatewayPass("' + data1.Table[i].visit_report_id + '",' + data1.Table[i].hospitalid + ',' + data1.Table[i].branch_id + ')>IP Gate Pass Print</button>';
                            }
                            else {
                                Discharge = '';
                                //IP_GatewayPass = '<button  data-toggle="tooltip" data-placement="bottom" title="Draft Summary Prinrt" type="button" class="btn btn-print btn-xs mr-5" onclick=IP_GatewayPass("' + data1.Table[i].visit_report_id + '",' + data1.Table[i].hospitalid + ',' + data1.Table[i].branch_id + ')>IP Gateway Pass</button>';
                            }
                            var status = '<span class="label label-success" style="margin-left: 8px;">Paid</span>';
                            if (parseFloat(data1.Table[i].due_amount) > 0) {
                                bill_due = '<a class="btn_r" style="cursor:pointer;" data-id="B_F1" data-type="role_rights_function"  data-name="/BillingMaster/billing_receipt?Billing_no=' + data1.Table[i].billing_no + ' " data-nav="redirect">Due Payment</a>';
                                status = '<span class="label label-danger" style="margin-left: 8px;">Due Payment</span>';
                            }


                            var netamount = data1.Table[i].total_net_amount   //- data1.Table[i].total_discount_amount;
                            var claim_amount = parseFloat(data1.Table[i].approved_amount) + parseFloat(data1.Table[i].mou_discount) + parseFloat(data1.Table[i].co_pay) + parseFloat(data1.Table[i].other_discount);

                            //  var edit = '<button type="button" class="btn btn-edit btn-xs mr-5" data-id="B_E1" data-type="role_rights_edit" data-nav="" data-name="" onclick=requestedit(' + data1.Table[i].billing_no + ',' + data1.Table[i].branch_id + ',"' + data1.Table[i].visit_report_id + '",' + data1.Table[i].due_amount + ',this)><i class="fa fa-pencil" aria-hidden="true"></i></button>';
                            //    var Del = '<button type="button" class="btn btn-delete btn-xs mr-5" data-id="B_D1" data-type="role_rights_delete" data-nav="" data-name="" onclick=requestdelete(' + data1.Table[i].billing_no + ',this)><i class="fa fa-trash-o" aria-hidden="true"></i></button>';
                            //var Del = '';
                            var view = '<button type="button" class="btn btn-blue btn-xs mr-5" data-id="B_V1" data-type="role_rights_view" data-nav="" data-name="" onclick=bill_preview(' + data1.Table[i].billing_no + ',' + data1.Table[i].patientid + ',' + data1.Table[i].hospitalid + ',' + data1.Table[i].branch_id + ',' + data1.Table[i].visit_type + ',this)><i class="fa fa fa-eye" aria-hidden="true"></i></button>';
                            var ipprint = '';
                            var ipdetails = '';
                            var a5print = '';
                            var a4print = '';
                            var reportPrintButtons = '';
                            var claim = '';
                            if (data1.Table[i].is_entity == '1') {
                                claim = '<a class="btn_r btn-blue" style="cursor:pointer;" data-id="B_F1" data-type="role_rights_function"  data-name="/BillingMaster/index?billcopyno=' + data1.Table[i].billing_copy_no + '&Patient_Id=' + data1.Table[i].patient_id + '&Branch_id=' + data1.Table[i].branch_id + ' " data-nav="redirect">Edit Insurance Bill</a>'
                            }
                            if (data1.Table[i].visit_type == 2) {
                                ipprint = '<button type="button" class="btn btn-blue btn-xs mr-5" data-id="B_F1" data-type="role_rights_function" data-nav="" data-name="" onclick=ip_bill_report(' + data1.Table[i].billing_no + ',' + data1.Table[i].patientid + ',' + data1.Table[i].hospitalid + ',' + data1.Table[i].branch_id + ',' + data1.Table[i].visit_type + ',this)><i class="fa fa fa-print" aria-hidden="true"></i> IP Summary </button>';
                                ipdetails = '<button type="button" class="btn btn-blue btn-xs mr-5" data-id="B_F1" data-type="role_rights_function" data-nav="" data-name="" onclick=ip_detail_report(' + data1.Table[i].billing_no + ',' + data1.Table[i].patientid + ',' + data1.Table[i].hospitalid + ',' + data1.Table[i].branch_id + ',' + data1.Table[i].visit_type + ',this)><i class="fa fa fa-print" aria-hidden="true"></i> IP Details </button>';
                                reportPrintButtons = '<li class="text-left">' + ipprint + '</li><li class="text-left">' + ipdetails + '</li>';

                            }
                            else {
                                print = '<button type="button" class="btn btn-blue btn-xs mr-5" data-id="B_F1" data-type="role_rights_function" data-nav="" data-name="" onclick=bill_report(' + data1.Table[i].billing_no + ',' + data1.Table[i].patientid + ',' + data1.Table[i].hospitalid + ',' + data1.Table[i].branch_id + ',' + '1' + ',this)><i class="fa fa fa-print" aria-hidden="true"></i> A4 Print </button>';
                                print1 = '<button type="button" class="btn btn-blue btn-xs mr-5" data-id="B_F1" data-type="role_rights_function" data-nav="" data-name="" onclick=bill_report(' + data1.Table[i].billing_no + ',' + data1.Table[i].patientid + ',' + data1.Table[i].hospitalid + ',' + data1.Table[i].branch_id + ',' + '2' + ',this)><i class="fa fa fa-print" aria-hidden="true"></i> A5 Print </button>';
                                reportPrintButtons = '<li class="text-left">' + print + '</li><li class="text-left">' + print1 + '</li>'
                            }

                            if (data1.Table[i].due_amount > 0) {
                                refund = '';
                            }
                            else {
                                refund = '<a class="btn_r btn-blue" style="cursor:pointer;" data-id="B_F1" data-type="role_rights_function"  data-name="/BillingMaster/refund?Billcode=' + data1.Table[i].billing_no + '&Patient_Id=' + data1.Table[i].patient_id + '&billing_type=4&Branch_id=' + data1.Table[i].branch_id + ' " data-nav="redirect">Refund</a>';
                            }

                            if (data1.Table[i].billing_channel == 2) {
                                Mobile = '<i class="fa fa-mobile icon-design ml-10 mr-10" style="color:blue;font-size:20px;" title="APP BILL" aria-hidden="true"></i>';
                            }
                            else {
                                Mobile = '';
                            }

                            //var refund = '<a class="btn_r" style="cursor:pointer;" data-id="B_F1" data-type="role_rights_function"  data-name="/BillingMaster/refund?Billcode=' + data1.Table[i].billing_no + '&Patient_Id=' + data1.Table[i].patient_id + '&billing_type=4&Branch_id=' + data1.Table[i].branch_id + ' " data-nav="redirect">Refund</a>';

                            other_info = '<div class="col-md-12 padding0"><div class="disp_if"><a href="#" class="dropdown-toggle btn btn-info-dots btn-xs" data-toggle="dropdown" aria-expanded="true"><span class="fa fa-ellipsis-h" data-toggle="tooltip" data-placement="bottom" title="Other Options" style="color:black;" aria-hidden="true"></span><span class="sr-only">Options</span></a><div class="dropdown-menu info-dropdown-workorder" id="">' + reportPrintButtons + '</ul></div></div>';

                            //row_data = row_data + '<tr id=reqv' + i + '><td>' + (i + 1) + '</td><td>' + data1.Table[i].billing_code + '</td><td>' + data1.Table[i].visit_report_id + '</td><td>' + data1.Table[i].total_amount + '</td><td>' + data1.Table[i].due_amount + '</td><td>' + data1.Table[i].received_amount + '</td><td class="details-control" id=service' + i + ' onclick=billingdetails(this,"' + data1.Table[i].billing_no + '");>' + data1.Table[i].billing_no + '<i class="fa fa-angle-double-down ml-20"></i></td><td><button type="button" class="btn btn-primaryuse btn-xs mr-5" onclick=requestedit(' + data1.Table[i].billing_no + ')><i class="fa fa-pencil-square-o" aria-hidden="true"></i></button><button type="button" class="btn btn-danger btn-xs mr-5" onclick=requestdelete(' + data1.Table[i].billing_no + ')><i class="fa fa-trash" aria-hidden="true"></i></button></td></tr>'
                            if (data1.Table[i].payment_type == 0 || data1.Table[i].payment_type == 2 || parseFloat(data1.Table[i].due_amount) == 0) {
                                row_data = row_data + '<tr id=reqv' + i + ' ><td onclick=billingdetails(this,"' + data1.Table[i].billing_no + '")>' + (i + 1) + " " + Mobile + '</td><td>' + data1.Table[i].created_on + '</td><td class="details-control" id=service' + i + ' onclick=billingdetails(this,"' + data1.Table[i].billing_no + '") style=" width: 10% !important;">' + data1.Table[i].billing_code + '</td><td onclick=billingdetails(this,"' + data1.Table[i].billing_no + '")>' + type + '</td><td onclick=billingdetails(this,"' + data1.Table[i].billing_no + '")>' + data1.Table[i].total_amount + '</td><td>' + data1.Table[i].total_discount_amount + '</td><td onclick=billingdetails(this,"' + data1.Table[i].billing_no + '")>₹ ' + netamount + '</td><td onclick=billingdetails(this,"' + data1.Table[i].billing_no + '")> ₹ ' + data1.Table[i].advance_amount + '</td><td onclick=billingdetails(this,"' + data1.Table[i].billing_no + '")>₹ ' + claim_amount + '</td><td onclick=billingdetails(this,"' + data1.Table[i].billing_no + '")> ₹' + data1.Table[i].received_amount + '</td><td onclick=billingdetails(this,"' + data1.Table[i].billing_no + '")> ₹' + data1.Table[i].due_amount + '</td><td>' + status + '</td><td>' + other_info + '</td></tr>'
                            }
                            else {
                                //row_data = row_data + '<tr id=reqv' + i + ' ><td onclick=billingdetails(this,"' + data1.Table[i].billing_no + '")>' + (i + 1) + '</td><td onclick=billingdetails(this,"' + data1.Table[i].billing_no + '")>' + data1.Table[i].branch_id + '</td><td>' + data1.Table[i].created_on + '</td><td class="details-control" id=service' + i + ' onclick=billingdetails(this,"' + data1.Table[i].billing_no + '") style=" width: 10% !important;">' + data1.Table[i].billing_code + '<i class="fa fa-angle-double-down ml-20"></i></td><td onclick=billingdetails(this,"' + data1.Table[i].billing_no + '")>' + data1.Table[i].patient_id + '</td><td onclick=billingdetails(this,"' + data1.Table[i].billing_no + '")>' + data1.Table[i].patient_name + '</td><td onclick=billingdetails(this,"' + data1.Table[i].billing_no + '")>' + data1.Table[i].total_amount + '</td><td onclick=billingdetails(this,"' + data1.Table[i].billing_no + '")>' + data1.Table[i].total_discount_amount + '</td><td onclick=billingdetails(this,"' + data1.Table[i].billing_no + '")>' + netamount + '</td><td onclick=billingdetails(this,"' + data1.Table[i].billing_no + '")>' + data1.Table[i].received_amount + '</td><td onclick=billingdetails(this,"' + data1.Table[i].billing_no + '")>' + data1.Table[i].due_amount + '</td><td><button type="button" class="btn btn-primaryuse btn-xs mr-5" onclick=lookup("' + data1.Table[i].cc_invoiceid + '","' + data1.Table[i].sms_invoice_no + '","' + data1.Table[i].cc_date + '")>Check Status</button><button type="button" class="btn btn-primaryuse btn-xs mr-5" onclick=resent("' + data1.Table[i].cc_invoiceid + '","' + data1.Table[i].tiny_url + '","' + data1.Table[i].phone_number + '","'+data1.Table[i].total_net_amount+'")>Resend link</button></td></tr>'
                                row_data = row_data + '<tr id=reqv' + i + ' ><td onclick=billingdetails(this,"' + data1.Table[i].billing_no + '")>' + (i + 1) + " " + Mobile + '</td><td>' + data1.Table[i].created_on + '</td><td class="details-control" id=service' + i + ' onclick=billingdetails(this,"' + data1.Table[i].billing_no + '") style=" width: 10% !important;">' + data1.Table[i].billing_code + '</td><td onclick=billingdetails(this,"' + data1.Table[i].billing_no + '")>' + type + '</td><td onclick=billingdetails(this,"' + data1.Table[i].billing_no + '")>' + data1.Table[i].total_amount + '</td><td>' + data1.Table[i].total_discount_amount + '</td><td onclick=billingdetails(this,"' + data1.Table[i].billing_no + '")> ₹ ' + netamount + '</td><td onclick=billingdetails(this,"' + data1.Table[i].billing_no + '")> ₹ ' + data1.Table[i].advance_amount + '</td><td onclick=billingdetails(this,"' + data1.Table[i].billing_no + '")> ₹ ' + claim_amount + '</td><td onclick=billingdetails(this,"' + data1.Table[i].billing_no + '")> ₹ ' + data1.Table[i].received_amount + '</td><td onclick=billingdetails(this,"' + data1.Table[i].billing_no + '")> ₹ ' + data1.Table[i].due_amount + '</td><td>' + status + '</td><td class="disp_if">' + other_info + '<button type="button" class="btn btn-primaryuse btn-xs mr-5" onclick=lookup("' + data1.Table[i].cc_invoiceid + '","' + data1.Table[i].sms_invoice_no + '","' + data1.Table[i].cc_date + '")>Check Status</button></td></tr>'

                            }
                        }
                        $('#billing_view_diag_body').html(row_data);
                        // $('#billing_view_diag').DataTable();
                        datatable("billing_view_diag");
                        // datatable('tbl_billing', 'billing_view', 'Legal');
                    }
                    else {
                        console.log(data1);
                        //   $('#billing_view_diag').DataTable();
                        datatable("billing_view_diag");
                        // datatable('tbl_billing', 'billing_view', 'Legal');
                    }
                }
            }
            else {
                console.log(data1);
                //    $('#billing_view_diag').DataTable();
                datatable("billing_view_diag");
                //  datatable('tbl_billing', 'billing_view', 'Legal');
            }
        }
    });
}


$('#paid_tab').click(function () {
    debugger;
    billing_paid_table();
})

function billing_paid_table() {
    debugger;
    var branch = ($('#hiddenRole_id').val() == "2") ? $('#SelBranchSearchPopup').val() : $('#HospitalBranchID').val();
    var patient_id = $('#Hpatient_id').val();

    debugger;
    $('#shade_slot').show();
    var DoctorData = {
        dml_indicator: "PBVP",
        hospital_id: $('#HospitalId').val(),
        branch_id: branch,
        patient_id: patient_id
    }
    $.ajax({
        async: true,
        type: 'POST',
        url: '/Billing/IP_OP_Billings',
        contentType: 'application/json; charset=UTF-8',
        data: JSON.stringify(DoctorData),
        success: function (data) {
            $('#patient_paid_billing_view_body').empty();
            $('#patient_paid_billing_view').dataTable().fnClearTable();
            $('#patient_paid_billing_view').dataTable().fnDraw();
            $('#patient_paid_billing_view').dataTable().fnDestroy();

            var data1 = JSON.parse(data)
            console.log(data1);
            $('#shade_slot').hide();
            debugger;
            if (data1.msg == "Success") {
                debugger;
                if (jQuery.isEmptyObject((data1.data))) {
                }
                else {
                    debugger;
                    var data1 = data1.data;
                    var row_data = "", Discharge = "", bill_due = '', refund = "";


                    if (data1.Table.length > 0) {

                        $('#patient_paid_billing_view_body').empty();
                        $('#patient_paid_billing_view').dataTable().fnClearTable();
                        $('#patient_paid_billing_view').dataTable().fnDraw();
                        $('#patient_paid_billing_view').dataTable().fnDestroy();

                        for (var i = 0; i < data1.Table.length; i++) {
                            bill_due = '';
                            var visit_type = data1.Table[i].visit_type;
                            var is_insurance = data1.Table[i].is_entity;
                            var type = '', IP_GatewayPass = '', Mobile = '';
                            if (visit_type == 1 || visit_type == 5 || visit_type == 6) {
                                type = '<span class="label label-used">OP</span>'
                            }
                            if (visit_type == 2) {
                                type = '<span class="label label-info">IP</span>'
                            }
                            if (visit_type == 1 && is_insurance == 1) {
                                type = '<span class="label label-used">OP ' + data1.Table[i].claim_status + '</span>'
                            }
                            if (visit_type == 2 && is_insurance == 1) {
                                type = '<span class="label label-info">IP ' + data1.Table[i].claim_status + '</span>'
                            }
                            if (visit_type == 3) {
                                type = '<span class="label label-warning">Homecare</span>'
                            }
                            if (visit_type == 4) {
                                type = '<span class="label label-primary">Diagnostics</span>'
                            }
                            if (visit_type == 7) {
                                type = '<span class="label label-primary">Daycare</span>'
                            }
                            if (visit_type == 8) {
                                type = '<span class="label label-primary">Emergency Registration</span>'
                            }
                            if (data1.Table[i].visit_type == 2 && data1.Table[i].ip_visit_report_status == 1 && parseFloat(data1.Table[i].due_amount) == 0) {
                                //Discharge = '<a onclick=IPDischarge("' + data1.Table[i].visit_report_id + '",' + data1.Table[i].due_amount + ')>Discharge</a>';
                                Discharge = '<a   onclick=discharge_reason("' + data1.Table[i].visit_report_id + '",' + data1.Table[i].due_amount + ',' + data1.Table[i].branch_id + ')>Discharge</a>';
                            }
                            else if (data1.Table[i].visit_type == 2 && data1.Table[i].ip_visit_report_status == 2) {
                                Discharge = '';
                                Discharge = '<button  data-toggle="tooltip" data-placement="bottom" title="IP Gate Pass Print" type="button" class="btn btn-print btn-xs mr-5" onclick=IP_GatewayPass("' + data1.Table[i].visit_report_id + '",' + data1.Table[i].hospitalid + ',' + data1.Table[i].branch_id + ')>IP Gate Pass Print</button>';
                            }
                            else {
                                Discharge = '';
                                //IP_GatewayPass = '<button  data-toggle="tooltip" data-placement="bottom" title="Draft Summary Prinrt" type="button" class="btn btn-print btn-xs mr-5" onclick=IP_GatewayPass("' + data1.Table[i].visit_report_id + '",' + data1.Table[i].hospitalid + ',' + data1.Table[i].branch_id + ')>IP Gateway Pass</button>';
                            }
                            var status = '<span class="label label-success" style="margin-left: 8px;">Paid</span>';
                            if (parseFloat(data1.Table[i].due_amount) > 0) {
                                bill_due = '<a class="btn_r" style="cursor:pointer;" data-id="B_F1" data-type="role_rights_function"  data-name="/BillingMaster/billing_receipt?Billing_no=' + data1.Table[i].billing_no + ' " data-nav="redirect">Due Payment</a>';
                                status = '<span class="label label-danger" style="margin-left: 8px;">Due Payment</span>';
                            }


                            var netamount = data1.Table[i].total_net_amount   //- data1.Table[i].total_discount_amount;
                            var claim_amount = parseFloat(data1.Table[i].approved_amount) + parseFloat(data1.Table[i].mou_discount) + parseFloat(data1.Table[i].co_pay) + parseFloat(data1.Table[i].other_discount);

                            //  var edit = '<button type="button" class="btn btn-edit btn-xs mr-5" data-id="B_E1" data-type="role_rights_edit" data-nav="" data-name="" onclick=requestedit(' + data1.Table[i].billing_no + ',' + data1.Table[i].branch_id + ',"' + data1.Table[i].visit_report_id + '",' + data1.Table[i].due_amount + ',this)><i class="fa fa-pencil" aria-hidden="true"></i></button>';
                            // var Del = '<button type="button" class="btn btn-delete btn-xs mr-5" data-id="B_D1" data-type="role_rights_delete" data-nav="" data-name="" onclick=requestdelete(' + data1.Table[i].billing_no + ',this)><i class="fa fa-trash-o" aria-hidden="true"></i></button>';
                            //var Del = '';
                            var view = '<button type="button" class="btn btn-blue btn-xs mr-5" data-id="B_V1" data-type="role_rights_view" data-nav="" data-name="" onclick=bill_preview(' + data1.Table[i].billing_no + ',' + data1.Table[i].patientid + ',' + data1.Table[i].hospitalid + ',' + data1.Table[i].branch_id + ',' + data1.Table[i].visit_type + ',this)><i class="fa fa fa-eye" aria-hidden="true"></i></button>';
                            var ipprint = '';
                            var ipdetails = '';
                            var a5print = '';
                            var a4print = '';
                            var reportPrintButtons = '';
                            var claim = '';
                            if (data1.Table[i].is_entity == '1') {
                                claim = '<a class="btn_r btn-blue" style="cursor:pointer;" data-id="B_F1" data-type="role_rights_function"  data-name="/BillingMaster/index?billcopyno=' + data1.Table[i].billing_copy_no + '&Patient_Id=' + data1.Table[i].patient_id + '&Branch_id=' + data1.Table[i].branch_id + ' " data-nav="redirect">Edit Insurance Bill</a>'
                            }
                            if (data1.Table[i].visit_type == 2) {
                                ipprint = '<button type="button" class="btn btn-blue btn-xs mr-5" data-id="B_F1" data-type="role_rights_function" data-nav="" data-name="" onclick=ip_bill_report(' + data1.Table[i].billing_no + ',' + data1.Table[i].patientid + ',' + data1.Table[i].hospitalid + ',' + data1.Table[i].branch_id + ',' + data1.Table[i].visit_type + ',this)><i class="fa fa fa-print" aria-hidden="true"></i> IP Summary </button>';
                                ipdetails = '<button type="button" class="btn btn-blue btn-xs mr-5" data-id="B_F1" data-type="role_rights_function" data-nav="" data-name="" onclick=ip_detail_report(' + data1.Table[i].billing_no + ',' + data1.Table[i].patientid + ',' + data1.Table[i].hospitalid + ',' + data1.Table[i].branch_id + ',' + data1.Table[i].visit_type + ',this)><i class="fa fa fa-print" aria-hidden="true"></i> IP Details </button>';
                                reportPrintButtons = '<li class="text-left">' + ipprint + '</li><li class="text-left">' + ipdetails + '</li>';

                            }
                            else {
                                print = '<button type="button" class="btn btn-blue btn-xs mr-5" data-id="B_F1" data-type="role_rights_function" data-nav="" data-name="" onclick=bill_report(' + data1.Table[i].billing_no + ',' + data1.Table[i].patientid + ',' + data1.Table[i].hospitalid + ',' + data1.Table[i].branch_id + ',' + '1' + ',this)><i class="fa fa fa-print" aria-hidden="true"></i> A4 Print </button>';
                                print1 = '<button type="button" class="btn btn-blue btn-xs mr-5" data-id="B_F1" data-type="role_rights_function" data-nav="" data-name="" onclick=bill_report(' + data1.Table[i].billing_no + ',' + data1.Table[i].patientid + ',' + data1.Table[i].hospitalid + ',' + data1.Table[i].branch_id + ',' + '2' + ',this)><i class="fa fa fa-print" aria-hidden="true"></i> A5 Print </button>';
                                reportPrintButtons = '<li class="text-left">' + print + '</li><li class="text-left">' + print1 + '</li>'
                            }

                            if (data1.Table[i].due_amount > 0) {
                                refund = '';
                            }
                            else {
                                refund = '<a class="btn_r btn-blue" style="cursor:pointer;" data-id="B_F1" data-type="role_rights_function"  data-name="/BillingMaster/refund?Billcode=' + data1.Table[i].billing_no + '&Patient_Id=' + data1.Table[i].patient_id + '&billing_type=4&Branch_id=' + data1.Table[i].branch_id + ' " data-nav="redirect">Refund</a>';
                            }

                            if (data1.Table[i].billing_channel == 2) {
                                Mobile = '<i class="fa fa-mobile icon-design ml-10 mr-10" style="color:blue;font-size:20px;" title="APP BILL" aria-hidden="true"></i>';
                            }
                            else {
                                Mobile = '';
                            }

                            //var refund = '<a class="btn_r" style="cursor:pointer;" data-id="B_F1" data-type="role_rights_function"  data-name="/BillingMaster/refund?Billcode=' + data1.Table[i].billing_no + '&Patient_Id=' + data1.Table[i].patient_id + '&billing_type=4&Branch_id=' + data1.Table[i].branch_id + ' " data-nav="redirect">Refund</a>';

                            other_info = '<div class="col-md-12 padding0"><div class="disp_if"><a href="#" class="dropdown-toggle btn btn-info-dots btn-xs" data-toggle="dropdown" aria-expanded="true"><span class="fa fa-ellipsis-h" data-toggle="tooltip" data-placement="bottom" title="Other Options" style="color:black;" aria-hidden="true"></span><span class="sr-only">Options</span></a><div class="dropdown-menu info-dropdown-workorder" id="">' + reportPrintButtons + '</ul></div></div>';
                            //row_data = row_data + '<tr id=reqv' + i + '><td>' + (i + 1) + '</td><td>' + data1.Table[i].billing_code + '</td><td>' + data1.Table[i].visit_report_id + '</td><td>' + data1.Table[i].total_amount + '</td><td>' + data1.Table[i].due_amount + '</td><td>' + data1.Table[i].received_amount + '</td><td class="details-control" id=service' + i + ' onclick=billingdetails(this,"' + data1.Table[i].billing_no + '");>' + data1.Table[i].billing_no + '<i class="fa fa-angle-double-down ml-20"></i></td><td><button type="button" class="btn btn-primaryuse btn-xs mr-5" onclick=requestedit(' + data1.Table[i].billing_no + ')><i class="fa fa-pencil-square-o" aria-hidden="true"></i></button><button type="button" class="btn btn-danger btn-xs mr-5" onclick=requestdelete(' + data1.Table[i].billing_no + ')><i class="fa fa-trash" aria-hidden="true"></i></button></td></tr>'
                            if (data1.Table[i].payment_type == 0 || data1.Table[i].payment_type == 2 || parseFloat(data1.Table[i].due_amount) == 0) {
                                row_data = row_data + '<tr id=reqv' + i + ' ><td onclick=billingdetails(this,"' + data1.Table[i].billing_no + '")>' + (i + 1) + " " + Mobile + '</td><td>' + data1.Table[i].created_on + '</td><td class="details-control" id=service' + i + ' onclick=billingdetails(this,"' + data1.Table[i].billing_no + '") style=" width: 10% !important;">' + data1.Table[i].billing_code + '</td><td onclick=billingdetails(this,"' + data1.Table[i].billing_no + '")>' + type + '</td><td onclick=billingdetails(this,"' + data1.Table[i].billing_no + '")>' + data1.Table[i].total_amount + '</td><td>' + data1.Table[i].total_discount_amount + '</td><td onclick=billingdetails(this,"' + data1.Table[i].billing_no + '")>₹ ' + netamount + '</td><td onclick=billingdetails(this,"' + data1.Table[i].billing_no + '")> ₹ ' + data1.Table[i].advance_amount + '</td><td onclick=billingdetails(this,"' + data1.Table[i].billing_no + '")>₹ ' + claim_amount + '</td><td onclick=billingdetails(this,"' + data1.Table[i].billing_no + '")> ₹' + data1.Table[i].received_amount + '</td><td onclick=billingdetails(this,"' + data1.Table[i].billing_no + '")> ₹' + data1.Table[i].due_amount + '</td><td>' + status + '</td><td>' + other_info + '</td></tr>'
                            }
                            else {
                                //row_data = row_data + '<tr id=reqv' + i + ' ><td onclick=billingdetails(this,"' + data1.Table[i].billing_no + '")>' + (i + 1) + '</td><td onclick=billingdetails(this,"' + data1.Table[i].billing_no + '")>' + data1.Table[i].branch_id + '</td><td>' + data1.Table[i].created_on + '</td><td class="details-control" id=service' + i + ' onclick=billingdetails(this,"' + data1.Table[i].billing_no + '") style=" width: 10% !important;">' + data1.Table[i].billing_code + '<i class="fa fa-angle-double-down ml-20"></i></td><td onclick=billingdetails(this,"' + data1.Table[i].billing_no + '")>' + data1.Table[i].patient_id + '</td><td onclick=billingdetails(this,"' + data1.Table[i].billing_no + '")>' + data1.Table[i].patient_name + '</td><td onclick=billingdetails(this,"' + data1.Table[i].billing_no + '")>' + data1.Table[i].total_amount + '</td><td onclick=billingdetails(this,"' + data1.Table[i].billing_no + '")>' + data1.Table[i].total_discount_amount + '</td><td onclick=billingdetails(this,"' + data1.Table[i].billing_no + '")>' + netamount + '</td><td onclick=billingdetails(this,"' + data1.Table[i].billing_no + '")>' + data1.Table[i].received_amount + '</td><td onclick=billingdetails(this,"' + data1.Table[i].billing_no + '")>' + data1.Table[i].due_amount + '</td><td><button type="button" class="btn btn-primaryuse btn-xs mr-5" onclick=lookup("' + data1.Table[i].cc_invoiceid + '","' + data1.Table[i].sms_invoice_no + '","' + data1.Table[i].cc_date + '")>Check Status</button><button type="button" class="btn btn-primaryuse btn-xs mr-5" onclick=resent("' + data1.Table[i].cc_invoiceid + '","' + data1.Table[i].tiny_url + '","' + data1.Table[i].phone_number + '","'+data1.Table[i].total_net_amount+'")>Resend link</button></td></tr>'
                                row_data = row_data + '<tr id=reqv' + i + ' ><td onclick=billingdetails(this,"' + data1.Table[i].billing_no + '")>' + (i + 1) + " " + Mobile + '</td><td>' + data1.Table[i].created_on + '</td><td class="details-control" id=service' + i + ' onclick=billingdetails(this,"' + data1.Table[i].billing_no + '") style=" width: 10% !important;">' + data1.Table[i].billing_code + '</td><td onclick=billingdetails(this,"' + data1.Table[i].billing_no + '")>' + type + '</td><td onclick=billingdetails(this,"' + data1.Table[i].billing_no + '")>' + data1.Table[i].total_amount + '</td><td>' + data1.Table[i].total_discount_amount + '</td><td onclick=billingdetails(this,"' + data1.Table[i].billing_no + '")> ₹ ' + netamount + '</td><td onclick=billingdetails(this,"' + data1.Table[i].billing_no + '")> ₹ ' + data1.Table[i].advance_amount + '</td><td onclick=billingdetails(this,"' + data1.Table[i].billing_no + '")> ₹ ' + claim_amount + '</td><td onclick=billingdetails(this,"' + data1.Table[i].billing_no + '")> ₹ ' + data1.Table[i].received_amount + '</td><td onclick=billingdetails(this,"' + data1.Table[i].billing_no + '")> ₹ ' + data1.Table[i].due_amount + '</td><td>' + status + '</td><td class="disp_if">' + other_info + '<button type="button" class="btn btn-primaryuse btn-xs mr-5" onclick=lookup("' + data1.Table[i].cc_invoiceid + '","' + data1.Table[i].sms_invoice_no + '","' + data1.Table[i].cc_date + '")>Check Status</button></td></tr>'

                            }
                        }
                        $('#patient_paid_billing_view_body').html(row_data);
                        //  $('#patient_paid_billing_view').DataTable();
                        datatable("patient_paid_billing_view");
                        // datatable('tbl_billing', 'billing_view', 'Legal');
                    }
                    else {
                        console.log(data1);
                        //  $('#patient_paid_billing_view').DataTable();
                        datatable("patient_paid_billing_view");
                        // datatable('tbl_billing', 'billing_view', 'Legal');
                    }
                }
            }
            else {
                console.log(data1);
                //   $('#patient_paid_billing_view').DataTable();
                datatable("patient_paid_billing_view");
                //  datatable('tbl_billing', 'billing_view', 'Legal');
            }
        }
    });
}


$('#paidhome_tab').click(function () {
    debugger;
    billing_paid_table_home();
})

function billing_paid_table_home() {
    debugger;
    var branch = ($('#hiddenRole_id').val() == "2") ? $('#SelBranchSearchPopup').val() : $('#HospitalBranchID').val();
    var patient_id = $('#Hpatient_id').val();

    debugger;
    $('#shade_slot').show();
    var DoctorData = {
        dml_indicator: "PBVPH",
        hospital_id: $('#HospitalId').val(),
        branch_id: branch,
        patient_id: patient_id
    }
    $.ajax({
        async: true,
        type: 'POST',
        url: '/Billing/IP_OP_Billings',
        contentType: 'application/json; charset=UTF-8',
        data: JSON.stringify(DoctorData),
        success: function (data) {
            $('#paid_billview_home_body').empty();
            $('#paid_billview_home').dataTable().fnClearTable();
            $('#paid_billview_home').dataTable().fnDraw();
            $('#paid_billview_home').dataTable().fnDestroy();

            var data1 = JSON.parse(data)
            console.log(data1);
            $('#shade_slot').hide();
            debugger;
            if (data1.msg == "Success") {
                debugger;
                if (jQuery.isEmptyObject((data1.data))) {
                }
                else {
                    debugger;
                    var data1 = data1.data;
                    var row_data = "", Discharge = "", bill_due = '', refund = "";


                    if (data1.Table.length > 0) {

                        $('#paid_billview_home_body').empty();
                        $('#paid_billview_home').dataTable().fnClearTable();
                        $('#paid_billview_home').dataTable().fnDraw();
                        $('#paid_billview_home').dataTable().fnDestroy();

                        for (var i = 0; i < data1.Table.length; i++) {
                            bill_due = '';
                            var visit_type = data1.Table[i].visit_type;
                            var is_insurance = data1.Table[i].is_entity;
                            var type = '', IP_GatewayPass = '', Mobile = '';
                            if (visit_type == 1 || visit_type == 5 || visit_type == 6) {
                                type = '<span class="label label-used">OP</span>'
                            }
                            if (visit_type == 2) {
                                type = '<span class="label label-info">IP</span>'
                            }
                            if (visit_type == 1 && is_insurance == 1) {
                                type = '<span class="label label-used">OP ' + data1.Table[i].claim_status + '</span>'
                            }
                            if (visit_type == 2 && is_insurance == 1) {
                                type = '<span class="label label-info">IP ' + data1.Table[i].claim_status + '</span>'
                            }
                            if (visit_type == 3) {
                                type = '<span class="label label-warning">Homecare</span>'
                            }
                            if (visit_type == 4) {
                                type = '<span class="label label-primary">Diagnostics</span>'
                            }
                            if (visit_type == 7) {
                                type = '<span class="label label-primary">Daycare</span>'
                            }
                            if (visit_type == 8) {
                                type = '<span class="label label-primary">Emergency Registration</span>'
                            }
                            if (data1.Table[i].visit_type == 2 && data1.Table[i].ip_visit_report_status == 1 && parseFloat(data1.Table[i].due_amount) == 0) {
                                //Discharge = '<a onclick=IPDischarge("' + data1.Table[i].visit_report_id + '",' + data1.Table[i].due_amount + ')>Discharge</a>';
                                Discharge = '<a   onclick=discharge_reason("' + data1.Table[i].visit_report_id + '",' + data1.Table[i].due_amount + ',' + data1.Table[i].branch_id + ')>Discharge</a>';
                            }
                            else if (data1.Table[i].visit_type == 2 && data1.Table[i].ip_visit_report_status == 2) {
                                Discharge = '';
                                Discharge = '<button  data-toggle="tooltip" data-placement="bottom" title="IP Gate Pass Print" type="button" class="btn btn-print btn-xs mr-5" onclick=IP_GatewayPass("' + data1.Table[i].visit_report_id + '",' + data1.Table[i].hospitalid + ',' + data1.Table[i].branch_id + ')>IP Gate Pass Print</button>';
                            }
                            else {
                                Discharge = '';
                                //IP_GatewayPass = '<button  data-toggle="tooltip" data-placement="bottom" title="Draft Summary Prinrt" type="button" class="btn btn-print btn-xs mr-5" onclick=IP_GatewayPass("' + data1.Table[i].visit_report_id + '",' + data1.Table[i].hospitalid + ',' + data1.Table[i].branch_id + ')>IP Gateway Pass</button>';
                            }
                            var status = '<span class="label label-success" style="margin-left: 8px;">Paid</span>';
                            if (parseFloat(data1.Table[i].due_amount) > 0) {
                                bill_due = '<a class="btn_r" style="cursor:pointer;" data-id="B_F1" data-type="role_rights_function"  data-name="/BillingMaster/billing_receipt?Billing_no=' + data1.Table[i].billing_no + ' " data-nav="redirect">Due Payment</a>';
                                status = '<span class="label label-danger" style="margin-left: 8px;">Due Payment</span>';
                            }


                            var netamount = data1.Table[i].total_net_amount   //- data1.Table[i].total_discount_amount;
                            var claim_amount = parseFloat(data1.Table[i].approved_amount) + parseFloat(data1.Table[i].mou_discount) + parseFloat(data1.Table[i].co_pay) + parseFloat(data1.Table[i].other_discount);

                            //  var edit = '<button type="button" class="btn btn-edit btn-xs mr-5" data-id="B_E1" data-type="role_rights_edit" data-nav="" data-name="" onclick=requestedit(' + data1.Table[i].billing_no + ',' + data1.Table[i].branch_id + ',"' + data1.Table[i].visit_report_id + '",' + data1.Table[i].due_amount + ',this)><i class="fa fa-pencil" aria-hidden="true"></i></button>';
                            //var Del = '<button type="button" class="btn btn-delete btn-xs mr-5" data-id="B_D1" data-type="role_rights_delete" data-nav="" data-name="" onclick=requestdelete(' + data1.Table[i].billing_no + ',this)><i class="fa fa-trash-o" aria-hidden="true"></i></button>';
                            //var Del = '';
                            var view = '<button type="button" class="btn btn-blue btn-xs mr-5" data-id="B_V1" data-type="role_rights_view" data-nav="" data-name="" onclick=bill_preview(' + data1.Table[i].billing_no + ',' + data1.Table[i].patientid + ',' + data1.Table[i].hospitalid + ',' + data1.Table[i].branch_id + ',' + data1.Table[i].visit_type + ',this)><i class="fa fa fa-eye" aria-hidden="true"></i></button>';
                            var ipprint = '';
                            var ipdetails = '';
                            var a5print = '';
                            var a4print = '';
                            var reportPrintButtons = '';
                            var claim = '';
                            if (data1.Table[i].is_entity == '1') {
                                claim = '<a class="btn_r btn-blue" style="cursor:pointer;" data-id="B_F1" data-type="role_rights_function"  data-name="/BillingMaster/index?billcopyno=' + data1.Table[i].billing_copy_no + '&Patient_Id=' + data1.Table[i].patient_id + '&Branch_id=' + data1.Table[i].branch_id + ' " data-nav="redirect">Edit Insurance Bill</a>'
                            }
                            if (data1.Table[i].visit_type == 2) {
                                ipprint = '<button type="button" class="btn btn-blue btn-xs mr-5" data-id="B_F1" data-type="role_rights_function" data-nav="" data-name="" onclick=ip_bill_report(' + data1.Table[i].billing_no + ',' + data1.Table[i].patientid + ',' + data1.Table[i].hospitalid + ',' + data1.Table[i].branch_id + ',' + data1.Table[i].visit_type + ',this)><i class="fa fa fa-print" aria-hidden="true"></i> IP Summary </button>';
                                ipdetails = '<button type="button" class="btn btn-blue btn-xs mr-5" data-id="B_F1" data-type="role_rights_function" data-nav="" data-name="" onclick=ip_detail_report(' + data1.Table[i].billing_no + ',' + data1.Table[i].patientid + ',' + data1.Table[i].hospitalid + ',' + data1.Table[i].branch_id + ',' + data1.Table[i].visit_type + ',this)><i class="fa fa fa-print" aria-hidden="true"></i> IP Details </button>';
                                reportPrintButtons = '<li class="text-left">' + ipprint + '</li><li class="text-left">' + ipdetails + '</li>';

                            }
                            else {
                                print = '<button type="button" class="btn btn-blue btn-xs mr-5" data-id="B_F1" data-type="role_rights_function" data-nav="" data-name="" onclick=bill_report(' + data1.Table[i].billing_no + ',' + data1.Table[i].patientid + ',' + data1.Table[i].hospitalid + ',' + data1.Table[i].branch_id + ',' + '1' + ',this)><i class="fa fa fa-print" aria-hidden="true"></i> A4 Print </button>';
                                print1 = '<button type="button" class="btn btn-blue btn-xs mr-5" data-id="B_F1" data-type="role_rights_function" data-nav="" data-name="" onclick=bill_report(' + data1.Table[i].billing_no + ',' + data1.Table[i].patientid + ',' + data1.Table[i].hospitalid + ',' + data1.Table[i].branch_id + ',' + '2' + ',this)><i class="fa fa fa-print" aria-hidden="true"></i> A5 Print </button>';
                                reportPrintButtons = '<li class="text-left">' + print + '</li><li class="text-left">' + print1 + '</li>'
                            }

                            if (data1.Table[i].due_amount > 0) {
                                refund = '';
                            }
                            else {
                                refund = '<a class="btn_r btn-blue" style="cursor:pointer;" data-id="B_F1" data-type="role_rights_function"  data-name="/BillingMaster/refund?Billcode=' + data1.Table[i].billing_no + '&Patient_Id=' + data1.Table[i].patient_id + '&billing_type=4&Branch_id=' + data1.Table[i].branch_id + ' " data-nav="redirect">Refund</a>';
                            }

                            if (data1.Table[i].billing_channel == 2) {
                                Mobile = '<i class="fa fa-mobile icon-design ml-10 mr-10" style="color:blue;font-size:20px;" title="APP BILL" aria-hidden="true"></i>';
                            }
                            else {
                                Mobile = '';
                            }

                            //var refund = '<a class="btn_r" style="cursor:pointer;" data-id="B_F1" data-type="role_rights_function"  data-name="/BillingMaster/refund?Billcode=' + data1.Table[i].billing_no + '&Patient_Id=' + data1.Table[i].patient_id + '&billing_type=4&Branch_id=' + data1.Table[i].branch_id + ' " data-nav="redirect">Refund</a>';

                            other_info = '<div class="col-md-12 padding0"><div class="disp_if"><a href="#" class="dropdown-toggle btn btn-info-dots btn-xs" data-toggle="dropdown" aria-expanded="true"><span class="fa fa-ellipsis-h" data-toggle="tooltip" data-placement="bottom" title="Other Options" style="color:black;" aria-hidden="true"></span><span class="sr-only">Options</span></a><div class="dropdown-menu info-dropdown-workorder" id="">' + reportPrintButtons + '</ul></div></div>';

                            //row_data = row_data + '<tr id=reqv' + i + '><td>' + (i + 1) + '</td><td>' + data1.Table[i].billing_code + '</td><td>' + data1.Table[i].visit_report_id + '</td><td>' + data1.Table[i].total_amount + '</td><td>' + data1.Table[i].due_amount + '</td><td>' + data1.Table[i].received_amount + '</td><td class="details-control" id=service' + i + ' onclick=billingdetails(this,"' + data1.Table[i].billing_no + '");>' + data1.Table[i].billing_no + '<i class="fa fa-angle-double-down ml-20"></i></td><td><button type="button" class="btn btn-primaryuse btn-xs mr-5" onclick=requestedit(' + data1.Table[i].billing_no + ')><i class="fa fa-pencil-square-o" aria-hidden="true"></i></button><button type="button" class="btn btn-danger btn-xs mr-5" onclick=requestdelete(' + data1.Table[i].billing_no + ')><i class="fa fa-trash" aria-hidden="true"></i></button></td></tr>'
                            if (data1.Table[i].payment_type == 0 || data1.Table[i].payment_type == 2 || parseFloat(data1.Table[i].due_amount) == 0) {
                                row_data = row_data + '<tr id=reqv' + i + ' ><td onclick=billingdetails(this,"' + data1.Table[i].billing_no + '")>' + (i + 1) + " " + Mobile + '</td><td>' + data1.Table[i].created_on + '</td><td class="details-control" id=service' + i + ' onclick=billingdetails(this,"' + data1.Table[i].billing_no + '") style=" width: 10% !important;">' + data1.Table[i].billing_code + '</td><td onclick=billingdetails(this,"' + data1.Table[i].billing_no + '")>' + type + '</td><td onclick=billingdetails(this,"' + data1.Table[i].billing_no + '")>' + data1.Table[i].total_amount + '</td><td>' + data1.Table[i].total_discount_amount + '</td><td onclick=billingdetails(this,"' + data1.Table[i].billing_no + '")>₹ ' + netamount + '</td><td onclick=billingdetails(this,"' + data1.Table[i].billing_no + '")> ₹ ' + data1.Table[i].advance_amount + '</td><td onclick=billingdetails(this,"' + data1.Table[i].billing_no + '")>₹ ' + claim_amount + '</td><td onclick=billingdetails(this,"' + data1.Table[i].billing_no + '")> ₹' + data1.Table[i].received_amount + '</td><td onclick=billingdetails(this,"' + data1.Table[i].billing_no + '")> ₹' + data1.Table[i].due_amount + '</td><td>' + status + '</td><td>' + other_info + '</td></tr>'
                            }
                            else {
                                //row_data = row_data + '<tr id=reqv' + i + ' ><td onclick=billingdetails(this,"' + data1.Table[i].billing_no + '")>' + (i + 1) + '</td><td onclick=billingdetails(this,"' + data1.Table[i].billing_no + '")>' + data1.Table[i].branch_id + '</td><td>' + data1.Table[i].created_on + '</td><td class="details-control" id=service' + i + ' onclick=billingdetails(this,"' + data1.Table[i].billing_no + '") style=" width: 10% !important;">' + data1.Table[i].billing_code + '<i class="fa fa-angle-double-down ml-20"></i></td><td onclick=billingdetails(this,"' + data1.Table[i].billing_no + '")>' + data1.Table[i].patient_id + '</td><td onclick=billingdetails(this,"' + data1.Table[i].billing_no + '")>' + data1.Table[i].patient_name + '</td><td onclick=billingdetails(this,"' + data1.Table[i].billing_no + '")>' + data1.Table[i].total_amount + '</td><td onclick=billingdetails(this,"' + data1.Table[i].billing_no + '")>' + data1.Table[i].total_discount_amount + '</td><td onclick=billingdetails(this,"' + data1.Table[i].billing_no + '")>' + netamount + '</td><td onclick=billingdetails(this,"' + data1.Table[i].billing_no + '")>' + data1.Table[i].received_amount + '</td><td onclick=billingdetails(this,"' + data1.Table[i].billing_no + '")>' + data1.Table[i].due_amount + '</td><td><button type="button" class="btn btn-primaryuse btn-xs mr-5" onclick=lookup("' + data1.Table[i].cc_invoiceid + '","' + data1.Table[i].sms_invoice_no + '","' + data1.Table[i].cc_date + '")>Check Status</button><button type="button" class="btn btn-primaryuse btn-xs mr-5" onclick=resent("' + data1.Table[i].cc_invoiceid + '","' + data1.Table[i].tiny_url + '","' + data1.Table[i].phone_number + '","'+data1.Table[i].total_net_amount+'")>Resend link</button></td></tr>'
                                row_data = row_data + '<tr id=reqv' + i + ' ><td onclick=billingdetails(this,"' + data1.Table[i].billing_no + '")>' + (i + 1) + " " + Mobile + '</td><td>' + data1.Table[i].created_on + '</td><td class="details-control" id=service' + i + ' onclick=billingdetails(this,"' + data1.Table[i].billing_no + '") style=" width: 10% !important;">' + data1.Table[i].billing_code + '</td><td onclick=billingdetails(this,"' + data1.Table[i].billing_no + '")>' + type + '</td><td onclick=billingdetails(this,"' + data1.Table[i].billing_no + '")>' + data1.Table[i].total_amount + '</td><td>' + data1.Table[i].total_discount_amount + '</td><td onclick=billingdetails(this,"' + data1.Table[i].billing_no + '")> ₹ ' + netamount + '</td><td onclick=billingdetails(this,"' + data1.Table[i].billing_no + '")> ₹ ' + data1.Table[i].advance_amount + '</td><td onclick=billingdetails(this,"' + data1.Table[i].billing_no + '")> ₹ ' + claim_amount + '</td><td onclick=billingdetails(this,"' + data1.Table[i].billing_no + '")> ₹ ' + data1.Table[i].received_amount + '</td><td onclick=billingdetails(this,"' + data1.Table[i].billing_no + '")> ₹ ' + data1.Table[i].due_amount + '</td><td>' + status + '</td><td class="disp_if">' + other_info + '<button type="button" class="btn btn-primaryuse btn-xs mr-5" onclick=lookup("' + data1.Table[i].cc_invoiceid + '","' + data1.Table[i].sms_invoice_no + '","' + data1.Table[i].cc_date + '")>Check Status</button></td></tr>'

                            }
                        }
                        $('#paid_billview_home_body').html(row_data);
                        //  $('#paid_billview_home').DataTable();
                        datatable("paid_billview_home");
                        // datatable('tbl_billing', 'billing_view', 'Legal');
                    }
                    else {
                        console.log(data1);
                        //    $('#paid_billview_home').DataTable();
                        datatable("paid_billview_home");
                        // datatable('tbl_billing', 'billing_view', 'Legal');
                    }
                }
            }
            else {
                console.log(data1);
                // $('#paid_billview_home').DataTable();
                datatable("paid_billview_home");
                //  datatable('tbl_billing', 'billing_view', 'Legal');
            }
        }
    });
}

$('#paiddiag_tab').click(function () {
    debugger;
    billing_paid_table_diag();
})

function billing_paid_table_diag() {
    debugger;
    var branch = ($('#hiddenRole_id').val() == "2") ? $('#SelBranchSearchPopup').val() : $('#HospitalBranchID').val();
    var patient_id = $('#Hpatient_id').val();

    debugger;
    $('#shade_slot').show();
    var DoctorData = {
        dml_indicator: "PBVPD",
        hospital_id: $('#HospitalId').val(),
        branch_id: branch,
        patient_id: patient_id
    }
    $.ajax({
        async: true,
        type: 'POST',
        url: '/Billing/IP_OP_Billings',
        contentType: 'application/json; charset=UTF-8',
        data: JSON.stringify(DoctorData),
        success: function (data) {
            $('#paid_billview_diag_body').empty();
            $('#paid_billview_diag').dataTable().fnClearTable();
            $('#paid_billview_diag').dataTable().fnDraw();
            $('#paid_billview_diag').dataTable().fnDestroy();

            var data1 = JSON.parse(data)
            console.log(data1);
            $('#shade_slot').hide();
            debugger;
            if (data1.msg == "Success") {
                debugger;
                if (jQuery.isEmptyObject((data1.data))) {
                }
                else {
                    debugger;
                    var data1 = data1.data;
                    var row_data = "", Discharge = "", bill_due = '', refund = "";


                    if (data1.Table.length > 0) {

                        $('#paid_billview_diag_body').empty();
                        $('#paid_billview_diag').dataTable().fnClearTable();
                        $('#paid_billview_diag').dataTable().fnDraw();
                        $('#paid_billview_diag').dataTable().fnDestroy();

                        for (var i = 0; i < data1.Table.length; i++) {
                            bill_due = '';
                            var visit_type = data1.Table[i].visit_type;
                            var is_insurance = data1.Table[i].is_entity;
                            var type = '', IP_GatewayPass = '', Mobile = '';
                            if (visit_type == 1 || visit_type == 5 || visit_type == 6) {
                                type = '<span class="label label-used">OP</span>'
                            }
                            if (visit_type == 2) {
                                type = '<span class="label label-info">IP</span>'
                            }
                            if (visit_type == 1 && is_insurance == 1) {
                                type = '<span class="label label-used">OP ' + data1.Table[i].claim_status + '</span>'
                            }
                            if (visit_type == 2 && is_insurance == 1) {
                                type = '<span class="label label-info">IP ' + data1.Table[i].claim_status + '</span>'
                            }
                            if (visit_type == 3) {
                                type = '<span class="label label-warning">Homecare</span>'
                            }
                            if (visit_type == 4) {
                                type = '<span class="label label-primary">Diagnostics</span>'
                            }
                            if (visit_type == 7) {
                                type = '<span class="label label-primary">Daycare</span>'
                            }
                            if (visit_type == 8) {
                                type = '<span class="label label-primary">Emergency Registration</span>'
                            }
                            if (data1.Table[i].visit_type == 2 && data1.Table[i].ip_visit_report_status == 1 && parseFloat(data1.Table[i].due_amount) == 0) {
                                //Discharge = '<a onclick=IPDischarge("' + data1.Table[i].visit_report_id + '",' + data1.Table[i].due_amount + ')>Discharge</a>';
                                Discharge = '<a   onclick=discharge_reason("' + data1.Table[i].visit_report_id + '",' + data1.Table[i].due_amount + ',' + data1.Table[i].branch_id + ')>Discharge</a>';
                            }
                            else if (data1.Table[i].visit_type == 2 && data1.Table[i].ip_visit_report_status == 2) {
                                Discharge = '';
                                Discharge = '<button  data-toggle="tooltip" data-placement="bottom" title="IP Gate Pass Print" type="button" class="btn btn-print btn-xs mr-5" onclick=IP_GatewayPass("' + data1.Table[i].visit_report_id + '",' + data1.Table[i].hospitalid + ',' + data1.Table[i].branch_id + ')>IP Gate Pass Print</button>';
                            }
                            else {
                                Discharge = '';
                                //IP_GatewayPass = '<button  data-toggle="tooltip" data-placement="bottom" title="Draft Summary Prinrt" type="button" class="btn btn-print btn-xs mr-5" onclick=IP_GatewayPass("' + data1.Table[i].visit_report_id + '",' + data1.Table[i].hospitalid + ',' + data1.Table[i].branch_id + ')>IP Gateway Pass</button>';
                            }
                            var status = '<span class="label label-success" style="margin-left: 8px;">Paid</span>';
                            if (parseFloat(data1.Table[i].due_amount) > 0) {
                                bill_due = '<a class="btn_r" style="cursor:pointer;" data-id="B_F1" data-type="role_rights_function"  data-name="/BillingMaster/billing_receipt?Billing_no=' + data1.Table[i].billing_no + ' " data-nav="redirect">Due Payment</a>';
                                status = '<span class="label label-danger" style="margin-left: 8px;">Due Payment</span>';
                            }


                            var netamount = data1.Table[i].total_net_amount   //- data1.Table[i].total_discount_amount;
                            var claim_amount = parseFloat(data1.Table[i].approved_amount) + parseFloat(data1.Table[i].mou_discount) + parseFloat(data1.Table[i].co_pay) + parseFloat(data1.Table[i].other_discount);

                            //  var edit = '<button type="button" class="btn btn-edit btn-xs mr-5" data-id="B_E1" data-type="role_rights_edit" data-nav="" data-name="" onclick=requestedit(' + data1.Table[i].billing_no + ',' + data1.Table[i].branch_id + ',"' + data1.Table[i].visit_report_id + '",' + data1.Table[i].due_amount + ',this)><i class="fa fa-pencil" aria-hidden="true"></i></button>';
                            //  var Del = '<button type="button" class="btn btn-delete btn-xs mr-5" data-id="B_D1" data-type="role_rights_delete" data-nav="" data-name="" onclick=requestdelete(' + data1.Table[i].billing_no + ',this)><i class="fa fa-trash-o" aria-hidden="true"></i></button>';
                            //var Del = '';
                            var view = '<button type="button" class="btn btn-blue btn-xs mr-5" data-id="B_V1" data-type="role_rights_view" data-nav="" data-name="" onclick=bill_preview(' + data1.Table[i].billing_no + ',' + data1.Table[i].patientid + ',' + data1.Table[i].hospitalid + ',' + data1.Table[i].branch_id + ',' + data1.Table[i].visit_type + ',this)><i class="fa fa fa-eye" aria-hidden="true"></i></button>';
                            var ipprint = '';
                            var ipdetails = '';
                            var a5print = '';
                            var a4print = '';
                            var reportPrintButtons = '';
                            var claim = '';
                            if (data1.Table[i].is_entity == '1') {
                                claim = '<a class="btn_r btn-blue" style="cursor:pointer;" data-id="B_F1" data-type="role_rights_function"  data-name="/BillingMaster/index?billcopyno=' + data1.Table[i].billing_copy_no + '&Patient_Id=' + data1.Table[i].patient_id + '&Branch_id=' + data1.Table[i].branch_id + ' " data-nav="redirect">Edit Insurance Bill</a>'
                            }
                            if (data1.Table[i].visit_type == 2) {
                                ipprint = '<button type="button" class="btn btn-blue btn-xs mr-5" data-id="B_F1" data-type="role_rights_function" data-nav="" data-name="" onclick=ip_bill_report(' + data1.Table[i].billing_no + ',' + data1.Table[i].patientid + ',' + data1.Table[i].hospitalid + ',' + data1.Table[i].branch_id + ',' + data1.Table[i].visit_type + ',this)><i class="fa fa fa-print" aria-hidden="true"></i> IP Summary </button>';
                                ipdetails = '<button type="button" class="btn btn-blue btn-xs mr-5" data-id="B_F1" data-type="role_rights_function" data-nav="" data-name="" onclick=ip_detail_report(' + data1.Table[i].billing_no + ',' + data1.Table[i].patientid + ',' + data1.Table[i].hospitalid + ',' + data1.Table[i].branch_id + ',' + data1.Table[i].visit_type + ',this)><i class="fa fa fa-print" aria-hidden="true"></i> IP Details </button>';
                                reportPrintButtons = '<li class="text-left">' + ipprint + '</li><li class="text-left">' + ipdetails + '</li>';

                            }
                            else {
                                print = '<button type="button" class="btn btn-blue btn-xs mr-5" data-id="B_F1" data-type="role_rights_function" data-nav="" data-name="" onclick=bill_report(' + data1.Table[i].billing_no + ',' + data1.Table[i].patientid + ',' + data1.Table[i].hospitalid + ',' + data1.Table[i].branch_id + ',' + '1' + ',this)><i class="fa fa fa-print" aria-hidden="true"></i> A4 Print </button>';
                                print1 = '<button type="button" class="btn btn-blue btn-xs mr-5" data-id="B_F1" data-type="role_rights_function" data-nav="" data-name="" onclick=bill_report(' + data1.Table[i].billing_no + ',' + data1.Table[i].patientid + ',' + data1.Table[i].hospitalid + ',' + data1.Table[i].branch_id + ',' + '2' + ',this)><i class="fa fa fa-print" aria-hidden="true"></i> A5 Print </button>';
                                reportPrintButtons = '<li class="text-left">' + print + '</li><li class="text-left">' + print1 + '</li>'
                            }

                            if (data1.Table[i].due_amount > 0) {
                                refund = '';
                            }
                            else {
                                refund = '<a class="btn_r btn-blue" style="cursor:pointer;" data-id="B_F1" data-type="role_rights_function"  data-name="/BillingMaster/refund?Billcode=' + data1.Table[i].billing_no + '&Patient_Id=' + data1.Table[i].patient_id + '&billing_type=4&Branch_id=' + data1.Table[i].branch_id + ' " data-nav="redirect">Refund</a>';
                            }

                            if (data1.Table[i].billing_channel == 2) {
                                Mobile = '<i class="fa fa-mobile icon-design ml-10 mr-10" style="color:blue;font-size:20px;" title="APP BILL" aria-hidden="true"></i>';
                            }
                            else {
                                Mobile = '';
                            }

                            //var refund = '<a class="btn_r" style="cursor:pointer;" data-id="B_F1" data-type="role_rights_function"  data-name="/BillingMaster/refund?Billcode=' + data1.Table[i].billing_no + '&Patient_Id=' + data1.Table[i].patient_id + '&billing_type=4&Branch_id=' + data1.Table[i].branch_id + ' " data-nav="redirect">Refund</a>';

                            other_info = '<div class="col-md-12 padding0"><div class="disp_if"><a href="#" class="dropdown-toggle btn btn-info-dots btn-xs" data-toggle="dropdown" aria-expanded="true"><span class="fa fa-ellipsis-h" data-toggle="tooltip" data-placement="bottom" title="Other Options" style="color:black;" aria-hidden="true"></span><span class="sr-only">Options</span></a><div class="dropdown-menu info-dropdown-workorder" id="">' + reportPrintButtons + '</ul></div></div>';

                            //row_data = row_data + '<tr id=reqv' + i + '><td>' + (i + 1) + '</td><td>' + data1.Table[i].billing_code + '</td><td>' + data1.Table[i].visit_report_id + '</td><td>' + data1.Table[i].total_amount + '</td><td>' + data1.Table[i].due_amount + '</td><td>' + data1.Table[i].received_amount + '</td><td class="details-control" id=service' + i + ' onclick=billingdetails(this,"' + data1.Table[i].billing_no + '");>' + data1.Table[i].billing_no + '<i class="fa fa-angle-double-down ml-20"></i></td><td><button type="button" class="btn btn-primaryuse btn-xs mr-5" onclick=requestedit(' + data1.Table[i].billing_no + ')><i class="fa fa-pencil-square-o" aria-hidden="true"></i></button><button type="button" class="btn btn-danger btn-xs mr-5" onclick=requestdelete(' + data1.Table[i].billing_no + ')><i class="fa fa-trash" aria-hidden="true"></i></button></td></tr>'
                            if (data1.Table[i].payment_type == 0 || data1.Table[i].payment_type == 2 || parseFloat(data1.Table[i].due_amount) == 0) {
                                row_data = row_data + '<tr id=reqv' + i + ' ><td onclick=billingdetails(this,"' + data1.Table[i].billing_no + '")>' + (i + 1) + " " + Mobile + '</td><td>' + data1.Table[i].created_on + '</td><td class="details-control" id=service' + i + ' onclick=billingdetails(this,"' + data1.Table[i].billing_no + '") style=" width: 10% !important;">' + data1.Table[i].billing_code + '</td><td onclick=billingdetails(this,"' + data1.Table[i].billing_no + '")>' + type + '</td><td onclick=billingdetails(this,"' + data1.Table[i].billing_no + '")>' + data1.Table[i].total_amount + '</td><td>' + data1.Table[i].total_discount_amount + '</td><td onclick=billingdetails(this,"' + data1.Table[i].billing_no + '")>₹ ' + netamount + '</td><td onclick=billingdetails(this,"' + data1.Table[i].billing_no + '")> ₹ ' + data1.Table[i].advance_amount + '</td><td onclick=billingdetails(this,"' + data1.Table[i].billing_no + '")>₹ ' + claim_amount + '</td><td onclick=billingdetails(this,"' + data1.Table[i].billing_no + '")> ₹' + data1.Table[i].received_amount + '</td><td onclick=billingdetails(this,"' + data1.Table[i].billing_no + '")> ₹' + data1.Table[i].due_amount + '</td><td>' + status + '</td><td>' + other_info + '</td></tr>'
                            }
                            else {
                                //row_data = row_data + '<tr id=reqv' + i + ' ><td onclick=billingdetails(this,"' + data1.Table[i].billing_no + '")>' + (i + 1) + '</td><td onclick=billingdetails(this,"' + data1.Table[i].billing_no + '")>' + data1.Table[i].branch_id + '</td><td>' + data1.Table[i].created_on + '</td><td class="details-control" id=service' + i + ' onclick=billingdetails(this,"' + data1.Table[i].billing_no + '") style=" width: 10% !important;">' + data1.Table[i].billing_code + '<i class="fa fa-angle-double-down ml-20"></i></td><td onclick=billingdetails(this,"' + data1.Table[i].billing_no + '")>' + data1.Table[i].patient_id + '</td><td onclick=billingdetails(this,"' + data1.Table[i].billing_no + '")>' + data1.Table[i].patient_name + '</td><td onclick=billingdetails(this,"' + data1.Table[i].billing_no + '")>' + data1.Table[i].total_amount + '</td><td onclick=billingdetails(this,"' + data1.Table[i].billing_no + '")>' + data1.Table[i].total_discount_amount + '</td><td onclick=billingdetails(this,"' + data1.Table[i].billing_no + '")>' + netamount + '</td><td onclick=billingdetails(this,"' + data1.Table[i].billing_no + '")>' + data1.Table[i].received_amount + '</td><td onclick=billingdetails(this,"' + data1.Table[i].billing_no + '")>' + data1.Table[i].due_amount + '</td><td><button type="button" class="btn btn-primaryuse btn-xs mr-5" onclick=lookup("' + data1.Table[i].cc_invoiceid + '","' + data1.Table[i].sms_invoice_no + '","' + data1.Table[i].cc_date + '")>Check Status</button><button type="button" class="btn btn-primaryuse btn-xs mr-5" onclick=resent("' + data1.Table[i].cc_invoiceid + '","' + data1.Table[i].tiny_url + '","' + data1.Table[i].phone_number + '","'+data1.Table[i].total_net_amount+'")>Resend link</button></td></tr>'
                                row_data = row_data + '<tr id=reqv' + i + ' ><td onclick=billingdetails(this,"' + data1.Table[i].billing_no + '")>' + (i + 1) + " " + Mobile + '</td><td>' + data1.Table[i].created_on + '</td><td class="details-control" id=service' + i + ' onclick=billingdetails(this,"' + data1.Table[i].billing_no + '") style=" width: 10% !important;">' + data1.Table[i].billing_code + '</td><td onclick=billingdetails(this,"' + data1.Table[i].billing_no + '")>' + type + '</td><td onclick=billingdetails(this,"' + data1.Table[i].billing_no + '")>' + data1.Table[i].total_amount + '</td><td>' + data1.Table[i].total_discount_amount + '</td><td onclick=billingdetails(this,"' + data1.Table[i].billing_no + '")> ₹ ' + netamount + '</td><td onclick=billingdetails(this,"' + data1.Table[i].billing_no + '")> ₹ ' + data1.Table[i].advance_amount + '</td><td onclick=billingdetails(this,"' + data1.Table[i].billing_no + '")> ₹ ' + claim_amount + '</td><td onclick=billingdetails(this,"' + data1.Table[i].billing_no + '")> ₹ ' + data1.Table[i].received_amount + '</td><td onclick=billingdetails(this,"' + data1.Table[i].billing_no + '")> ₹ ' + data1.Table[i].due_amount + '</td><td>' + status + '</td><td class="disp_if">' + other_info + '<button type="button" class="btn btn-primaryuse btn-xs mr-5" onclick=lookup("' + data1.Table[i].cc_invoiceid + '","' + data1.Table[i].sms_invoice_no + '","' + data1.Table[i].cc_date + '")>Check Status</button></td></tr>'

                            }
                        }
                        $('#paid_billview_diag_body').html(row_data);
                        // $('#paid_billview_diag').DataTable();
                        datatable("paid_billview_diag");
                        // datatable('tbl_billing', 'billing_view', 'Legal');
                    }
                    else {
                        console.log(data1);
                        //   $('#paid_billview_diag').DataTable();
                        datatable("paid_billview_diag");
                        // datatable('tbl_billing', 'billing_view', 'Legal');
                    }
                }
            }
            else {
                console.log(data1);
                //  $('#paid_billview_diag').DataTable();
                datatable("paid_billview_diag");
                //  datatable('tbl_billing', 'billing_view', 'Legal');
            }
        }
    });
}

$('#Visits_tab').click(function () {
    debugger;
    visits_tab_op();
})

function visits_tab_op() {
    debugger;
    var billing = {
        patient_id: $('#Hpatient_id').val(),
        dml_indicator: "PVRO"
    }
    $.ajax({
        async: true,
        type: 'POST',
        url: '/Billing/IP_OP_Billings',
        contentType: 'application/json; charset=UTF-8',
        data: JSON.stringify(billing),
        success: function (data) {
            console.log(data);
            var data1 = JSON.parse(data);
            console.log(data1);
            if (data1.msg == "Success") {
                debugger;
                var data1 = data1.data;
                if (jQuery.isEmptyObject((data1))) {
                    $('#visit_op_body').empty();
                    $('#visit_op').dataTable().fnClearTable();
                    $('#visit_op').dataTable().fnDraw();
                    $('#visit_op').dataTable().fnDestroy();
                }
                else {
                    $('#visit_op_body').empty();
                    $('#visit_op').dataTable().fnClearTable();
                    $('#visit_op').dataTable().fnDraw();
                    $('#visit_op').dataTable().fnDestroy();

                    var j = 0, b = '', tr = '', print = '';


                    b = data1.Table;
                    $.each(b, function (i, emp) {
                        j++
                        print = '<h3 class="panel-title"><span class="pull-right"><a href="javascript:void(0);" onclick=\'printpdf(\"' + emp.visit_report_id + '\",\"' + emp.visit_reportid + '\",\"' + emp.patientid + '\",\"' + emp.hospitalid + '\",\"' + emp.branch_id + '\",\"' + emp.doctorname + '\",\"' + emp.hospitalname + '\",\"' + emp.phonenumber + '\",\"' + emp.patientemailid + '\")\'><i class="fa fa-print "></i> print </a>&nbsp;&nbsp;&nbsp;&nbsp;</span></h3>'

                        tr = tr + '<tr' + j + '"></td><td>' + j + '</td><td>' + emp.visit_date + '</td><td>' + print + '</td></tr>';

                    });
                    $('#visit_op_body').html(tr);
                    $('#visit_op').DataTable();
                    //datatable("visit_op");


                }
            }
            else {
                console.log(data);
            }
        }
    });

}

$('#Labs_tab').click(function () {
    debugger;
    labs_tab_op();
})

function labs_tab_op() {
    debugger;
    var request_data = {
        Dml_Indicator: 'PVRO',
        // doctor_id: $('#doctorId').val(),
        patient_id: $('#Hpatient_id').val()
        //  visit_report_id: $('#VisitReportID').val()
    }
    $.ajax({
        async: true,
        type: 'POST',
        url: '/Billing/IP_OP_Request',
        contentType: 'application/json; charset=UTF-8',
        data: JSON.stringify(request_data),
        success: function (data) {
            console.log(data);
            var data1 = JSON.parse(data);
            if (jQuery.isEmptyObject((data1))) {
                $('#ip_labview_body').empty();
                $('#ip_labview').dataTable().fnClearTable();
                $('#ip_labview').dataTable().fnDraw();
                $('#ip_labview').dataTable().fnDestroy();
            }
            else {

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

                    debugger;
                    $('#ip_labview_body').empty();
                    $('#ip_labview').dataTable().fnClearTable();
                    $('#ip_labview').dataTable().fnDraw();
                    $('#ip_labview').dataTable().fnDestroy();
                    var tr = "";
                    $.each(data, function (i, emp) {
                        var action = "-";
                        //  var payment = '';
                        if (emp.is_lab == 1 || emp.is_appointment == 1) {
                            // var lab_document = '';
                            if (emp.document_path != null && emp.document_path != "") {
                                var str = emp.document_path;
                                var temp = new Array();
                                temp = str.split(",");
                                var strarray = str.split(',');
                                //for (var k = 0; k < strarray.length; k++) {
                                //    lab_document = lab_document + '<a href="' + $('#hdngetlabfilepath').val() + $('#HdnHospitalid').val() + "/" + $('#HBranchID').val() + "/Lab_Documents/" + strarray[k] + '" target="_blank" style="margin-right: 10px;">Lab Document ' + (k + 1) + '</a>' + "/";
                                //}
                            }

                            action = '<button type="button" class="btn btn-primaryuse btn-xs mr-5" style="margin-right: 10px;" onclick=jobprint_patientsearchpopup("' + emp.work_order_id + '","' + emp.hospitalid + '","' + emp.patientid + '","' + emp.branchid + '","' + emp.master_service_id + '","' + emp.barcodeid + '")><i class="fa fa fa-print" aria-hidden="true"></i></button>';
                            // payment = ((emp.is_bill == 1 || emp.is_bill == "1") && emp.due_amount == "0.00") ? '<a><span class="label label-success" style="background-color: green !important;">PAID</span></a>' : '<a><span class="label label-danger">PENDING</span></a>';
                            if (emp.is_appointment == 1 && emp.is_lab != 1) {
                                action = '<button type="button" class="btn btn-primaryuse btn-xs mr-5" style="margin-right: 10px;" onclick=jobprintappointemnt("' + emp.work_order_id + '","' + emp.hospital_id + '","' + emp.patientid + '","' + emp.branchid + '","' + emp.work_order_details_id + '")><i class="fa fa fa-print" aria-hidden="true"></i></button>';
                            }
                        }

                        if (emp.base_amount_type == 4) {

                            tr = tr + '<tr><td>' + (i + 1) + '</td><td>' + emp.service_date + '</td><td>' + emp.service_code + '</td><td>' + emp.service_name + '</td><td>' + action + '</td></tr>'
                        }
                        else {

                            tr = tr + '<tr><td>' + (i + 1) + '</td><td>' + emp.service_date + '</td><td>' + emp.service_code + '</td><td>' + emp.service_name + '</td><td>' + action + '</td></tr>'
                        }
                    })
                    $('#ip_labview_body').append(tr);
                    $('#ip_labview').DataTable();
                    //  datatable("ip_labview");
                }
                else {
                    console.log(data);
                }
            }
        }
    })
}

$('#homecare_lab_tab').click(function () {
    debugger;
    labs_tab_home();
})

function labs_tab_home() {
    debugger;
    var request_data = {
        Dml_Indicator: 'PVRH',
        // doctor_id: $('#doctorId').val(),
        patient_id: $('#Hpatient_id').val()
        //  visit_report_id: $('#VisitReportID').val()
    }
    $.ajax({
        async: true,
        type: 'POST',
        url: '/Billing/IP_OP_Request',
        contentType: 'application/json; charset=UTF-8',
        data: JSON.stringify(request_data),
        success: function (data) {
            console.log(data);
            var data1 = JSON.parse(data);
            if (jQuery.isEmptyObject((data1))) {
                $('#home_labview_body').empty();
                $('#home_labview').dataTable().fnClearTable();
                $('#home_labview').dataTable().fnDraw();
                $('#home_labview').dataTable().fnDestroy();
            }
            else {

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

                    debugger;


                    $('#home_labview_body').empty();
                    $('#home_labview').dataTable().fnClearTable();
                    $('#home_labview').dataTable().fnDraw();
                    $('#home_labview').dataTable().fnDestroy();
                    var tr = "";
                    $.each(data, function (i, emp) {
                        var action = "-";
                        // var payment = '';
                        if (emp.is_lab == 1 || emp.is_appointment == 1) {
                            //  var lab_document = '';
                            if (emp.document_path != null && emp.document_path != "") {
                                var str = emp.document_path;
                                var temp = new Array();
                                temp = str.split(",");
                                var strarray = str.split(',');
                                //for (var k = 0; k < strarray.length; k++) {
                                //    lab_document = lab_document + '<a href="' + $('#hdngetlabfilepath').val() + $('#HdnHospitalid').val() + "/" + $('#HBranchID').val() + "/Lab_Documents/" + strarray[k] + '" target="_blank" style="margin-right: 10px;">Lab Document ' + (k + 1) + '</a>' + "/";
                                //}
                            }

                            action = '<button type="button" class="btn btn-primaryuse btn-xs mr-5" style="margin-right: 10px;" onclick=jobprint_patientsearchpopup("' + emp.work_order_id + '","' + emp.hospitalid + '","' + emp.patientid + '","' + emp.branchid + '","' + emp.master_service_id + '","' + emp.barcodeid + '")><i class="fa fa fa-print" aria-hidden="true"></i></button>';
                            //  payment = ((emp.is_bill == 1 || emp.is_bill == "1") && emp.due_amount == "0.00") ? '<a><span class="label label-success" style="background-color: green !important;">PAID</span></a>' : '<a><span class="label label-danger">PENDING</span></a>';
                            if (emp.is_appointment == 1 && emp.is_lab != 1) {
                                action = '<button type="button" class="btn btn-primaryuse btn-xs mr-5" style="margin-right: 10px;" onclick=jobprintappointemnt("' + emp.work_order_id + '","' + emp.hospital_id + '","' + emp.patientid + '","' + emp.branchid + '","' + emp.work_order_details_id + '")><i class="fa fa fa-print" aria-hidden="true"></i></button>';
                            }
                        }

                        if (emp.base_amount_type == 4) {

                            tr = tr + '<tr><td>' + (i + 1) + '</td><td>' + emp.service_date + '</td><td>' + emp.service_code + '</td><td>' + emp.service_name + '</td><td>' + action + '</td></tr>'
                        }
                        else {

                            tr = tr + '<tr><td>' + (i + 1) + '</td><td>' + emp.service_date + '</td><td>' + emp.service_code + '</td><td>' + emp.service_name + '</td><td>' + action + '</td></tr>'
                        }
                    })
                    $('#home_labview_body').append(tr);
                    $('#home_labview').DataTable();

                    // datatable("home_labview");
                }
                else {
                    console.log(data);
                }
            }
        }
    })
}


$('#casesheet_view').click(function () {
    debugger;
    window.location.href = '/casestudy/CaseStudyView?patient_id=' + $('#Hpatient_id').val() + '&Did=' + $('#HiddenDoctorID').val() + ''
})


function bill_report(bill_no, patientid, hospitalid, branch_id, papertype, event) {
    debugger;
    var did = $(event).attr("data-id");
    var navigation = $(event).attr("data-nav");
    var name = $(event).attr("data-name");
    var columntype = $(event).attr("data-type");
    debugger;
    var chkprevilige = check_previlige(did, navigation, name, columntype);
    $.when(chkprevilige)
        .then(function (data) {
            var data1 = JSON.parse(data);
            if (data1.msg == "Success") {
                var data1 = data1.data;
                if (jQuery.isEmptyObject((data1))) {
                }
                else {
                    var j = 0;
                    var status = data1.Table[0].role_rights_add
                    if (status == 0) {

                        return;
                    }
                    else {
                        var fromdate = ''; var todate = '';
                        if ($('#txtfrom_date').val() != null && $('#txtfrom_date').val() != "") {
                            var fromdate = $('#txtfrom_date').val();
                            var a = fromdate.split('/');
                            fromdate = a[2] + '-' + a[1] + '-' + a[0];
                        }

                        if ($('#txtto_date').val() != null && $('#txtto_date').val() != "") {
                            var todate = $('#txtto_date').val();
                            var a = todate.split('/');
                            todate = a[2] + '-' + a[1] + '-' + a[0];

                        }

                        var load_data = {
                            formid: ((papertype == 1 || papertype == '1') ? "105" : "65"),
                            branchid: branch_id,
                            hospitalid: hospitalid,
                            patientid: patientid,
                            billno: bill_no

                        }
                        //window.open("/reports/PrintCrystalReport?data=" + JSON.stringify(load_data))

                        $.ajax({
                            async: true,
                            type: 'POST',
                            url: '/reports/PrintCrystalReport',
                            contentType: 'application/json; charset=UTF-8',
                            data: JSON.stringify(load_data),
                            success: function (data) {
                                var byteArray = new Uint8Array(data);
                                var blob = new Blob([byteArray], { type: "application/pdf" });
                                var link = window.URL.createObjectURL(blob);
                                //window.open(link, '_blank');
                                iframe = document.createElement('iframe'); //load content in an iframe to print later
                                document.body.appendChild(iframe);

                                iframe.style.display = 'none';
                                iframe.src = link;
                                iframe.onload = function () {
                                    setTimeout(function () {
                                        iframe.focus();
                                        iframe.contentWindow.print();
                                    }, 1);
                                };
                            }
                        });

                    }
                }
            }
        })

}

function printpdf(VisitReportID, visitid, patientid, hospitalid, branchid, doctorname, hospitalname, phone_number, email_id) {
    debugger;
    if ($('#HCasesheetPrintType').val() == 0) {
        window.open('/PatientDashboard/PPDF?visitreportid=' + VisitReportID + '&lantype=' + $('#sellang').val() + '&btnval=1', "_blank");
    }
    else {
        //var load_data = {
        //    formid: "137",
        //    branchid: branchid,
        //    hospitalid: hospitalid,
        //    patientid: patientid,
        //    visit_reportid: visitid
        //}
        //$.ajax({
        //    async: true,
        //    type: 'POST',
        //    url: '/reports/PrintCrystalReport',
        //    contentType: 'application/json; charset=UTF-8',
        //    data: JSON.stringify(load_data),
        //    success: function (data) {
        //        debugger;

        //        var byteArray = new Uint8Array(data);
        //        var blob = new Blob([byteArray], { type: "application/pdf" });
        //        var link = window.URL.createObjectURL(blob);
        //        window.open(link, '_blank');

        //    }
        //});

        var load_data = {
            formid: '137',
            branchid: branchid,
            hospitalid: hospitalid,
            patientid: patientid,
            visit_reportid: visitid,
            doctorname: doctorname,
            hospital_name: hospitalname,
            phone_number: phone_number,
            email_id: email_id
        }
        $.ajax({
            async: true,
            type: 'POST',
            url: '/reports/SetPrescriptionReportParameters',
            contentType: 'application/json; charset=UTF-8',
            data: JSON.stringify(load_data),
            success: function (data) {
                window.open('/Webform/PrescriptionPrint.aspx', '_blank');
            }
        });
    }
}

function jobprintappointemnt(work_order_id, hospital_id, patientid, branchid, work_order_details_id) {
    debugger;
    var load_data = {
        //formid: "73", 
        formid: "135",
        branchid: branchid,
        hospitalid: hospital_id,
        work_order_id: work_order_id,
        work_order_details_id: work_order_details_id

    }

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

            var byteArray = new Uint8Array(data);
            var blob = new Blob([byteArray], { type: "application/pdf" });
            var link = window.URL.createObjectURL(blob);
            window.open(link, '_blank');

        }
    });

}

function jobprint_patientsearchpopup(work_order_id, hospitalid, patientid, branchid, master_service_id, barcodeid) {
    debugger;
    var load_data = {
        //formid: "73", 
        formid: "108",
        branchid: branchid,
        hospitalid: hospitalid,
        work_order_id: work_order_id,
        patientid: patientid,
        barcodeid: barcodeid,
        masterserviceid: master_service_id

    }

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

            var byteArray = new Uint8Array(data);
            var blob = new Blob([byteArray], { type: "application/pdf" });
            var link = window.URL.createObjectURL(blob);
            window.open(link, '_blank');

        }
    });

}


function AddTemplatePopup(event, work_orderid, work_order_details_id, master_service_id, samplebarid, sample_id, samplbarcodeid, workorderTemplateId) {
    debugger;
    $('#Tempopworkorder_id').val(work_orderid)
    $('#Tempopwork_order_details_id').val(work_order_details_id)
    $('#Tempopmaster_service_id').val(master_service_id)
    $('#Tempopsamplebarid').val(samplebarid)
    $('#Tempopsample_id').val(sample_id)
    $('#Tempopsamplbarcodeid').val(samplbarcodeid)
    $('#TempopworkorderTemplateId').val(workorderTemplateId)

    var ObjVal = {
        Dml_Indicator: 'GTC',
        work_orderid: $('#Tempopworkorder_id').val(),
        work_order_details_id: $('#Tempopwork_order_details_id').val(),
        master_service_id: $('#Tempopmaster_service_id').val(),
        spname: "SP_Work_Order_Action",
    }

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

            var data = JSON.parse(data);
            var content = "";
            content = "<p></p>";
            $('#summernote').summernote('code', content);

            console.log(data);
            if (data.msg == "Success") {
                var data1 = data.data;
                if (jQuery.isEmptyObject((data1))) {
                }
                else {
                    if (data1.Table.length > 0) {
                        content = "<p>" + data1.Table[0].description + "</p>"; // Replace with your desired content
                        $('#summernote').summernote('code', content);
                    }
                    else {
                        content = "<p></p>"; // Replace with your desired content
                        $('#summernote').summernote('code', content);
                    }

                }
            }
        }
    })
}

$('#btnSaveAddTemplate').click(function () {
    debugger;

    var RichTextBoxValue = $('#summernote').summernote('code');
    var content = $('<div>').html(RichTextBoxValue).text();

    if (content == "") {
        $('#ptxtsummernote').show();
        $('#ptxtsummernote').fadeOut(8000);
        $('#ptxtsummernote').html('Enter the Values')
        $('#ptxtsummernote').focus();
        return false;
    }

    var ObjVal = {
        Dml_Indicator: 'SATM',
        work_orderid: $('#Tempopworkorder_id').val(),
        work_order_details_id: $('#Tempopwork_order_details_id').val(),
        master_service_id: $('#Tempopmaster_service_id').val(),
        barcodeid: $('#Tempopsamplebarid').val(),
        sample_id: $('#Tempopsample_id').val(),
        samplbarcodeid: $('#Tempopsamplbarcodeid').val(),
        servicename: RichTextBoxValue,
        UserId: $('#hiddenUser_id').val(),
        spname: "SP_Work_Order_Action",
    }

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

            var data = JSON.parse(data);
            console.log(data);
            if (data.msg == "Success") {
                var data1 = data.data;
                if (jQuery.isEmptyObject((data1))) {
                }
                else {
                    if (data1.Table[0].msg == "inserted") {
                        toastr.success("Saved Successfully")
                        $('#AddTemplate_popup').modal('hide');
                    }
                    else if (data1.Table[0].msg == "updated") {
                        toastr.success("Updated Successfully")
                        $('#AddTemplate_popup').modal('hide');
                    }
                    else {
                        toastr.warning("Somthing went Wrong")
                    }
                }
            }
        }
    })
})

$('#btnLabTemplatePrint').click(function () {
    debugger;

    var ObjVal = {
        formid: "151",
        branchid: $('#popbranchid').val(),
        hospitalid: $('#pophospitalid').val(),
        work_order_id: $('#Tempopworkorder_id').val(),
        work_order_details_id: $('#Tempopwork_order_details_id').val(),
        patientid: 0,
        barcodeid: 0,
        masterserviceid: $('#Tempopmaster_service_id').val(),
        samplbarcodeid: $('#Tempopsamplbarcodeid').val(),
    }

    $.ajax({
        async: true,
        type: 'POST',
        url: '/reports/PrintCrystalReport',
        contentType: 'application/json; charset=UTF-8',
        data: JSON.stringify(ObjVal),
        success: function (data) {
            debugger;
            var byteArray = new Uint8Array(data);
            var blob = new Blob([byteArray], { type: "application/pdf" });
            var link = window.URL.createObjectURL(blob);
            //window.open(link, '_blank');
            iframe = document.createElement('iframe'); //load content in an iframe to print later
            document.body.appendChild(iframe);

            iframe.style.display = 'none';
            iframe.src = link;
            iframe.onload = function () {
                setTimeout(function () {
                    iframe.focus();
                    iframe.contentWindow.print();
                }, 1);
            };
        }
    })
})

//patient search view pop up -----------end -------------------