$(document).ready(function () {
    $('#btnpay_update').hide();
    $('#div_notes_receipt').hide();
    sessionStorage.clear();
    let loadBrch = LoadBranch();
    $.when(loadBrch)
           .then(function (data) {
               if ($('#QUtrId').val()) {
                   LoadUTRData(1);

               }
               else if (($('#RBilling_no').val() == '' || $('#RBilling_no').val() == null) && ($('#HBilling_no').val() == '' || $('#HBilling_no').val() == null) && !$('#QUtrId').val()) {
                   Loadtype();
               }
           })


    $('.c_dateformat1').datepicker({
        autoclose: true,
        todayHighlight: true,
        format: "dd/mm/yyyy",

    });
})
//Receipt Type change function
$('#rec_type').change(function () {
    debugger;
    var type = $('#rec_type').val();
    if (type == 1) {
        $('.pat-strip').hide();
        $('#div_notes_receipt').hide();
        $('#Hpatientid').val('');
        $('#txtPaitentSearch_1').val('');
        $('#div_txtPaitentSearch_1').show();
        $('#div_billno').hide();
        $('.bill_detail').hide();
        $('#payment_type').val(0);
        $('#rec_amount').val('');
        $('#rec_tds').val('');
        $('#rec_mou').val('');
        $('#rec_others').val('');
        $('#rec_trans').val('');
        $('#div_rec_trans').hide();
        $('.div_pay').show();
        $('#HBilling_no').val('');
        $('#Receipt_Div').addClass('hidden');
        $('#div_utrtype').hide();
        $('#div_branchid').show();
        $('#utrid').val(0)
        $('#divpayCheck').hide()
        LoadReceipt(type);
    }
    else if (type == 2) {
        $('.pat-strip').hide();
        $('#Hpatientid').val('');
        $('#billno_search').val('');
        $('#div_txtPaitentSearch_1').hide();
        if ($('#HBilling_no').val() == '' && $('#RBilling_no').val() == '') {
            $('#div_billno').show();
        }
        $('#payment_type').val(0);
        $('#rec_amount').val('');
        $('#rec_tds').val('');
        $('#rec_mou').val('');
        $('#rec_others').val('');
        $('#rec_trans').val('');
        $('#div_rec_trans').hide();
        $('.div_pay').hide();
        $('.div_sms').hide();
        $('#Receipt_Div').addClass('hidden');
        $('#div_notes_receipt').hide();
        $('#div_utrtype').hide();
        $('#div_branchid').show();
        $('#utrid').val(0)
        LoadReceipt(type);
    }
    else if (type == 3) {
        $('.pat-strip').hide();
        $('#Hpatientid').val('');
        $('#billno_search').val('');
        $('#div_txtPaitentSearch_1,#div_billno').hide();
        $('#div_utrtype').show();
        $('#div_billno,#divpayCheck').hide();
        $('.bill_detail').hide();
        $('#payment_type').val(0);
        $('#rec_amount').val('');
        $('#rec_tds').val('');
        $('#rec_mou').val('');
        $('#rec_others').val('');
        $('#rec_trans').val('');
        $('#div_rec_trans').hide();
        $('.div_pay').hide();
        $('.div_sms').hide();
        if ($('#pkg_branch_id').val() != 0 && $('#pkg_branch_id').val() != '') {
            $('#utr_search').removeAttr('disabled');
        }

    }
    $('.c_dateformat1').datepicker({
        autoclose: true,
        todayHighlight: true,
        format: "dd/mm/yyyy",

    });
})
//Loading Receipt Code
function LoadReceipt(type) {
    var receipt_data = {
        Dml_Indicator: 'RC',
        receipt_type: type,
        branch_id: $('#pkg_branch_id').val()
    }
    $.ajax({
        async: true,
        type: 'POST',
        url: '/Billing/Billing_Receipt',
        contentType: 'application/json; charset=UTF-8',
        data: JSON.stringify(receipt_data),
        success: function (data) {
            var data1 = JSON.parse(data);
            if (data1.msg == "Success") {
                var data1 = data1.data.Table;
                console.log(data1);
                if (jQuery.isEmptyObject((data1))) {
                }
                else {
                    $('#rec_code').val(data1[0].receipt_code);
                    $('#rec_date').val(data1[0].receipt_date);
                    //LoadPayment_Type();
                }
            }
        }
    })
}
//Loading Payment Type
function LoadPayment_Type() {
    var receipt_data = {
        Dml_Indicator: 'PL',
        branch_id: $('#pkg_branch_id').val()
    }
    $.ajax({
        async: true,
        type: 'POST',
        url: '/Billing/Billing_Receipt',
        contentType: 'application/json; charset=UTF-8',
        data: JSON.stringify(receipt_data),
        success: function (data) {
            var data = JSON.parse(data);
            if (data.msg == "Success") {
                var data1 = data.data.Table;
                var data2 = data.data.Table1;
                console.log(data1);
                if (jQuery.isEmptyObject((data))) {
                }
                else {
                    $('#payment_type').empty();
                    $('#rec_bank').empty();
                    var Service = '', service1 = '';
                    var default_opt = '<option value="0">--Select--</option>';
                    $.each(data1, function (i, emp) {
                        Service = Service + '<option value="' + emp.master_servie_type_id + '">' + emp.master_service_name + '</option>';
                    });
                    $('#payment_type').append(default_opt + Service);
                    $.each(data2, function (i, emp) {
                        service1 = service1 + '<option value="' + emp.master_servie_type_id + '">' + emp.master_service_name + '</option>';
                    });
                    $('#rec_bank').append(default_opt + service1);
                }
            }
            else {
                console.log(data1);
            }
        }
    })
}
//Payment mode change function
$('#payment_type').change(function () {
    debugger;
    if ($('#payment_type option:selected').text().toLowerCase() != 'cash' && $('#payment_type').val() != 0) {
        $('#div_rec_trans').show();
    }
    else {
        $('#div_rec_trans').hide();
        $('#rec_trans').val('');
    }
    if ($('#payment_type option:selected').text().toLowerCase().includes('card')) {
        $('#div_rec_bank').show();
    }
    else {
        $('#div_rec_bank').hide();
        $('#rec_bank').val('');
    }
})
//Payment add function
$('#btnpay_add').click(function () {
    debugger;
    if ($('#rec_type').val() == 1) {
        if ($('#Hpatientid').val() == '') {
            $('#PtxtPaitentSearch_1').show();
            $('#PtxtPaitentSearch_1').fadeOut(8000);
            $('#PtxtPaitentSearch_1').html('Search Patient');
            $('#txtPaitentSearch_1').focus();
            $('#txtPaitentSearch_1').val('');
            return false;
        }
    }
    if (($('#EditReceipt_id').val() == '' || $('#EditReceipt_id').val() == null) && ($('#RBilling_no').val() == '')) {

        if ($('#rec_type').val() == 2) {
            if ($('#billno_search').val() == '') {
                $('#Pbillno_search').show();
                $('#Pbillno_search').fadeOut(8000);
                $('#Pbillno_search').html('Search Bill No..');
                $('#billno_search').focus();
                $('#billno_search').val('');
                return false;
            }
        }
    }
    if ($('#rec_type').val() == 3) {
        if ($('#utr_search').val() == '') {
            $('#Putr_search').show();
            $('#Putr_search').fadeOut(8000);
            $('#Putr_search').html('Search UTR No..');
            $('#utr_search').focus();
            $('#utr_search').val('');
            return false;
        }
    }
    if ($.trim($('#payment_type').val()) == '' || $.trim($('#payment_type').val()) == 0) {
        $('#Ppayment_type').show();
        $('#Ppayment_type').fadeOut(4000);
        $('#Ppayment_type').html('Select Payment Type');
        $('#payment_type').focus();
        $('#payment_type').val('');
        return false;
    }
    if ($('#payment_type option:selected').text().toUpperCase().includes('CARD')) {
        if ($('#rec_bank').val() == '' || $('#rec_bank').val() == 0) {
            $('#Prec_bank').show();
            $('#Prec_bank').fadeOut(8000);
            $('#Prec_bank').html('Please Enter Bank Name');
            $('#rec_bank').focus();
            $('#rec_bank').val();
            return false;
        }
    }

    if ($.trim($('#rec_amount').val()) == '') {
        $('#Prec_amount').show();
        $('#Prec_amount').fadeOut(4000);
        $('#Prec_amount').html('Enter the amount');
        $('#rec_amount').focus();
        $('#rec_amount').val('');
        return false;
    }

    else {

        var tot_rowM = $.trim($('#PaymentTableRowCount').val());
        var paymentmodeexists = 0;
        if (tot_rowM > 0) {
            var L = 0;
            for (j = 1; j <= tot_rowM; j++) {
                var a = $('#payment_table tbody').children('tr').eq(L);
                var b = a.prop('id');
                L++;
                var gkey = b;
                var row_data = sessionStorage.getItem(gkey);
                if (row_data != null && row_data != "") {
                    row_data = row_data.split(',');
                    if ($('#payment_type').val() == row_data[0]) {
                        paymentmodeexists++;
                    }
                }
            }
        }

        if (paymentmodeexists > 0) {
            toastr.warning('This payment mode already exists');
            return false;
        }


        debugger;


        var payment_type = $('#payment_type').val();
        var payment_name = $('#payment_type option:selected').text();
        var amount = $('#rec_amount').val();
        var ref_no = $('#rec_trans').val();
        var bank_name = $('#rec_bank').val();
        var bank_name_txt = $('#rec_bank option:selected').text();
        var tds = $('#rec_tds').val();
        var mou = $('#rec_mou').val();
        var others = $('#rec_others').val();
        var billno = $('#HBilling_no').val();
        var PatientId = $('#Hpatientid').val();
        var Patient_Id = $('#hdnPatient_Id').val();
        var billCode = $('#Hbill_no').val();
        var PatientName = $('#hdn_PatientName').val();
        var ClaimDue = $('#Hclaimdue').val();
        var VisitReport_Id = $('#Hvisitid').val();
        var sess_key;
        var rowcount = $.trim($('#PaymentTableRowCount').val());
        var tot_row = (Number(rowcount) + 1);
        if (tds == '') {
            tds = 0;
        }
        if (mou == '') {
            mou = 0;
        }
        if (others == '') {
            others = 0;
        }
        var pay_amount = parseFloat(amount) + parseFloat(tds) + parseFloat(mou) + parseFloat(others);
        var ClaimDuePending = parseFloat($('#Hclaimdue').val()) - parseFloat(pay_amount);
        var sess_data_ser = payment_type + "," + payment_name + "," + amount + "," + ref_no + "," + tds + "," + mou + "," + others + "," + bank_name + "," + 0 + "," + billno + "," + billCode + "," + PatientId + "," + PatientName + "," + Patient_Id + "," + ClaimDue + "," + ClaimDuePending + "," + VisitReport_Id + "," + 0;

        var key = '';
        if (rowcount >= 1) {
            var getEid = $('#payment_table tbody  tr').last();
            var actId = getEid.prop('id');
            var afterSplit = actId.split('row_');
            afterInc = parseInt(afterSplit[1]) + 1;
            console.log(afterInc);
            ikey_pay = 'row_' + afterInc;
        }
        else {

            ikey_pay = 'row_' + tot_row;
        }
        sessionStorage.setItem(ikey_pay, sess_data_ser);
        $('#payment_table thead').empty();

        if ($('#rec_type').val() == 1) {
            $('#payment_table tfoot').empty();
            var thead = '<tr><th>S.no</th><th>Type</th><th>Bank Name</th><th>Transaction ID</th><th>Amount</th></tr></thead>';
            $('#payment_table thead').append(thead);
            var tbody = '<tr id="row_' + tot_row + '" data-id=0><td>' + tot_row + '</td><td>' + payment_name + '</td><td>' + bank_name_txt + '</td><td>' + ref_no + '</td><td>' + amount + '</td></tr>';
            $('#payment_table tbody').append(tbody);
            var previousval = 0.0;
            $('#payment_table > tbody  > tr').each(function () {
                $(this).find("td:gt(3):lt(4)").each(function () {
                    var temp = $(this).html();
                    previousval = parseFloat(previousval) + parseFloat(temp);
                });
            });
            $('#PaymentTableRowCount').val(tot_row);
            var tfoot = '<tr><td colspan="4" style="text-align:right;">Total Amount Received</td>'
            var td = '<td id="foot_total">' + previousval + '</td></tr>';
            $('#pay_tot').val(previousval);
            $('#payment_table tfoot').append(tfoot + td);
            $('#rec_type').attr('disabled', true);
            $('#pkg_branch_id').attr('disabled', true);
            $('#txtPaitentSearch_1').attr('disabled', true);
            $('#billno_search').attr('disabled', true);


        }
        else if ($('#rec_type').val() == 2) {
            var action = "<button class='btn btn-xs btn-edit mr-10'onclick='rec_edit(\"" + payment_type + "\",0,\"" + tot_row + "\")' ><i class='fa fa-pencil' aria-hidden='true'></i></button>"
            var thead = '<tr><th>S.no</th><th>Type</th><th>Bank Name</th><th>Transaction ID</th><th>TDS(Tax)</th><th>MOU</th><th>Others</th><th>Amount</th><th>Actions</th></tr></thead>';
            $('#payment_table thead').append(thead);
            var tbody = '<tr id="row_' + tot_row + '" data-id=0><td>' + tot_row + '</td><td id=paymentMode_' + tot_row + ' data-id=' + payment_type + '>' + payment_name + '</td><td id=BName_' + tot_row + ' data-id=' + bank_name + '>' + bank_name_txt + '</td><td id=RefNo_' + tot_row + '>' + ref_no + '</td><td id=TDS_' + tot_row + '>' + tds + '</td><td id=MOU_' + tot_row + '>' + mou + '</td><td id=Others_' + tot_row + '>' + others + '</td><td id=Amount_' + tot_row + '>' + amount + '</td><td>' + action + '</td></tr>';
            $('#payment_table tbody').append(tbody);
            var previousval = 0.0;
            $('#payment_table > tbody  > tr').each(function () {
                $(this).find("td:gt(3):lt(4)").each(function () {
                    var temp = $(this).html();
                    previousval = parseFloat(previousval) + parseFloat(temp);
                });

            });
            const due_check = (parseFloat($('#due_amount').val()) - parseFloat(pay_amount));
            if (parseInt(due_check) >= 0) {

                $('#payment_table tfoot').empty();
                $('#due_amount').html('&#8377;' + ((parseFloat($('#due_amount').val()) - parseFloat(pay_amount))).toFixed(2));
                $('#due_amount').val((parseFloat($('#due_amount').val()) - parseFloat(pay_amount)).toFixed(2));
                $('#PaymentTableRowCount').val(tot_row);
                var tfoot = '<tr><td colspan="8" style="text-align:right;">Total Amount</td>'
                $('#pay_tot').val(previousval);
                var due_amount = $('#Hdueamount').val();
                var td = '<td id="foot_total">' + parseFloat(previousval) + '</td></tr>';
                $('#payment_table tfoot').append(tfoot + td);
                $('#rec_type').attr('disabled', true);
                $('#pkg_branch_id').attr('disabled', true);
                $('#txtPaitentSearch_1').attr('disabled', true);
                $('#billno_search').attr('disabled', true);
                $('#Cclaim').attr('disabled', true);

            }
            else {
                $("#row_" + tot_row).remove();
                sessionStorage.removeItem('row_' + tot_row)

                toastr.warning('Payment exceeds the due amount');
            }
        }
        else if ($('#rec_type').val() == 3) {
            debugger;
            var action = "<button class='btn btn-xs btn-edit mr-10'onclick='rec_edit(\"" + payment_type + "\",0,\"" + tot_row + "\")' ><i class='fa fa-pencil' aria-hidden='true'></i></button>"
            var thead = '<tr><th>S.no</th><th>Bill Code</th><th>Patient Name</th><th>Type</th><th>Bank Name</th><th>Transaction ID</th><th>TDS(Tax)</th><th>MOU</th><th>Others</th><th>Amount</th><th>Actions</th></tr></thead>';
            $('#payment_table thead').append(thead);
            var tbody = '<tr id="row_' + tot_row + '" data-id2=' + tot_row + ' data-id1=0><td>' + tot_row + '</td><td id=billCode_' + tot_row + ' data-id=' + billno + '>' + billCode + '</td><td id=patientCode_' + tot_row + ' data-id=' + PatientId + '>' + PatientName + '</td><td id=paymentMode_' + tot_row + ' data-id=' + payment_type + '>' + payment_name + '</td><td id=BName_' + tot_row + ' data-id=' + bank_name + '>' + bank_name_txt + '</td><td id=RefNo_' + tot_row + '>' + ref_no + '</td><td id=TDS_' + tot_row + '>' + tds + '</td><td id=MOU_' + tot_row + '>' + mou + '</td><td id=Others_' + tot_row + '>' + others + '</td><td id=Amount_' + tot_row + '>' + amount + '</td><td>' + action + '</td></tr>';
            $('#payment_table tbody').append(tbody);
            var previousval = 0.0, billdue = [];
            $('#payment_table > tbody  > tr').each(function () {
                //$(this).find("td:gt(5):lt(7)").each(function () {
                //    var temp = $(this).html();
                //    previousval = parseFloat(previousval) + parseFloat(temp);
                //});
                var id = $(this).closest("tr").prop("id")
                var dataid = parseInt($(this).closest("tr").attr('data-id2'));
                if (parseInt($('#billCode_' + dataid).attr('data-id')) == billno && dataid != tot_row) {
                    billdue.push($(this).closest("tr").prop("id"))
                }
                var columnsToSum = $(this).find("td").slice(6, 10);

                columnsToSum.each(function () {
                    var temp = $(this).html();
                    previousval += parseFloat(temp) || 0;
                });

            });
            var billsamechk = 0;
            if (billdue.length > 0) {
                var rowData = sessionStorage.getItem(billdue[0]);
                rowData = rowData.split(",");
                billsamechk = parseFloat(rowData[15]) - parseFloat(pay_amount);
                billdue.push('row_' + tot_row);

            }
            const due_check = ((parseFloat($('#due_amount').val()) - parseFloat(pay_amount))).toFixed(2);

            if (parseFloat(due_check) >= 0 && parseFloat(ClaimDuePending) >= 0 && parseFloat(billsamechk) >= 0) {
                if (billdue.length > 0) {

                    for (var i = 0; i < billdue.length; i++) {
                        var rowData = sessionStorage.getItem(billdue[i]);
                        rowData = rowData.split(",");
                        rowData[15] = billsamechk;
                        sessionStorage.removeItem(billdue[i]);
                        rowData = rowData.toString();
                        sessionStorage.setItem(billdue[i], rowData);
                    }
                }
                $('#due_amount').html('&#8377;' + ((parseFloat($('#due_amount').val()) - parseFloat(pay_amount))).toFixed(2));
                $('#due_amount').val((parseFloat($('#due_amount').val()) - parseFloat(pay_amount)).toFixed(2));
                $('#payment_table tfoot').empty();
                $('#PaymentTableRowCount').val(tot_row);
                var tfoot = '<tr><td colspan="10" style="text-align:right;">Total Amount</td>'
                $('#pay_tot').val(previousval);

                var td = '<td id="foot_total">' + parseFloat(previousval) + '</td></tr>';
                $('#payment_table tfoot').append(tfoot + td);
                $('#rec_type').attr('disabled', true);
                $('#pkg_branch_id').attr('disabled', true);
                $('#utr_search').attr('disabled', true);
            }
            else {
                $("#row_" + tot_row).remove();
                sessionStorage.removeItem('row_' + tot_row)
                toastr.warning('Payment exceeds the Bill  due amount');
            }
            $('#billno_searchutr').val('');
            $('#hdn_PatientName').val('');
            $('#hdnPatientId').val(0);
            $('#Hbill_no').val('');
            $('#HBilling_no').val(0);
            $('#Hclaimdue,#Hclaimpen').val(0);
        }
        $('#rec_amount').val('');
        $('#rec_trans').val('');
        $('#rec_tds').val('');
        $('#rec_mou').val('');
        $('#rec_others').val('');
        $('#payment_type').val('');
        $('#rec_bank').val('');
        $('#div_rec_bank').hide();
    }
})
//Submiting the Payment
$('#rec_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 ($('#rec_type').val() == 1) {
        if ($('#Hpatientid').val() == '') {
            $('#PtxtPaitentSearch_1').show();
            $('#PtxtPaitentSearch_1').fadeOut(8000);
            $('#PtxtPaitentSearch_1').html('Search Patient');
            $('#txtPaitentSearch_1').focus();
            $('#txtPaitentSearch_1').val('');
            return false;
        }
    }
    if (($('#EditReceipt_id').val() == '' || $('#EditReceipt_id').val() == null) && ($('#RBilling_no').val() == '')) {
        if ($('#rec_type').val() == 2) {
            if ($('#billno_search').val() == '') {
                $('#Pbillno_search').show();
                $('#Pbillno_search').fadeOut(8000);
                $('#Pbillno_search').html('Search Bill No..');
                $('#billno_search').focus();
                $('#billno_search').val('');
                return false;
            }
        }
    }
    if ($('#rec_type').val() == 3 && !$('#EditReceipt_id').val()) {
        if ($('#utr_search').val() == '') {
            $('#Putr_search').show();
            $('#Putr_search').fadeOut(8000);
            $('#Putr_search').html('Search UTR No..');
            $('#utr_search').focus();
            $('#utr_search').val('');
            return false;
        }
    }
    //if ($('#payment_table  >tbody >tr').length == 0 || sessionStorage.length == 0) {
    //   // var due_amount = $('#Hdueamount').val();

    //            if ($('#EditReceipt_id').val() != '' && $('#EditReceipt_id').val() != null) {

    //        toastr.warning('Please enter the amount');
    //        return false;
    //    }
    //    else {
    //        $('#Ppayment_type').show();
    //        $('#Ppayment_type').fadeOut(4000);
    //        $('#Ppayment_type').html('Select Payment Type');
    //        $('#payment_type').focus();
    //        $('#payment_type').val('');
    //        return false;
    //    }

    //    }



    //  else {
    $('#shade_slot_submit').show();
    $('#rec_submit').attr('disabled', true);
    var indicator_id = '';
    var date = $('#rec_date').val().split('/');
    var rec_date = date[2] + '-' + date[1] + '-' + date[0];
    if ($('#rec_type').val() == 3 && !$('#EditReceipt_id').val()) {
        msg = 'Data Saved Successfully';
        var tot_rowM = $.trim($('#PaymentTableRowCount').val());
        var total_amount = 0;
        if (tot_rowM > 0) {
            var L = 0;
            var service = new Array();
            for (j = 1; j <= tot_rowM; j++) {
                debugger;
                var service_data = {}
                var a = $('#payment_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(',');
                    service_data.receipt_id = row_data[17],
                    service_data.payment_type = row_data[0],
                    service_data.Dml_Indicator = 'RUTR'
                    service_data.user_created_by = $('#hiddenUser_id').val(),
                    service_data.total_amount = row_data[2],
                    service_data.referrence_no = row_data[3],
                    service_data.tds = row_data[4],
                    service_data.mou = row_data[5],
                    service_data.others = row_data[6],
                    service_data.bank_name = (!row_data[7] || row_data[7] == 'null') ? '' : row_data[7],

                    service_data.receipt_date = rec_date,
                    service_data.receipt_code = $('#rec_code').val(),
                    service_data.patient_id = row_data[13],
                    service_data.visit_report_id = row_data[16],
                    service_data.receipt_type = $('#rec_type').val(),
                    service_data.billing_code = row_data[10],
                    service_data.branch_id = $('#pkg_branch_id').val(),
                    service_data.billing_no = row_data[9],
                    service_data.due_amount = row_data[15],
                    service_data.hospital_id = $('#HospitalId').val(),
                    service_data.remarks = remarks,
                    service_data.is_claim = ($('#Cclaim').val() == '') ? 0 : $('#Cclaim').val();
                    service_data.UTRNumber = $('#utrnumber').val(),
                    service_data.UTRId = $('#utrid').val();
                    service_data.UTRAmount = ($('#due_amount').val() == '' || $('#due_amount').val() == null) ? 0 : $('#due_amount').val()

                    console.log(service.push(service_data));
                }

            }
            $.ajax({
                async: true,
                type: 'POST',
                url: '/Billing/Billing_receipt_detail',
                contentType: 'application/json; charset=UTF-8',
                data: JSON.stringify(service),
                success: function (data) {
                    var data1 = JSON.parse(data);
                    var rec = data1.data.Table.stringMsg;
                    if (rec == 'Not Success') {
                        toastr.warning("Cash Deposit should not greater than 200000/-. Please take Payment in other Mode.",
                                                   {
                                                       closeButton: false,
                                                       progressBar: true,
                                                       allowHtml: true,
                                                       timeOut: 0,
                                                   })
                    }
                    else {
                        toastr.success("Data Saved Successfully",
                       {
                           closeButton: false,
                           progressBar: true,
                           allowHtml: true,
                           timeOut: 0,
                       })
                        setTimeout(function () {
                            window.location.href = '/BillingMaster/billing_receipt_view'
                        }, 2000);
                    }


                    //setTimeout(function () {
                    //    window.location.href = '/BillingMaster/billing_receipt_view'
                    //}, 2000);
                }
            })
        }
    }
    else {
        var receipt_id = ($('#EditReceipt_id').val() == '' || $('#EditReceipt_id').val() == null) ? 0 : $('#EditReceipt_id').val();
        var billing_no = ($('#HBilling_no').val() == '' || $('#HBilling_no').val() == null) ? ($('#RBilling_no').val() == '' || $('#RBilling_no').val() == null) ? 0 : $('#RBilling_no').val() : $('#HBilling_no').val();
        var due_amount = ($('#due_amount').val() == '' || $('#due_amount').val() == null) ? 0 : $('#due_amount').val();
        var remarks = $('#notes_receipt').val();
        var msg = '';


        if (receipt_id == 0) {
            //indicator_id = 'I'
            msg = 'Data Saved Successfully';

            // added by nandhini on 30/03/2023 for receipt each payment mode

            var tot_rowM = $.trim($('#PaymentTableRowCount').val());
            var total_amount = 0;
            if (tot_rowM > 0) {
                var L = 0;
                var service = new Array();
                for (j = 1; j <= tot_rowM; j++) {
                    debugger;
                    var service_data = {}
                    var a = $('#payment_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(',');
                        service_data.receipt_id = 0,
                        service_data.payment_type = row_data[0],
                        service_data.Dml_Indicator = 'RIM'
                        service_data.user_created_by = $('#hiddenUser_id').val(),
                        service_data.total_amount = row_data[2],
                        service_data.referrence_no = row_data[3],
                        service_data.tds = row_data[4],
                        service_data.mou = row_data[5],
                        service_data.others = row_data[6],
                        service_data.bank_name = row_data[7],

                        service_data.receipt_date = rec_date,
                        service_data.receipt_code = $('#rec_code').val(),
                        service_data.patient_id = $('#Hpatientid').val(),
                        service_data.visit_report_id = $('#Hvisitid').val(),
                        service_data.receipt_type = $('#rec_type').val(),
                        service_data.billing_code = $('#Hbill_no').val(),
                        service_data.branch_id = $('#pkg_branch_id').val(),
                        service_data.billing_no = billing_no,
                        service_data.due_amount = due_amount,
                        service_data.hospital_id = $('#HospitalId').val(),
                        service_data.remarks = remarks,
                        service_data.is_claim = ($('#Cclaim').val() == '') ? 0 : $('#Cclaim').val();

                        console.log(service.push(service_data));
                    }

                }
                $.ajax({
                    async: true,
                    type: 'POST',
                    url: '/Billing/Billing_receipt_detail',
                    contentType: 'application/json; charset=UTF-8',
                    data: JSON.stringify(service),
                    success: function (data) {
                        var data1 = JSON.parse(data);
                        var rec = data1.data.Table[0].stringMsg;
                        if (rec == 'Not Success') {
                            toastr.warning("Cash Deposit should not greater than 200000/-. Please take Payment in other Mode.",
                                                       {
                                                           closeButton: false,
                                                           progressBar: true,
                                                           allowHtml: true,
                                                           timeOut: 0,
                                                       })
                        }
                        else {
                            toastr.success("Data Saved Successfully",
                           {
                               closeButton: false,
                               progressBar: true,
                               allowHtml: true,
                               timeOut: 0,
                           })
                        }


                        setTimeout(function () {
                            window.location.href = '/BillingMaster/billing_receipt_view'
                        }, 2000);
                    }
                })
            }

        }
        else {
            indicator_id = 'U'
            msg = 'Data Updated Successfully';


            var receipt_data = {
                receipt_date: rec_date,
                receipt_code: $('#rec_code').val(),
                total_amount: $('#pay_tot').val(),
                patient_id: $('#Hpatientid').val(),
                visit_report_id: $('#Hvisitid').val(),
                receipt_type: $('#rec_type').val(),
                billing_code: $('#Hbill_no').val(),
                branch_id: $('#pkg_branch_id').val(),
                Dml_Indicator: indicator_id,
                receipt_id: receipt_id,
                billing_no: billing_no,
                due_amount: due_amount,
                is_claim: ($('#Cclaim').val() == '') ? 0 : $('#Cclaim').val()
            }
            $.ajax({
                async: true,
                type: 'POST',
                url: '/Billing/Billing_Receipt',
                contentType: 'application/json; charset=UTF-8',
                data: JSON.stringify(receipt_data),
                success: function (data) {
                    var data1 = JSON.parse(data);
                    if (data1.msg == "Success") {
                        $('#shade_slot_submit').hide();
                        $('#rec_submit').attr('disabled', false);
                        var data1 = data1.data.Table;
                        console.log(data1);
                        if (jQuery.isEmptyObject((data1))) {
                        }
                        else {
                            var service = new Array();
                            var rec_id = data1[0].receipt_id
                            var tot_rowM = $.trim($('#PaymentTableRowCount').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 = $('#payment_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(',');
                                        service_data.receipt_id = rec_id,
                                        service_data.payment_type = row_data[0],
                                        service_data.Dml_Indicator = 'RI'
                                        service_data.user_created_by = $('#hiddenUser_id').val(),
                                        service_data.total_amount = row_data[2],
                                        service_data.referrence_no = row_data[3],
                                        service_data.tds = row_data[4],
                                        service_data.mou = row_data[5],
                                        service_data.others = row_data[6],
                                        service_data.bank_name = row_data[7],
                                        service_data.is_claim = ($('#Cclaim').val() == '') ? 0 : $('#Cclaim').val(),
                                        service_data.receipt_details_id = (!row_data[8]) ? 0 : row_data[8]
                                        console.log(service.push(service_data));
                                    }

                                }
                            }
                            $.ajax({
                                async: true,
                                type: 'POST',
                                url: '/Billing/Billing_receipt_detail',
                                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 {

                                        }
                                    }
                                    else {
                                        console.log(data1);
                                    }
                                }
                            })
                            toastr.success(msg,
                                 {
                                     closeButton: false,
                                     progressBar: true,
                                     allowHtml: true,
                                     timeOut: 0,
                                 })
                            setTimeout(function () {
                                window.location.href = '/BillingMaster/billing_receipt_view'
                            }, 2000);
                        }
                    }
                    else {
                        console.log(data1);
                    }
                }
            })

        }

    }



    /////////
    //  }

})
//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;
                    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,#rec_ip_branch_srch').append(SubDepartment);
                        $('#pkg_branch_id').change();
                    }
                    else {

                        $('#pkg_branch_id,#rec_ip_branch_srch').append(default_opt + SubDepartment);
                    }

                    //Only KinderSurge
                    //if ($('#hiddenRole_id').val() == 1) {
                    //    $('#pkg_branch_id').val($('#HospitalBranchID').val());
                    //    $('#payment_type').attr('disabled', false);
                    //    $('#txtPaitentSearch_1').attr('disabled', false);
                    //    $('#billno_search').attr('disabled', false);
                    //    LoadReceipt($('#rec_type').val());
                    //    LoadPayment_Type();
                    //}
                    //else
                    if ($('#hiddenRole_id').val() != 2) {
                        $('#pkg_branch_id').val($('#HospitalBranchID').val());
                        $('#rec_ip_branch_srch').val($('#HospitalBranchID').val());
                        $('#pkg_branch_id,#rec_ip_branch_srch').attr('disabled', true);
                        $('#payment_type').attr('disabled', false);
                        $('#txtPaitentSearch_1').attr('disabled', false);
                        $('#billno_search').attr('disabled', false);
                        LoadReceipt($('#rec_type').val());
                        LoadPayment_Type();
                    }
                    // $('#pkg_branch_id').val(val);
                    if ($('#EditReceipt_id').val() != '' && $('#EditReceipt_id').val() != null) {
                        receiptedit($('#EditReceipt_id').val(), $('#EditBilling_no').val(), $('#Hvisit_id').val());
                        $('#payment_type').attr('disabled', false);

                    }


                }
            }
            else {
                console.log(data1);
            }
            if ($('#RBilling_no').val() != '' && $('#RBilling_no').val() != null) {
                receiptDue($('#RBilling_no').val());
                $('#payment_type').attr('disabled', false);
            }

            //added by nandhini on 18/04/2022 for redirection from patient list
            if ($('#FilterPatientID').val() != "" && $('#FilterPatientID').val() != null) {
                debugger;
                $('#pkg_branch_id').val($('#FilterBranchID').val());
                $('#pkg_branch_id').attr('disabled', true);
                $('#payment_type').attr('disabled', false);
                $('#txtPaitentSearch_1').attr('disabled', false);
                $('#billno_search').attr('disabled', false);
                LoadReceipt($('#rec_type').val());
                LoadPayment_Type();
                $('#txtPaitentSearch_1').val($('#FilterPatientID').val());
                $('#txtPaitentSearch_1').prop('disabled', true);
                $('#rec_type').attr('disabled', true);
                $('#Receipt_Div').removeClass('hidden');
                PatientSearch($("#FilterPatientID").val(), 2, $('#FilterBranchID').val());
            }
        }
    });
}
//Due Payment from Billing page
function receiptDue(bill_no) {
    debugger
    var request_data = {
        Dml_Indicator: 'RBD',
        receipt_id: bill_no
    }
    $.ajax({
        async: true,
        type: 'POST',
        url: '/Billing/Billing_Receipt',
        contentType: 'application/json; charset=UTF-8',
        data: JSON.stringify(request_data),
        success: function (data) {
            debugger;
            var data1 = JSON.parse(data);
            if (data1.msg == "Success") {
                var data1 = data1.data.Table[0];
                console.log(data1);
                if (jQuery.isEmptyObject((data1))) {
                }
                else {

                    PatientSearch(data1.patient_id, data1.visit_type, data1.branch_id, data1.visit_report_id);
                    $('#Receipt_Div').removeClass('hidden');
                    $('#Hdueamount').val(data1.due_amount);
                    $('#Hbill_no').val(data1.billno);
                    $('.div_pay').hide();
                    $('#div_txtPaitentSearch_1').hide();
                    $('.bill_detail').show();
                    $('#bill_no').html(data1.billing_code);
                    var Total_Claim_Amount = (!data1.authorized_amount) ? 0 : data1.authorized_amount;
                    var Collected_Claim_Amount = (!data1.approved_amount) ? 0 : data1.approved_amount;
                    (parseFloat(Total_Claim_Amount) > 0) ? $('#divpayCheck').show() : $('#divpayCheck').hide()
                    $('#Hclaimdue').val(parseFloat(Total_Claim_Amount) - parseFloat(Collected_Claim_Amount));
                    $('#Hselfdue').val(data1.due_amount);
                    $('#due_amount').html('&#8377;' + data1.due_amount);
                    $('#due_amount').val(data1.due_amount);
                    $('#rec_type').val(2);
                    Loadtype(2)
                    $('#rec_type').attr('disabled', true);

                    //$('#div_billno').hide();

                    $('#pkg_branch_id').val(data1.branch_id);
                    $('#pkg_branch_id').attr('disabled', true);
                    LoadReceipt(2);
                    LoadPayment_Type();
                }
            }
        }
    })
}
//Branch change function
$('#pkg_branch_id').change(function () {
    if ($('#pkg_branch_id').val() == '' || $('#pkg_branch_id').val() == 0) {
        $('#payment_type').attr('disabled', true);
        $('#txtPaitentSearch_1').attr('disabled', true);
        $('#billno_search').attr('disabled', true);
        $('#txtPaitentSearch_1').val('');
        $('#billno_search').val('');
        $('.pat-strip').hide();
        $('#Hpatientid').val('')
    }
    else {
        $('#txtPaitentSearch_1').val('');
        $('#billno_search').val('');
        $('.pat-strip').hide();
        $('#payment_type').attr('disabled', false);
        $('#txtPaitentSearch_1').attr('disabled', false);
        $('#billno_search').attr('disabled', false);
        $('#Hpatientid').val('');
        $('#rec_amount').val('');
        $('#rec_tds').val('');
        $('#rec_mou').val('');
        $('#rec_others').val('');
        $('.bill_detail').hide();
        $('#rec_trans').val('');
        $('#div_rec_trans').hide();
        $('#utr_search').removeAttr('disabled');
        LoadReceipt($('#rec_type').val());
        LoadPayment_Type();
    }
})
//Receipt Edit
function receiptedit() {

    // $('#EditBilling_no').val(billing_no)
    //LoadBranch();
    var request_data = {
        Dml_Indicator: 'RE',
        receipt_id: $('#EditReceipt_id').val() //$('#HBilling_no').val()
    }
    $.ajax({
        async: true,
        type: 'POST',
        url: '/Billing/Billing_Receipt',
        contentType: 'application/json; charset=UTF-8',
        data: JSON.stringify(request_data),
        success: function (data) {
            debugger;
            var data1 = JSON.parse(data);
            if (data1.msg == "Success") {
                var data1 = data1.data.Table[0];
                console.log(data1);
                if (jQuery.isEmptyObject((data1))) {
                }
                else {
                    payment_detail($('#EditReceipt_id').val())
                    $('#div_txtPaitentSearch_1').hide();
                    $('.bill_detail').show();

                    $('#bill_no').html(data1.billing_code);
                    var patient_id = data1.search_option.split('-')[1];
                    PatientSearch(patient_id, data1.visit_type, data1.branch_id, $('#Hvisit_id').val());
                    $('#Receipt_Div').removeClass('hidden');

                    if (data1.is_claim == 1) {
                        var dueClaim = parseFloat(data1.Total_Claim_Amount) - parseFloat(data1.Collected_Claim_amount);
                        $('#due_amount').html('&#8377;' + dueClaim);
                        $('#due_amount').val(dueClaim)
                        $('#divpayCheck').show();
                        $('#Cclaim').prop('checked', true).attr('disabled', true);
                        $('#Cclaim').val(1);

                    }
                    else {
                        if (parseFloat(data1.Total_Claim_Amount) > 0) {
                            $('#divpayCheck').show();
                            $('#Cclaim').prop('checked', false).attr('disabled', true);
                            $('#Cclaim').val(0);
                        }
                        $('#Hdueamount').val(data1.due_amount);
                        $('#due_amount').html('&#8377;' + data1.due_amount);
                        $('#due_amount').val(data1.due_amount)
                    }
                    $('#Hbill_no').val(data1.billno);


                    $('#rec_type').val(data1.type_id);
                    Loadtype(data1.type_id);
                    $('#rec_type').attr('disabled', true);
                    $('#rec_code').val(data1.receipt_code);
                    $('#rec_date').val(data1.receipt_date);
                    //$('#div_billno').hide();

                    $('#pkg_branch_id').val(data1.branch_id);
                    $('#pkg_branch_id').attr('disabled', true);
                    $('#divpay_add').hide();
                    $('#rec_submit').html('Update');

                    if ($('#due_amount').val() == 0) {
                        debugger;
                        $('#rec_amount').attr('disabled', true);
                        $('#rec_tds').attr('disabled', true);
                        $('#rec_mou').attr('disabled', true);
                        $('#rec_others').attr('disabled', true);
                    }
                    else {
                        $('#rec_amount').attr('disabled', false);
                        $('#rec_tds').attr('disabled', false);
                        $('#rec_mou').attr('disabled', false);
                        $('#rec_others').attr('disabled', false);
                    }


                    LoadPayment_Type();
                }
            }
        }
    })
}
function payment_detail(receipt_id) {
    debugger;
    var request_data = {
        Dml_Indicator: 'PD',
        receipt_id: receipt_id
    }
    $.ajax({
        async: true,
        type: 'POST',
        url: '/Billing/Billing_Receipt',
        contentType: 'application/json; charset=UTF-8',
        data: JSON.stringify(request_data),
        success: function (data) {
            debugger;
            var data1 = JSON.parse(data);
            if (data1.msg == "Success") {
                var data1 = data1.data.Table;
                console.log(data1);
                if (jQuery.isEmptyObject((data1))) {
                }
                else {
                    // $('#payment_table').empty();
                    var thead = '<tr><th>S.no</th><th>Type</th><th>Bank Name</th><th>Transaction ID</th><th>TDS(Tax)</th><th>MOU</th><th>Others</th><th>Amount</th><th>Actions</th></tr></thead>';
                    $('#payment_table thead').append(thead);
                    var tot_row = 0;
                    $.each(data1, function (i, emp) {
                        debugger;
                        receipt_detail_id = emp.receipt_details_id;
                        payment_type = emp.payment_mode;
                        payment_name = emp.master_service_name;
                        amount = emp.amount;
                        ref_no = emp.reference_no;
                        tds = emp.TDS;
                        mou = emp.MOU_Discount;
                        others = emp.others;
                        bank_name = emp.bank_name;
                        b_name = emp.b_name
                        var sess_key;
                        rowcount = $.trim($('#PaymentTableRowCount').val());
                        tot_row = (Number(rowcount) + 1);
                        if (tds == '') {
                            tds = 0;
                        }
                        if (mou == '') {
                            mou = 0;
                        }
                        if (others == '') {
                            others = 0;
                        }
                        var sess_data_ser = payment_type + "," + payment_name + "," + amount + "," + ref_no + "," + tds + "," + mou + "," + others + "," + bank_name + "," + receipt_detail_id;
                        var key = '';
                        if (rowcount >= 1) {
                            var getEid = $('#payment_table tbody  tr').last();
                            var actId = getEid.prop('id');
                            var afterSplit = actId.split('row_');
                            afterInc = parseInt(afterSplit[1]) + 1;
                            console.log(afterInc);
                            ikey_pay = 'row_' + afterInc;
                        }
                        else {

                            ikey_pay = 'row_' + tot_row;
                        }
                        sessionStorage.setItem(ikey_pay, sess_data_ser);
                        //var key = '';
                        var action = "<button class='btn btn-xs btn-edit mr-10' onclick='rec_edit(\"" + emp.payment_mode + "\",\"" + emp.master_receipt_id + "\",\"" + tot_row + "\")'><i class='fa fa-pencil' aria-hidden='true'></i></button>"
                        var tbody = '<tr id="row_' + tot_row + '" data-id=' + receipt_detail_id + '><td>' + tot_row + '</td><td id=paymentMode_' + tot_row + ' data-id=' + emp.payment_mode + '>' + payment_name + '</td><td id=BName_' + tot_row + ' data-id=' + emp.bank_name + '>' + b_name + '</td><td id=RefNo_' + tot_row + '>' + ref_no + '</td><td id=TDS_' + tot_row + '>' + tds + '</td><td id=MOU_' + tot_row + '>' + mou + '</td><td id=Others_' + tot_row + '>' + others + '</td><td id=Amount_' + tot_row + '>' + amount + '</td><td>' + action + '</td></tr>';
                        $('#payment_table tbody').append(tbody);
                        $('#PaymentTableRowCount').val(tot_row);
                    })
                    var previousval = 0.0;
                    $('#payment_table > tbody  > tr').each(function () {
                        debugger;
                        $(this).find("td:gt(3):lt(4)").each(function () {
                            debugger;
                            var temp = $(this).html();
                            previousval = parseFloat(previousval) + parseFloat(temp);
                        });

                    });


                    var tfoot = '<tr><td colspan="8" style="text-align:right;">Total Amount</td>'
                    $('#pay_tot').val(previousval);
                    var due_amount = $('#Hdueamount').val();
                    var td = '<td>' + (previousval) + '</td></tr>';
                    $('#payment_table tfoot').append(tfoot + td);

                    $('#rec_amount').val('');
                    $('#rec_trans').val('');
                    $('#rec_tds').val('');
                    $('#rec_mou').val('');
                    $('#rec_others').val('');
                    $('#payment_type').val('');
                    $('#rec_bank').val('');
                }
            }
        }
    })
}
//Payment via SMS code started
$('#pay_via_sms').click(function () {
    $('#div_paymentType').hide();

    $('#divpay_add').hide();
    $('.div_sms').show();
    $('#btnsmspayment').show();
    $('#rec_submit').hide();
    $('#pay_via_sms').hide();
    $('#pay_via_modes').show();
})
$('#pay_via_modes').click(function () {
    $('#div_paymentType').show();

    $('#divpay_add').show();
    $('.div_sms').hide();
    $('#btnsmspayment').hide();
    $('#rec_submit').show();
    $('#pay_via_sms').show();
    $('#pay_via_modes').hide();
})
//send link button
$('#btnsmspayment').click(function () {
    if ($.trim($('#rec_amount').val()) == '') {
        $('#Prec_amount').show();
        $('#Prec_amount').fadeOut(4000);
        $('#Prec_amount').html('Enter the amount');
        $('#rec_amount').focus();
        $('#rec_amount').val('');
        return false;
    }
    if ($('#txtmobile_no').val() == '') {
        $('#Ptxtmobile_no').show();
        $('#Ptxtmobile_no').fadeOut(8000);
        $('#Ptxtmobile_no').html('Please enter mobile number');
        $('#txtmobile_no').focus();
        return false;
    }
    if ($('#txtemail').val() == '') {
        $('#Ptxtemail').show();
        $('#Ptxtemail').fadeOut(8000);
        $('#Ptxtemail').html('Please enter mobile number');
        $('#txtemail').focus();
        return false;
    }
    else {
        var date = $('#rec_date').val().split('/');
        var rec_date = date[2] + '-' + date[1] + ',' + date[0];
        var receipt_data = {
            receipt_date: rec_date,
            receipt_code: $('#rec_code').val(),
            total_amount: $('#rec_amount').val(),
            patient_id: $('#Hpatientid').val(),
            visit_report_id: $('#Hvisitid').val(),
            receipt_type: $('#rec_type').val(),

            branch_id: $('#pkg_branch_id').val(),
            Dml_Indicator: 'RS',


        }
        $.ajax({
            async: true,
            type: 'POST',
            url: '/Billing/Billing_Receipt',
            contentType: 'application/json; charset=UTF-8',
            data: JSON.stringify(receipt_data),
            success: function (data) {
                var data1 = JSON.parse(data);
                if (data1.msg == "Success") {
                    var data1 = data1.data.Table;
                    console.log(data1);
                    if (jQuery.isEmptyObject((data1))) {
                    }
                    else {
                        var rec_id = data1[0].receipt_id
                        sms_payment(rec_id);
                    }
                }
            }
        })
    }
})

function sms_payment(rec_id) {
    debugger;
    console.log(rec_id);
    var invoice_no_temp = "";
    var Amount_temp = "";
    invoice_no_temp = invoice_no_temp + ',' + rec_id;
    Amount_temp = Amount_temp + ',' + $('#rec_amount').val();
    var smspayment = {
        email_id: $('#txtemail').val(),
        phone_number: $('#txtmobile_no').val(),
        created_by: $('#hiddenUser_id').val(),
        valid_for: '2',
        valid_type: 'days',
        valid_date: '',
        currency: 'INR',
        amount: $('#rec_amount').val(),
        due_date: '',
        invoice_no: '2',
        Dml_Indicator: 'I',
        patient_id: $('#Hpatientid').val(),
        customer_name: $('#PatName').val(),
        invoice_no_temp: invoice_no_temp,
        Amount_temp: Amount_temp,
        //doctor_id: $('#pop_doctor_id').val()
    }
    $.ajax({
        async: true,
        type: 'POST',
        url: '/caseStudy/sms_invoice_payment',
        contentType: 'application/json; charset=UTF-8',
        data: JSON.stringify(smspayment),
        success: function (data) {
            if (jQuery.isEmptyObject((data))) {

            }
            else {
                debugger;
                var data = JSON.parse(data);
                var data = data.data;
                if (data.length > 0) {
                    var sms_invoice_no = data[0].sms_invoice_no;
                    var email_id = data[0].email_id;
                    var phone_number = data[0].phone_number;
                    var amount = data[0].amount;
                    var invoice_no = "";
                    var Amount = "";
                    var invoice_no_temp = "";
                    var Amount_temp = "";
                    var smspayment = {
                        email_id: $('#txtemail').val(),
                        phone_number: $('#txtmobile_no').val(),
                        created_by: $('#hiddenUser_id').val(),
                        valid_for: '2',
                        valid_type: 'days',
                        valid_date: '',
                        currency: 'INR',
                        amount: $('#rec_amount').val(),
                        due_date: '',
                        sms_invoice_no: sms_invoice_no,
                        Dml_Indicator: 'sms',
                        patient_id: $('#Hpatientid').val(),
                        customer_name: $('#PatName').val()

                    }
                    $.ajax({
                        async: true,
                        type: 'POST',
                        url: '/caseStudy/sms_invoice_payment',
                        contentType: 'application/json; charset=UTF-8',
                        data: JSON.stringify(smspayment),
                        success: function (data) {
                            if (jQuery.isEmptyObject((data))) {

                            }
                            else {
                                toastr.success('Payment link sent');
                                window.location.href = '/BillingMaster/billing_receipt_view';

                            }
                        }
                    });
                }
            }
        }
    })

}
function Loadtype(val) {
    debugger;
    $('#rec_type').empty();
    var type = {
        Dml_Indicator: "RFT"
    }
    $.ajax({
        async: true,
        type: 'POST',
        url: '/Billing/Billing_Receipt',
        contentType: 'application/json; charset=UTF-8',
        data: JSON.stringify(type),
        success: function (data) {
            debugger;
            var data1 = JSON.parse(data);
            if (jQuery.isEmptyObject((data1.data))) {
            }
            else {
                if (data1.msg == "Success") {
                    var data2 = data1.data;
                    $('#rec_type').empty();
                    var rec_type;
                    var default_opt = '<option value="0">--Select--</option>';
                    if (!$('#EditReceipt_id').val()) {
                        data2.Table = data2.Table.filter((item) =>item.type_id != 4);
                    }
                    $.each(data2.Table, function (i, emp) {
                        rec_type = rec_type + '<option value="' + emp.type_id + '">' + emp.type_name + '</option>';
                    });
                    if (data2.Table.length == 1) {
                        $('#rec_type').append(rec_type);
                        if (data2.Table[0].type_id == 2 && ($('#RBilling_no').val() == '' || $('#RBilling_no').val() == null)) {
                            $('#rec_type').change()
                        }
                    }
                    else {
                        $('#rec_type').append(rec_type);
                    }
                    if (val != '' && val != 0 && val != null) {
                        $('#rec_type').val(val)
                    }
                    $('#Htypestsid').val(data2.Table[0].status)
                }
                else {
                    console.log(data);
                }
            }
        }
    });
}
//Amount change function
$('#rec_amount').change(function () {
    var type = $('#rec_type').val();
    if (type == 1 && $('.div_sms').is(':visible') == true) {
        if (parseFloat($('#rec_amount').val()) > 1000000) {
            $('#Prec_amount').show();
            $('#Prec_amount').fadeOut(4000);
            $('#Prec_amount').html('Amount should be less than 10 lakhs');
            $('#rec_amount').focus();
            $('#rec_amount').val('');
            return false;
        }
    }
})

//payment mode edit concept--starts
function rec_edit(pay_mode, id, rowcount) {
    debugger;
    if ($('#rec_type').val() == 3 && !$('#EditReceipt_id').val()) {
        var emp = sessionStorage.getItem('row_' + rowcount);
        emp = emp.split(',');

        $('#Hmaster_receiptid').val(emp[17]);
        $('#Hvisitid').val(emp[16]);
        var pay_amount = parseFloat($('#Amount_' + rowcount).html()) + parseFloat($('#TDS_' + rowcount).html()) + parseFloat($('#MOU_' + rowcount).html()) + parseFloat($('#Others_' + rowcount).html());

        $('#Hclaimdue').val(parseFloat(emp[14]));
        var dataid1 = $('#row_' + rowcount).attr('data-id1');
        if (dataid1 == 0) {
            $('#Hclaimpen').val(parseFloat(emp[15]) + parseFloat(pay_amount));
        }
        else {
            $('#Hclaimpen').val(parseFloat(emp[15]))
        }
        $('#hdn_PatientName').val(emp[12])
        $('#Hbill_no').val(emp[10]);
        $('#HBilling_no').val(emp[9]);
        $('#Hpatientid').val(emp[11]);
        $('#hdnPatient_Id').val(emp[13])
        $('#billno_searchutr').val(emp[10]);
        $('#billno_searchutr').attr('disabled', true);
        $('#payment_type').attr('disabled', false);
    }
    $('#payment_type').val('');
    $('#payment_type').val($('#paymentMode_' + rowcount).attr('data-id'));
    $('#payment_type').change();
    $('#rec_bank').val($('#BName_' + rowcount).attr('data-id'));
    $('#rec_trans').val($('#RefNo_' + rowcount).html());
    $('#rec_amount').val($('#Amount_' + rowcount).html());
    $('#rec_tds').val($('#TDS_' + rowcount).html());
    $('#rec_mou').val($('#MOU_' + rowcount).html());
    $('#rec_others').val($('#Others_' + rowcount).html());
    $('#Hreceipt_id').val('');
    $('#Hreceipt_id').val(id);
    $('#Hrowdata').val('');
    $('#Hrowdata').val(rowcount);
    $('#btnpay_add').hide()
    $('#btnpay_update').show();
    if (($('#EditReceipt_id').val() != '' && $('#EditReceipt_id').val() != null) || ($('#rec_type').val() == 3 && parseFloat(dataid1) != 0)) {
        $('#rec_amount').attr('disabled', true);
        $('#rec_tds').attr('disabled', true);
        $('#rec_mou').attr('disabled', true);
        $('#rec_others').attr('disabled', true);
    }
    else {
        $('#rec_amount').attr('disabled', false);
        $('#rec_tds').attr('disabled', false);
        $('#rec_mou').attr('disabled', false);
        $('#rec_others').attr('disabled', false);
    }

}
//Payment mode update
$('#btnpay_update').click(function () {
    debugger;
    var payment_type = $('#payment_type').val();
    var payment_name = $('#payment_type option:selected').text();
    var amount = $('#rec_amount').val();
    var ref_no = $('#rec_trans').val();
    var bank_name = $('#rec_bank').val();
    var b_name = $('#rec_bank option:selected').text();
    var tds = $('#rec_tds').val();
    var mou = $('#rec_mou').val();
    var others = $('#rec_others').val();
    var billno = $('#HBilling_no').val();
    var PatientId = $('#Hpatientid').val();
    var Patient_Id = $('#hdnPatient_Id').val();
    var billCode = $('#Hbill_no').val();
    var PatientName = $('#hdn_PatientName').val();
    var ClaimDue = $('#Hclaimdue').val();
    var ClaimDuePending = $('#Hclaimpen').val();
    var VisitReport_Id = $('#Hvisitid').val();
    var master_receipt_id = $('#Hmaster_receiptid').val();

    var sess_key;

    var tot_row = $('#Hrowdata').val();
    var receipt_details_id = $('#row_' + tot_row).attr('data-id');
    if (tds == '') {
        tds = 0;
    }
    if (mou == '') {
        mou = 0;
    }
    if (others == '') {
        others = 0;
    }
    var pay_amount = parseFloat(amount) + parseFloat(tds) + parseFloat(mou) + parseFloat(others);
    //sessionStorage.removeItem('row_' + tot_row);

    //var sess_data_ser = payment_type + "," + payment_name + "," + amount + "," + ref_no + "," + tds + "," + mou + "," + others + "," + bank_name + "," + receipt_details_id;
    //sessionStorage.setItem('row_' + tot_row, sess_data_ser);
    $('#paymentMode_' + tot_row).html(payment_name);
    $('#paymentMode_' + tot_row).attr('data-id', payment_type);
    $('#BName_' + tot_row).html(b_name);
    $('#BName_' + tot_row).attr('data-id', bank_name);
    $('#RefNo_' + tot_row).html(ref_no);
    if ($('#rec_type').val() == 3 && !$('#EditReceipt_id').val()) {
        var previousval = 0.0;
        var dataid1 = $('#row_' + tot_row).attr('data-id1');
        var billdue = [], due_check = 0;
        if (parseInt(dataid1) == 0) {
            ClaimDuePending = parseFloat(ClaimDuePending) - parseFloat(pay_amount);
            $('#payment_table > tbody  > tr').each(function () {
                var payid = $(this).prop("id");
                var chkid = "row_" + tot_row
                if (payid != chkid) {

                    var columnsToSum = $(this).find("td").slice(6, 10);

                    columnsToSum.each(function () {
                        var temp = $(this).html();
                        previousval += parseFloat(temp) || 0;
                    });
                    var id = $(this).closest("tr").prop("id")
                    var dataid = parseInt($(this).closest("tr").attr('data-id2'));
                    if (parseInt($('#billCode_' + dataid).attr('data-id')) == billno) {
                        billdue.push($(this).closest("tr").prop("id"))
                    }
                }

            });
            if (billdue.length > 0) {
                for (var i = 0; i < billdue.length; i++) {
                    var rowData = sessionStorage.getItem(billdue[i]);
                    rowData = rowData.split(",");
                    rowData[15] = ClaimDuePending;
                    sessionStorage.removeItem(billdue[i]);
                    rowData = rowData.toString();
                    sessionStorage.setItem(billdue[i], rowData);
                }
            }
            due_check = (parseFloat($('#Hdueamount').val()) - (parseFloat(previousval) + parseFloat(pay_amount)));
        }

        if ((parseInt(due_check) >= 0 && parseFloat(ClaimDuePending) >= 0 && parseInt(dataid1) == 0) || parseInt(dataid1) != 0) {
            sessionStorage.removeItem('row_' + tot_row);
            var sess_data_ser = payment_type + "," + payment_name + "," + amount + "," + ref_no + "," + tds + "," + mou + "," + others + "," + bank_name + "," + 0 + "," + billno + "," + billCode + "," + PatientId + "," + PatientName + "," + Patient_Id + "," + ClaimDue + "," + ClaimDuePending + "," + VisitReport_Id + "," + master_receipt_id;


            sessionStorage.setItem('row_' + tot_row, sess_data_ser);


            $('#payment_table tfoot').empty();
            if (parseInt(dataid1) == 0) {
                $('#Amount_' + tot_row).html(amount);
                $('#TDS_' + tot_row).html(tds);
                $('#MOU_' + tot_row).html(mou);
                $('#Others_' + tot_row).html(others);
                $('#due_amount').html('&#8377;' + ((parseFloat($('#Hdueamount').val()) - (parseFloat(previousval + parseFloat(pay_amount))))).toFixed(2));
                $('#due_amount').val((parseFloat($('#Hdueamount').val()) - (parseFloat(previousval) + parseFloat(pay_amount))).toFixed(2));
            }
            //$('#PaymentTableRowCount').val(tot_row);
            var tfoot = '<tr><td colspan="10" style="text-align:right;">Total Amount</td>'
            $('#pay_tot').val(previousval);

            var td = '<td id="foot_total">' + parseFloat(previousval) + '</td></tr>';
            $('#payment_table tfoot').append(tfoot + td);
            $('#rec_type').attr('disabled', true);
            $('#pkg_branch_id').attr('disabled', true);
            $('#utr_search').attr('disabled', true);
        }
        else {

            toastr.warning('Payment exceeds the Bill  due amount');
            return false;
        }
    }
    if (($('#EditReceipt_id').val() == '' || $('#EditReceipt_id').val() == null) && $('#rec_type').val() != 3) {
        var previousval = 0.0;
        $('#payment_table > tbody  > tr').each(function () {
            var payid = $(this).prop("id");
            var chkid = "row_" + tot_row
            if (payid != chkid) {


                $(this).find("td:gt(3):lt(4)").each(function () {
                    var temp = $(this).html();
                    previousval = parseFloat(previousval) + parseFloat(temp);
                });
            }

        });
        const due_check = (parseFloat($('#Hdueamount').val()) - (parseFloat(previousval) + parseFloat(pay_amount)));
        if (parseInt(due_check) >= 0) {
            sessionStorage.removeItem('row_' + tot_row);
            var sess_data_ser = payment_type + "," + payment_name + "," + amount + "," + ref_no + "," + tds + "," + mou + "," + others + "," + bank_name + "," + receipt_details_id + "," + billno + "," + billCode + "," + PatientId + "," + PatientName + "," + Patient_Id + "," + ClaimDue + "," + ClaimDuePending + "," + VisitReport_Id + "," + master_receipt_id;


            sessionStorage.setItem('row_' + tot_row, sess_data_ser);
            $('#Amount_' + tot_row).html(amount);
            $('#TDS_' + tot_row).html(tds);
            $('#MOU_' + tot_row).html(mou);
            $('#Others_' + tot_row).html(others);
            $('#payment_table tfoot').empty();
            $('#due_amount').html('&#8377;' + ((parseFloat($('#Hdueamount').val()) - (parseFloat(previousval + parseFloat(pay_amount))))).toFixed(2));
            $('#due_amount').val((parseFloat($('#Hdueamount').val()) - (parseFloat(previousval) + parseFloat(pay_amount))).toFixed(2));
            // $('#PaymentTableRowCount').val(tot_row);
            var tfoot = '<tr><td colspan="8" style="text-align:right;">Total Amount</td>'
            $('#pay_tot').val(parseFloat(previousval) + parseFloat(pay_amount));
            var due_amount = $('#Hdueamount').val();
            var td = '<td id="foot_total">' + (parseFloat(previousval) + parseFloat(pay_amount)) + '</td></tr>';
            $('#payment_table tfoot').append(tfoot + td);
            $('#rec_type').attr('disabled', true);
            $('#pkg_branch_id').attr('disabled', true);
            $('#txtPaitentSearch_1').attr('disabled', true);
            $('#billno_search').attr('disabled', true);
            $('#Cclaim').attr('disabled', true);

        }
        else {

            toastr.warning('Payment exceeds the due amount');
            return false;
        }
    }
    else if ($('#EditReceipt_id').val()) {
        sessionStorage.removeItem('row_' + tot_row);
        var sess_data_ser = payment_type + "," + payment_name + "," + amount + "," + ref_no + "," + tds + "," + mou + "," + others + "," + bank_name + "," + receipt_details_id + "," + billno + "," + billCode + "," + PatientId + "," + PatientName + "," + Patient_Id + "," + ClaimDue + "," + ClaimDuePending + "," + VisitReport_Id + "," + master_receipt_id;


        sessionStorage.setItem('row_' + tot_row, sess_data_ser);
    }
    $('#rec_amount').val('');
    $('#rec_trans').val('');
    $('#rec_tds').val('');
    $('#rec_mou').val('');
    $('#rec_others').val('');
    $('#payment_type').val('');
    $('#rec_bank').val('');
    $('#div_rec_bank').hide();
    if ($('#EditReceipt_id').val() == '' || $('#EditReceipt_id').val() == null) {
        $('#btnpay_add').show();
    }
    $('#btnpay_update').hide();
    $('#rec_amount').attr('disabled', false);
    $('#rec_tds').attr('disabled', false);
    $('#rec_mou').attr('disabled', false);
    $('#rec_others').attr('disabled', false);
    $('#billno_searchutr').attr('disabled', false);
    $('#billno_searchutr').val('');
    $('#Hclaimpen').val(0);

})
//Payment mode edit concept-ends
//for Claim due pay check box change function
$('#Cclaim').change(function () {
    debugger;
    this.value = this.checked ? 1 : 0;
    if (this.value == '1') {
        $('#due_amount').html('&#8377;' + $('#Hclaimdue').val());
        $('#due_amount').val($('#Hclaimdue').val());
    }
    else {
        $('#due_amount').html('&#8377;' + $('#Hselfdue').val());
        $('#due_amount').val($('#Hselfdue').val());
    }
})
//IP Search Concept Starts
//IP List Search
$('#rec_ip_search').click(function () {
    debugger;
    $('#pay_table1').show();
    $('#view_advance').hide();
    $('#tbl_search_advance tbody').empty();
    var fromDate = '', toDate = ''
    if ($('#rec_ip_fromDate').val()) {
        var fromDate1 = $('#rec_ip_fromDate').val().split("/");
        fromDate = fromDate1[2] + '-' + fromDate1[1] + '-' + fromDate1[0]
    }
    if ($('#rec_ip_toDate').val()) {
        var toDate1 = $('#rec_ip_toDate').val().split("/");
        toDate = toDate1[2] + '-' + toDate1[1] + '-' + toDate1[0]
    }
    var type = {
        Dml_Indicator: "RSP",
        patient_id: $('#rec_ip_pat_srch').val(),
        visit_report_id: $('#rec_ip_num_srch').val(),
        condition: fromDate,
        type_name: toDate,
        branch_id: $('#rec_ip_branch_srch').val() == '' ? 0 : $('#rec_ip_branch_srch').val()
    }
    $.ajax({
        async: true,
        type: 'POST',
        url: '/Billing/Billing_Receipt',
        contentType: 'application/json; charset=UTF-8',
        data: JSON.stringify(type),
        success: function (data) {
            debugger;
            $('#tbl_search_IP tbody').empty();
            var data1 = JSON.parse(data);
            if (jQuery.isEmptyObject((data1.data))) {
            }
            else {
                if (data1.msg == "Success") {
                    var data2 = data1.data.Table;
                    var tr = ''
                    $.each(data2, function (i, emp) {
                        var type = ''
                        if (emp.is_advance == 1) {
                            type = '<span class="label label-used">Pay Advance</span>'
                        }
                        else {
                            type = '<span class="label label-info">Pay Due</span>'
                        }
                        tr = tr + '<tr onclick=\'FetchList(' + JSON.stringify(emp) + ')\'><td>' + (i + 1) + '</td><td>' + emp.branch_name + '</td><td>' + emp.visit_report_id + '</td><td>' + emp.patient_id + '</td><td>' + emp.first_name + '</td><td>' + emp.ip_admission_date + '</td><td>' + type + '</td></tr>'
                    });
                    $('#tbl_search_IP tbody').append(tr);
                }
                else {
                    console.log(data);
                }
            }
        }
    });
})
// Row Click to fetch Receipt Data
function FetchList(data) {
    debugger;

    $('#pkg_branch_id').val(data.branch_id);
    $('#pkg_branch_id').change();
    $('#rec_type').val(data.is_advance);
    $('#rec_type').change();
    $('#payment_table thead,#payment_table tbody,#payment_table tfoot').empty();
    $('#PaymentTableRowCount').val(0);
    if (data.is_advance == 1) {
        $('#txtPaitentSearch_1').val(data.SearchOption);
        $('#div_notes_receipt').show();
        bill_check(data.patient_id, data.branch_id);
    }
    else {
        $('#billno_search').val(data.SearchOption);
        $('.bill_detail').show();
        $('#divpay_add').show();
        $('#rec_submit').show();
        $('#div_paymentType').show();
        $('#div_notes_receipt').show();
        $('#due_amount').html('&#8377;' + data.due_amount);
        $('#due_amount').val(data.due_amount);
        $('#bill_no').html(data.billno);
        $('#Hvisit_type').val(2);
        $('#Hvisitid').val(data.visit_report_id);

        var card = PatientSearch(data.patient_id, 2, $('#pkg_branch_id').val(), data.visit_report_id);
        $.when(card)
               .then(function (data) {

                   var data = JSON.parse(data);
                   if (data.msg == "Success") {
                       var data1 = data.data;
                       if (data1.length > 0) {
                           $('#Receipt_Div').removeClass('hidden');
                       }
                       else {
                           $('#Receipt_Div').addClass('hidden');
                       }
                   }

               });
        $('#Hdueamount').val(data.due_amount);
        $('#Hbill_no').val(data.billno);
        $('#HBilling_no').val(data.billing_no);
        $('#Hclaimdue').val(parseFloat(data.Total_Claim_Amount) - parseFloat(data.Collected_Claim_Amount));
        $('#Hselfdue').val(data.due_amount);
        if (data.Total_Claim_Amount > 0) {
            $('#divpayCheck').show();
        }
        else {
            $('#divpayCheck').hide();
        }
    }
    $('#RecPopSearch').modal("toggle");
}
$('#RecPopSearch').on('shown.bs.modal', function (e) {
    if ($('#hiddenRole_id').val() == 2) {
        $('#rec_ip_branch_srch').val('0')
    }
    $('#rec_ip_num_srch').val('')
    $('#rec_ip_pat_srch').val('')
    $('#rec_ip_fromDate').val('')
    $('#rec_ip_toDate').val('')   
})

function bill_check(patient_id, branch_id) {
    debugger;
    var receipt_data = {
        patient_id: patient_id,
        branch_id: branch_id,
        Dml_Indicator: 'BC'
    }
    $.ajax({
        async: true,
        type: 'POST',
        url: '/Billing/Billing_receipt',
        contentType: 'application/json; charset=UTF-8',
        data: JSON.stringify(receipt_data),
        success: function (data) {

            var data1 = JSON.parse(data);
            if (data1.msg == "Success") {
                var data1 = data1.data.Table;
                console.log(data1);
                if (jQuery.isEmptyObject((data1))) {
                }
                else {
                    if (data1[0].Strmsg == 'paid') {
                        toastr.warning("Paid Invoice");
                        $('#txtPaitentSearch_1').val('')
                        return false;
                    }
                    var card = PatientSearch(patient_id, 2, $('#pkg_branch_id').val());

                    $.when(card)
                           .then(function (data) {

                               var data = JSON.parse(data);
                               if (data.msg == "Success") {
                                   var data1 = data.data;
                                   if (data1.length > 0) {
                                       $('#Receipt_Div').removeClass('hidden');
                                   }
                                   else {
                                       $('#Receipt_Div').addClass('hidden');
                                   }
                               }

                           });
                }
            }
        }
    })
}
//Search Advance
$('#rec_ip_search_advance').click(function () {
    $('#pay_table1').hide();
    $('#view_advance').show();
    $('#tbl_search_IP tbody').empty();
    var fromDate = '', toDate = ''
    if ($('#rec_ip_fromDate').val()) {
        var fromDate1 = $('#rec_ip_fromDate').val().split("/");
        fromDate = fromDate1[2] + '-' + fromDate1[1] + '-' + fromDate1[0]
    }
    if ($('#rec_ip_toDate').val()) {
        var toDate1 = $('#rec_ip_toDate').val().split("/");
        toDate = toDate1[2] + '-' + toDate1[1] + '-' + toDate1[0]
    }
    request_data = {
        receipt_date: fromDate,
        type_name: toDate,
        branch_id: $('#rec_ip_branch_srch').val() == '' ? 0 : $('#rec_ip_branch_srch').val(),
        patient_id: $('#rec_ip_pat_srch').val(),
        visit_report_id: $('#rec_ip_num_srch').val(),
        receipt_type: 2,//((visit_type=='' || visit_type==null)) ? 0 : visit_type,
        visit_report_id: $('#rec_ip_num_srch').val(),
        Dml_Indicator: 'TV'

    }
    $.ajax({
        async: true,
        type: 'POST',
        url: '/Billing/Billing_Receipt',
        contentType: 'application/json; charset=UTF-8',
        data: JSON.stringify(request_data),
        success: function (data) {
            $('#tbl_search_advance tbody').empty();
            var data1 = JSON.parse(data);
            $('#shade_slot').hide();
            if (data1.msg == "Success") {
                var data1 = data1.data.Table;
                console.log(data1);
                if (jQuery.isEmptyObject((data1))) {
                }
                else {


                    var tr = ''
                    data1 = data1.filter((item) =>item.receipt_type == 1)
                    $.each(data1, function (i, emp) {
                        var type = '', others = 0;

                        if (emp.others == "") {
                            others = 0;
                        }
                        else {
                            others = emp.others;
                        }
                        type = '<span class="label label-used">IP</span>'
                        tr = tr + '<tr><td>' + (i + 1) + '</td><td>' + emp.receipt_code + '</td><td>' + emp.receipt_date + '</td><td>' + emp.patient_name + '</td><td>' + emp.patient_id + '</td><td>' + emp.visit_report_id + '</td><td>' + type + '</td><td>' + (parseFloat(emp.amount) + parseFloat(emp.TDS) + parseFloat(emp.MOU_Discount) + parseFloat(others)) + '</td><td>' + emp.payment_mode + '</td><td class="col-sm-2">' + emp.branch_name + '</td></tr>'
                    });
                    $('#tbl_search_advance tbody').append(tr);

                }
            }
        }
    })
})
//Load Data based on UTR
function LoadUTRData(Type) {
    debugger;
    var request_data = {
        Dml_Indicator: 'UE',
        receipt_id: (Type == 1) ? $('#QUtrId').val() : $('#utrid').val() //$('#HBilling_no').val()
    }
    $.ajax({
        async: true,
        type: 'POST',
        url: '/Billing/Billing_Receipt',
        contentType: 'application/json; charset=UTF-8',
        data: JSON.stringify(request_data),
        success: function (data) {
            debugger;
            var data = JSON.parse(data);
            if (data.msg == "Success") {
                data = data.data
                var data1 = data.Table[0];
                console.log(data1);
                if (jQuery.isEmptyObject((data1))) {
                }
                else {
                    if (Type == 1) {
                        $('#Receipt_Div').removeClass('hidden');
                        $('#div_billno').hide();
                        $('.divutrbillno,#div_utrtype').show();
                        $('.bill_detail').show();
                        $('#bill_no').html(data1.UTRNumber);
                        $('#lbl_no').html('UTR No');
                        $('#lbl_amt').html('UTR Amount');
                        $('#utrid').val($('#QUtrId').val());
                        $('#utrnumber').val(data1.UTRNumber);
                        $('#due_amount').html('&#8377;' + data1.BalanceAmount);
                        $('#due_amount,#Hdueamount').val(data1.BalanceAmount);
                        $('#rec_type').val(3);
                        $('#utr_search').val(data1.SearchOption);
                        $('#hdninsuranceid').val(data1.insurance);
                        Loadtype(3);
                        $('#rec_type').attr('disabled', true);

                        // $('#rec_date').val(data1.receipt_date);
                        //$('#div_billno').hide();

                        $('#pkg_branch_id').val(data1.branch_id);
                        $('#pkg_branch_id').attr('disabled', true);
                        $('#rec_date').val(moment().format("DD/MM/YYYY"))
                        $('#rec_submit').html('Update');

                        if ($('#due_amount').val() == 0) {
                            debugger;
                            $('#divpay_add').hide();
                            $('#rec_amount').attr('disabled', true);
                            $('#rec_tds').attr('disabled', true);
                            $('#rec_mou').attr('disabled', true);
                            $('#rec_others').attr('disabled', true);
                        }
                        else {
                            $('#divpay_add').show();
                            $('#rec_amount').attr('disabled', false);
                            $('#rec_tds').attr('disabled', false);
                            $('#rec_mou').attr('disabled', false);
                            $('#rec_others').attr('disabled', false);
                        }
                    }
                    var thead = '<tr><th>S.no</th><th>Bill Code</th><th>Patient Name</th><th>Type</th><th>Bank Name</th><th>Transaction ID</th><th>TDS(Tax)</th><th>MOU</th><th>Others</th><th>Amount</th><th>Actions</th></tr></thead>';
                    $('#payment_table thead').append(thead);
                    var action = '', tbody = ''
                    $.each(data.Table, function (i, emp) {
                        action = '', tbody = ''
                        var payment_type = emp.payment_mode;
                        var payment_name = emp.PaymentName;
                        var amount = emp.amount;
                        var ref_no = emp.reference_no;
                        var bank_name = emp.bankid;
                        var bank_name_txt = emp.bank_name;
                        var tds = emp.TDS;
                        var mou = emp.MOU_Discount;
                        var others = emp.others;
                        var billno = emp.billing_no;
                        var PatientId = emp.patientid;
                        var Patient_Id = emp.patient_id;
                        var billCode = emp.billing_code;
                        var PatientName = emp.PatientName;
                        var ClaimDue = emp.ClaimAmount;
                        var VisitReport_Id = emp.visit_report_id;
                        var master_receipt_id = emp.master_receipt_id

                        var sess_key;
                        var rowcount = $.trim($('#PaymentTableRowCount').val());
                        var tot_row = (Number(rowcount) + 1);
                        $('#PaymentTableRowCount').val(tot_row);
                        if (tds == '') {
                            tds = 0;
                        }
                        if (mou == '') {
                            mou = 0;
                        }
                        if (others == '') {
                            others = 0;
                        }
                        var pay_amount = parseFloat(amount) + parseFloat(tds) + parseFloat(mou) + parseFloat(others);
                        // var ClaimDuePending = parseFloat(ClaimDue) - parseFloat(pay_amount);

                        var sess_data_ser = payment_type + "," + payment_name + "," + amount + "," + ref_no + "," + tds + "," + mou + "," + others + "," + bank_name + "," + 0 + "," + billno + "," + billCode + "," + PatientId + "," + PatientName + "," + Patient_Id + "," + ClaimDue + "," + ClaimDue + "," + VisitReport_Id + "," + master_receipt_id;
                        var key = '';
                        if (rowcount >= 1) {
                            var getEid = $('#payment_table tbody  tr').last();
                            var actId = getEid.prop('id');
                            var afterSplit = actId.split('row_');
                            afterInc = parseInt(afterSplit[1]) + 1;
                            console.log(afterInc);
                            ikey_pay = 'row_' + afterInc;
                        }
                        else {

                            ikey_pay = 'row_' + tot_row;
                        }
                        sessionStorage.setItem(ikey_pay, sess_data_ser);
                        action = "<button class='btn btn-xs btn-edit mr-10'onclick='rec_edit(\"" + payment_type + "\",0,\"" + tot_row + "\")' ><i class='fa fa-pencil' aria-hidden='true'></i></button>"

                        tbody = '<tr id="row_' + tot_row + '" data-id=0 data-id2=' + tot_row + ' data-id1=' + master_receipt_id + '><td>' + tot_row + '</td><td id=billCode_' + tot_row + ' data-id=' + billno + '>' + billCode + '</td><td id=patientCode_' + tot_row + ' data-id=' + PatientId + '>' + PatientName + '</td><td id=paymentMode_' + tot_row + ' data-id=' + payment_type + '>' + payment_name + '</td><td id=BName_' + tot_row + ' data-id=' + bank_name + '>' + bank_name_txt + '</td><td id=RefNo_' + tot_row + '>' + ref_no + '</td><td id=TDS_' + tot_row + '>' + tds + '</td><td id=MOU_' + tot_row + '>' + mou + '</td><td id=Others_' + tot_row + '>' + others + '</td><td id=Amount_' + tot_row + '>' + amount + '</td><td>' + action + '</td></tr>';
                        $('#payment_table tbody').append(tbody);
                    })

                    var previousval = 0.0;
                    $('#payment_table > tbody  > tr').each(function () {
                        //$(this).find("td:gt(5):lt(7)").each(function () {
                        //    var temp = $(this).html();
                        //    previousval = parseFloat(previousval) + parseFloat(temp);
                        //});
                        var columnsToSum = $(this).find("td").slice(6, 10);

                        columnsToSum.each(function () {
                            var temp = $(this).html();
                            previousval += parseFloat(temp) || 0;
                        });

                    });




                    $('#payment_table tfoot').empty();

                    var tfoot = '<tr><td colspan="10" style="text-align:right;">Total Amount</td>'
                    $('#pay_tot').val(previousval);

                    var td = '<td id="foot_total">' + parseFloat(previousval) + '</td></tr>';
                    $('#payment_table tfoot').append(tfoot + td);
                    $('#rec_type').attr('disabled', true);
                    $('#pkg_branch_id').attr('disabled', true);
                    $('#utr_search').attr('disabled', true);


                }

                LoadPayment_Type()

            }
        }
    })
}


