var Deleteid = new Array();
var commaSeparatedIds = ''

$(document).ready(function () {
    debugger;

    LoadForms();
    LoadScheduledList($("#Hdn_schedule_bookingid").val());
    LoadEngage($("#Hdn_patient_id_var").val(), $("#Hdn_visit_code").val());
    LoadStore();


    if ($('#Hdn_Type').val() == "2") {
        LoadResults();
    }
});

function LoadAddedProductForPatient() {
    debugger
    var patientid = $("#Hdn_patient_id").val();
    $('#shade_slot').show();
    var values = {
        PatientId: patientid
    };

    $.ajax({
        async: true,
        type: 'POST',
        url: '/CaseStudy/ProductList',
        contentType: 'application/json; charset=UTF-8',
        data: JSON.stringify(values),
        success: function (data) {
            $('#producttableoverall_body').empty();
            $('#producttableoverall').dataTable().fnClearTable();
            $('#producttableoverall').dataTable().fnDraw();
            $('#producttableoverall').dataTable().fnDestroy();
            $('#shade_slot').hide();
            var data1 = JSON.parse(data);
            console.log(data1);
            if (data1.msg == "Success") {
                debugger;
                var data2 = data1.data;
                if (!$.isEmptyObject(data2)) {
                    var htmlRows = '';
                    var productsval = '';

                    $.each(data2, function (i, emp) {
                        debugger;
                        var product_status = '', edit = '', del = '', other_info = '', filled_by = '', print = '', upload = '', Task_Type_Id = '', TaskDescription = '';

                        if (emp.Converted == '0') {
                            product_status = '<span class="label label-warning">Pending</span>';
                        } else if (emp.Converted == '1') {
                            product_status = '<span class="label label-success">Completed</span>';
                        }

                        if (i < 3) {
                            if (productsval == "") {
                                productsval = emp.ItemName;
                            }
                            else {
                                productsval = productsval + " , " + emp.ItemName;
                            }
                        }


                        htmlRows += '<tr><td>' + (i + 1) + '</td><td>' + emp.ItemName + '</td><td>' + emp.BrandName + '</td><td>' + emp.ModelNumberName + '</td><td>' + emp.SizeName + '</td><td>' + emp.ServiceQuantity + '</td><td>' + product_status + '</td></tr>';
                    });

                    $('#producttableoverall_body').html(htmlRows);
                    $('#producttableoverall').DataTable();

                    $('#products').html(productsval);
                    //datatable('producttableoverall', 'product_view', 'Legal');

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

function LoadResults() {
    var OTBdata = {
        P_Dml_Indicator: "WSRL",
        service_name: $('#Hdn_schedule_bookingid').val()
    }

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

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

                }
                else {
                    var b = data1.Table;

                    var str = b[0].document_path;
                    if (str != "" && str != null) {
                        $('#docpathvalue').val(str);
                        var temp = new Array();
                        temp = str.split(",");

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



function LoadForms() {
    var valdc = {
        P_Dml_Indicator: "AF",
        DMO: $('#Hdn_DMO').val()
    };
    debugger;
    $.ajax({
        async: true,
        type: 'POST',
        url: '/Calender/OTList',
        contentType: 'application/json',
        data: JSON.stringify(valdc),
        success: function (data) {
            var data1 = JSON.parse(data);
            if (data1.msg == "Success") {
                var data1 = data1.data;

                if (jQuery.isEmptyObject(data1)) {

                } else {
                    if (data1.Table.length > 0) {
                        var menutr = '';
                        for (var i = 0; i < data1.Table.length; i++) {
                            menutr = menutr + ('<li class="" id="csTab_' + data1.Table[i].casesheet_module_id + '" role="presentation" data-id=' + data1.Table[i].casesheet_module_id + ' data-flag=' + data1.Table[i].flag + ' onclick=load_form1(' + data1.Table[i].casesheet_module_id + ',1)><a href="#cssteps' + data1.Table[i].casesheet_module_id + '" data-toggle="tab" aria-controls="csstep2" role="tab" data-placement="bottom" title="' + data1.Table[i].tap_name + '"><span class="no_circle"><img src="' + $('#hdnlabfilepath').val() + "/" + $('#HdnHospitalid').val() + "/" + "FormBuilderFileUpload/" + data1.Table[i].tap_image + '" /></span><span class="tab_menu_text">' + data1.Table[i].tap_name + '</span></a></li>');
                            loadtabcontent(data1.Table[i].casesheet_module_id)

                        }
                        $('#divFormsList').append(menutr);
                    }
                }
            }
        }
    });
}

function loadtabcontent(form_id) {
    var tabContents = "";
    tabContents += '<div class="tab-pane" role="tabpanel" id="cssteps' + form_id + '">';
    tabContents += '<div><div class="container-fluid"><div class="">';
    tabContents += '<iframe class="responsive-iframe iframe_form" src="" id="iframe_form_' + form_id + '"></iframe>';
    tabContents += '</div></div></div></div>';
    $('#iframeform').append(tabContents);
}

function load_form1(form_id, flag) {
    debugger;
    $('#f1dy').addClass('active');
    var request_data = {
        Dml_Indicator: 'EC',
        Patient_id: $('#Hdn_patient_id_var').val(),
        assesed_by: form_id,
        visit_report_id: $('#Hdn_visit_code').val()
    }
    $.ajax({
        async: true,
        type: 'POST',
        url: '/CaseStudy/CaseStudy_Form',
        contentType: 'application/json; charset=UTF-8',
        data: JSON.stringify(request_data),
        success: function (data) {
            debugger;
            console.log(data);
            var data1 = JSON.parse(data);
            if (jQuery.isEmptyObject((data1))) {
            }
            else {

                if (data1.msg == "Success") {
                    var data = data1.data;
                    var tabContents = "";
                    $('#cssteps' + form_id).trigger('click');
                    var iframesrc = $('#iframe_form_' + form_id).attr('src');
                    if (iframesrc == "") {
                        if (data.Table[0].msg == 'add') {
                            $('#iframe_form_' + form_id).attr('src', $('#Hdformurl').val() + 'form/' + form_id + '?visit_reportid=' + btoa($('#form_Visitid').val()) + '&patientid=' + btoa($('#form_Patientid').val()) + '')


                        }
                        else {

                            $('#iframe_form_' + form_id).attr('src', $('#Hdformurl').val() + 'edit-form/' + data.Table[0].id + '?visit_reportid=' + btoa($('#form_Visitid').val()) + '&patientid=' + btoa($('#form_Patientid').val()) + '')


                        }
                    }




                }
            }
        }
    });

}

function LoadEngage(patient_id, visit_Report_id) {
    var valdc = {
        P_Dml_Indicator: "AWO",
        Patient_Name: patient_id,
        visit_reportid: visit_Report_id
    };
    debugger;
    $.ajax({
        async: true,
        type: 'POST',
        url: '/Calender/OTList',
        contentType: 'application/json',
        data: JSON.stringify(valdc),
        success: function (data) {
            var data1 = JSON.parse(data);
            var valdc = data1.data.Table[0];
            $("#patientid").text(valdc.patient_id);
            $("#patientname").text(valdc.patient_name);
            $("#refdoc").html(valdc.referral_doctor_name);
            var age = ''
            if (valdc.DOB == '' || valdc.DOB == null) {
                if (valdc.age_registered_date == "" || valdc.age_registered_date == null) {
                    age = '-';
                }
                else {
                    var dob = (valdc.age_registered_date);
                    dob = new Date(dob);
                    var today = new Date();
                    age = Math.floor((today - dob) / (365.25 * 24 * 60 * 60 * 1000));
                    age = age + ' years';
                }
            }
            else {
                var dob = (valdc.DOB);
                dob = new Date(dob);
                var today = new Date();
                age = Math.floor((today - dob) / (365.25 * 24 * 60 * 60 * 1000));
                age = age + ' years';
            }
            $("#age").html(age);
            $("#contact").text(valdc.contact);
            $("#Hdn_visit_id").val(valdc.visit_reportid);
            $("#Hdn_patient_id").val(valdc.patientid);
            $('#bloodgrp').html(valdc.patient_blood_group);

            if (valdc.patient_height == '' || valdc.patient_height_metric == null) {
                $('#height').html('-');
            }
            else {
                var hieghtdb = parseInt(valdc.patient_height * 12) + parseInt(valdc.patient_height_metric);
                var hieghtout = Math.round(hieghtdb * 2.54);
                $('#height').html(hieghtout + ' cm');
            }

            if (valdc.patient_weight == '' || valdc.patient_weight == null) {
                $('#kg').html('-');
            }
            else {
                $('#kg').html(valdc.patient_weight + " kg");
            }
        }
    });

    LoadAddedProductForPatient();
}

$("#addnew").on("click", function () {
    openModalAndLoadEngage();
});
// Define openModalAndLoadEngage function
function openModalAndLoadEngage() {
    debugger;
    var patient_id = $("#Hdn_patient_id_var").val();
    var patientid = $("#Hdn_patient_id").val();
    var visit_reportid = $("#Hdn_visit_id").val();
    var visit_id = $("#Hdn_visit_code").val();
    var patient_name = $("#Hdn_patient_name").val();
    var branch_id = $("#Hdn_branch_id").val();

    LoadEngage(patient_id, patientid, visit_reportid, visit_id, patient_name, branch_id);
    PatientGeneralDetails(patient_id, branch_id);
    product_name()
    Loadpacksize()
    LoadBrand()
    LoadModel()
    LoadSize()
    BindingProduct()
    $("#product-to-popup").modal("show");
}

$("#btnAddNewCRM").on("click", function () {
    openModalAndLoadcrm();
});
debugger;
function openModalAndLoadcrm() {
    debugger;
    var patient_id = $("#Hdn_patient_id_var").val();
    var patientid = $("#Hdn_patient_id").val();
    var visit_reportid = $("#Hdn_visit_id").val();
    var visit_id = $("#Hdn_visit_code").val();
    var branch_id = $("#Hdn_branch_id").val();

    BindingCrmService(patient_id, patientid, visit_reportid, branch_id)
    $("#crm_popup").modal("show");
}

function crmload() {
    debugger;
    var patient_id = $("#Hdn_patient_id_var").val();
    var patientid = $("#Hdn_patient_id").val();
    var visit_reportid = $("#Hdn_visit_id").val();
    var visit_id = $("#Hdn_visit_code").val();
    var branch_id = $("#Hdn_branch_id").val();

    BindingCrmServices(patient_id, patientid, visit_reportid, branch_id)

}
function BindingCrmServices(patient_id, patientid, visit_reportid, branch_id) {

    $('#crm_service').val('');
    $("#crmtable tbody").html('');
    $("#crm_table tbody").html('');
    $('#CrmServiceTableRowCount').val(0)
    $('#Hdn_patient_id').val(patientid);
    $('#Hdn_visit_id').val(visit_reportid);
    PatientGeneralDetails(patient_id, branch_id);
    debugger
    var values = {
        Dml_Indicator: "LBPID",
        PatientId: patientid,
        VisitReportId: visit_reportid,
        flag: 0,
        hospitalid: $('#HdnHospitalidInt').val()
    };

    $.ajax({
        async: true,
        type: 'POST',
        url: '/Billing/CrmTaskList',
        contentType: 'application/json; charset=UTF-8',
        data: JSON.stringify(values),
        success: function (data) {
            var data1 = JSON.parse(data);
            console.log(data1);
            var data2 = data1.data
            var service = new Array();
            var taskidMapping = {};
            var taskstatus = {};

            for (var j = 0; j < data2.length; j++) {
                var id = parseInt(data2[j].ServiceId, 10);
                service.push(id)

                var taskId = data2[j].Id;
                taskidMapping[id] = taskId;

                var TaskStatus = data2[j].TaskStatus;
                taskstatus[id] = TaskStatus

            }
            var commaSeparatedIds = service.join(', ');

            crmlists(commaSeparatedIds, taskidMapping, taskstatus)
        }
    })
}

function crmlists(commaSeparatedIds, taskidMapping, taskstatus) {
    debugger
    var values = {
        P_Dml_Indicator: "CRMSE",
        service_code: commaSeparatedIds
    };

    $.ajax({
        async: true,
        type: 'POST',
        url: '/Billing/Service_Master_Ins_upd_sel',
        contentType: 'application/json; charset=UTF-8',
        data: JSON.stringify(values),
        success: function (data) {
            var data1 = JSON.parse(data);
            console.log(data1);
            var data2 = data1.data
            for (var j = 0; j < data2.length; j++) {
                var ser_name = data2[j].service_name
                var ser_id = data2[j].master_service_id
                var ser_code = data2[j].service_code
                var taskid = taskidMapping[ser_id]
                var TaskStatus = taskstatus[ser_id]
                if (ser_name == null || ser_name == "") {
                    return false;
                }
                var sess_key;
                var rowcount = $.trim($('#CrmServiceTableRowCount').val());
                var tot_row = (Number(rowcount) + 1);
                var sess_data_ser = ser_name + "," + ser_code + "," + ser_id + "," + taskid + "," + taskstatus;
                var key = '';
                if (rowcount >= 1) {
                    var getEid = $('#crmtable  tr').last();
                    var getEid = $('#crm_table  tr').last();
                    var actId = getEid.prop('id');
                    var afterSplit = actId.split('row');
                    afterSplit = afterSplit[1].split('_')
                    afterInc = parseInt(afterSplit[0]) + 1;
                    console.log(afterInc);
                    ikey_Deit = 'row' + afterInc;
                }
                else {
                    ikey_Deit = 'row' + tot_row;
                }
                ikey_Deit = ikey_Deit + "_" + ser_id

                var value = ''

                // if (rowcount == 0) {
                sessionStorage.setItem(ikey_Deit, sess_data_ser);

                if ($('#Hbase_amount_type').val() != 4) {
                    //  value = "<tr id=" + ikey_Deit + "><td class='ser_id_column' style='display:none;'>" + ser_id + "</td><td>" + ser_name + "</td><td>" + ser_code + "</td><td>" + num_use + "</td><td>" + req_time + "</td><td>" + remarks + "</td><td><button class='delete btn btn-danger btn-xs btn-add' onclick='Servicedelete(\"" + ikey_Deit + "\")'><i class='fa fa-trash' aria-hidden='true'></i></button></td></tr>";
                    value = "<tr id=" + ikey_Deit + " data-taskid='" + taskid + "'>" + "<td class='ser_id_column' style='display:none;'>" + ser_id + "</td><td>" + ser_name + "</td><td>" + ser_code + "</td></tr>";

                }
                else {
                    // value = "<tr id=" + ikey_Deit + "><td class='ser_id_column' style='display:none;'>" + ser_id + "</td><td>" + ser_name + "</td><td>" + ser_code + "</td><td>" + num_use + "</td><td>" + req_time + " - " + req_end_time + "</td><td>" + remarks + "</td><td><button class='delete btn btn-danger btn-xs btn-add' onclick='Servicedelete(\"" + ikey_Deit + "\")'><i class='fa fa-trash' aria-hidden='true'></i></button></td></tr>";
                    value = "<tr id=" + ikey_Deit + " data-taskid='" + taskid + "'>" + "<td class='ser_id_column' style='display:none;'>" + ser_id + "</td><td>" + ser_name + "</td><td>" + ser_code + "</td></td></tr>";

                }
                $('#crmtable > tbody:last').append(value);
                $('#crm_table > tbody:last').append(value);
                $('#CrmServiceTableRowCount').val(tot_row);
                //  $('#Crm_submit').html('Update')
            }
        }
    })
}
$('#crm_service').autocomplete({
    source: function (request, response) {
        $.ajax({
            async: true,
            url: '/Billing/AutoCompleteService?SName=' + $('#crm_service').val() + '&P_Dml_Indicator=CSAC',
            type: "POST",
            dataType: "json",
            data: { Prefix: request.term },
            success: function (data) {
                console.log(data);
                response($.map(data, function (item) {
                    return { label: item.service_name, value: item.service_name, id: item.master_service_id, code: item.service_code, type: item.base_amount_type };
                }))

            }
        })
    },
    minLength: 1,
    select: function (event, ui) {
        debugger
        $('#HCmaster_service_id').val(ui.item.id)
        $('#HCservice_code').val(ui.item.code)
        $('#Hbase_amount_type').val(ui.item.type)
        $('#crm_time').prop("disabled", false);
        // loadservicedetails(ui.item.id);
    },
    html: true,
    open: function (event, ui) {
        $(".ui-autocomplete").css("z-index", 1000);

    }

});

function Loadpacksize(id) {
    debugger;
    var packsize = {
        Dml_Indicator: "LS",
        Hospital_id: $('#HospitalId').val(),
    }
    $.ajax({
        async: true,
        type: 'POST',
        url: '/CaseStudy/Packsize',
        contentType: 'application/json; charset=UTF-8',
        data: JSON.stringify(packsize),
        success: function (data) {
            debugger;
            $('#pack_size').empty()
            var data1 = JSON.parse(data);
            if (data1.msg == "Success") {
                if (typeof id !== 'undefined' && id !== '') {

                    var filteredData = data1.data.filter(function (item) {
                        return item.Id == id;
                    });
                }
                else {
                    var filteredData = data1.data;
                }
                console.log(filteredData);
                if (jQuery.isEmptyObject((filteredData))) {
                }
                else {
                    var SubDepartment;
                    var default_opt = '<option value="0">--Select--</option>';
                    $.each(filteredData, function (i, emp) {
                        SubDepartment = SubDepartment + '<option value="' + emp.Id + '" data-name="' + emp.Name + '">' + emp.Name + '</option>';
                    });
                    if (filteredData.length == 1) {
                        $('#pack_size').append(SubDepartment);
                        //   $('#pack_size').val(emp.Id)
                    }
                    else {
                        $('#pack_size').append(default_opt + SubDepartment);
                    }
                    if (id != 'undefined' || id != '') {
                        $('#pack_size').val(id)
                        var selectedName = $('#pack_size').find(':selected').data('name');
                        $('#Hdpacksize').val(selectedName)
                        //  $('#pack_size').val(0)
                    }
                }
            }
            else {
                console.log(filteredData);
            }
        }
    });
}


$('#pack_size').change(function () {
    var selectedName = $(this).find(':selected').data('name');
    $('#Hdpacksize').val(selectedName)
});

function LoadBrand(id) {
    debugger;
    var LoadBrand = {
        Dml_Indicator: "LS",
        Hospital_id: $('#HospitalId').val(),
    }
    $.ajax({
        async: true,
        type: 'POST',
        url: '/CaseStudy/ItemConfiguration',
        contentType: 'application/json; charset=UTF-8',
        data: JSON.stringify(LoadBrand),
        success: function (data) {
            debugger;
            $('#Brand').empty()
            var data1 = JSON.parse(data);
            if (data1.msg == "Success") {
                // var data1 = data1.data;
                if (typeof id !== 'undefined' && id !== '') {

                    var Brands = id.split(',').map(function (item) {
                        return parseInt(item.trim());
                    });

                    var filteredData = data1.data.filter(function (item) {
                        return Brands.includes(item.Id) && item.ICTypeId == 1;
                    });
                }
                else {
                    var filteredData = data1.data.filter(function (item) {
                        return item.ICTypeId == 1;
                    });
                }
                console.log(filteredData);
                if (jQuery.isEmptyObject((filteredData))) {
                }
                else {
                    var SubDepartment;
                    var default_opt = '<option value="0">--Select--</option>';
                    $.each(filteredData, function (i, emp) {
                        SubDepartment = SubDepartment + '<option value="' + emp.Id + '" data-name="' + emp.Name + '">' + emp.Name + '</option>';
                    });
                    if (filteredData.length == 1) {
                        $('#Brand').append(SubDepartment);
                        //  $('#Brand').val(emp.Id)
                    }
                    else {
                        $('#Brand').append(default_opt + SubDepartment);
                        $('#Brand').val(0)
                    }
                    if (id != '') {
                        $('#Brand').val(id)
                        var selectedName = $('#Brand').find(':selected').data('name');
                        $('#Hdbrand').val(selectedName)
                    }
                }
            }
            else {
                console.log(data1);
            }
        }
    });
}

$('#Brand').change(function () {
    var selectedName = $(this).find(':selected').data('name');
    $('#Hdbrand').val(selectedName)
});

function LoadModel(id) {
    debugger;
    var Model = {
        Dml_Indicator: "LS",
        Hospital_id: $('#HospitalId').val(),
    }
    $.ajax({
        async: true,
        type: 'POST',
        url: '/CaseStudy/ItemConfiguration',
        contentType: 'application/json; charset=UTF-8',
        data: JSON.stringify(Model),
        success: function (data) {
            debugger;
            $('#catalog_number').empty()
            var data1 = JSON.parse(data);
            if (data1.msg == "Success") {
                if (typeof id !== 'undefined' && id !== '') {
                    var modelNumbers = id.split(',').map(function (item) {
                        return parseInt(item.trim()); // Convert each item to integer
                    });

                    var filteredData = data1.data.filter(function (item) {
                        return modelNumbers.includes(item.Id) && item.ICTypeId == 2;
                    });
                }
                else {
                    var filteredData = data1.data.filter(function (item) {
                        return item.ICTypeId == 2;
                    });
                }
                console.log(filteredData);
                if (jQuery.isEmptyObject((filteredData))) {
                }
                else {
                    var SubDepartment;
                    var default_opt = '<option value="0">--Select--</option>';
                    $.each(filteredData, function (i, emp) {
                        SubDepartment = SubDepartment + '<option value="' + emp.Id + '" data-name="' + emp.Name + '">' + emp.Name + '</option>';
                    });
                    if (filteredData.length == 1) {
                        $('#catalog_number').append(SubDepartment);
                        //   $('#catalog_number').val(emp.Id)
                    }
                    else {
                        $('#catalog_number').append(default_opt + SubDepartment);
                        $('#catalog_number').val(0)
                    }

                    if (id != '') {
                        $('#catalog_number').val(id)
                        var selectedName = $('#catalog_number').find(':selected').data('name');
                        $('#Hdmodel').val(selectedName)
                    }
                }
            }
            else {
                console.log(data1);
            }
        }
    });
}

$('#catalog_number').change(function () {
    var selectedName = $(this).find(':selected').data('name');
    $('#Hdmodel').val(selectedName)
});

function LoadSize(id) {
    debugger;
    var Model = {
        Dml_Indicator: "LS",
        Hospital_id: $('#HospitalId').val(),
    }
    $.ajax({
        async: true,
        type: 'POST',
        url: '/CaseStudy/ItemConfiguration',
        contentType: 'application/json; charset=UTF-8',
        data: JSON.stringify(Model),
        success: function (data) {
            debugger;
            $('#size').empty()
            var data1 = JSON.parse(data);
            if (data1.msg == "Success") {
                //var data1 = data1.data;
                if (typeof id !== 'undefined' && id !== '') {
                    var Sizes = id.split(',').map(function (item) {
                        return parseInt(item.trim()); // Convert each item to integer
                    });

                    var filteredData = data1.data.filter(function (item) {
                        return Sizes.includes(item.Id) && item.ICTypeId == 3;
                    });
                }
                else {
                    var filteredData = data1.data.filter(function (item) {
                        return item.ICTypeId == 3;
                    });
                }
                console.log(filteredData);
                if (jQuery.isEmptyObject((filteredData))) {
                }
                else {
                    var SubDepartment;
                    var default_opt = '<option value="0">--Select--</option>';
                    $.each(filteredData, function (i, emp) {
                        SubDepartment = SubDepartment + '<option value="' + emp.Id + '" data-name="' + emp.Name + '">' + emp.Name + '</option>';
                    });
                    if (filteredData.length == 1) {
                        $('#size').append(SubDepartment);
                        // $('#size').val(emp.Id)
                    }
                    else {
                        $('#size').append(default_opt + SubDepartment);
                        $('#size').val(0)
                    }
                    if (id != '') {
                        $('#size').val(id)
                        var selectedName = $('#size').find(':selected').data('name');
                        $('#Hdsize').val(selectedName)
                    }
                }
            }
            else {
                console.log(data1);
            }
        }
    });
}

$('#size').change(function () {
    var selectedName = $(this).find(':selected').data('name');
    $('#Hdsize').val(selectedName)
});

$('#product_add').click(function () {
    debugger;
    product_add()
    //$('#SelStore').attr('disabled', true);
})

function product_add() {
    debugger;

    var item = $('#product_name').val() ? $('#product_name').val() : ''
    var itemid = $('#Hditem').val() ? $('#Hditem').val() : 0
    var packsize = 0
    var packsizename = ''
    var Brand = $('#Brand').val() ? $('#Brand').val() : 0
    var Brandname = $('#Hdbrand').val() ? $('#Hdbrand').val() : ''
    var model = $('#catalog_number').val() ? $('#catalog_number').val() : 0
    var modelname = $('#Hdmodel').val() ? $('#Hdmodel').val() : ''
    var size = $('#size').val() ? $('#size').val() : 0
    var sizename = $('#Hdsize').val() ? $('#Hdsize').val() : ''
    var Quantity = $('#pro_quantity').val() ? $('#pro_quantity').val() : 0
    var StoreId = $('#SelStore').val()
    var UOMId = $('#pack_size').val() ? $('#pack_size').val() : 0
    var UOM = $('#Hdpacksize').val() ? $('#Hdpacksize').val() : ''
    var CategoryId = $('#HdCategoryId').val() ? $('#HdCategoryId').val() : 0
    var CategoryName = $('#HdCategoryName').val() ? $('#HdCategoryName').val() : ''
    var ItemCode = $('#HdItemCode').val() ? $('#HdItemCode').val() : ''
    var Rate = $('#HdMRP').val() ? $('#HdMRP').val() : 0
    var SalesType = $('#HdSalesType').val() ? $('#HdSalesType').val() : 0
    var TotalAmount = Rate * Quantity
    var SalesPercentage = $('#HdSalesPercentage').val() ? $('#HdSalesPercentage').val() : 0
    var TaxPercentage = 0
    var TaxAmount = 0
    if (SalesType == '1') {
        TaxPercentage = SalesPercentage;
        TaxAmount = Math.round((SalesPercentage / 100) * TotalAmount)
    } else if (SalesType == '2') {
        TaxAmount = SalesPercentage;
        TaxPercentage = Math.round((SalesPercentage * 100) / TotalAmount);
    }
    var NetAmount = TotalAmount + TaxAmount
    var RequestId = 0
    var PatientId = 0
    var VisitReportId = 0
    var VisitReportCode = 0
    var VisitType = 0
    var PatientCode = 0
    var PatientName = 0
    var CreatedBy = 0
    var HMSHospitalId = 0
    var HMSBranchId = 0
    var HospitalId = 0
    var BranchId = 0
    var DoctorId = 0
    var DoctorName = 0
    var RefId = 0
    var DocType = 0
    var Converted = 0
    var BillingNo = 0


    var sess_key;
    var rowcount = $.trim($('#product_table>tbody>tr').length);
    var tot_row = (Number(rowcount) + 1);
    var sess_data_ser = item + "," + packsize + "," + packsizename + "," + Brand + "," + Brandname + "," +
        model + "," + modelname + "," + size + "," + sizename + "," + Quantity + "," + itemid + "," + StoreId + "," + UOMId + "," + UOM + "," + CategoryId + "," +
        CategoryName + "," + ItemCode + "," + Rate + "," + TotalAmount + "," + TaxPercentage + "," + TaxAmount + "," + NetAmount + "," + RequestId + "," +
        PatientId + "," + VisitReportId + "," + VisitReportCode + "," + VisitType + "," + PatientCode + "," + PatientName + "," +
        CreatedBy + "," + HMSHospitalId + "," + HMSBranchId + "," + HospitalId + "," + BranchId + "," + DoctorId + "," +
        DoctorName + "," + RefId + "," + DocType + "," + Converted + "," + BillingNo + "," + 0;

    var key = '';
    if (rowcount >= 1) {
        var getEid = $('#product_table  tr').last();
        var actId = getEid.prop('id');
        var afterSplit = actId.split('row');
        afterSplit = afterSplit[1].split('_')
        afterInc = parseInt(afterSplit[0]) + 1;
        console.log(afterInc);
        ikey_Deit = 'row' + afterInc;
    }
    else {
        ikey_Deit = 'row' + tot_row;
    }
    ikey_Deit = ikey_Deit + "_" + itemid

    var value = ''
    debugger;
    var L = 0;
    var arr = [];
    for (i = 0; i < $('#product_table_Audio >tbody >tr').length; i++) {

        var b = $('#product_table tbody').children('tr').eq(L)
        var id = b.prop('id');
        L++;
        id = id.split('_')[1];
        arr.push(id);
    }
    console.log(arr);
    if ($.inArray(itemid, arr) == -1) {
        sessionStorage.setItem(ikey_Deit, sess_data_ser);

        value = "<tr id=" + ikey_Deit + "><td class='itemid_column' style='display:none;'>" + itemid + "</td><td>" + item + "</td><td data-id = " + Brand + " >" + Brandname + "</td><td data-id = " + model + ">" + modelname + "</td><td data-id = " + size + ">" + sizename + "</td><td>" + Quantity + "</td><td><button class='delete btn btn-danger btn-xs btn-add' onclick='ProductServicedelete(\"" + ikey_Deit + "\")'><i class='fa fa-trash' aria-hidden='true'></i></button></td></tr>";

        $('#product_table_Audio > tbody:last').append(value);
        $('#productTableRowCount').val(tot_row);
        clearproduct()
    }
    else {
        var K = 0;
        //    var brand1 = $("#" + ikey_Deit).find("td").eq(1).attr("data-id");
        for (i = 0; i < $('#product_table_Audio >tbody >tr').length; i++) {
            var b = $('#product_table_Audio tbody').children('tr').eq(K)
            var ItemId1 = b.find("td").eq(0).text();
            var Brand1 = b.find("td").eq(2).attr("data-id");
            var model1 = b.find("td").eq(3).attr("data-id");
            var size1 = b.find("td").eq(4).attr("data-id");
            K++
            if ((itemid == ItemId1)) {
                if (((Brand == Brand1) || (Brand || 0)) && ((model == model1) || (model == 0)) && ((size == size1) || (size == 0))) {
                    toastr.warning("<button type='button' id='confirmationRevertYes' class='btn btn-warning btn-xs mt20'>Yes</button>", 'Do you need to add this quantity to the already existing product?',
                        {
                            closeButton: true,
                            progressBar: true,
                            allowHtml: true,
                            timeOut: 20000000,

                            onShown: function (toast) {
                                $("#confirmationRevertYes").click(function () {
                                    debugger
                                    var existingQuantity = parseInt(b.find("td").eq(5).text());
                                    var newQuantity = existingQuantity + parseInt(Quantity);
                                    b.find("td").eq(5).text(newQuantity);
                                    clearproduct()
                                });

                            }
                        });
                    return false;
                }
                else {
                    sessionStorage.setItem(ikey_Deit, sess_data_ser);

                    value = "<tr id=" + ikey_Deit + "><td class='itemid_column' style='display:none;'>" + itemid + "</td><td>" + item + "</td><td data-id = " + Brand + " >" + Brandname + "</td><td data-id = " + model + ">" + modelname + "</td><td data-id = " + size + ">" + sizename + "</td><td>" + Quantity + "</td><td><button class='delete btn btn-danger btn-xs btn-add' onclick='ProductServicedelete(\"" + ikey_Deit + "\")'><i class='fa fa-trash' aria-hidden='true'></i></button></td></tr>";

                    $('#product_table_Audio > tbody:last').append(value);
                    $('#productTableRowCount').val(tot_row);
                    clearproduct()
                    return false;
                }
            }
            else {
                continue;
            }
        }

    }
}

function clearproduct() {
    $('#product_name').val('');
    $('#pack_size').val(0);
    $('#Brand').val(0);
    $('#catalog_number').val(0);
    $('#size').val(0);
    $('#pro_quantity').val('');
    $('#Hditem').val(0)
    $('#Hdpacksize').val('')
    $('#Hdbrand').val('')
    $('#Hdmodel').val('')
    $('#Hdsize').val('')
    $('#HdSalesUnit').val(0)
    $('#HdSalesUnitName').val('')
    $('#HdCategoryId').val(0)
    $('#HdCategoryName').val('')
    $('#HdItemCode').val('')
    $('#HdMRP').val('')
    $('#HdSalesType').val(0)
    $('#HdSalesPercentage').val('')
    $('#SelStore').val(0);
    $('#SelStore').attr('disabled', false);
}

$('#product_submit').click(function () {
    debugger;
    $('#product_submit').attr('disabled', true);
    var Productservice_data1 = [];
    var tot_rowM = parseInt($('#productTableRowCount').val());
    if (tot_rowM > 0) {
        var L = 0;
        for (j = 1; j <= tot_rowM; j++) {
            var a = $('#product_table_Audio 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) {
                row_data = row_data.split(',');
                var product = {};
                if (row_data[39] != 1) {
                    // crm1.Dml_Indicator = 'CSCRML',
                    product.ItemId = row_data[10],
                        product.Packsize = row_data[1],
                        product.Brand = row_data[3],
                        product.Model = row_data[5]
                    product.Size = row_data[7]
                    product.ServiceQuantity = row_data[9]
                    product.StoreId = row_data[11]
                    product.PatientId = $("#Hdn_patient_id").val();
                    product.VisitReportId = $("#Hdn_visit_id").val();
                    product.VisitReportCode = $("#Hdn_visit_code").val();
                    product.VisitType = 1
                    product.PatientCode = $("#Hdn_patient_id_var").val()
                    product.PatientName = $("#Hdn_patient_name").val();
                    product.HMSBranchId = $("#Hdn_branch_id").val();
                    product.DoctorId = 0
                    product.DoctorName = ""
                    product.ItemName = row_data[0]
                    product.UOMId = row_data[12]
                    product.UOM = row_data[13]
                    product.CategoryId = row_data[14]
                    product.CategoryName = row_data[15]
                    product.ItemCode = row_data[16]
                    product.Rate = row_data[17]
                    product.TotalAmount = row_data[18]
                    product.TaxPercentage = row_data[19]
                    product.TaxAmount = row_data[20]
                    product.NetAmount = row_data[21]
                    product.HMSHospitalId = $('#HdnHospitalidInt').val()
                    product.CreatedBy = $('#hiddenUser_id').val()
                    product.CreatedAt = moment().format("YYYY-MM-DDTHH🇲🇲ss.SSSZ")
                    product.HospitalId = 0,
                        product.BranchId = 0,
                        product.RequestId = $('#PHRequestId').val(),
                        product.BrandName = row_data[4]
                    product.ModelNumberName = row_data[6]
                    product.SizeName = row_data[8]
                    product.ID = row_data[40] || 0

                    Productservice_data1.push(product);
                }
            }
        }
        $.ajax({
            async: true,
            type: 'POST',
            url: '/CaseStudy/productXml',
            contentType: 'application/json; charset=UTF-8',
            data: JSON.stringify(Productservice_data1),
            success: function (data) {
                var data = JSON.parse(data);
                if (data.msg == "Success") {
                    toastr.success("Submitted Successfully",
                        {
                            closeButton: false,
                            progressBar: true,
                            allowHtml: true,
                            timeOut: 0,
                        })

                    setTimeout(function () {
                        $('#product_submit').attr('disabled', false);
                        $('.clsProductPopUpClose').click();
                    }, 2000);

                }
                else {
                    console.log(data);
                }
            }
        });
        if (commaSeparatedIds != '') {
            deleteccrm()
        }
    }

})


function LoadStore(id) {
    debugger;
    var store = {
        Dml_Indicator: "LS",
        Hospital_id: $('#HospitalId').val(),
    }
    $.ajax({
        async: true,
        type: 'POST',
        url: '/Billing/ServiceStore',
        contentType: 'application/json; charset=UTF-8',
        data: JSON.stringify(store),
        success: function (data) {
            debugger;
            $('#SelStore').empty()
            var data1 = JSON.parse(data);
            if (data1.msg == "Success") {
                var data1 = data1.data;
                console.log(data1);
                if (jQuery.isEmptyObject((data1))) {
                }
                else {
                    var SubDepartment;
                    var default_opt = '<option value="0">--Select--</option>';
                    $.each(data1, function (i, emp) {
                        SubDepartment = SubDepartment + '<option value="' + emp.Id + '">' + emp.Name + '</option>';
                    });
                    $('#SelStore').append(default_opt + SubDepartment);

                    if (id != '' && id != null) {
                        $('#SelStore').val(id)
                        $('#SelStore').attr('disabled', true);
                    }
                }
            }
            else {
                console.log(data1);
            }
        }
    });
}


function product_name() {
    debugger
    var item = {
        ItemId: $('#Hditem').val(),
        Hospital_Id: $('#HdnHospitalid').val(),
        BranchId: $("#Hdn_branch_id").val()
    }
    $.ajax({
        async: true,
        type: 'POST',
        url: '/CaseStudy/Itemchange',
        contentType: 'application/json; charset=UTF-8',
        data: JSON.stringify(item),
        success: function (data) {
            debugger;
            var data1 = JSON.parse(data);
            if (data1.msg == "Success") {
                var data1 = data1.data;
                Loadpacksize(data1[0].SalesUnit)
                LoadBrand(data1[0].Brand)
                LoadModel(data1[0].ModelNumber)
                LoadSize(data1[0].Size)
                $('#HdMRP').val(data1[0].MRP)
                $('#HdSalesUnit').val(data1[0].SalesUnit)
                $('#HdSalesUnitName').val(data1[0].SalesUnitName)
                $('#HdSalesPercentage').val(data1[0].SalesPercentage)
                $('#HdSalesType').val(data1[0].SalesType)
                $('#HdCategoryName').val(data1[0].CategoryLableName)
                $('#HdCategoryId').val(data1[0].CategoryId)
                $('#HdStockInHand').val(data1[0].StockInHand)
                $('#HdItemCode').val(data1[0].ItemCode)
            }
            else {
                console.log(data1);
            }
        }
    });
};

$("#pro_quantity").keyup(function () {
    debugger
    var input = $(this).val();
    var stockAvl = parseFloat($('#HdStockAvl').val());
    var errorMessage = $("#Ppro_quantity");


    if (stockAvl < input) {
        errorMessage.text("Please enter a valid number.");
    } else {
        errorMessage.text("");
    }
});
function BindingProduct() {
    debugger
    var values = {
        VisitReportId: $("#Hdn_visit_id").val(),
        PatientId: $("#Hdn_patient_id").val()
    };
    $.ajax({
        async: true,
        type: 'POST',
        url: '/CaseStudy/ProductList',
        contentType: 'application/json; charset=UTF-8',
        data: JSON.stringify(values),
        success: function (data) {
            var data1 = JSON.parse(data);
            console.log(data1);
            var data2 = data1.data
            for (var j = 0; j < data2.length; j++) {

                var id = data2[j].ID
                var item = data2[j].ItemName
                var itemid = data2[j].ItemId
                var packsize = data2[j].PackSize
                var packsizename = ''
                var Brand = data2[j].Brand
                var Brandname = data2[j].BrandName
                var model = data2[j].Model
                var modelname = data2[j].ModelNumberName
                var size = data2[j].Size
                var sizename = data2[j].SizeName
                var Quantity = data2[j].ServiceQuantity
                var StoreId = data2[j].StoreId
                var UOMId = data2[j].UOMId
                var UOM = data2[j].UOM
                var CategoryId = data2[j].CategoryId
                var CategoryName = data2[j].CategoryName
                var ItemCode = data2[j].ItemCode
                var Rate = data2[j].Rate
                var SalesType = 0
                var TotalAmount = data2[j].TotalAmount
                var SalesPercentage = 0
                var TaxPercentage = data2[j].TaxPercentage
                var TaxAmount = data2[j].TaxAmount
                var NetAmount = data2[j].NetAmount
                var PatientId = data2[j].PatientId
                var VisitReportId = data2[j].VisitReportId
                var VisitReportCode = data2[j].VisitReportCode
                var VisitType = data2[j].VisitType
                var PatientCode = data2[j].PatientCode
                var PatientName = data2[j].PatientName
                var CreatedBy = data2[j].CreatedBy
                var HMSHospitalId = data2[j].HMSHospitalId
                var HMSBranchId = data2[j].HMSBranchId
                var HospitalId = data2[j].HospitalId
                var BranchId = data2[j].BranchId
                var DoctorId = data2[j].DoctorId
                var DoctorName = data2[j].DoctorName
                var RefId = data2[j].RefId
                var DocType = data2[j].DocType
                var Converted = data2[j].Converted
                var BillingNo = data2[j].BillingNo
                var RequestId = data2[j].RequestId
                var Id = data2[j].ID || 0;

                var sess_key;
                var rowcount = $.trim($('#productTableRowCount').val());
                var tot_row = (Number(rowcount) + 1);
                var sess_data_ser = item + "," + packsize + "," + packsizename + "," + Brand + "," + Brandname + "," +
                    model + "," + modelname + "," + size + "," + sizename + "," + Quantity + "," + itemid + "," + StoreId + "," + UOMId + "," + UOM + "," + CategoryId + "," +
                    CategoryName + "," + ItemCode + "," + Rate + "," + TotalAmount + "," + TaxPercentage + "," + TaxAmount + "," + NetAmount + "," + RequestId + "," +
                    PatientId + "," + VisitReportId + "," + VisitReportCode + "," + VisitType + "," + PatientCode + "," + PatientName + "," +
                    CreatedBy + "," + HMSHospitalId + "," + HMSBranchId + "," + HospitalId + "," + BranchId + "," + DoctorId + "," +
                    DoctorName + "," + RefId + "," + DocType + "," + Converted + "," + BillingNo + "," + Id;
                var key = '';
                if (rowcount >= 1) {
                    var getEid = $('#product_table_Audio  tr').last();
                    var actId = getEid.prop('id');
                    var afterSplit = actId.split('row');
                    afterSplit = afterSplit[1].split('_')
                    afterInc = parseInt(afterSplit[0]) + 1;
                    console.log(afterInc);
                    ikey_Deit = 'row' + afterInc;
                }
                else {
                    ikey_Deit = 'row' + tot_row;
                }
                ikey_Deit = ikey_Deit + "_" + itemid

                var value = ''

                sessionStorage.setItem(ikey_Deit, sess_data_ser);

                if (Converted == 1) {
                    value = "<tr id=" + ikey_Deit + "><td class='itemid_column' style='display:none;'>" + itemid + "</td><td>" + item + "</td><td data-id = " + Brand + " >" + Brandname + "</td><td data-id = " + model + ">" + modelname + "</td><td data-id = " + size + ">" + sizename + "</td><td>" + Quantity + "</td></tr>";

                }
                else {
                    $('#PHRequestId').val(RequestId);
                    // value = "<tr id=" + ikey_Deit + "><td>" + item + "</td><td>" + Brandname + "</td><td>" + modelname + "</td><td>" + sizename + "</td><td>" + Quantity + "</td><td><button class='delete btn btn-danger btn-xs btn-add' onclick='ProductServicedelete(\"" + ikey_Deit + "\")'><i class='fa fa-trash' aria-hidden='true'></i></button></td></tr>";
                    value = "<tr id=" + ikey_Deit + "><td class='itemid_column' style='display:none;'>" + itemid + "</td><td>" + item + "</td><td data-id = " + Brand + " >" + Brandname + "</td><td data-id = " + model + ">" + modelname + "</td><td data-id = " + size + ">" + sizename + "</td><td>" + Quantity + "</td><td><button class='delete btn btn-danger btn-xs btn-add' onclick='ProductServicedelete(\"" + ikey_Deit + "\")'><i class='fa fa-trash' aria-hidden='true'></i></button></td></tr>";

                }
                $('#product_table_Audio > tbody:last').append(value);
                $('#productTableRowCount').val(tot_row);
                LoadStore(StoreId)


            }
        }
    })
}

function ProductServicedelete(id) {
    sessionStorage.removeItem(id);
    $('#' + id).remove();
    var rowcount = $.trim($('#productTableRowCount').val());
    rowcount = rowcount - 1;
    $('#productTableRowCount').val(rowcount);
}

function Product_table() {
    debugger
    var patientid = $("#Hdn_patient_id_var").val();
    $('#shade_slot').show();
    var values = {
        VisitReportId: $("#Hdn_visit_id").val(),
        PatientId: patientid
    };

    $.ajax({
        async: true,
        type: 'POST',
        url: '/CaseStudy/ProductList',
        contentType: 'application/json; charset=UTF-8',
        data: JSON.stringify(values),
        success: function (data) {
            $('#product_bill_list tbody').empty();

            $('#shade_slot').hide();
            var data1 = JSON.parse(data);
            console.log(data1);
            if (data1.msg == "Success") {
                debugger;
                var data2 = data1.data;
                if (!$.isEmptyObject(data2)) {
                    var htmlRows = '';

                    $.each(data2, function (i, emp) {
                        debugger;
                        var product_status = ''

                        if (emp.Converted == '0') {
                            product_status = '<span class="label label-warning">Pending</span>';
                        } else if (emp.Converted == '1') {
                            product_status = '<span class="label label-success">Completed</span>';
                        }


                        htmlRows += '<tr><td>' + (i + 1) + '</td><td>' + emp.ItemCode + '</td><td>' + emp.ItemName + '</td><td>' + emp.BrandName + '</td><td>' + emp.ModelNumberName + '</td><td>' + emp.SizeName + '</td><td>' + emp.ServiceQuantity + '</td><td>' + product_status + '</td></tr>';
                    });

                    $('#product_bill_list tbody').append(htmlRows);


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

$('#crm_add').click(function () {
    debugger;
    $('#crm_add').attr('disabled', true);
    if ($('#HCmaster_service_id').val() == '' || $('#HCmaster_service_id').val() == 0) {
        $('#Pcrm_service').show();
        $('#Pcrm_service').fadeOut(8000);
        $('#Pcrm_service').html('Select Service Name');
        $('crm_service').focus();
        $('#crm_add').attr('disabled', false);
        return false;
    }

    else {
        debugger;

        Crmservice_add();

    }
})


function Crmservice_add() {
    debugger;
    var ser_name = $("#crm_service").val();
    var ser_id = $('#HCmaster_service_id').val();
    if (ser_name == null || ser_name == "") {
        return false;
    }
    var ser_code = $('#HCservice_code').val();
    var num_use = 1;
    var work_order = $('#Hworkorder').val();
    var work_order_type = $('#Hwork_order_type').val();
    var pack = $('#Hpackage_id').val();
    var req_time = $('#crm_time').val();
    var req_end_time = $('#crm_end_time').val();
    var base_amount_type = $('#Hbase_amount_type').val();
    var range_min = $('#Hrange_min').val();
    var range_max = $('#Hrange_max').val();
    var remarks = $('#crm_remarks').val();
    var doc_name = '-', doc_id = '';

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

    var value = ''
    if (remarks == '') {
        remarks = '-'
    }
    // if (rowcount == 0) {
    debugger;
    var L = 0;
    var arr = [];
    for (i = 0; i < $('#crm_table >tbody >tr').length; i++) {
        var b = $('#crm_table tbody').children('tr').eq(L)
        var id = b.prop('id');
        L++;
        id = id.split('_')[1];
        arr.push(id);
    }
    console.log(arr);
    if ($.inArray(ser_id, arr) == -1) {
        sessionStorage.setItem(ikey_Deit, sess_data_ser);

        if ($('#Hbase_amount_type').val() != 4) {
            //  value = "<tr id=" + ikey_Deit + "><td class='ser_id_column' style='display:none;'>" + ser_id + "</td><td>" + ser_name + "</td><td>" + ser_code + "</td><td>" + num_use + "</td><td>" + req_time + "</td><td>" + remarks + "</td><td><button class='delete btn btn-danger btn-xs btn-add' onclick='Servicedelete(\"" + ikey_Deit + "\")'><i class='fa fa-trash' aria-hidden='true'></i></button></td></tr>";
            value = "<tr id=" + ikey_Deit + "><td class='ser_id_column' style='display:none;'>" + ser_id + "</td><td>" + ser_name + "</td><td>" + ser_code + "</td><td><button class='delete btn btn-danger btn-xs btn-add' onclick='CrmServicedelete(\"" + ikey_Deit + "\")'><i class='fa fa-trash' aria-hidden='true'></i></button></td></tr>";

        }
        else {
            // value = "<tr id=" + ikey_Deit + "><td class='ser_id_column' style='display:none;'>" + ser_id + "</td><td>" + ser_name + "</td><td>" + ser_code + "</td><td>" + num_use + "</td><td>" + req_time + " - " + req_end_time + "</td><td>" + remarks + "</td><td><button class='delete btn btn-danger btn-xs btn-add' onclick='Servicedelete(\"" + ikey_Deit + "\")'><i class='fa fa-trash' aria-hidden='true'></i></button></td></tr>";
            value = "<tr id=" + ikey_Deit + "><td class='ser_id_column' style='display:none;'>" + ser_id + "</td><td>" + ser_name + "</td><td>" + ser_code + "</td><td><button class='delete btn btn-danger btn-xs btn-add' onclick='CrmServicedelete(\"" + ikey_Deit + "\")'><i class='fa fa-trash' aria-hidden='true'></i></button></td></tr>";

        }
    }
    else {
        $('#Pcrm_service').show();
        $('#Pcrm_service').fadeOut(8000);
        $('#Pcrm_service').html('This particular service can be added only after the completion of the previous similar service');
        $('#crm_service').focus();
        $('#crm_service').val('');
        $('#crm_service').val(1);
        return false;
    }
    // }

    $('#crm_table > tbody:last').append(value);
    $('#CrmServiceTableRowCount').val(tot_row);
    $('#crm_service').val('');
    $('#crm_service_code').val('');
    $('#crm_quantity').val(1);
    $('#HCmaster_service_id').val('');
    //  $('#crm_time').val(new_date);
    $('#crm_add').attr('disabled', false);
}
//Service Table Delete
function CrmServicedelete(id, TaskStatus) {
    debugger
    if (TaskStatus == 1) {
        sessionStorage.removeItem(id);
        $('#' + id).remove();
        var rowcount = $.trim($('#CrmServiceTableRowCount').val());
        rowcount = rowcount - 1;
        $('#CrmServiceTableRowCount').val(rowcount);

        var idParts = id.split('_');
        var dataId = idParts[1]; // Assuming the data id is at index 1

        // Push dataId to the Deleteid array
        Deleteid.push(dataId);
        commaSeparatedIds = Deleteid.join(', ');
        toastr.success('Deleted Successfully')
    }
    else {
        toastr.error('Service is mapped, You cant delete the service')

    }
}


$('#Crm_submit').click(function () {
    debugger;
    var Crmservice_data1 = [];
    var tot_rowM = parseInt($('#CrmServiceTableRowCount').val());
    if (tot_rowM > 0) {
        var L = 0;
        for (j = 1; j <= tot_rowM; j++) {
            var a = $('#crm_table tbody').children('tr').eq(L);
            var b = a.prop('id');
            L++;

            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) {
                row_data = row_data.split(',');
                var crm1 = {};
                crm1.Dml_Indicator = 'CSCRML',
                    crm1.ServiceId = row_data[17],
                    crm1.Patient_id = $("#Hdn_patient_id").val(),
                    crm1.VisitReportId = $("#Hdn_visit_id").val(),
                    crm1.Id = row_data[3]
                Crmservice_data1.push(crm1);
            }
        }
        $.ajax({
            async: true,
            type: 'POST',
            url: '/Billing/CrmServiceXml',
            contentType: 'application/json; charset=UTF-8',
            data: JSON.stringify(Crmservice_data1),
            success: function (data) {
                var data = JSON.parse(data);
                if (data.msg == "Success") {
                    toastr.success("Submitted Successfully",
                        {
                            closeButton: false,
                            progressBar: true,
                            allowHtml: true,
                            timeOut: 0,
                        })

                    setTimeout(function () {
                        $('#Crm_submit').attr('disabled', false);
                        $('.clsServicePopUpClose').click();
                    }, 2000);
                    crmload();

                }
                else {
                    console.log(data);
                }
            }
        });
        if (commaSeparatedIds != '') {
            deleteccrm()
        }
    }
    else {
        if (commaSeparatedIds != '') {
            deleteccrm()
        }
    }

})



function deleteccrm() {
    debugger;
    var values = {
        Dml_Indicator: "DBSID",
        Name: commaSeparatedIds,
        VisitReportId: $("#Hdn_visit_id").val()
    };

    $.ajax({
        async: true,
        type: 'POST',
        url: '/Billing/CrmTaskList',
        contentType: 'application/json; charset=UTF-8',
        data: JSON.stringify(values),
        success: function (data) {
            var data1 = JSON.parse(data);
            console.log(data1);
            var data2 = data1.data
            var tot_rowM = parseInt($('#CrmServiceTableRowCount').val());
            toastr.success("Submitted Successfully")
            setTimeout(function () {
                $('#Crm_submit').attr('disabled', false);
                $('.clsServicePopUpClose').click();
            }, 2000);
        }
    })
}


function BindingCrmService(patient_id, patientid, visit_reportid, branch_id) {

    $('#crm_service').val('');
    $("#crmtable tbody").html('');
    $("#crm_table tbody").html('');
    $('#CrmServiceTableRowCount').val(0)
    $('#Hdn_patient_id').val(patientid);
    $('#Hdn_visit_id').val(visit_reportid);
    PatientGeneralDetails(patient_id, branch_id);
    debugger
    var values = {
        Dml_Indicator: "LBPID",
        PatientId: patientid,
        VisitReportId: visit_reportid,
        flag: 0,
        hospitalid: $('#HdnHospitalidInt').val()
    };

    $.ajax({
        async: true,
        type: 'POST',
        url: '/Billing/CrmTaskList',
        contentType: 'application/json; charset=UTF-8',
        data: JSON.stringify(values),
        success: function (data) {
            var data1 = JSON.parse(data);
            console.log(data1);
            var data2 = data1.data
            var service = new Array();
            var taskidMapping = {};
            var taskstatus = {};

            for (var j = 0; j < data2.length; j++) {
                var id = parseInt(data2[j].ServiceId, 10);
                service.push(id)

                var taskId = data2[j].Id;
                taskidMapping[id] = taskId;

                var TaskStatus = data2[j].TaskStatus;
                taskstatus[id] = TaskStatus

            }
            var commaSeparatedIds = service.join(', ');

            crmlist(commaSeparatedIds, taskidMapping, taskstatus)
        }
    })
}

function crmlist(commaSeparatedIds, taskidMapping, taskstatus) {
    debugger
    var values = {
        P_Dml_Indicator: "CRMSE",
        service_code: commaSeparatedIds
    };

    $.ajax({
        async: true,
        type: 'POST',
        url: '/Billing/Service_Master_Ins_upd_sel',
        contentType: 'application/json; charset=UTF-8',
        data: JSON.stringify(values),
        success: function (data) {
            var data1 = JSON.parse(data);
            console.log(data1);
            var data2 = data1.data
            for (var j = 0; j < data2.length; j++) {
                var ser_name = data2[j].service_name
                var ser_id = data2[j].master_service_id
                var ser_code = data2[j].service_code
                var taskid = taskidMapping[ser_id]
                var TaskStatus = taskstatus[ser_id]
                if (ser_name == null || ser_name == "") {
                    return false;
                }
                var sess_key;
                var rowcount = $.trim($('#CrmServiceTableRowCount').val());
                var tot_row = (Number(rowcount) + 1);
                var sess_data_ser = ser_name + "," + ser_code + "," + ser_id + "," + taskid + "," + taskstatus;
                var key = '';
                if (rowcount >= 1) {
                    var getEid = $('#crmtable  tr').last();
                    var getEid = $('#crm_table  tr').last();
                    var actId = getEid.prop('id');
                    var afterSplit = actId.split('row');
                    afterSplit = afterSplit[1].split('_')
                    afterInc = parseInt(afterSplit[0]) + 1;
                    console.log(afterInc);
                    ikey_Deit = 'row' + afterInc;
                }
                else {
                    ikey_Deit = 'row' + tot_row;
                }
                ikey_Deit = ikey_Deit + "_" + ser_id

                var value = ''

                // if (rowcount == 0) {
                sessionStorage.setItem(ikey_Deit, sess_data_ser);

                if ($('#Hbase_amount_type').val() != 4) {
                    //  value = "<tr id=" + ikey_Deit + "><td class='ser_id_column' style='display:none;'>" + ser_id + "</td><td>" + ser_name + "</td><td>" + ser_code + "</td><td>" + num_use + "</td><td>" + req_time + "</td><td>" + remarks + "</td><td><button class='delete btn btn-danger btn-xs btn-add' onclick='Servicedelete(\"" + ikey_Deit + "\")'><i class='fa fa-trash' aria-hidden='true'></i></button></td></tr>";
                    value = "<tr id=" + ikey_Deit + " data-taskid='" + taskid + "'>" + "<td class='ser_id_column' style='display:none;'>" + ser_id + "</td><td>" + ser_name + "</td><td>" + ser_code + "</td><td><button class='delete btn btn-danger btn-xs btn-add' onclick='CrmServicedelete(\"" + ikey_Deit + "\",\"" + TaskStatus + "\")'><i class='fa fa-trash' aria-hidden='true'></i></button></td></tr>";

                }
                else {
                    // value = "<tr id=" + ikey_Deit + "><td class='ser_id_column' style='display:none;'>" + ser_id + "</td><td>" + ser_name + "</td><td>" + ser_code + "</td><td>" + num_use + "</td><td>" + req_time + " - " + req_end_time + "</td><td>" + remarks + "</td><td><button class='delete btn btn-danger btn-xs btn-add' onclick='Servicedelete(\"" + ikey_Deit + "\")'><i class='fa fa-trash' aria-hidden='true'></i></button></td></tr>";
                    value = "<tr id=" + ikey_Deit + " data-taskid='" + taskid + "'>" + "<td class='ser_id_column' style='display:none;'>" + ser_id + "</td><td>" + ser_name + "</td><td>" + ser_code + "</td><td><button class='delete btn btn-danger btn-xs btn-add' onclick='CrmServicedelete(\"" + ikey_Deit + "\",\"" + TaskStatus + "\")'><i class='fa fa-trash' aria-hidden='true'></i></button></td></tr>";

                }
                $('#crmtable > tbody:last').append(value);
                $('#crm_table > tbody:last').append(value);
                $('#CrmServiceTableRowCount').val(tot_row);
                //  $('#Crm_submit').html('Update')
            }
        }
    })
}

$(document).ready(function () {
    $('a[href="#ServicesLog"]').on('click', function () {
        LoadScheduledList();
    });
});

function LoadScheduledList(schedule_booking_id) {
    debugger;
    var OTBdata = {
        P_Dml_Indicator: "WSL",
        DMO: $('#hiddenRole_id').val() == "2" ? "" : $('#hiddenUser_id').val(),
        Patient_Name: $("#Hdn_patient_id_var").val(),
        id: schedule_booking_id,
    }

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

                if (jQuery.isEmptyObject((data1))) {
                    tr = '';
                    $('#workscheduletable2').dataTable().fnClearTable();
                    $('#workscheduletable2').dataTable().fnDestroy();
                    $('#workscheduletable_body2').html(tr);
                    datatable('workscheduletable2');
                } else {
                    var b = data1.Table;
                    $('#workscheduletable_body2').empty();
                    $('#workscheduletable2').dataTable().fnClearTable();
                    $('#workscheduletable2').dataTable().fnDestroy();
                    tr = '';

                    $.each(b, function (i, emp) {
                        tr += '<tr>' +
                            //'<td class="tbl-name">' +
                            //'<span class="patientname" data-patient-id="' + emp.Patientid + '" style="cursor: pointer;" ' +
                            //'onclick="billing_details(\'' + emp.Patientid + '\', \'' + emp.patient_first_name + '\', \'' + emp.phone_number_1 + '\', \'' + emp.service_name + '\', \'' + emp.Date + '\', \'' + emp.Time + '\', \'' + emp.audiologist_name + '\', \'' + emp.schedule_status + '\')">' +
                            //emp.patient_first_name + '</span>' +
                            //'<span class="tbl_pno"><br>' + emp.Patientid + '</span></td>' +
                            //'<td id="ldtphone_number_1_' + i + '">' + emp.phone_number_1 + '</td>' +
                            '<td>' + emp.service_name + '</td>' +
                            '<td>' + emp.fromDate + '</td>' +
                            '<td>' + emp.fromTime + '</td>' +
                            '<td>' + emp.audiologist_name + '</td>' +
                            '<td>' + (emp.schedule_status == 4 ? "Scheduled" : emp.schedule_status == 5 ? "Completed" : "Pending") + '</td>' +
                            '</tr>';
                    });

                    $('#workscheduletable_body2').html(tr);
                    //datatable('workscheduletable2');
                    $('#workscheduletable2').DataTable();

                }
            }
        }
    });
}

$('#product_name').autocomplete({
    source: function (request, response) {
        $.ajax({
            async: true,
            url: "/CaseStudy/AutoCompletelist?dataflags=" + $('#phy_data_flag').val() + "&MedicineName=" + $('#product_name').val() + "&PharmacyID=" + $('#txtPharmacyID').val() + "&typeid=" + 0 + "&BranchId=" + $('#Hdn_popupbranch_id').val() + "&is_pharmacy=" + $('#His_pharmacy').val(),
            type: "POST",
            dataType: "json",
            data: { Prefix: request.term, StoreId: ((!$('#SelStore').val()) ? 0 : $('#SelStore').val()) },
            success: function (data) {
                response($.map(data, function (item) {
                    return {
                        label: item.medicine_status + "   ",
                        value: item.medicine_name,
                        medicine_type_id: item.medicine_type_id,
                        id: item.medicine_id,
                        StockAvl: item.StockAvl,
                        NoDuration: item.NoDuration
                    };
                }))
            }
        })
    },
    select: function (event, ui) {
        $('#Hditem').val(ui.item.id)
        $('#HdStockAvl').val(ui.item.StockAvl)
        product_name()
    }
})




$('#fileToUploadAudio').change(function () {
    debugger;
    packageimageupload();

});

function packageimageupload() {
    debugger;
    var uploadpath = $('#fileToUploadAudio').val();
    var fileExtension = uploadpath.substring(uploadpath.lastIndexOf(".") + 1, uploadpath.length);

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

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

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


        $.ajax({
            url: '/Workorder/UploadIDProof?branch_id=' + $('#Hdn_branch_id').val(),
            type: "POST",
            contentType: false,
            processData: false,
            data: fileData,
            success: function (result) {
                debugger;
                $.each(result, function (i, emp) {
                    debugger;
                    var pathName = ($.trim($('#docpathvalue').val()));
                    if (pathName !== "") {
                        pathName = pathName + "," + result.img;
                    }
                    else {
                        pathName = result.img;
                    }
                    console.log(pathName);
                    var paths = pathName.split(',');


                    $('#photologAudio').text('');


                    paths.forEach(function (path) {
                        $('#photologAudio').append('<a href="' + $('#hdnfilepath1').val() + $('#HospitalId').val() + "/" + $('#Hdn_branch_id').val() + "/Lab_Documents/" + path.trim() + '" target="_blank">' + path.trim() + '</a><br>');
                    });

                    $('#docpathvalue').val(pathName);
                });
            }
        });
    }
}

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

    var OTBdata = {
        P_Dml_Indicator: "WSR",
        service_name: $('#Hdn_schedule_bookingid').val(),
        Remarks: $('#docpathvalue').val()
    }

    debugger;
    $.ajax({
        async: true,
        type: 'POST',
        url: '/Calender/OTCreation',
        contentType: 'application/json; charset=UTF-8',
        data: JSON.stringify(OTBdata),
        success: function (data) {
            debugger;
            var data = JSON.parse(data);
            debugger;
            if (data.msg == "Success") {
                var data1 = data.data;
                toastr.success('Updated Successfully');
                LoadWorkSceduledList();
            }
        }
    });

})

$('#btnPageClose').click(function () {
    toastr.warning(
        "<button type='button' id='confirmationRevertYes' class='btn btn-warning btn-xs mt20'>Yes</button>",
        'Do you want to close?', {
        closeButton: true,
        progressBar: true,
        allowHtml: true,
        timeOut: 20000000,
        onShown: function (toast) {
            $("#confirmationRevertYes").click(function () {
                var typeid = $('#Hdn_type').val();
                if (typeid == 2) {
                    window.location.href = "/workorder/audiologistorder";
                } else {
                    var bookingId = $('#Hdn_schedule_bookingid').val();
                    var scheduleenddata = {
                        P_Dml_Indicator: "ET",
                        id: bookingId
                    };

                    $.ajax({
                        async: true,
                        type: 'POST',
                        url: '/Calender/OTCreation',
                        contentType: 'application/json; charset=UTF-8',
                        data: JSON.stringify(scheduleenddata),
                        success: function (response) {
                            var data = JSON.parse(response);
                            if (jQuery.isEmptyObject(data)) {
                                console.log("Empty response data");
                            } else {
                                if (data.msg == "Success") {
                                    console.log("Operation successful");
                                    window.location.href = "/workorder/audiologistorder";
                                } else {
                                    console.log(data);
                                }
                            }
                        },
                        error: function (xhr, status, error) {
                            console.log("AJAX request failed: " + status + ", " + error);
                        }
                    });
                }
            });
        }
    });
});



function loadtabcontent(form_id) {
    var tabContents = "";
    tabContents += '<div class="tab-pane" role="tabpanel" id="cssteps' + form_id + '">';
    tabContents += '<div class="wrapper"><div class="container-fluid"><div class="">';
    tabContents += '<iframe class="responsive-iframe iframe_form" src="" id="iframe_form_' + form_id + '"></iframe>';
    tabContents += '</div></div></div></div>';
    $('#iframeform').append(tabContents);
}





function load_form1(form_id, flag) {
    debugger;
    $('#f1dy').addClass('active');
    var request_data = {
        Dml_Indicator: 'EC',
        Patient_id: $('#form_Patientid').val(),
        assesed_by: form_id,
        visit_report_id: $('#form_Visitid').val()
    }
    $.ajax({
        async: true,
        type: 'POST',
        url: '/CaseStudy/CaseStudy_Form',
        contentType: 'application/json; charset=UTF-8',
        data: JSON.stringify(request_data),
        success: function (data) {
            debugger;
            console.log(data);
            var data1 = JSON.parse(data);
            if (jQuery.isEmptyObject((data1))) {
            }
            else {

                if (data1.msg == "Success") {
                    var data = data1.data;
                    var tabContents = "";
                    $('#cssteps' + form_id).trigger('click');
                    var iframesrc = $('#iframe_form_' + form_id).attr('src');
                    if (iframesrc == "") {
                        if (data.Table[0].msg == 'add') {
                            $('#iframe_form_' + form_id).attr('src', $('#Hdformurl').val() + 'form/' + form_id + '?visit_reportid=' + btoa($('#form_Visitid').val()) + '&patientid=' + btoa($('#form_Patientid').val()) + '')


                        }
                        else {

                            $('#iframe_form_' + form_id).attr('src', $('#Hdformurl').val() + 'edit-form/' + data.Table[0].id + '?visit_reportid=' + btoa($('#form_Visitid').val()) + '&patientid=' + btoa($('#form_Patientid').val()) + '')


                        }
                    }




                }
            }
        }
    });

}