$(document).ready(function () {

    if ($("#EditRequest_id").val() == '' && $("#IPVisitReport_Id").val() == "") {
        loadvisit_type(0);
    }
    else {
        if ($('#pkg_branch_id').val() == '' || $('#pkg_branch_id').val() == 0) {
            $('#req_service').attr('disabled', true);
        }
        else {
            $('#req_service').attr('disabled', false);
        }
    }
    //LoadService();
    LoadBranch();
    sessionStorage.clear();
})
//Loading Request Code
function LoadReqCode(type) {
    debugger;
    var service_data = {
        Dml_Indicator: "LR",
        visit_type: type,
        branch_id: $('#pkg_branch_id').val()
    }
    $.ajax({
        async: true,
        type: 'POST',
        url: '/Billing/IP_OP_Request',
        contentType: 'application/json; charset=UTF-8',
        data: JSON.stringify(service_data),
        success: function (data) {
            var data1 = JSON.parse(data);
            if (data1.msg == "Success") {
                var data1 = data1.data;
                console.log(data1);
                if (jQuery.isEmptyObject((data1))) {
                }
                else {
                    $('#req_code').val(data1[0].request_code);
                    $('#req_date').val(data1[0].request_date)
                }
            }
        }
    })
}
//visit_type change function
$('#visit_type').change(function () {
    debugger;
    $('#txtPaitentSearch_1').val('');
    $('.pat-strip').hide();
    $('#req_service').val('');
    $('#req_service_code').val('');
    $('#SelDoctor').val('');
    $('#HSelDoctor').val('0');
    $('#service_amount').val('');
    $('#Hworkorder').val('');
    $('#Hwork_order_type').val('');
    $('#H_is_package').val('');
    $('#Hpackage_id').val('');
    $('#Hmaster_service_id').val('');
    $('#Hpatientid').val('');
    LoadReqCode($('#visit_type').val());
    
})
//Load Service--- not in use
function LoadService() {
    var service_data = {
        P_Dml_Indicator: "S",
        branch_id: 1
    }
    $.ajax({
        async: true,
        type: 'POST',
        url: '/Billing/Service_Master_Ins_upd_sel',
        contentType: 'application/json; charset=UTF-8',
        data: JSON.stringify(service_data),
        success: function (data) {
            var data1 = JSON.parse(data);
            if (data1.msg == "Success") {
                var data1 = data1.data;
                console.log(data1);
                if (jQuery.isEmptyObject((data1))) {
                }
                else {
                    var Service;
                    var default_opt = '<option value="0">--Select--</option>';
                    $.each(data1, function (i, emp) {
                        Service = Service + '<option value="' + emp.master_service_id + '">' + emp.service_name + '</option>';
                    });
                    $('#req_service').append(default_opt + Service);
                }
            }
            else {
                console.log(data1);
            }
        }
    })
}
//Service Name onchange for loading service code
function loadservicedetails(id) {
    $('#Hmaster_service_id').val(id);
    
    indicator_id = 'SLCI'
    var wardid = 0, Hbilling_class = 0
    if ($('#Hwardid').val() == '') {
        wardid = 0
    }
    else {
        wardid = $('#Hwardid').val();
    }
    if ($('#Hbilling_class').val() == '') {
        Hbilling_class = 0
    }
    else {
        Hbilling_class = $('#Hbilling_class').val();
    }
    var service_data = {
        Dml_Indicator: indicator_id,
        master_service_id: id,
        wardid: wardid,
        billing_class: Hbilling_class
    }
    $.ajax({
        async: true,
        type: 'POST',
        url: '/Billing/IP_OP_Request',
        contentType: 'application/json; charset=UTF-8',
        data: JSON.stringify(service_data),
        success: function (data) {
            debugger;
            var data1 = JSON.parse(data);
            if (data1.msg == "Success") {
                var data1 = data1.data;
                console.log(data1);
                if (jQuery.isEmptyObject((data1))) {
                }
                else {
                    if (data1.length > 0) {
                        $('#Hbase_amount_type').val(data1[0].base_amount_type);
                        if (data1[0].base_amount_type == 1 || data1[0].base_amount_type == 3)
                        {
                            //$('#div_service_amt').show();
                            $('#service_amount').attr('disabled', false);
                            if (data1[0].base_amount_type == 3) {
                                $('#Pservice_amount').html("Enter the amount between " + data1[0].range_min + ' - ' + data1[0].range_max);
                                $('#Hrange_min').val(data1[0].range_min);
                                $('#Hrange_max').val(data1[0].range_max);
                            }
                        }
                        else {
                            // $('#div_service_amt').hide();
                         //   $('#service_amount').attr('disabled', true); -->Medway Requirement 1/11/23--Tharuni
                        }
                        if (data1[0].base_amount_type == 4) {
                            $('#div_req_end').show();
                            $('#req_quantity').prop('disabled', true);
                           // $('#req_quantity').removeAttr('name', 'numeric_only');
                            $('#req_quantity').attr('onkeyup', 'numeric_dot("req_quantity")');
                        }
                        else {
                            $('#div_req_end').hide();
                            $('#req_quantity').prop('disabled', false);
                            if (data1[0].work_order == 3) {
                                $('#req_quantity').attr('onkeyup', 'numeric_dot("req_quantity")');
                            }
                            else {
                                $('#req_quantity').attr('onkeyup', 'numeric_only("req_quantity")');
                            }
                        }
                        var dateNow = new Date();

                        var new_date = moment(dateNow).format('DD/MM/YYYY hh:mm A')
                        $('#req_time').val(new_date);
                        $('#req_time').prop("disabled", false);
                        $('#req_service_code').val(data1[0].service_code);
                        $('#service_amount').val(data1[0].base_amount_value);
                        $('#service_tot_amount').val(parseFloat(data1[0].base_amount_value)*1);
                        $('#Hservice_amount').val(data1[0].base_amount_value);
                        $('#Hworkorder').val(data1[0].work_order);
                        $('#Hwork_order_type').val(data1[0].work_order_type);
                        $('#H_is_package').val(data1[0].is_package);
                        $('#Hpackage_id').val(data1[0].package_id);
                        if (data1[0].is_doctor == 1) {
                            $('#divSelDoctor').show();
                            $('#divlDoctorFee').show();
                            $('#SelDoctor').prop('disabled', false);
                           //- LoadDoctor();
                        }
                        else {
                            $('#divSelDoctor').hide();
                            $('#divlDoctorFee').hide();
                            $('#SelDoctor').val('');
                            $('#SelDoctor').prop('disabled', true);
                        }
                        $('#His_description').val(data1[0].is_description);
                        if (data1[0].is_description == 1) {
                            $('#desc_div').removeClass("hidden");
                        }
                        else {
                            $('#desc_div').addClass("hidden");
                        }
                    }
                }
            }
            else {
                console.log(data1);
            }
        }
    })
}
//service amount change function for input and range service type
$('#service_amount').change(function () {
   
    if ($('#Hbase_amount_type').val() == 3) {
        debugger;
        var range_min = $('#Hrange_min').val();
        var range_max = $('#Hrange_max').val();
        
        if ($('#service_amount').val() == '' || $('#service_amount').val() == 0 || (parseInt($('#service_amount').val()) < parseInt(range_min) || parseInt($('#service_amount').val()) > parseInt(range_max)) ) {
            
            $('#service_amount').val(range_min)
        }
    }
    var unit_rate = $('#service_amount').val() || 0;
    var qtys = $('#req_quantity').val() || 0;
    $('#service_tot_amount').val(parseFloat(unit_rate) * parseFloat(qtys));
})
//Loading Doctor
function LoadDoctor() {
    var roleId = $('#hiddenRole_id').val();
    var DoctorId = $('#HiddenDoctorID').val();
    var DoctorData = {
        Dml_Indicator: "DLR",
        hospital_id: $('#HospitalId').val(),
        branch_id: $('#pkg_branch_id').val()
    }

    $.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 = '';
                    $('#SelDoctor').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>';
                        }
                        $('#SelDoctor').html(default_opt + SelRole);
                    }

                }
            }
            else {
                console.log(data1);
            }
        }
    });
}
//Loading Doctor
function LoadVisitDoctor(val) {
    debugger;
    var roleId = $('#hiddenRole_id').val();
    var branchid = ($('#EditBranch_id').val() == '' || $('#EditBranch_id').val() == 0) ? $('#pkg_branch_id').val() : $('#EditBranch_id').val();
    var DoctorId = $('#HiddenDoctorID').val();
    var DoctorData = {
        Dml_Indicator: "HDL",
        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 = '';
                    $('#VisitDoctor').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>';
                        }
                        $('#VisitDoctor').html(default_opt + SelRole);
                        if(val!='' && val!=null )
                        {
                            $('#VisitDoctor').val(val);
                        }
                    }

                }
            }
            else {
                console.log(data1);
            }
        }
    });
}
//Adding Services
$('#req_add').click(function () {
    debugger;
    if ($.trim($('#pkg_branch_id').val()) == "" || $('#pkg_branch_id').val() == '0') {
        $('#Ppkg_branch_id').show();
        $('#Ppkg_branch_id').fadeOut(8000);
        $('#Ppkg_branch_id').html('Select Branch');
        $('#pkg_branch_id').focus();
        $('#pkg_branch_id').val('');
        return false;
    }
    if ($('#Hpatientid').val() == '') {
        $('#PtxtPaitentSearch_1').show();
        $('#PtxtPaitentSearch_1').fadeOut(8000);
        $('#PtxtPaitentSearch_1').html('Search Patient');
        $('#txtPaitentSearch_1').focus();
        $('#txtPaitentSearch_1').val('');
        return false;
    }
    if ($('#Hmaster_service_id').val() == '' || $('#Hmaster_service_id').val() == 0) {
        $('#Preq_service').show();
        $('#Preq_service').fadeOut(8000);
        $('#Preq_service').html('Select Service Name');
        $('req_service').focus();
        return false;
    }
    if (($('#Hbase_amount_type').val() == 1 || $('#Hbase_amount_type').val() == 3) && ($('#service_amount').val()=='' || $('#service_amount').val()==0))
    {
        $('#Pservice_amount').show();
        $('#Pservice_amount').fadeOut(8000);
        $('#Pservice_amount').html('Enter the amount');
        $('#service_amount').focus();
        return false;
    }
    if ($('#req_quantity').val() == '' || $('#req_quantity').val() == 0) {
        $('#Preq_quantity').show();
        $('#Preq_quantity').fadeOut(8000);
        $('#Preq_quantity').html('Enter Quantity');
        $('#req_quantity').focus();
        return false;
    }
    if ($('#req_time').val() == '' || $('#req_time').val() == 0) {
        $('#Preq_time').show();
        $('#Preq_time').fadeOut(8000);
        $('#Preq_time').html('Enter Quantity');
        $('#req_time').focus();
        return false;
    }
    
    if ($('#SelDoctor').prop('disabled') == false) {
        if ($.trim($('#SelDoctor').val()) == '' || $('#HSelDoctor').val() == 0) {
            $('#PSelDoctor').show();
            $('#PSelDoctor').fadeOut(8000);
            $('#PSelDoctor').html('Select Doctor Name');
            $('#SelDoctor').focus();
            $('#HSelDoctor').val('0');
            return false;
        }

        //if ($('#Doctor_Fee').val() == '' || $('#Doctor_Fee').val() == 0) {
        //    $('#PDoctor_Fee').show();
        //    $('#PDoctor_Fee').fadeOut(8000);
        //    $('#PDoctor_Fee').html('Enter Doctor Fee');
        //    $('#Doctor_Fee').focus();
        //    return false;
        //}

        //if ($('#desc_div').hasClass('hidden') == false && $.trim($('#req_remarks').val()) == "") {
            
        //        $('#Preq_remarks').show();
        //        $('#Preq_remarks').fadeOut(8000);
        //        $('#Preq_remarks').html('Enter Description');
        //        $('#req_remarks').focus();
        //        return false;
           
        //}
        else {
            var tot_rowM = $.trim($('#ServiceTableRowCount').val());
            if ($('#visit_type').val() == 1) {
                if ($('#H_is_package').val() == 1) {
                    if (tot_rowM > 0) {
                        package_check_scenario1()
                    }
                    else {
                        service_add();
                    }
                }
                else {
                    if (tot_rowM > 0) {
                        package_check_scenario2()
                    }
                    else {
                        service_add();
                    }
                }
            }
            else {
                service_add();
            }
        }
    }
    
    else {
        debugger;
        //if ($('#desc_div').hasClass('hidden') == false) {
        //    if ($.trim($('#req_remarks').val()) == "") {
        //        $('#Preq_remarks').show();
        //        $('#Preq_remarks').fadeOut(8000);
        //        $('#Preq_remarks').html('Enter Description');
        //        $('#req_remarks').focus();
        //        return false;
        //    }
        //}
        var tot_rowM = $.trim($('#ServiceTableRowCount').val());
        if ($('#visit_type').val() == 1) {
            if ($('#H_is_package').val() == 1) {
                if (tot_rowM > 0) {
                    package_check_scenario1()
                }
                else {
                    service_add();
                }
            }
            else {
                if (tot_rowM > 0) {
                    package_check_scenario2()
                }
                else {
                    service_add();
                }
            }
        }
        else {
            service_add();
        }

    }
})
//Package check-(if any individual service present in package that is going to be added)
function package_check_scenario1() {

    var request_data = {
        master_service_id: $('#Hmaster_service_id').val(),
        Dml_Indicator: 'CPP'
    }
    $.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 (data1.msg == "Success") {
                console.log(data1);
                var data1 = data1.data;
                if (jQuery.isEmptyObject((data1))) {

                }
                else {
                    debugger;
                    
                    var l = 0;
                    for (i = 0; i < data1.length; i++) {
                        var service_id = data1[i].master_service_id;
                        var L = 0;
                        var tot_rowM = $.trim($('#ServiceTableRowCount').val());
                        for (j = 1; j <= tot_rowM; j++) {
                            debugger;
                            if (l == 0) {
                                var a = $('#req_table tbody').children('tr').eq(L);
                                var b = a.prop('id');
                                L++;
                                var s_id = b.split('_')[1];
                                if (s_id == service_id) {
                                    Servicedelete(b);
                                    //var row_data = sessionStorage.getItem(b);
                                    //var row_data_split = row_data.split(',');
                                    //var ser_name=row_data_split[0];
                                    //$('#Preq_service').show();
                                    //$('#Preq_service').fadeOut(8000);
                                    //$('#Preq_service').html('Please delete ' + ser_name+' and include the Package');
                                    //$('#req_service').focus();
                                    //l++;
                                    //break;
                                    //return false;
                                }
                            }
                        }
                    }

                    service_add();

                }
            }
        }
    })
}
//Package Check-checking the individual service present in package that is in table
function package_check_scenario2() {
    debugger;
    var tot_rowM = $.trim($('#ServiceTableRowCount').val());
    var total_amount = 0, count = 0;

    var L = 0, t1 = 0;
    for (let j = 1; j <= tot_rowM; j++) {
        debugger;
        count++;


        var a = $('#req_table tbody').children('tr').eq(L);
        var b = a.prop('id');
        var s_id = b.split('_')[1];
        L++;
        var request_data = {
            master_service_id: s_id,
            Dml_Indicator: 'CP'
        }
        $.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 (data1.msg == "Success") {
                    console.log(data1);
                    var data1 = data1.data;
                    if (jQuery.isEmptyObject((data1))) {

                    }
                    else {

                        if (data1[0].Stringmsg == 'Not_Package') {
                            //service_add();
                        }
                        else {

                            var service_id = $('#Hmaster_service_id').val();
                            var i;
                            for (i = 0; i < data1.length; i++) {

                                debugger;
                                if (service_id == data1[i].master_service_id) {

                                    $('#Preq_service').show();
                                    $('#Preq_service').fadeOut(8000);
                                    $('#Preq_service').html('Service Name already included in Package you listed..');
                                    $('#req_service').focus();
                                    $('#req_service').val('');
                                    $('#req_service_code').val('');
                                    $('#req_quantity').val(1);
                                    $('#SelDoctor').val('');
                                    $('#HSelDoctor').val('0');
                                    $('#req_remarks').val('');
                                    $('#divSelDoctor').hide();
                                    $('#desc_div').hide();

                                    t1 = t1 + 1;
                                    break;
                                    return false;
                                }
                            }


                        }
                        if (count == 1) {
                            if ((j) == tot_rowM && t1 == 0) {

                                service_add();
                            }
                        }
                        else {
                            if ((j) == tot_rowM && t1 == 0) {

                                service_add();
                            }
                        }
                    }
                }
            }
        })
    }


}
//Service add
function service_add() {
    debugger;
    var ser_name = $("#req_service").val();
    var ser_id = $('#Hmaster_service_id').val();
    var ser_code = $('#req_service_code').val();
    var num_use = $('#req_quantity').val();
    var work_order = $('#Hworkorder').val();
    var work_order_type = $('#Hwork_order_type').val();
    var pack = $('#Hpackage_id').val();
    var doc_name = '-', doc_id = '';
    var req_time = $('#req_time').val();
    var req_end_time = $('#req_end_time').val();
    var range_min = $('#Hrange_min').val();
    var range_max = $('#Hrange_max').val();
    var remarks = $('#req_remarks').val();
    var is_description = $('#His_description').val();
    if ($('#VisitDoctor').val() == 0 || $('#VisitDoctor').val() == '' || $('#VisitDoctor').val() == null) {
        doc_name = '-'
    }
    else {
        //doc_name = $("#VisitDoctor option:selected").text();
        //doc_id = $('#VisitDoctor').val();
        doc_name = $("#SelDoctor").val();
        doc_id = $('#HSelDoctor').val();
    }
    var doctor_fee = '';
    if ($('#Doctor_Fee').val() == 0 || $('#Doctor_Fee').val() == '' || $('#Doctor_Fee').val() == null)
    {
        doctor_fee = '-';
    }
    else {
        doctor_fee = $('#Doctor_Fee').val();
    }
    

    var base_amount = $('#service_amount').val();
    var base_amount_org = $('#Hservice_amount').val()
    var base_amount_type=$('#Hbase_amount_type').val()
    var total_amount = base_amount * num_use
    var sess_key;
    var rowcount = $.trim($('#ServiceTableRowCount').val());
    var tot_row = (Number(rowcount) + 1);
    var sess_data_ser = ser_name + "," + ser_code + "," + num_use + "," + doc_name + "," + base_amount + "," + total_amount + "," + doc_id + "," + work_order + "," + work_order_type + "," + pack + "," + req_time + "," + req_end_time + "," + base_amount_type + "," + 0 + "," + range_min + "," + range_max + "," + remarks + "," + doctor_fee + "," + is_description + "," + base_amount_org;
    var key = '';
    if (rowcount >= 1) {
        var getEid = $('#req_table  tr').last();
        var actId = getEid.prop('id');
        var afterSplit = actId.split('row');
        afterSplit=afterSplit[1].split('_')
        afterInc = parseInt(afterSplit[0]) + 1;
        console.log(afterInc);
        ikey_Deit = 'row' + afterInc;
    }
    else {
        ikey_Deit = 'row' + tot_row;
    }
    ikey_Deit=ikey_Deit+"_"+ser_id
    
    var value = ''
    if (remarks == '') {
        remarks='-'
    }
    var doctor_fee1=''
    if (doctor_fee == '')
    {
        doctor_fee1=''
    }

    var doctor_name_fee = doc_name + '/' + doctor_fee;

    var doc_nme_fee = ''
    if (doctor_name_fee == '-/-')
    {
        doc_nme_fee='-'
    }
    else
    {
        doc_nme_fee = doctor_name_fee
    }

    if (rowcount == 0 || work_order !=1 ) {
        debugger;
        sessionStorage.setItem(ikey_Deit, sess_data_ser);
        //if ($('#Hbase_amount_type').val() != 4) {
        //    value = "<tr id=" + ikey_Deit + "><td>" + ser_name + "</td><td>" + ser_code + "</td><td>" + doc_name + "</td><td>" + num_use + "</td><td>" + req_time + "</td><td>"+remarks+"</td><td><button class='btn btn-edit btn-xs' onclick=serviceedit('" + ikey_Deit + "')><i class='fa fa-pencil' aria-hidden='true'></i></button><button class='delete btn btn-delete btn-xs btn-add' onclick='Servicedelete(\"" + ikey_Deit + "\")'><i class='fa fa-trash' aria-hidden='true'></i></button></td></tr>";
        //}
        //else {
        //    value = "<tr id=" + ikey_Deit + "><td>" + ser_name + "</td><td>" + ser_code + "</td><td>" + doc_name + "</td><td>" + num_use + "</td><td>" + req_time + " - " + req_end_time + "</td><td>"+remarks+"</td><td><button class='btn btn-edit btn-xs' onclick=serviceedit('" + ikey_Deit + "')><i class='fa fa-pencil' aria-hidden='true'></i></button><button class='delete btn btn-delete btn-xs btn-add' onclick='Servicedelete(\"" + ikey_Deit + "\")'><i class='fa fa-trash' aria-hidden='true'></i></button></td></tr>";
        //}
        if ($('#Hbase_amount_type').val() != 4) {
            value = "<tr id=" + ikey_Deit + "><td>" + ser_name + "</td><td>" + ser_code + "</td><td>" + doc_nme_fee + "</td><td>" + num_use + "</td><td>" + req_time + "</td><td>" + remarks + "</td><td><button class='btn btn-edit btn-xs' onclick=serviceedit('" + ikey_Deit + "')><i class='fa fa-pencil' aria-hidden='true'></i></button><button class='delete btn btn-delete btn-xs btn-add' onclick='Servicedelete(\"" + ikey_Deit + "\")'><i class='fa fa-trash' aria-hidden='true'></i></button></td></tr>";
        }
        else {
            value = "<tr id=" + ikey_Deit + "><td>" + ser_name + "</td><td>" + ser_code + "</td><td>" + doc_nme_fee + "</td><td>" + num_use + "</td><td>" + req_time + " - " + req_end_time + "</td><td>" + remarks + "</td><td><button class='btn btn-edit btn-xs' onclick=serviceedit('" + ikey_Deit + "')><i class='fa fa-pencil' aria-hidden='true'></i></button><button class='delete btn btn-delete btn-xs btn-add' onclick='Servicedelete(\"" + ikey_Deit + "\")'><i class='fa fa-trash' aria-hidden='true'></i></button></td></tr>";
        }
    }
    else {
        debugger;
        var L = 0;
        var arr = [];
        for(i=0;i<$('#req_table >tbody >tr').length;i++)
        {
            var b = $('#req_table tbody').children('tr').eq(L)
            var id = b.prop('id');
            L++;
            id = id.split('_')[1];
            arr.push(id);
        }
        console.log(arr);
        //if($.inArray(ser_id,arr)==-1)
        //{
            sessionStorage.setItem(ikey_Deit, sess_data_ser);
            //if ($('#Hbase_amount_type').val() != 4) {
            //    value = "<tr id=" + ikey_Deit + "><td>" + ser_name + "</td><td>" + ser_code + "</td><td>" + doc_name + "</td><td>" + num_use + "</td><td>" + req_time + "</td><td>"+remarks+"</td><td><button class='btn btn-edit btn-xs' onclick=serviceedit('" + ikey_Deit + "')><i class='fa fa-pencil' aria-hidden='true'></i></button><button class='delete btn btn-delete btn-xs btn-add' onclick='Servicedelete(\"" + ikey_Deit + "\")'><i class='fa fa-trash' aria-hidden='true'></i></button></td></tr>";
            //}
            //else {
            //    value = "<tr id=" + ikey_Deit + "><td>" + ser_name + "</td><td>" + ser_code + "</td><td>" + doc_name + "</td><td>" + num_use + "</td><td>" + req_time + " - " + req_end_time + "</td><td>"+remarks+"</td><td><button class='btn btn-edit btn-xs' onclick=serviceedit('" + ikey_Deit + "')><i class='fa fa-pencil' aria-hidden='true'></i></button><button class='delete btn btn-delete btn-xs btn-add' onclick='Servicedelete(\"" + ikey_Deit + "\")'><i class='fa fa-trash' aria-hidden='true'></i></button></td></tr>";
            //}
            if ($('#Hbase_amount_type').val() != 4) {
                value = "<tr id=" + ikey_Deit + "><td>" + ser_name + "</td><td>" + ser_code + "</td><td>" + doc_nme_fee + "</td><td>" + num_use + "</td><td>" + req_time + "</td><td>" + remarks + "</td><td><button class='btn btn-edit btn-xs' onclick=serviceedit('" + ikey_Deit + "')><i class='fa fa-pencil' aria-hidden='true'></i></button><button class='delete btn btn-delete btn-xs btn-add' onclick='Servicedelete(\"" + ikey_Deit + "\")'><i class='fa fa-trash' aria-hidden='true'></i></button></td></tr>";
            }
            else {
                value = "<tr id=" + ikey_Deit + "><td>" + ser_name + "</td><td>" + ser_code + "</td><td>" + doc_nme_fee + "</td><td>" + num_use + "</td><td>" + req_time + " - " + req_end_time + "</td><td>" + remarks + "</td><td><button class='btn btn-edit btn-xs' onclick=serviceedit('" + ikey_Deit + "')><i class='fa fa-pencil' aria-hidden='true'></i></button><button class='delete btn btn-delete btn-xs btn-add' onclick='Servicedelete(\"" + ikey_Deit + "\")'><i class='fa fa-trash' aria-hidden='true'></i></button></td></tr>";
            }
    //    }
        //else {
        //    $('#Preq_service').show();
        //    $('#Preq_service').fadeOut(8000);
        //    $('#Preq_service').html('This particular service can be added only after the completion of the previous similar service');
        //    $('#req_service').focus();
        //    $('#req_service').val('');
        //    $('#req_quantity').val(1);
        //    return false;
        //}
    }
    //if ($('table#req_table').find('#' + ser_id).length == 0) {
    //    if ($('#Hbase_amount_type').val() != 4) {
    //        var value = "<tr id=" + ser_id + "><td>" + ser_name + "</td><td>" + ser_code + "</td><td>" + doc_name + "</td><td>" + num_use + "</td><td>" + req_time + "</td><td><button class='btn btn-edit btn-xs' onclick=serviceedit('" + ser_id + "')><i class='fa fa-pencil' aria-hidden='true'></i></button><button class='delete btn btn-delete btn-xs btn-add' onclick='Servicedelete(\"" + ser_id + "\")'><i class='fa fa-trash' aria-hidden='true'></i></button></td></tr>";
    //    }
    //    else {
    //        var value = "<tr id=" + ser_id + "><td>" + ser_name + "</td><td>" + ser_code + "</td><td>" + doc_name + "</td><td>" + num_use + "</td><td>" + req_time +" - "+req_end_time+ "</td><td><button class='btn btn-edit btn-xs' onclick=serviceedit('" + ser_id + "')><i class='fa fa-pencil' aria-hidden='true'></i></button><button class='delete btn btn-delete btn-xs btn-add' onclick='Servicedelete(\"" + ser_id + "\")'><i class='fa fa-trash' aria-hidden='true'></i></button></td></tr>";
    //    }
    //}
    //else {
    //    $('#Preq_service').show();
    //    $('#Preq_service').fadeOut(8000);
    //    $('#Preq_service').html('Service Name already selected');
    //    $('req_service').focus();
    //    $('req_service').val('');
    //    return false;
    //}

    $('#req_table > tbody:last').append(value);
  
   
        $('#visit_type').attr('disabled', true);
        $('#pkg_branch_id').attr('disabled', true);
        $('#txtPaitentSearch_1').attr('disabled', true);
        $('#Doc_Visit').attr('disabled', true);
    
    $('#req_quantity').prop('disabled', false);
    $('#ServiceTableRowCount').val(tot_row);
    $('#req_service').val('');
    $('#req_service_code').val('');
    $('#req_quantity').val(1);
    $('#SelDoctor').val('');
    $('#HSelDoctor').val('0');
    $('#SelDoctor').prop('disabled', true);
    $('#divSelDoctor').hide();

    $('#Doctor_Fee').val('');
    $('#divlDoctorFee').hide();

    $('#Hmaster_service_id').val('');
    $('#req_remarks').val('');
    var dateNow = new Date();
    
    var new_date = moment(dateNow).format('DD/MM/YYYY hh:mm A')
    $('#req_time').val(new_date);
    $('#req_time').prop('disabled', true);
    $('#req_end_time').val('');
    $('#div_req_end').hide();
    $('#desc_div').addClass("hidden");
    //  $('#div_service_amt').hide();
    $('#service_amount').attr('disabled', false);
    $('#service_amount').val(0);
    $('#Hservice_amount').val(0);
    $('#service_tot_amount').val(0);
    $('#Pservice_amount').html('');
    $('#His_description').val(0);
    $('#req_quantity').attr('onkeyup', 'numeric_only("req_quantity")');
    $("#datetimepicker1").datepicker("destroy");
    $('#datetimepicker1').datetimepicker({
       format: 'DD/MM/YYYY hh:mm A',
        //defaultDate: new_date
    }).datetimepicker("setDate", new Date());;
    //$('#datetimepicker2').datetimepicker({
    //    format: 'DD/MM/YYYY hh:mm A'
    //});
}
//Service Table Delete
function Servicedelete(id) {
    var gkey = id;
    var s_id = id.split('_')[1];
    //var row_data = sessionStorage.getItem(gkey);
    //var row_data_split = row_data.split(',');
    //var packageid = 0;
    //if (row_data_split[9] != 0)
    //{
    //    packageid = row_data_split[9];
    //}
    debugger;


    var msg = ''
    msg = 'Are you sure, you want to Delete this Service?'
    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>", msg,
                   {
                       closeButton: true,
                       progressBar: true,
                       allowHtml: true,
                       timeOut: 20000000,

                       onShown: function (toast) {
                           debugger;
                           $("#confirmationRevertYes").click(function () {
                               if ($('#EditVisit_type').val() != '') {
                                   var request_data = {
                                       request_id: $("#EditRequest_id").val(),
                                       master_service_id: s_id,
                                       Dml_Indicator: 'WSC',
                                       //visit_type: $('#EditVisit_type').val()
                                       visit_type: 2  //check if it is from Request (because of non-billable concept OP too will go to work order)
                                   }
                                   $.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 (data1.msg == "Success") {
                                               debugger;
                                               var data1 = data1.data;
                                               if (data1[0].StringMsg == 'success') {
                                                   delService(id);
                                               }
                                               else {
                                                   toastr.warning('Service is used under work order. Unable to delete this service')
                                               }
                                           }
                                           else {
                                               console.log(data1)

                                           }
                                       }
                                   })
                               }
                               else {
                                   debugger;
                                   delService(id);
                               }
                           })
                           $('#confirmationRevertNo').click(function () {

                           })
                       }
                   })

    //else {
    //    $('#visit_type').attr('disabled', true);
    //    $('#pkg_branch_id').attr('disabled', true);
    //    $('#txtPaitentSearch_1').attr('disabled', true);
    //}
}

function delService(id) {
    sessionStorage.removeItem(id);
    $('#' + id).remove();
    var rowcount = $.trim($('#ServiceTableRowCount').val());
    rowcount = rowcount - 1;
    $('#ServiceTableRowCount').val(rowcount);
    if ($('#req_table  >tbody >tr').length == 0) {
        $('#visit_type').attr('disabled', false);
        $('#pkg_branch_id').attr('disabled', false);
        $('#txtPaitentSearch_1').attr('disabled', false);
    }
}
//Service Table Edit
function serviceedit(id) {
    debugger;
    var s_id = id.split('_')[1];
    //if ($('#EditVisit_type').val() == 2) {
    if ($('#EditVisit_type').val()) {
        var request_data = {
            request_id: $("#EditRequest_id").val(),
            master_service_id: s_id,
            Dml_Indicator: 'WSE',
            //visit_type: $('#visit_type').val()
            visit_type: 2 //Setting this to 2 because its from request (non-billable need to check for OP scenario)
        }
        $.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 (data1.msg == "Success") {
                    debugger;
                    var data1 = data1.data;
                    if (data1[0].StringMsg == 'success') {
                        editService(id);
                    }
                    else {
                        if (data1[0].quantity == 0) {
                            toastr.warning('Service is used under work order. Unable update this service')
                        }
                        else {
                           
                            $('#work_quantity').val(data1[0].quantity);
                            editService(id);
                        }
                    }
                }
                else {
                    console.log(data1)

                }
            }
        })
    }
    else {
        debugger;
        editService(id);
    }
    
}
function editService(id) {
    debugger;
    $('#req_add').hide();
    $('#req_update').show();
    $('#service_table_id').val(id);

    var gkey = id;
    var row_data = sessionStorage.getItem(gkey);
    var row_data_split = row_data.split(',');
    $('#Hmaster_service_id').val(id);
    $('#req_service').val(row_data_split[0]);
    $('#req_service_code').val(row_data_split[1]);
    $('#req_quantity').val(row_data_split[2]);
    if (row_data_split[6] == '0' || row_data_split[6]=="") {
        $('#divSelDoctor').hide();
        $('#divlDoctorFee').hide();
        $('#SelDoctor').prop('disabled', true);
        $('#SelDoctor').val('');
        $('#HSelDoctor').val('0');
        $('#Doctor_Fee').val('');
    }
    else {
       
        $('#divSelDoctor').show();
        $('#divlDoctorFee').show();
        $('#SelDoctor').prop('disabled', false);
        $('#SelDoctor').val(row_data_split[3]);
        $('#HSelDoctor').val(row_data_split[6])
        $('#Doctor_Fee').val(row_data_split[17])
    }
    $('#service_amount').val(row_data_split[4]);
    $('#service_tot_amount').val(Math.round(parseFloat(row_data_split[4])* parseFloat(row_data_split[2])));
    //$('#Hservice_amount').val(row_data_split[4])
    $('#Hservice_amount').val(row_data_split[19])
    $('#Hworkorder').val(row_data_split[7])
    $('#Hwork_order_type').val(row_data_split[8]);
    $('#Hpackage_id').val(row_data_split[9]);
    $('#req_time').val(row_data_split[10]);
    $('#req_time').prop("disabled", false);
    $('#Hrequest_details_id').val(row_data_split[13]);
    $('#Hrange_min').val(row_data_split[14]);
    $('#Hrange_max').val(row_data_split[15]);
    //if ($.trim(row_data_split[16]) != '') {
    if ($.trim(row_data_split[18]) ==1) {
        $('#req_remarks').val(row_data_split[16]);
        $('#desc_div').removeClass('hidden');
        $('#His_description').val(1);
    }
    else {
        $('#desc_div').addClass('hidden');
    }
    $('#datetimepicker1').datetimepicker({
        format: 'DD/MM/YYYY hh:mm A',
        defaultDate: row_data_split[10]
    });
    $('#Hbase_amount_type').val(row_data_split[12]);
    if (row_data_split[12] == 4)
    {
       
        $('#div_req_end').show();
        $('#req_end_time').val(row_data_split[11]);
        $('#datetimepicker1').datetimepicker({
            format: 'DD/MM/YYYY hh:mm A',
            defaultDate: row_data_split[11]
        });
        $('#req_quantity').prop('disabled', true);
    }
    if (row_data_split[12] == 1 || row_data_split[12] == 3) {
        debugger;
        //  $('#div_service_amt').show();
        $('#service_amount').attr('disabled', false);
        if(row_data_split[12]==3)
        {
            $('#Pservice_amount').html("Enter the amount between " + row_data_split[14] + ' - ' + row_data_split[15]);
        }
        else {
            $('#Pservice_amount').html('')
        }
    }
    else {
        //$('#div_service_amt').hide();
     //   $('#service_amount').attr('disabled', true); --Medway Requirement 1/11/23-Tharuni

        $('#Pservice_amount').html('');
    }
   
    if ($('#Hworkorder').val() == 3) {
        $('#req_quantity').attr('onkeyup', 'numeric_dot("req_quantity")');
    }
    else {
        $('#req_quantity').attr('onkeyup', 'numeric_only("req_quantity")');
    }
    $('#req_service').prop('disabled', true);
}
//Service Table Update
$('#req_update').click(function () {

    debugger;
    if (($('#Hbase_amount_type').val() == 1 || $('#Hbase_amount_type').val() == 3) && ($('#service_amount').val() == '' || $('#service_amount').val() == 0)) {
        $('#Pservice_amount').show();
        $('#Pservice_amount').fadeOut(8000);
        $('#Pservice_amount').html('Enter the amount');
        $('#service_amount').focus();
        return false;
    }
    if ($('#req_quantity').val() == '' || $('#req_quantity').val() == 0) {
        $('#Preq_quantity').show();
        $('#Preq_quantity').fadeOut(8000);
        $('#Preq_quantity').html('Enter Quantity');
        $('#req_quantity').focus();
        return false;
    }
    
    else {
        //if ($('#desc_div').hasClass('hidden') == false) {
        //    if ($.trim($('#req_remarks').val()) == "") {
        //        $('#Preq_remarks').show();
        //        $('#Preq_remarks').fadeOut(8000);
        //        $('#Preq_remarks').html('Enter Description');
        //        $('#req_remarks').focus();
        //        return false;
        //    }
        //}
        var ser_name = $("#req_service").val();
        var ser_id = $('#Hmaster_service_id').val();
        var ser_code = $('#req_service_code').val();
        var num_use = $('#req_quantity').val();
        var doc_name = '-', doc_id = '';
        var work_order = $('#Hworkorder').val();
        var work_order_type = $('#Hwork_order_type').val();
        var pack = $('#Hpackage_id').val();
        var req_time = $('#req_time').val();
        var req_end_time = $('#req_end_time').val();
        var base_amount_type = $('#Hbase_amount_type').val();
        var range_min = $('#Hrange_min').val();
        var range_max = $('#Hrange_max').val();
        var remarks = $('#req_remarks').val();
        var is_description = $('#His_description').val();
        if ($('#SelDoctor').val() == 0 || $('#SelDoctor').val() == '' || $('#SelDoctor').val() == null) {
            doc_name = '-'
        }
        else {
            //doc_name = $("#SelDoctor option:selected").text();
            //doc_id = $('#SelDoctor').val();
            doc_name = $("#SelDoctor").val();
            doc_id = $('#HSelDoctor').val();
        }

        var doctor_fee=''
        if ($('#Doctor_Fee').val() == 0 || $('#Doctor_Fee').val() == '' || $('#Doctor_Fee').val() == null)
        {
            doctor_fee = '0';
        }
        else
        {
            doctor_fee = $('#Doctor_Fee').val();
        }

        var base_amount = $('#service_amount').val()
        var base_amount_org = $('#Hservice_amount').val()
        var total_amount = base_amount * num_use
        var sess_key;
        var rowcount = $.trim($('#ServiceTableRowCount').val());
        var tot_row = (Number(rowcount) + 1);
        var sess_data_ser = ser_name + "," + ser_code + "," + num_use + "," + doc_name + "," + base_amount + "," + total_amount + "," + doc_id + "," + work_order + "," + work_order_type + "," + pack + "," + req_time + "," + req_end_time + "," + base_amount_type + "," + $('#Hrequest_details_id').val() + "," + range_min + "," + range_max + "," + remarks + "," + doctor_fee + "," + is_description + "," + base_amount_org;
        var key = '';
        var s_id = $('#service_table_id').val();
        sessionStorage.setItem(s_id, sess_data_ser);
        debugger;
        var row_data = sessionStorage.getItem(s_id);
        row_data = row_data.split(',');
        if (row_data[16] == '') {
            row_data[16] = '-'
        }

        var doctor_name_fee = row_data[3] + '/' + row_data[17]

        //if ($('#Hbase_amount_type').val() != 4) {
        //    var value = "<td>" + row_data[0] + "</td><td>" + row_data[1] + "</td><td>" + row_data[3] + "</td><td>" + row_data[2] + "</td><td>" + row_data[10] + "</td><td>"+row_data[16]+"</td><td><button class='btn btn-edit btn-xs' onclick=serviceedit('" + ser_id + "')><i class='fa fa-pencil' aria-hidden='true'></i></button><button class='delete btn btn-delete btn-xs btn-add' onclick='Servicedelete(\"" + ser_id + "\")'><i class='fa fa-trash' aria-hidden='true'></i></button></td>";
        //}
        //else {
        //    var value = "<td>" + row_data[0] + "</td><td>" + row_data[1] + "</td><td>" + row_data[3] + "</td><td>" + row_data[2] + "</td><td>" + row_data[10] + "-" + row_data[11] + "</td><td>"+row_data[16]+"</td><td><button class='btn btn-edit btn-xs' onclick=serviceedit('" + ser_id + "')><i class='fa fa-pencil' aria-hidden='true'></i></button><button class='delete btn btn-delete btn-xs btn-add' onclick='Servicedelete(\"" + ser_id + "\")'><i class='fa fa-trash' aria-hidden='true'></i></button></td>";
        //}
        if ($('#Hbase_amount_type').val() != 4) {
            var value = "<td>" + row_data[0] + "</td><td>" + row_data[1] + "</td><td>" + doctor_name_fee + "</td><td>" + row_data[2] + "</td><td>" + row_data[10] + "</td><td>" + row_data[16] + "</td><td><button class='btn btn-edit btn-xs' onclick=serviceedit('" + ser_id + "')><i class='fa fa-pencil' aria-hidden='true'></i></button><button class='delete btn btn-delete btn-xs btn-add' onclick='Servicedelete(\"" + ser_id + "\")'><i class='fa fa-trash' aria-hidden='true'></i></button></td>";
        }
        else {
            var value = "<td>" + row_data[0] + "</td><td>" + row_data[1] + "</td><td>" + doctor_name_fee + "</td><td>" + row_data[2] + "</td><td>" + row_data[10] + "-" + row_data[11] + "</td><td>" + row_data[16] + "</td><td><button class='btn btn-edit btn-xs' onclick=serviceedit('" + ser_id + "')><i class='fa fa-pencil' aria-hidden='true'></i></button><button class='delete btn btn-delete btn-xs btn-add' onclick='Servicedelete(\"" + ser_id + "\")'><i class='fa fa-trash' aria-hidden='true'></i></button></td>";
        }
        $('#req_table #' + s_id).html(value);
        //$('#req_table > tbody:last').empty();
        //var tot_row = 0;
        //for (let i = 0; i < sessionStorage.length; i++) {
        //    const key = sessionStorage.key(i);
        //    var row_data = sessionStorage.getItem(key);
        //    if (row_data != null) {
        //        row_data = row_data.split(',');
        //        var value = "<tr id=" + key + "><td>" + row_data[0] + "</td><td>" + row_data[1] + "</td><td>" + row_data[3] + "</td><td>" + row_data[2] + "</td><td>"+row_data[10]+"</td><td><button class='btn btn-edit btn-xs' onclick=serviceedit('" + key + "')><i class='fa fa-pencil' aria-hidden='true'></i></button><button class='delete btn btn-delete btn-xs btn-add' onclick='Servicedelete(\"" + key + "\")'><i class='fa fa-trash' aria-hidden='true'></i></button></td></tr>";
        //        $('#req_table > tbody:last').append(value);
        //        tot_row = tot_row + 1;
        //    }
        //}
        //$('#ServiceTableRowCount').val(tot_row);
        $('#req_service').val('');
        $('#req_service_code').val('');
        $('#req_quantity').val(1);
        $('#req_quantity').prop('disabled', false);
        $('#SelDoctor').val('');
        $('#HSelDoctor').val('0');
        $('#His_description').val(0);
        $('#divSelDoctor').hide();

        $('#Doctor_Fee').val('');
        $('#divlDoctorFee').hide();
        
        $('#req_service').attr('disabled', false);
        $('#req_add').show();
        $('#req_update').hide();
        $('#SelDoctor').prop('disabled', true);
        $('#Hmaster_service_id').val('');
        $('#req_remarks').val('');
        $('#desc_div').addClass('hidden');
        var dateNow = new Date();

        var new_date = moment(dateNow).format('DD/MM/YYYY hh:mm A')
        $("#datetimepicker1").datepicker("destroy");
        $('#datetimepicker1').datetimepicker({
            format: 'DD/MM/YYYY hh:mm A',
            defaultDate: new_date
        });
        $('#req_time').val(new_date);
        $('#req_time').prop('disabled', true);
        $('#req_end_time').val('');
        $('#div_req_end').hide();
        // $('#div_service_amt').hide();
        $('#service_amount').attr('disabled', false);
        $('#service_amount').val(0);
        $('#service_tot_amount').val(0);
        $('#Pservice_amount').html('');
        $('#req_quantity').attr('onkeyup', 'numeric_only("req_quantity")');
        //}
    }
})
//Submitting IP/OP request 
$('#req_submit').click(function () {
    debugger;
  
    if ($.trim($('#pkg_branch_id').val()) == "" || $('#pkg_branch_id').val() == '0') {
        $('#Ppkg_branch_id').show();
        $('#Ppkg_branch_id').fadeOut(8000);
        $('#Ppkg_branch_id').html('Select Branch');
        $('#pkg_branch_id').focus();
        $('#pkg_branch_id').val('');
        return false;
    }
    if ($('#Hpatientid').val() == '') {
        $('#PtxtPaitentSearch_1').show();
        $('#PtxtPaitentSearch_1').fadeOut(8000);
        $('#PtxtPaitentSearch_1').html('Search Patient');
        $('#txtPaitentSearch_1').focus();
        $('#txtPaitentSearch_1').val('');
        return false;
    }
    if ($('#req_code').val() == '') {
        $('#Preq_code').show();
        $('#Preq_code').fadeOut(8000);
        $('#Preq_code').html('Enter Request Code');
        $('#req_code').focus();
        $('#req_code').val('');
        return false;
    } 
    if ($('#req_date').val() == '') {
        $('#Preq_date').show();
        $('#Preq_date').fadeOut(8000);
        $('#Preq_date').html('Request Date Empty');
        $('#req_date').focus();
        $('#req_date').val('');
        return false;
    }
   
        if (!($('#VisitDoctor').val()) || $('#HVisitDoctor').val() == 0){
            $('#PVisitDoctor').show();
            $('#PVisitDoctor').fadeOut(8000);
            $('#PVisitDoctor').html('Select Doctor');
            $('#VisitDoctor').focus();
            $('#VisitDoctor').val('');
            $('#HVisitDoctor').val('0');
            return false;
        }
    
    if ($('#req_table  >tbody >tr').length == 0) {
        $('#Preq_service').show();
        $('#Preq_service').fadeOut(8000);
        $('#Preq_service').html('Select Service Name');
        $('req_service').focus();
        return false;
    }
    else {
      
        request_insert_update();
    }
})
function request_insert_update() {
    debugger;
    $('#shade_slot_submit').show();
    $('#req_submit').hide();

    var tot_rowM = $.trim($('#ServiceTableRowCount').val());
    var total_amount = 0;
    if (tot_rowM > 0) {
        var L = 0;
        for (j = 1; j <= tot_rowM; j++) {
            debugger;
            var a = $('#req_table tbody').children('tr').eq(L);
            var b = a.prop('id');
            L++;
            //var C = b.split('_');
            var gkey = b;
            var row_data = sessionStorage.getItem(gkey);
            var K = 0;
            if (row_data == "") {
                console.log(gkey + '--------->' + row_data);
            }
            if (row_data != "" && row_data != null) {
                console.log(gkey + '-------' + row_data);
                row_data = row_data.split(',');
                total_amount = total_amount + parseInt(row_data[5]);
            }
        }
    }
    var indicator = '', wardid = 0, bedid = 0,alertMsg='';
    if ($('#req_submit').html() == 'Submit') {
        indicator = 'I'
        indicator_ser = 'SI'

    }
    else {
        indicator = 'U'
        indicator_ser = 'SU'
    }
    if ($('#Hwardid').val() == '' || $('#Hwardid').val() == '-') {
        wardid = 0
    }
    else {
        wardid = $('#Hwardid').val();
    }
    if ($('#Hbedid').val() == '' || $('#Hbedid').val() == '-') {
        bedid = 0
    }
    else {
        bedid = $('#Hbedid').val();
    }
    var date = $('#req_date').val().split('/');
    var req_date = date[2] + '-' + date[1] + '-' + date[0];
    var requestid = ($('#EditRequest_id').val() == '' || $('#EditRequest_id').val() == null) ? 0 : $('#EditRequest_id').val();
    var doc_id = ($('#HVisitDoctor').val() == '' || $('#HVisitDoctor').val() == 0) ? $('#HiddenDoctorID').val() : $('#HVisitDoctor').val();
    var request_data = {
        patient_id: $('#Hpatientid').val(),
        visit_report_id: $('#Hvisitid').val(),
        visit_type: $('#visit_type').val(),
        total_amount: total_amount,
        billing_class: $('#Hbilling_class').val(),
        doctor_id: doc_id,
        wardid: wardid,
        bedid: bedid,
        Dml_Indicator: indicator,
        request_code: $('#req_code').val(),
        request_date: req_date,
        branch_id: $('#pkg_branch_id').val(),
        request_id: requestid
    }
    $.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 (data1.msg == "Success") {
                console.log(data1);
                var data1 = data1.data;
                var data2 = data1;
                if (jQuery.isEmptyObject((data1))) {

                }
                else {
                    debugger;
                    var service = new Array();
                    var req_id = data1[0].request_id
                    var audit_log_req_id = data1[0].audit_log_request_id
                    var tot_rowM = $.trim($('#ServiceTableRowCount').val());
                    var total_amount = 0;
                    if (tot_rowM > 0) {
                        var L = 0;
                        for (j = 1; j <= tot_rowM; j++) {
                            debugger;
                            var service_data = {}
                            var a = $('#req_table tbody').children('tr').eq(L);
                            var b = a.prop('id');
                            L++;
                            //var C = b.split('_');
                            //var gkey = C[0];
                            var gkey = b;
                            var row_data = sessionStorage.getItem(gkey);
                            var K = 0;
                            if (row_data == "") {
                                console.log(gkey + '--------->' + row_data);
                            }
                            if (row_data != "" && row_data != null) {
                                console.log(gkey + '-------' + row_data);
                                debugger;
                                row_data = row_data.split(',');
                                var date = row_data[10].split(" ")[0];
                                var time = row_data[10].split(" ")[1] + " " + row_data[10].split(" ")[2];
                                var end_date, end_time;
                                if (row_data[12] == 4) {
                                    end_date = row_data[11].split(" ")[0];
                                    end_time = row_data[11].split(" ")[1] + " " + row_data[10].split(" ")[2];
                                }
                                else {
                                    end_date = null;
                                    end_time = null;
                                }
                                service_data.master_service_id = gkey.split('_')[1],
                                service_data.quantity = row_data[2],
                                service_data.request_id = req_id,
                                service_data.Dml_Indicator = indicator_ser
                                service_data.user_created_by = $('#hiddenUser_id').val(),
                                service_data.total_amount = row_data[5],
                                service_data.base_amount = row_data[4],
                                service_data.is_manual_amount = (parseFloat(row_data[4]) == parseFloat(row_data[17]) ? 0 : 1)
                                service_data.base_amount_orginal = row_data[19]
                                service_data.doctor_id = row_data[6],
                                service_data.work_order = row_data[7],
                                service_data.work_order_type = row_data[8],
                                service_data.package_id = row_data[9],
                                service_data.service_date=date,
                                service_data.service_time=time,
                                service_data.service_end_date=end_date,
                                service_data.service_end_time=end_time,
                                service_data.request_details_id=row_data[13],
                                service_data.remarks = (row_data[16] == '' || row_data[16] == "null") ? null : row_data[16],
                                service_data.doctor_fee = (row_data[17] == "-" || row_data[17] == null || row_data[17] == "null" || row_data[17] == "") ? 0 : row_data[17],
                                service_data.audit_log_request_id = audit_log_req_id
                            }
                            service.push(service_data);
                        }
                    }
                    $.ajax({
                        async: true,
                        type: 'POST',
                        url: '/Billing/IP_OP_Service',
                        contentType: 'application/json; charset=UTF-8',
                        data: JSON.stringify(service),
                        success: function (data) {
                            var data1 = JSON.parse(data);
                            if (data1.msg == "Success") {
                                var data1 = data1.data;
                                if (jQuery.isEmptyObject((data1))) {
                                }
                                else {

                                    $('#shade_slot_submit').hide();
                                    $('#req_submit').show();
                                    toastr.success(data2[0].StringMsg,
                         {
                             closeButton: false,
                             progressBar: true,
                             allowHtml: true,
                             timeOut: 0,
                         })
                                    setTimeout(function () {
                                        if ($("#IPVisitReport_Id").val() != "") {
                                            InventoryCRMInsert(req_id);
                                            window.location.href = '/BillingMaster/billingreqviewpage?Patient_Id=' + $("#IPPatient_Id").val() + '&IPVisitReport_Id=' + $('#IPVisitReport_Id').val() + '&IPDischarge_Id=""&branch_id=' + $('#EditBranch_id').val() + '&Investigation='+$('#IPInvestigation').val()+'';
                                        }
                                        else {
                                            InventoryCRMInsert(req_id);
                                            window.location.href = '/BillingMaster/billingreqviewpage'
                                        }
                                    }, 2000);
                                }
                            }
                            else {
                                console.log(data1);
                            }
                        }
                    })
                    
                }
            }
            else {
                console.log(data1);
            }
        }
    })

}
function InventoryCRMInsert(request_id) {
    debugger;
    var load_data = {
        dml_indicator: "CRMR",
        request_id: request_id

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

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

        }
    });
}
//Edit Request
function requestedit(id) {
    $('#shade_slot').show();
    var request_data = {
        request_id: id,
        Dml_Indicator: 'RE'
    }
    $.ajax({
        async: true,
        type: 'POST',
        url: '/Billing/IP_OP_Request',
        contentType: 'application/json; charset=UTF-8',
        data: JSON.stringify(request_data),
        success: function (data) {
            var data1 = JSON.parse(data);
            $('#shade_slot').hide();
            if (data1.msg == "Success") {
                var data1 = data1.data;
                console.log(data1);
                if (jQuery.isEmptyObject((data1))) {
                }
                else {
                    debugger;
                   
                    var value = '', tot_row = 0, count = 0, rowcount = 0;
                    $('#req_code').val(data1[0].request_code);
                    $('#req_date').val(data1[0].request_date);
                    //$('#EditBranch_id').val(data1[0].branchid);
                    if ($('#EditBranch_id').val() == null || $('#EditBranch_id').val() == 0) {
                        $('#pkg_branch_id').attr('disabled', false);
                    }
                    else {
                        $('#pkg_branch_id').attr('disabled', true);
                    }
                    //if (data1[0].is_casesheet == 1)
                    //{
                    //    LoadDoctor();
                    //}
                    //- LoadVisitDoctor(data1[0].visit_doctor_id);
                    $('#HVisitDoctor').val(data1[0].visit_doctor_id)
                    $('#VisitDoctor').val(data1[0].visit_doctor_name)
                    if ($('#IPInvestigation').val() == 1) {
                        data1 = data1.filter((item) =>item.work_order == 1)
                    }
                    $.each(data1, function (i, emp) {
                        debugger;
                       
                        var ser_name = emp.service_name;
                        var ser_id = emp.master_service_id;
                        var ser_code = emp.service_code;
                        var num_use = emp.quantity;
                        var work_order = emp.work_order;
                        var work_order_type = emp.work_order_type;
                        var pack = emp.package_id;
                        var service_date = emp.service_date + " " + emp.service_time;
                        var service_end = emp.service_end_date + " " + emp.service_end_time;
                        var base_amount_type = emp.base_amount_type;
                        var request_details_id = emp.request_details_id;
                        var range_min = emp.range_min;
                        var range_max = emp.range_max;
                        var remarks = emp.remarks;
                        var doctor_fee = emp.doctor_fee;
                        var is_description = emp.is_description;
                        

                        var doc_name = '-', doc_id = '';
                        if (emp.doctorid == '' || emp.doctorid == null) {
                            doc_name = '-'
                        }
                        else {
                            LoadDoctor();
                            doc_name = emp.doctor_name;
                            doc_id = emp.doctor_id;
                        }
                        var base_amount = emp.base_amount
                        var base_amount_org = emp.base_amount_orginal
                        var total_amount = emp.total_amount
                        var sess_key;
                        rowcount = $.trim($('#ServiceTableRowCount').val());
                        tot_row = (Number(rowcount) + 1);
                        var sess_data_ser = ser_name + "," + ser_code + "," + num_use + "," + doc_name + "," + base_amount + "," + total_amount + "," + doc_id + "," + work_order + "," + work_order_type + "," + pack + "," + service_date + "," + service_end + "," + base_amount_type + "," + request_details_id + "," + range_min + "," + range_max + "," + remarks + "," + doctor_fee + "," + is_description + "," + base_amount_org;
                        var key = '';
                        if (rowcount >= 1) {
                            var getEid = $('#req_table  tr').last();
                            var actId = getEid.prop('id');
                            var afterSplit = actId.split('row');
                            afterSplit = afterSplit[1].split('_')
                            afterInc = parseInt(afterSplit[0]) + 1;
                            console.log(afterInc);
                            ikey_Deit = 'row' + afterInc;
                        }
                        else {
                            ikey_Deit = 'row' + tot_row;
                        }
                        ikey_Deit = ikey_Deit + "_" + ser_id
                        sessionStorage.setItem(ikey_Deit, sess_data_ser);
                        //if ($('table#req_table').find('#' + ser_id).length == 0) {
                        if (remarks == '' || remarks==null)
                        {
                            remarks = '';
                        }
                        var d_fee=''
                        if (doctor_fee == null || doctor_fee == '' || doctor_fee == 0)
                        {
                            d_fee =''
                        }
                        else {
                            d_fee = doctor_fee
                        }
                        var dtr_name_fee = '';
                        var doctor_name_fee = doc_name + '/' + d_fee;
                        if (doctor_name_fee == '/' || doctor_name_fee == '-/')
                        {
                            dtr_name_fee = ''
                        }
                        else
                        {
                            dtr_name_fee = doctor_name_fee;
                        }

                            //if (base_amount_type != 4) {
                            //    value = "<tr id=" + ikey_Deit + "><td>" + ser_name + "</td><td>" + ser_code + "</td><td>" + doc_name + "</td><td>" + num_use + "</td><td>" + service_date + "</td><td>"+remarks+"</td><td><button class='btn btn-edit btn-xs' onclick=serviceedit('" + ikey_Deit + "')><i class='fa fa-pencil' aria-hidden='true'></i></button><button class='delete btn btn-delete btn-xs btn-add' onclick='Servicedelete(\"" + ikey_Deit + "\")'><i class='fa fa-trash' aria-hidden='true'></i></button></td></tr>";
                            //}
                            //else {
                            //    value = "<tr id=" + ikey_Deit + "><td>" + ser_name + "</td><td>" + ser_code + "</td><td>" + doc_name + "</td><td>" + num_use + "</td><td>" + service_date + " - " + service_end + "</td><td>"+remarks+"</td><td><button class='btn btn-edit btn-xs' onclick=serviceedit('" + ikey_Deit + "')><i class='fa fa-pencil' aria-hidden='true'></i></button><button class='delete btn btn-delete btn-xs btn-add' onclick='Servicedelete(\"" + ikey_Deit + "\")'><i class='fa fa-trash' aria-hidden='true'></i></button></td></tr>";
                        //}
                        if (base_amount_type != 4) {
                            value = "<tr id=" + ikey_Deit + "><td>" + ser_name + "</td><td>" + ser_code + "</td><td>" + dtr_name_fee + "</td><td>" + num_use + "</td><td>" + service_date + "</td><td>" + remarks + "</td><td><button class='btn btn-edit btn-xs' onclick=serviceedit('" + ikey_Deit + "')><i class='fa fa-pencil' aria-hidden='true'></i></button><button class='delete btn btn-delete btn-xs btn-add' onclick='Servicedelete(\"" + ikey_Deit + "\")'><i class='fa fa-trash' aria-hidden='true'></i></button></td></tr>";
                        }
                        else {
                            value = "<tr id=" + ikey_Deit + "><td>" + ser_name + "</td><td>" + ser_code + "</td><td>" + dtr_name_fee + "</td><td>" + num_use + "</td><td>" + service_date + " - " + service_end + "</td><td>" + remarks + "</td><td><button class='btn btn-edit btn-xs' onclick=serviceedit('" + ikey_Deit + "')><i class='fa fa-pencil' aria-hidden='true'></i></button><button class='delete btn btn-delete btn-xs btn-add' onclick='Servicedelete(\"" + ikey_Deit + "\")'><i class='fa fa-trash' aria-hidden='true'></i></button></td></tr>";
                        }
                        //}
                            $('#req_table > tbody:last').append(value);
                        if (count != 1) {
                            if (emp.is_doctor == 1 || emp.doctorid == '' || emp.doctorid == null) {
                                LoadDoctor();
                                count = count + 1;
                            }
                        }
                        $('#ServiceTableRowCount').val(tot_row);
                    })
                    

                    $('#req_submit').html('Update');
                }
            }
        }
    })
}
//Load Branch
function LoadBranch() {
    document.getElementById("pkg_branch_id").innerHTML = null;

    //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;
                    //$('#pkg_branch_id').attr('disabled', true);
                    var SubDepartment;
                    var default_opt = '<option value="0">--Select--</option>';
                    $.each(data1.Table, function (i, emp) {
                        SubDepartment = SubDepartment + '<option value="' + emp.hospital_branch_id + '">' + emp.branch_name + '</option>';
                    });
                    if (data1.Table.length == 1) {
                        $('#pkg_branch_id').append(SubDepartment);
                        $('#pkg_branch_id').change();
                    }
                    else {
                        $('#pkg_branch_id').append(default_opt + SubDepartment);
                    }


                    //if ($('#hiddenRole_id').val() == 1 && ($('#EditBranch_id').val() == null || $('#EditBranch_id').val() == '')) {
                    //    $('#pkg_branch_id').val($('#HospitalBranchID').val());
                    //    $('#txtPaitentSearch_1').attr('disabled', false);
                    //    LoadReqCode($('#visit_type').val());
                    //    LoadVisitDoctor();
                    //}
                    //else 
                    if ($('#hiddenRole_id').val() != 2 && ($('#EditBranch_id').val() == null || $('#EditBranch_id').val() == '')) {
                        $('#pkg_branch_id').val($('#HospitalBranchID').val());
                        $('#pkg_branch_id').attr('disabled', true);
                        $('#txtPaitentSearch_1').attr('disabled', false);
                        LoadReqCode($('#visit_type').val());
                       //- LoadVisitDoctor();
                    }
                    if ($('#EditBranch_id').val() != null && $('#EditBranch_id').val() != '') {
                        $('#pkg_branch_id').val($('#EditBranch_id').val());
                        $('#pkg_branch_id').attr('disabled', true);
                        LoadDoctor();
                    }
                    if ($("#IPVisitReport_Id").val() != null && $("#IPVisitReport_Id").val() != '') {
                        $('#pkg_branch_id').val($('#EditBranch_id').val());
                        $('#pkg_branch_id').attr('disabled', true);
                        LoadReqCode(2);
                        //if ($('#EditBranch_id').val() != null && $('#EditBranch_id').val() != '') {
                        //    LoadVisitDoctor();
                        //}
                    }
                    

                }
            }
            else {
                console.log(data1);
            }
        }
    });
}
//branch change function to load service based on it
//$('#pkg_branch_id').change(function () {
//    if ($('#Hpatientid').val() == '') {
//        $('#PtxtPaitentSearch_1').show();
//        $('#PtxtPaitentSearch_1').fadeOut(8000);
//        $('#PtxtPaitentSearch_1').html('Search Patient');
//        $('#txtPaitentSearch_1').focus();
//        $('#txtPaitentSearch_1').val('');
//        $('#pkg_branch_id').val('');
//        return false;
//    }
//    else if($('#pkg_branch_id').val()=='' || $('#pkg_branch_id').val()==0)
//    {
//        $('#req_service').attr('disabled', true);
//    }
//    else {
//        $('#req_service').attr('disabled', false);
//    }
//})

$('#pkg_branch_id').change(function () {
    var val = $('#txtPaitentSearch_1').val();
    if (val == '' || val == null) {
        $('#txtPaitentSearch_1').attr('disabled', false);
    }
    else {
        $('.pat-strip').hide();
        $('#txtPaitentSearch_1').val('');
    }
    LoadReqCode($('#visit_type').val());
  //-  LoadVisitDoctor();
    

})

//service request end date change function


$('#datetimepicker2,#datetimepicker1').on('change dp.change', function (e) {
    debugger;
    var start_date = $('#req_time').val();
    var end_date = $('#req_end_time').val();
    if (start_date != '' && end_date != '') {
        var quantity = 0;
        var start_date = new Date(moment($('#req_time').val(), ["DD/MM/YYYY hh:mm A"]).format('YYYY-MM-DD H:mm:ss'))
        var end_date = new Date(moment($('#req_end_time').val(), ["DD/MM/YYYY hh:mm A"]).format('YYYY-MM-DD H:mm:ss'))
        console.log(start_date);
        console.log(end_date);
        var diff = (end_date - start_date) / 1000 / 60 / 60;
        console.log(diff);
        diff1 = diff.toString();
        var a = diff1.split('.')[0];
        if (diff != a) {
            console.log(a);
            var chk = a + '.5';
            if (parseFloat(diff) <= parseFloat(chk)) {
                quantity = parseFloat(chk);
            }
            else {
                quantity = Math.ceil(diff);
            }
        }
        else {
            quantity = diff;
        }
        console.log(quantity);
        $('#req_quantity').val(quantity);
        $('#req_quantity').prop("disabled", true);
    }
})

$('#req_quantity').change(function () {
    debugger;
    if($('#EditVisit_type').val())
    {
        if($('#req_update').is(':visible')){
            if($('#work_quantity').val()>$('#req_quantity').val() && $('#req_quantity').val()!='')
            {
                toastr.warning('Already ' + $('#work_quantity').val() +' quantity used under work order');
                debugger;
                //$('#Preq_quantity').show();
                //$('#Preq_quantity').fadeOut(8000);
                //$('#Preq_quantity').html('Quantity should be atleast '+$('#work_quantity').val());
                $('#req_quantity').focus();
                $('#req_quantity').val($('#work_quantity').val());
                return false;
            }
        }
    }
    var unit_rate = $('#service_amount').val() || 0;
    var qtys = $('#req_quantity').val() || 0;
    $('#service_tot_amount').val(parseFloat(unit_rate) * parseFloat(qtys));
})

//load visit type
function loadvisit_type(val) {
    var data = {
        P_Dml_Indicator: 'STR'
    }
    $.ajax({
        async: true,
        type: 'POST',
        url: '/Billing/Service_Master_Ins_upd_sel',
        contentType: 'application/json; charset=UTF-8',
        data: JSON.stringify(data),
        success: function (data) {
            debugger;

            var data2 = JSON.parse(data);

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

            }
            else {

                if (data2.msg == "Success") {
                    $('#visit_type').empty();
                    var option = "";
                    var data1 = data2.data;
                    var default_option = "<option value='0'>--Select--</option>";
                    $.each(data1, function (i, emp) {
                        option = option + "<option value=" + emp.visit_typeid + " >" + emp.visit_type_name + "</option>"
                    })
                    $('#visit_type').append(default_option + option);
                    if (val != 0 && val != null) {
                        $('#visit_type').val(val);
                    }
                }
            }
        }
    })
}
//Doctor Autocomplete
$('#VisitDoctor').autocomplete({
    source: function (request, response) {
        $.ajax({
            async: true,
            url: "/Ipmanagement/DoctorNameAutoCompletelist",
            type: "POST",
            dataType: "json",
            data: { Prefix: request.term, Dml_Indicator: "HDL", branch_id: $('#pkg_branch_id').val() },
            success: function (data) {
                debugger;
                $('#HdnadmDoctorid').val('');
                // var data2 = JSON.parse(data);
                var data2 = data;
                response($.map(data2, function (item) {
                    return { label: item.doctorname, value: item.doctorname, id: item.doctorid };
                }))
            }
        })
    },
    minLength: 1,
    select: function (event, ui) {
        debugger;
        $('#HVisitDoctor').val(ui.item.id);
    },
    html: true,
    open: function (event, ui) {
        $(".ui-autocomplete").css("z-index", 1000);

    }
});
$('#SelDoctor').autocomplete({
    source: function (request, response) {
        $.ajax({
            async: true,
            url: "/Ipmanagement/DoctorNameAutoCompletelist",
            type: "POST",
            dataType: "json",
            data: { Prefix: request.term, Dml_Indicator: "HDL", branch_id: $('#pkg_branch_id').val() },
            success: function (data) {
                debugger;
                $('#HdnadmDoctorid').val('');
                // var data2 = JSON.parse(data);
                var data2 = data;
                response($.map(data2, function (item) {
                    return { label: item.doctorname, value: item.doctorname, id: item.doctorid };
                }))
            }
        })
    },
    minLength: 1,
    select: function (event, ui) {
        debugger;
        $('#HSelDoctor').val(ui.item.id);
    },
    html: true,
    open: function (event, ui) {
        $(".ui-autocomplete").css("z-index", 1000);

    }
});

