$(document).ready(function () {
    // Call LoadBranch function
    LoadBranch();
    load_doctor_type()
    loadserviceaccordion()
    userService()




})


function LoadBranch() {
    $('#SelBranch').empty();
    /*  $('#SelBranch1').empty();*/
    var subdepartment = {
        Dml_Indicator: "LBRAN"
    };
    $.ajax({
        async: true,
        type: 'POST',
        url: '/Hospitalsetup/Category_Department_Ins_Upd_sel',
        contentType: 'application/json; charset=UTF-8',
        data: JSON.stringify(subdepartment),
        success: function (responseData) {
            var data1 = JSON.parse(responseData);
            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 += '<option value="' + emp.hospital_branch_id + '">' + emp.branch_name + '</option>';
                    });
                    $('#SelBranch').append(default_opt + SubDepartment);
                    //  $('#SelBranch1').append(default_opt + SubDepartment);

                    if ($('#hiddenRole_id').val() != 2) {
                        $('#SelBranch').val($('#HospitalBranchID').val());
                        $('#SelBranch').attr('disabled', true);
                        doctorlist();

                        //$('#SelBranch1').val($('#HospitalBranchID').val());
                        //$('#SelBranch1').attr('disabled', true);
                        doctorlist1();
                    }
                }
            } else {
                console.log(data1);
            }
        }
    });
}
$('#SelBranch').change(function () {
    debugger;
    doctorlist();
});
function load_doctor_type(doctor_typeid) {
    debugger;
    var load_type = {
        Dml_Indicator: "DT"
    }

    $.ajax({
        async: true,
        type: 'POST',
        url: '/DoctorProfile/DoctorUpdation',
        contentType: 'application/json; charset=UTF-8',
        data: JSON.stringify(load_type),
        success: function (data) {
            debugger;
            var data1 = JSON.parse(data);

            if (data1.msg == "Success") {

                var data1 = data1.data;
                console.log(data1);
                if (jQuery.isEmptyObject((data1))) {

                }
                else {
                    $('#doctor_type').empty();
                    var doctor_type = '';

                    var default_opt = '<option value="0">--Select--</option>';

                    $.each(data1, function (i, emp) {
                        doctor_type = doctor_type + '<option value="' + emp.id + '">' + emp.type_name + '</option>';
                    });
                    if (data1.length == 1) {
                        $('#doctor_type').append(doctor_type);
                    }
                    else {
                        $('#doctor_type').append(default_opt + doctor_type);
                    }

                    if (doctor_typeid != null && doctor_typeid != '') {
                        $('#doctor_type').val(doctor_typeid)
                        $('#doctor_type').attr('disabled', true)
                    }
                }
            }

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


$('#submit').click(function () {
    debugger;
    var applicable_from = null, applicable_to = null;
    if ($("#applicable_from").val() != '')
    {
        var date1 = $("#applicable_from").val().split('/');
        applicable_from = date1[2] + '-' + date1[1] + '-' + date1[0]; 
    }
    else ($("#applicable_to").val() != '')
    {
        var date2 = $("#applicable_to").val().split('/');
        applicable_to = date2[2] + '-' + date2[1] + '-' + date2[0]; 
    }

    var PolicycreationData = {
        Dml_Indicator: "I",
        hospital_id: $('#HospitalId').val(),
        hospitalid: $('#hiddenUser_id').val(),
        branch_id: $('#SelBranch').val(),
        policy_name: $('#policy_name').val(),
        applicable_from: applicable_from,
        applicable_to: applicable_to,     
        created_by: $('#hiddenUser_id').val(),
        is_active: "1"
    };

    $.ajax({
        type: 'POST',
        url: '/DoctorPayout/PolicyCreation',
        contentType: 'application/json; charset=UTF-8',
        data: JSON.stringify(PolicycreationData),
        success: function (response) {
            console.log(response);
            var data1 = JSON.parse(response);
            if (data1.msg == 'Success') {
                var payout_policy_id = data1.data.Table[0].payout_policy_master_id
                userService(payout_policy_id)
            }
        },
        error: function (error) {
            console.log(error);
        }
    });
});


function doctorlist() {
    debugger;
    var DoctorData = {
        Dml_Indicator: "PDL",
        user_role: $('#hiddenRole_id').val(),
        doctor_id: $('#SelDoctor').val(),
        hospital_id: $('#SelHospital').val(),
        branch_id: $('#SelBranch').val()
    };
    $.ajax({
        async: true,
        type: 'POST',
        url: '/Prescription_Settings/casesheet_configurations',
        contentType: 'application/json; charset=UTF-8',
        data: JSON.stringify(DoctorData),
        success: function (responseData) {
            var data1 = JSON.parse(responseData);
            if (data1.msg == "Success") {
                var data1 = data1.data;
                if (jQuery.isEmptyObject(data1)) {
                } else {
                    var tr = '';
                    var SelRole = '';
                    $('#SelDoctor').empty();

                    var default_opt = '< option value="0">--Select--';
                    var j = 0;
                    debugger;
                    if (data1.Table.length > 0) {
                        for (var i = 0; i < data1.Table.length; i++) {
                            j++;
                            SelRole += '< option value="' + data1.Table[i].doctor_id + '">' + data1.Table[i].doctor_name + '';
                        }
                        $('#SelDoctor').html(default_opt + SelRole);
                    }
                    var module_id = '';
                    if (data1.Table1.length > 0) {
                        for (var i = 0; i < data1.Table1.length; i++) {
                            j++;
                            module_id += '< option value="' + data1.Table1[i].casesheet_module_id + '">' + data1.Table1[i].tap_name + '';
                        }
                        $('#uscslistmenus').html(default_opt + module_id);
                    }
                    $('#csmenusortable').empty();
                }
            } else {
                console.log(data1);
            }
        }
    });
}
var CategoryArray = [];
var ServiceArray = [];
function loadserviceaccordion() {
    debugger;
    var load_type = {
        Dml_Indicator: "SS"
    }

    $.ajax({
        async: true,
        type: 'POST',
        url: '/DoctorPayout/PolicyCreation',
        contentType: 'application/json; charset=UTF-8',
        data: JSON.stringify(load_type),
        success: function (data) {
            debugger;
            var data1 = JSON.parse(data);
            console.log(data1);

            if (data1.msg == 'Success') {
                data1 = data1.data;
                var accordiondata = ''
                var ServiceArr = [];
                var collapse = ''
                CategoryArray = data1.Table1;
                ServiceArray = data1.Table;
                $.each(data1.Table1, function (i, emp) {
                    ServiceArr = [];
                    accordiondata = ''
                    i = i + 1;
                    collapse = (i == 1) ? 'in' : ''
                    ServiceArr = data1.Table.filter((item) => item.master_category_id == emp.master_category_id);
                    accordiondata = '<div class="panel panel-default single-panel" id="CatAccordion_' + i + '" data-id=' + emp.master_category_id + '> '
                        + ' <div class="panel-heading newaccordion-panel-heading">'
                        + '<div class="d_flex_jsb">'
                        + ' <div><p class="mb-0 newaccordion-heading">' + i + '.' + emp.category_name + '</p></div>'
                        + '<div class="d_flex_jsb">'
                        
                    + '<input type="text" class="form-control mr-15" name="input1" onchange=validateSumCategory("cattxt",' + emp.master_category_id + ') id="cattxt1_' + emp.master_category_id + '" style="width:75px">'
                        + '<input type="text" class="form-control mr-15" name="input2"  onchange=validateSumCategory("cattxt",' + emp.master_category_id + ')  id="cattxt2_' + emp.master_category_id + '" style="width:75px">'
                        + '<p id="Pcattxt_' + emp.master_category_id + '" class="validate_errupb75" style="color:red;margin-top: 33px;"></p>'
                        + '<input type="hidden" class="form-control mr-15" id="servicecategory_id_' + i + '" value="' + emp.master_category_id + '" >'
                        + '<i class="fa fa-angle-double-down" data-toggle="collapse" data-parent="#serviceaccordion" href="#servicecollapse' + emp.master_category_id + '"></i>'
                        + '</div></div></div>'
                        + '<div id="servicecollapse' + emp.master_category_id + '" class="panel-collapse collapse ' + collapse + '">'
                        + '<div class="panel-body"><ul>'

                    $.each(ServiceArr, function (j, emp1) {
                        j = j + 1;
                        accordiondata = accordiondata + '<li class="d_flex_jsb mb-15">'
                            + '<div><p class="mb-0 light_txt">' + i + '.' + j + ' ' + emp1.service_name + '</p></div>'
                            + '<div class="d_flex_jsb">'
                            + '<input type="hidden" class="form-control mr-15" id="service_id_' + j + '" value="' + emp1.master_service_id + '" >'
                            + '<input type="text" class="form-control mr-15  categoryservice1_' + emp.master_category_id + '"  onchange=validateSum("servicetxt",' + emp1.master_service_id + ') name="" id="servicetxt1_' + emp1.master_service_id + '" style="width:75px">'
                            + '<input type="text" class="form-control mr-25 categoryservice2_' + emp.master_category_id + '"  onchange=validateSum("servicetxt",' + emp1.master_service_id + ') name="" id="servicetxt2_' + emp1.master_service_id + '" style="width:75px">'
                            + '<p id="Pservicetxt_' + emp1.master_service_id + '" class="validate_errupb75" style="color:red;margin-top: 33px;"></p>'
                            + '</div></li>'
                    })
                    accordiondata = accordiondata + '</ul></div></div></div>'
                    $('#serviceaccordion').append(accordiondata);
                })

            }


        }
    })
}

function validateSum(Idtxt, id) {
    var txt1 = $('#' + Idtxt + '1_' + id).val();
    var txt2 = $('#' + Idtxt + '2_' + id).val();
    if (txt1 != null && txt2 != null && txt1 != '' && txt2 != '') {
        if ((parseInt(txt1) + parseInt(txt2)) > 100 || (parseInt(txt1) + parseInt(txt2)) < 100) {
            $('#P' + Idtxt + '_' + id).show();
            $('#P' + Idtxt + '_' + id).fadeOut(8000);
            $('#P' + Idtxt + '_' + id).html('Invalid Percentage');
            $('#' + Idtxt + '1_' + id).focus();
            $('#' + Idtxt + '1_' + id).val('')
            $('#' + Idtxt + '2_' + id).val('');
        }
    }
}

function validateSumCategory(Idtxt, id) {
    var txt1 = $('#' + Idtxt + '1_' + id).val();
    var txt2 = $('#' + Idtxt + '2_' + id).val();
    if (txt1 != null && txt2 != null && txt1 != '' && txt2 != '') {
        if ((parseInt(txt1) + parseInt(txt2)) > 100 || (parseInt(txt1) + parseInt(txt2)) < 100) {
            $('#P' + Idtxt + '_' + id).show();
            $('#P' + Idtxt + '_' + id).fadeOut(8000);
            $('#P' + Idtxt + '_' + id).html('Invalid Percentage');
            $('#' + Idtxt + '1_' + id).focus();
            $('#' + Idtxt + '1_' + id).val('')
            $('#' + Idtxt + '2_' + id).val('');
        }
        else {
            $('.categoryservice1_' + id).val(txt1);
            $('.categoryservice2_' + id).val(txt2);
        }
    }
}


function userService(payout_policy_id) {
    debugger;


    var ObjArray = new Array();
    for (var i = 0; i < CategoryArray.length; i++) {
        if ($('#cattxt1_').val() || $('#cattxt2_').val()) {
            var Obj = {}
            Obj.Dml_Indicator = 'UPP';
            Obj.FromDate = $('#applicable_from').val();
            Obj.ToDate = $('#applicable_to').val();
            //Obj.PatientType = $('#PatientType').val();
            Obj.DocType = $('#doctor_type').val();
            //Obj.Applicability = $('#Applicability').val();
            Obj.ServiceId = 0;
            Obj.ServiceCategoryid = CategoryArray[0].master_category_id
            Obj.HOSPSharePer = $('#cattxt1_' + CategoryArray[0].master_category_id).val();
            Obj.DOCSharePer = $('#cattxt2_' + CategoryArray[0].master_category_id).val();
            //Obj.CreatedBy = $('#CreatedBy').val();
            //Obj.ModifiedBy = $('#ModifiedBy').val();
            Obj.IsActive = $('#IsActive').val();
            master_category_id: $('#master_category_id').val();
            Obj.payout_policy_id = payout_policy_id;
            ObjArray.push(Obj);
            var SerFilArr = ServiceArray.filter((item) => item.master_category_id == CategoryArray[0].master_category_id)
            console.log(ServiceArray);
            for (var j = 0; j < SerFilArr.length; j++) {
                if ($('#servicetxt1_').val() || $('#servicetxt2_').val()) {
                    Obj = {}
                    Obj.Dml_Indicator = 'UPP';
                    Obj.FromDate = $('#applicable_from').val();
                    Obj.ToDate = $('#applicable_to').val();
                    //Obj.PatientType = $('#PatientType').val();
                    Obj.DocType = $('#doctor_type').val();
                    //Obj.Applicability = $('#Applicability').val();
                    Obj.ServiceId = SerFilArr[0].master_service_id
                    Obj.ServiceCategoryid = CategoryArray[i].master_category_id
                    Obj.HOSPSharePer = $('#servicetxt1_' + SerFilArr[0].master_service_id).val();
                    Obj.DOCSharePer = $('#servicetxt2_' + SerFilArr[0].master_service_id).val();
                    //Obj.CreatedBy = $('#CreatedBy').val();
                    //Obj.ModifiedBy = $('#ModifiedBy').val();
                    Obj.IsActive = $('#IsActive').val();
                    master_category_id: $('#master_category_id').val();
                    Obj.payout_policy_id = payout_policy_id;
                    ObjArray.push(Obj);
                } else {
                    console.log('Values for #servicetxt1_ and/or #servicetxt2_ are missing.');
                }
            }
        } else {
            console.log('Values for #cattxt1_ and/or #cattxt2_ are missing.');
        }
    }


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

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

        }
    })
}

   

//function userService(payout_policy_id) {
//    debugger;

//    var ObjArray = new Array();

//    for (var i = 0; i < CategoryArray.length; i++) {
        
//            var Obj = {};
//            Obj.Dml_Indicator = 'UPP';
//            Obj.FromDate = $('#applicable_from').val();
//            Obj.ToDate = $('#applicable_to').val();
//            Obj.DocType = $('#doctor_type').val();
//            Obj.ServiceId = 0;
//            Obj.ServiceCategoryid = CategoryArray[0].master_category_id;
//            Obj.HOSPSharePer = $('#cattxt1_' + CategoryArray[0].master_category_id).val();
//            Obj.DOCSharePer = $('#cattxt2_' + CategoryArray[0].master_category_id).val();
//            Obj.IsActive = $('#IsActive').val();
//            Obj.master_category_id = $('#master_category_id').val();
//            Obj.payout_policy_id = payout_policy_id;
//            ObjArray.push(Obj);

//            var SerFilArr = ServiceArray.filter((item) => item.master_category_id == CategoryArray[0].master_category_id);
//            console.log(ServiceArray);

//            for (var j = 0; j < SerFilArr.length; j++) {
//                if ($('#servicetxt1_').val() && $('#servicetxt2_').val()) {
//                    Obj = {};
//                    Obj.Dml_Indicator = 'UPP';
//                    Obj.FromDate = $('#applicable_from').val();
//                    Obj.ToDate = $('#applicable_to').val();
//                    Obj.DocType = $('#doctor_type').val();
//                    Obj.ServiceId = SerFilArr[j].master_service_id;
//                    Obj.ServiceCategoryid = CategoryArray[i].master_category_id;
//                    Obj.HOSPSharePer = $('#servicetxt1_' + SerFilArr[j].master_service_id).val();
//                    Obj.DOCSharePer = $('#servicetxt2_' + SerFilArr[j].master_service_id).val();
//                    Obj.IsActive = $('#IsActive').val();
//                    Obj.master_category_id = $('#master_category_id').val();
//                    Obj.payout_policy_id = payout_policy_id;
//                    ObjArray.push(Obj);
//                } else {
//                    console.log('Values for #servicetxt1_ and/or #servicetxt2_ are missing.');
//                }
//            }
//        } 
    



 



