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

function loadGeneralForms(val) {
    debugger;
    $('#selectform').empty();
    var forms = {
        Dml_Indicator: "SGF",
    }

    $.ajax({
        async: true,
        type: 'POST',
        url: "/Form_builder/GetGeneralForms",
        contentType: 'application/json; charset=UTF-8',
        data: JSON.stringify(forms),
        success: function (data) {
            debugger;
            var data2 = JSON.parse(data);
            if (jQuery.isEmptyObject((data2.data))) {

            }
            else {

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

                    var data1 = data2.data.Table;

                    var Form_Name;

                    var default_opt = '<option value="0">--Select--</option>';
                    $.each(data1, function (i, emp) {

                        Form_Name = Form_Name + '<option value="' + emp.Formid + '" data-id="' + emp.is_multiple + '">' + emp.Form_Name + '</option>';

                    });
                    $('#selectform').append(default_opt + Form_Name);
                    if (val != 0) {
                        $('#selectform').val(val).prop('disabled', true);;
                    }
                }
                else {
                    console.log(data);
                }
            }
        }
    });

}

$('#selectform').change(function () {
    debugger;
    var selectid = $('#selectform').val()
    selectedOptionText = $(this).find('option:selected').text();

    $('#formShow_header').html(selectedOptionText);

    $('#formShow').attr('src', $("#Hdformurl").val() + 'form/' + selectid + '?patientid=' + btoa(0) + '&visit_reportid=' + btoa(0) + '')


})

function generalformslist() {
    debugger;
  //  $('#shade_slot').show();

    var userid= 0 ;
    if ($("#hiddenRole_id").val() != 2) {
        userid=$("#hiddenUser_id").val()
    }

    var values = {
        Dml_Indicator: "LGF",
        Created_By: userid
    };

    $.ajax({
        async: true,
        type: 'POST',
        url: "/Form_builder/GetGeneralForms",
        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 = '';
            $('#tbl_generalformtbody').html(tr);
        }
        else {

            var b = data1.Table;
            $('#tbl_generalformtbody').empty();
            $('#generalforms_table').dataTable().fnClearTable();
            //$('#outsourceworkordertable').dataTable().fnDraw();
            $('#generalforms_table').dataTable().fnDestroy();
            tr = '';
             var j = 0, edit = '', del = '', other_info = '', print = '';

            $.each(b, function (i, emp) {
                j++;
                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=openformprint("' + emp.form_master_data_id + '")><i class="fa fa-print" aria-hidden="true"></i></a>';
                edit = '<a data-toggle="tooltip" title="Edit" class="btn btn-edit btn-xs" data-id="GF_E1" data-type="role_rights_edit" data-nav="sp_div" data-name="c_details_form"  href="javascript:void(0);"onclick="formedit(this,\'' + emp.form_master_data_id + '\', \'' + emp.Form_Name.replace(/'/g, "\\'") + '\', \'' + 0 + '\', \'' + 0 + '\', \'' + emp.Formid + '\', \'' + emp.AccessRightsUserid + '\', \'' + emp.formcreatedate + '\', \'' + emp.Module_Type + '\')"><i class="fa fa-pencil" aria-hidden="true"></i></a>';
                del = '<a  data-toggle="tooltip" title="Delete"  id="GFdel_" class="btn deleteicon-btn btn-xs"  data-id="GF_D1" data-type="role_rights_delete" data-nav="sp_delete" data-name="c_details_form"  href="javascript:void(0);" onclick="formdelete(this,\'' + emp.form_master_data_id + '\', \'' + emp.AccessRightsUserid + '\', \'' + emp.formcreatedate + '\', \'' + emp.Module_Type + '\')"><i class="fa fa-trash" aria-hidden="true"></i></a>';
                other_info = '<div class="col-md-12 padding0"><div class="disp_if">' + edit + ' ' + del + ' ' + print + '</div></div>'

                tr = tr + '<tr id="t_' + j + '"><td>' + j + '</td><td>' + emp.Date + '</td><td>' + emp.filled_by + '</td><td>' + emp.Form_Name + '</td>' + '<td>' + '<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>' + '<a data-toggle="tooltip" title="Edit" class="edit_icon" data-id="GF_E1" data-type="role_rights_edit" data-nav="sp_div" data-name="c_details_form"  href="javascript:void(0);"onclick="formedit(this,\'' + emp.form_master_data_id + '\', \'' + emp.Form_Name.replace(/'/g, "\\'") + '\', \'' + 0 + '\', \'' + 0 + '\', \'' + emp.Formid + '\', \'' + emp.AccessRightsUserid + '\', \'' + emp.formcreatedate + '\', \'' + emp.Module_Type + '\')"><i class="fa fa-pencil" aria-hidden="true"></i></a>' + '</li>' + '<li>' + '<a  data-toggle="tooltip" title="Delete"  id="GFdel_" class="delete_icon"  data-id="GF_D1" data-type="role_rights_delete" data-nav="sp_delete" data-name="c_details_form"  href="javascript:void(0);" onclick="formdelete(this,\'' + emp.form_master_data_id + '\', \'' + emp.AccessRightsUserid + '\', \'' + emp.formcreatedate + '\', \'' + emp.Module_Type + '\')"><i class="fa fa-trash" aria-hidden="true"></i></a>' + '</li>' + '</div>' + '<li>' + '<a data-toggle="tooltip" title="Print"  id="" class="btn_r"  data-id="" data-type="role_rights_function" data-nav="sp_div" data-name="c_details_form"  href="javascript:void(0);" onclick=openformprint("' + emp.form_master_data_id + '")>Print</a>' + '</a>' + '</li>' + '</ul>' + '</div>' + '</td>' +'</tr>';

                     //+ '<td>' + '<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>' + '<a data-toggle="tooltip" title="Edit" class="edit_icon" data-id="GF_E1" data-type="role_rights_edit" data-nav="sp_div" data-name="c_details_form"  href="javascript:void(0);"onclick="formedit(this,\'' + emp.form_master_data_id + '\', \'' + emp.Form_Name.replace(/'/g, "\\'") + '\', \'' + 0 + '\', \'' + 0 + '\', \'' + emp.Formid + '\', \'' + emp.AccessRightsUserid + '\', \'' + emp.formcreatedate + '\', \'' + emp.Module_Type + '\')"><i class="fa fa-pencil" aria-hidden="true"></i></a>' + '</li>' + '<li>' + '<a  data-toggle="tooltip" title="Delete"  id="GFdel_" class="delete_icon"  data-id="GF_D1" data-type="role_rights_delete" data-nav="sp_delete" data-name="c_details_form"  href="javascript:void(0);" onclick="formdelete(this,\'' + emp.form_master_data_id + '\', \'' + emp.AccessRightsUserid + '\', \'' + emp.formcreatedate + '\', \'' + emp.Module_Type + '\')"><i class="fa fa-trash" aria-hidden="true"></i></a>' + '</li>' + '</div>' + '<li>' + '<a data-toggle="tooltip" title="Print"  id="" class="btn_r"  data-id="" data-type="role_rights_function" data-nav="sp_div" data-name="c_details_form"  href="javascript:void(0);" onclick=openformprint("' + emp.form_master_data_id + '")>Print</a>' + '</a>' + '</li>' + '</ul>' + '</div>' + '</td>'

            });

            $('#tbl_generalformtbody').html(tr);

            datatable('generalforms_table');

        }
    }
}
    });
}
//formedit
function formedit(event, form_data_id, Form_name, patient_id, IsUpload, Formid, AccessRightsUserid, Form_CreatedDate, Module_Type) {
    var did = $(event).attr("data-id");
    var navigation = $(event).attr("data-nav");
    var name = $(event).attr("data-name");
    var columntype = $(event).attr("data-type");
    debugger;
    var chkprevilige = check_previlige(did, navigation, name, columntype);
    $.when(chkprevilige)
     .then(function (data) {
         var data1 = JSON.parse(data);
         if (data1.msg == "Success") {
             var data1 = data1.data;
             if (jQuery.isEmptyObject((data1))) {
             }
             else {
                 var j = 0;
                 var status = data1.Table[0].role_rights_add
                 if (status == 0) {

                     return;
                 }
                 else {
                     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) {
                         loadGeneralForms(Formid)
                             EditForm(form_data_id, Form_name, patient_id, IsUpload)
                     }
                     else if (accessRightsArray.includes($("#hiddenUser_id").val())) {
                         if (timeDifference < twentyFourHoursInMs && Module_Type == 7) {
                             loadGeneralForms(Formid)
                             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")
                     }
                 }
             }
         }
     });
}
//formdelete
function formdelete(event, Id, AccessRightsUserid, Form_CreatedDate, Module_Type) {
    debugger;
    var did = $(event).attr("data-id");
    var navigation = $(event).attr("data-nav");
    var name = $(event).attr("data-name");
    var columntype = $(event).attr("data-type");
    debugger;
    var chkprevilige = check_previlige(did, navigation, name, columntype);
    $.when(chkprevilige)
     .then(function (data) {
         var data1 = JSON.parse(data);
         if (data1.msg == "Success") {
             var data1 = data1.data;
             if (jQuery.isEmptyObject((data1))) {
             }
             else {
                 var j = 0;
                 var status = data1.Table[0].role_rights_add
                 if (status == 0) {

                     return;
                 }
                 else {
                     //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 || accessRightsArray.includes($("#hiddenUser_id").val())) {
                         if ($("#hiddenRole_id").val() == 2 || timeDifference < twentyFourHoursInMs && Module_Type == 7) {

                     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/GetGeneralForms",
                                           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");
                                               }
                                               generalformslist()
                                           }
                                       });
                                   });
                               }
                           })

                         }
                         else {
                             toastr.warning("No Rights to Access Delete")
                         }
                     }
                     else {
                         toastr.warning("No Rights to Access Delete")
                     }
                 }
             }
         }
     });

}
//print form 
function openformprint(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);
            //window.open(link, '_blank');   // to open in new window

            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);
            };
        }
    });
}