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

});


function LoadAllformstable() {
    debugger;
    //var branch = ($('#hiddenRole_id').val() == "2") ? $('#SelBranchSearchPopup').val() : $('#HospitalBranchID').val();
    //var patient_id = $('#Hidpatient_id').val();
    $('#shade_slot').show();
    $('#servicedata_body').empty();
    $('#service_table_list').dataTable().fnClearTable();
    $('#service_table_list').dataTable().fnDraw();
    $('#service_table_list').dataTable().fnDestroy();
    var values = {
        Dml_Indicator: "AFL",
        //Patient_Id: patient_id,
        //branchId: branch
    };

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

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

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

                        if (emp.form_status == '1') {
                            filled_by = emp.filled_by
                            edit = '<a data-toggle="tooltip" title="Edit" class="btn btn-edit btn-xs" data-id="" data-type="role_rights_edit" data-nav="sp_div" data-name="c_details_form"  href="javascript:void(0);"onclick="ChkEditForm(\'' + emp.form_master_data_id + '\', \'' + emp.Form_Name.replace(/'/g, "\\'") + '\', \'' + emp.patient_id + '\', \'' + emp.IsUpload + '\', \'' + emp.AccessRightsUserid + '\', \'' + emp.formcreatedate + '\', \'' + emp.Module_Type + '\', \'' + emp.discharge_status + '\')"><i class="fa fa-pencil" aria-hidden="true"></i></a>';
                            del = ' <a  data-toggle="tooltip" title="Delete"  id="TPAdel_" class="btn deleteicon-btn btn-xs"  data-id="" data-type="role_rights_delete" data-nav="sp_delete" data-name="c_details_form"  href="javascript:void(0);" onclick="formdelete(\'' + emp.form_master_data_id + '\', \'' + emp.AccessRightsUserid + '\', \'' + emp.formcreatedate + '\', \'' + emp.Module_Type + '\', \'' + emp.discharge_status + '\')"><i class="fa fa-trash" aria-hidden="true"></i></a>';
                            print = ' <a  data-toggle="tooltip" title="Print"  id="" class="btn btn-edit btn-xs"  data-id="" data-type="role_rights_function" data-nav="sp_div" data-name="c_details_form"  href="javascript:void(0);" onclick=formprint("' + emp.form_master_data_id + '")><i class="fa fa-print" aria-hidden="true"></i></a>';
                            if (emp.FileUpload == '' || emp.FileUpload == null) {
                                upload = ''
                            }
                            else {
                                upload = '<a title="download" class="btn btn-edit btn-xs"   onclick= "window.open(\'' + $('#hdnEmrformfilepath').val() + $('#HospitalId').val() + '/' + 'FormBuilderFileUpload/' + emp.FileUpload + '\', \'_blank\');"><i class="fa fa-download" aria-hidden="true"></i></a>';
                            }
                        }
                        other_info = '<div class="col-md-12 padding0"><div class="disp_if">' + edit + ' ' + del + '' + print + '' + upload + '</div></div>'

                        htmlRows += '<tr><td>' + (i + 1) + '</td><td>' + emp.Date + '</td><td>' + emp.doctorname + '</td><td>' + filled_by + '</td><td>' + emp.Form_Name + '</td><td>' + emp.service_name + '</td><td>' + emp.patientname + '</td><td>' + form_status + '</td><td>' + other_info + '</td></tr>';
                    });
                    $('#allForms_list_body').html(htmlRows);
                    $('#allForms_list').DataTable()

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

function ChkEditForm(form_data_id, Form_name,patient_id, IsUpload, AccessRightsUserid, Form_CreatedDate, Module_Type, discharge_status) {
    debugger;

    //24 hrs convert
    var createdDate = new Date(Form_CreatedDate);
    var currentDate = new Date();
    var timeDifference = currentDate - createdDate;
    var twentyFourHoursInMs = 24 * 60 * 60 * 1000;
    //
    var accessRightsArray = AccessRightsUserid.split(',');
    if ($("#hiddenRole_id").val() == 2) {
        EditForm(form_data_id, Form_name, patient_id, IsUpload);
    }
    else if (accessRightsArray.includes($("#hiddenUser_id").val())) {
        if (timeDifference < twentyFourHoursInMs && Module_Type == 1 || discharge_status != 2 && Module_Type == 2) {
            EditForm(form_data_id, Form_name, patient_id, IsUpload);
        }
        else {
            toastr.warning("No Rights to Access Edit")
        }
    }
    else {
        toastr.warning("No Rights to Access Edit")
    }

}

function formdelete(Id, AccessRightsUserid, Form_CreatedDate, Module_Type, discharge_status) {
    //24 hrs convert
    var createdDate = new Date(Form_CreatedDate);
    var currentDate = new Date();
    var timeDifference = currentDate - createdDate;
    var twentyFourHoursInMs = 24 * 60 * 60 * 1000;
    debugger;
    var accessRightsArray = AccessRightsUserid.split(',');
    if ($("#hiddenRole_id").val() == 2 || accessRightsArray.includes($("#hiddenUser_id").val())) {
        if ($("#hiddenRole_id").val() == 2 || timeDifference < twentyFourHoursInMs && Module_Type == 1 || discharge_status != 2 && Module_Type == 2) {
            var status = "";
            if (Id != '0') {
                status = "Are You Sure, 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: 'FD',
                                  FormId: Id
                              }

                              $.ajax({
                                  async: true,
                                  type: 'POST',
                                  url: '/Form_builder/GetForms',
                                  contentType: 'application/json; charset=UTF-8',
                                  data: JSON.stringify(Delete),
                                  success: function (data) {
                                      debugger;
                                      var data1 = JSON.parse(data);
                                      console.log(data1);
                                      if (data1.data.Table[0].status == "deleted") {

                                          toastr.success("Deleted Successfully");
                                      }

                                      var tabValue = $('#forms .nav-tabs .active a').data('value');
                                      console.log(tabValue);
                                      formtable(tabValue)
                                  }
                              });
                          });
                      }
                  })
        }
        else {
            toastr.warning("No Rights to Access Delete")
        }
    }
    else {
        toastr.warning("No Rights to Access Delete")
    }
}

function formprint(formmaster_data_id) {
    debugger;
    var load_data = {
        formid: 163,
        patientid: formmaster_data_id

    }
    $.ajax({
        async: true,
        type: 'POST',
        url: '/reports/PrintCrystalReport',
        contentType: 'application/json; charset=UTF-8',
        responseType: 'arraybuffer',
        data: JSON.stringify(load_data),
        success: function (data) {
            console.log(data);
            var byteArray = new Uint8Array(data);
            var blob = new Blob([byteArray], { type: "application/pdf" });
            var link = window.URL.createObjectURL(blob);

            iframe = document.createElement('iframe');
            document.body.appendChild(iframe);

            iframe.style.display = 'none';

            iframe.src = link;
            iframe.onload = function () {
                setTimeout(function () {
                    iframe.focus();
                    iframe.contentWindow.print();
                }, 1);
            };
        }
    });
}



$('#forms_filter_section').click(function () {
    LoadBranch();
})


function LoadBranch() {
    debugger;
    document.getElementById("pkg_branch_id").innerHTML = null;
    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 (data) {
            var data1 = JSON.parse(data);
            if (data1.msg == "Success") {
                var data1 = data1.data;
                console.log(data1);
                if (jQuery.isEmptyObject((data1))) {
                }
                else {
                    debugger;
                    var SubDepartment;
                    var default_opt = '<option value="0">All</option>';
                    $.each(data1.Table, function (i, emp) {
                        SubDepartment = SubDepartment + '<option value="' + emp.hospital_branch_id + '">' + emp.branch_name + '</option>';
                    });
                    $('#pkg_branch_id').append(default_opt + SubDepartment);

                    if ($('#hiddenRole_id').val() != 2) {

                        $('#pkg_branch_id').val($('#HospitalBranchID').val());
                        $('#pkg_branch_id').attr('disabled', true);

                        $('#pkg_branch_id').change();
                    }
                    LoadRole()
                }
            }
            else {
                console.log(data1);
            }
        }
    });
}