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


function Load_templates(templ) {
    debugger
    var data = {
        Dml_Indicator: "LTN",
        hospital_id: $('#HospitalId').val()
    }
    $.ajax({
        async: true,
        type: 'POST',
        url: '/CaseStudy/CasesheetTemplates_Ins_upd_del',
        contentType: 'application/json; charset=UTF-8',
        data: JSON.stringify(data),
        success: function (data) {
            debugger;
            var data2 = JSON.parse(data);
            if (jQuery.isEmptyObject((data2.data))) {
            }
            else {
                if (data2.msg == "Success") {
                    $('#templates').empty();
                    var option = "";
                    var data1 = data2.data.Table;
                    var default_option = "<option value='0'>--Select--</option>";
                    $.each(data1, function (i, emp) {
                        option = option + "<option value=" + emp.casesheet_template_id + " >" + emp.template_name + "</option>"
                    })
                    $('#templates').append(default_option + option);
                    if (templ != '' && templ != null) {
                        $('#templates').val(templ)
                    }
                   
                }
            }
        }
    })
}

$('#btn_template_submit').click(function () {
    debugger;
    var parameters_data1 = [];
    var tot_len = $('#Add_parameterTable>tbody>tr').length;

    if (tot_len > 0) {
        $("#Add_parameterTable tbody tr").each(function () {
            let id = $(this).prop("id");
            let i = $('#' + id).attr('data-id');
            var paraMeter = {
                Dml_Indicator: 'IPM',
                parameter_id: $('#para_name_' + i).attr('data-id'),
                parameter_name: $('#para_name_' + i).html(),
                hospital_id: $('#HospitalId').val(),
                casesheet_templateid: $('#templates').val(),
                header_name: $('#header_name').val(),
                column_span: $('#column_span').val()
            };
            parameters_data1.push(paraMeter);
        });

        $.ajax({
            async: true,
            type: 'POST',
            url: '/CaseStudy/Casesheet_parameters_Ins_upd_del',
            contentType: 'application/json; charset=UTF-8',
            data: JSON.stringify(parameters_data1),
            success: function () {
                if ($('#btn_template_submit').html() == 'Update') {
                    toastr.success('Updated Successfully');
                } else {
                    toastr.success('Added Successfully');
                }
                goback();
                form_clear();
                casesheetTemplatelist();
            },
            error: function () {
                toastr.error('Something Went Wrong');
            }
        });
    } else {
        toastr.error('No parameters to submit');
    }
});

$('#column_span').on('keyup', function () {
    var column_span = $('#column_span').val();
    if (!/^[1-4]$/.test(column_span)) {
        $('#Pcolumn_span').show().html('Please enter a number between 1 and 4').fadeOut(8000);
        $('#column_span').val('');
    }
})

$('#new_add_parameter').click(function () {
    debugger;
    if ($('#parameter_name').val() == "" || $('#parameter_name').val() == null) {
        $('#Pparameter_name').show();
        $('#Pparameter_name').fadeOut(8000);
        $('#Pparameter_name').html('Please Add Parameter');
        $('#Pparameter_name').focus();
        $('#parameter_name').val('');
        return false;
    }
    else {     
        if ($('#new_add_parameter').html() == 'Update') {
            updateParam($('#HRowId').val())
        }
        else {   
            var ikey = "0";
            var rowcount = $('#Add_parameterTable >tbody >tr').length;
            if (rowcount == 0) {
                var ikey = 1
            }
            else {
                var max = 0;
                $('.number').each(function () {
                    var value = parseInt($(this).data('id'));
                    max = (value > max) ? value : max;

                });
                var ikey = Number(max) + 1;
            }
                var c = $('#Add_parameterTable>tbody>tr').length;
                var serialNumber = c + 1;
                var trow = '<tr class="number" id=row_' + ikey + ' data-id=' + ikey + '><td>' + serialNumber + '</td><td id="para_name_' + ikey + '" data-id="0">' + $('#parameter_name').val() + '</td><td><span class="btn btn-edit btn-xs" onclick="parameterEdit(' + ikey + ',0)"><i class="fa fa-pencil" aria-hidden="true"></i></span><span class="btn deleteicon-btn btn-xs" onclick="DeleteParam(' + ikey + ',0)"><i class="fa fa-trash-o" aria-hidden="true"></i></span></td></tr>';
                $("#Add_parameterTable tbody:last").append(trow);
                $('#parameter_name').val('');
                $('#new_add_parameter').html('Add');
                $('#templates').attr('disabled', true)
        }
    }
});

function casesheetTemplatelist() {
    debugger;
    var values = {
        Dml_Indicator: "CTL",
      
    };
    $.ajax({
        async: true,
        type: 'POST',
        url: '/CaseStudy/CasesheetTemplates_Ins_upd_del',
        contentType: 'application/json; charset=UTF-8',
        data: JSON.stringify(values),
        success: function (data) {
            debugger;

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

                    var b = data1.Table;
                    $('#template_tbl_tbody').empty();
                    $('#template_tbl').dataTable().fnClearTable();
                    $('#template_tbl').dataTable().fnDestroy();
                    tr = '';
                    var j = 0, edit = '', del = '', other_info = '';

                    $.each(b, function (i, emp) {
                        j++;
                        //edit = '<a data-toggle="tooltip" title="Edit" class="btn btn-edit btn-xs" data-id="" data-type="" data-nav="" data-name="" onclick=templateEdit("'+ emp.casesheet_template_id+'")><i class="fa fa-pencil" aria-hidden="true"></i></a>';
                        //del = ' <a  data-toggle="tooltip" title="Delete"  id="" class="btn deleteicon-btn btn-xs"  data-id="" data-type="" data-nav="" data-name=""  href="javascript:void(0);" onclick=Templatedel("' + emp.casesheet_template_id + '")><i class="fa fa-trash" aria-hidden="true"></i></a>';
                        //other_info = '<div class="col-md-12 padding0"><div class="disp_if">' + edit + ' ' + del + ' ' + '</div></div>'

                        edit = '<a title="Edit" class="edit_icon" data-id="" data-type="" data-nav="" data-name="" onclick=templateEdit("' + emp.casesheet_template_id + '")><i class="fa fa-pencil" aria-hidden="true"></i></a>';
                        del = ' <a title="Delete"  id="" class="delete_icon"  data-id="" data-type="" data-nav="" data-name=""  href="javascript:void(0);" onclick=Templatedel("' + emp.casesheet_template_id + '")><i class="fa fa-trash-o" aria-hidden="true"></i></a>';
                        other_info = '<div class="dropdown"><i class="fa fa-ellipsis-h dropdown-toggle pull-right" data-toggle="dropdown" aria-expanded="true"></i> <ul class="dropdown-menu info-dropdown-new"><div class="disp_if mb-10"><li>' + edit + '</li><li>' + del + '</li></div></ul></div>';

                        tr = tr + '<tr id="t_' + j + '"><td>' + j + '</td><td>' + emp.template_name + '</td><td>' + emp.header_name + '</td><td>' + emp.column_span + '</td><td>' + other_info + '</td></tr>';
                    });
                    $('#template_tbl_tbody').html(tr);
                    datatable('template_tbl');

                }
            }
        }
    });
}

function templateEdit(Id) {
    debugger;
    $('.table_view').hide();
    $('#add_new_template').hide();
    $('#add_new_template_form').show();
    $('#templates').attr('disabled', true);
    $('#goback2').show();
    var values = {
        Dml_Indicator: "TE",
        casesheet_template_id: Id
    }

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

            Load_templates(emp[0].casesheet_template_id)
            $("#header_name").val(emp[0].header_name);
            $("#column_span").val(emp[0].column_span);
            editparam(Id)
            $('#btn_template_submit').html('Update');
        }
    });
}

function editparam(Id) {
    debugger;
    var values = {
        Dml_Indicator: "PE",
        casesheet_templateid: Id
    };
    $.ajax({
        async: true,
        type: 'POST',
        url: '/CaseStudy/Casesheet_parameters_sel',
        contentType: 'application/json; charset=UTF-8',
        data: JSON.stringify(values),
        success: function (data) {
            debugger;
            console.log(data);
            var data3 = JSON.parse(data);
            if (jQuery.isEmptyObject(data3) || data3.data === 'Records Not Found') {
              
            } else {
                var b = data3.data.Table;
                $('#Add_parameterTable tbody').empty();
                $.each(b, function (i, emp) {
                    var parameter_name = emp.parameter_name;
                    var edit = '', del = '', other_info = '';
                    edit = '<a data-toggle="tooltip" title="Edit" class="btn btn-edit btn-xs" data-id="" data-type="" data-nav="" data-name="" onclick=parameterEdit("' + (i + 1) + '")><i class="fa fa-pencil" aria-hidden="true"></i></a>';
                    del = '<a data-toggle="tooltip" title="Delete" class="btn deleteicon-btn btn-xs" data-id="" data-type="" data-nav="" data-name="" onclick="DeleteParam(\'' + (i + 1) + '\')"><i class="fa fa-trash" aria-hidden="true"></i></a>';
                    other_info = '<div class="col-md-12 padding0"><div class="disp_if">' + edit + ' ' + del + ' ' + '</div></div>'
                    var tr = '<tr class="number" id=row_'+(i+1)+' data-id='+(i+1)+' ><td>' + (i + 1) + '</td><td id=para_name_' + (i + 1) + ' data-id=' + emp.parameter_id + '>' + parameter_name + '</td><td>' + other_info + '</td></tr>';
                    $("#Add_parameterTable tbody").append(tr);
                });
                $('#btn_consumables_Add').html('Update');
            }
        }
    });
}

function parameterEdit(Id) {
    debugger;
    $('#HRowId').val(Id);
    $('#Hidparam_id').val($('#para_name_' + Id).attr('data-id'));
    $("#parameter_name").val($('#para_name_' + Id).html());
    $('#new_add_parameter').html('Update');
}


function updateParam(Id) {
    debugger;
    $('#para_name_' + Id).attr('data-id',$('#Hidparam_id').val())
    $('#para_name_' + Id).html( $("#parameter_name").val())
    $('#new_add_parameter').html('Add');
    $("#parameter_name").val('');   
 }


function DeleteParam(Id) {
    debugger;
    $('#row_' + Id).remove();
    toastr.success('Deleted Successfully');
}

function Templatedel(Id) {
    debugger;
    var status = "";
    if (Id != '') {
        status = "Are you sure, Do you want to Delete?";

        toastr.warning("<button type='button' id='confirmationRevertYes' class='btn btn-warning btn-xs mt20'>Yes</button><button type='button' id='confirmationRevertNo' class='btn btn-warning btn-xs mt20'>No</button>", status, {
            closeButton: true,
            progressBar: true,
            allowHtml: true,
            timeOut: 20000000,

            onShown: function (toast) {
                $("#confirmationRevertYes").click(function () {
                    var Delete = {
                        Dml_Indicator: 'D',
                        casesheet_templateid: Id
                    };

                    $.ajax({
                        async: true,
                        type: 'POST',
                        url: '/CaseStudy/Casesheet_parameters_sel',
                        contentType: 'application/json; charset=UTF-8',
                        data: JSON.stringify(Delete),
                        success: function (data) {
                            debugger;
                            var data1 = JSON.parse(data);
                            if (data1.msg == "Success") {
                                if (data1.data.Table[0].msg == 'Deleted') {
                                    toastr.success("Deleted Successfully");
                                    casesheetTemplatelist();
                                } else {
                                    toastr.warning("Something Went Wrong");
                                }
                            } else {
                                toastr.warning("Something Went Wrong");
                            }
                        },
                        error: function () {
                            toastr.error("Error occurred while deleting template");
                        }
                    });
                });
            }
        });
    }
}



















   
