//BedManagement JS//

$(document).ready(function () {

    if (($('#HBWardID').val() != null) && ($('#HBWardID').val() != '')) {
        loadBedPage();
        ShowBed();
        LoadFloor();
    }
});


function loadBed(event, val) {

    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 {
                     var Warddata = {
                         Bed_ID: val,
                         Dml_Indicator: "ID"
                     }

                     $.ajax({
                         async: true,
                         type: 'POST',
                         url: 'BedManagement_Ins_Upd',
                         contentType: 'application/json; charset=UTF-8',
                         data: JSON.stringify(Warddata),
                         success: function (data) {
                             var data2 = JSON.parse(data);
                             if (jQuery.isEmptyObject((data2.data))) {
                             }
                             else {

                                 if (data2.msg == "Success") {
                                     var data1 = data2.data;
                                     $.each(data1, function (i, emp) {

                                         $('#txtBedName').val(emp.Bed_Name),
                                         $('#txtBedDescription').val(emp.Bed_Description),
                                         $('#ddBedStatus').val(emp.Bed_Status),
                                         $('#HBWardID').val(emp.wardid),
                                         $('#HBedID').val(emp.bedid),
                                         $('#ddFloor').val(emp.bed_floorid),
                                         $('#btnBedAdd').val("update")
                                     });
                                 }
                                 else {
                                     console.log(data);
                                 }

                             }
                         }
                     });
                 }
             }
         }
     });
}

function loadBedPage() {
    debugger;
    var WardBeddata = {
        ward_id: $('#HBWardID').val(),
        Dml_Indicator: "WS"
    }

    $.ajax({
        async: true,
        type: 'POST',
        url: '/Ipmanagement/WardManagement_Ins_Upd_sel',
        contentType: 'application/json; charset=UTF-8',
        data: JSON.stringify(WardBeddata),
        success: function (data) {
            var data2 = JSON.parse(data);
            if (jQuery.isEmptyObject((data))) {
            }
            else {

                if (data2.msg == "Success") {
                    var data1 = data2.data;
                    $.each(data1.Table, function (i, emp) {
                        $('#txtWardIDName').val(emp.ward_id + "/" + emp.ward_name);
                        $('#HBedIDCont').val(emp.BedCount);
                        $('#HWardBedCount').val(emp.no_of_beds);
                        $('.TotalBed').html(emp.no_of_beds);
                        $('.RemBed').html(emp.BedCount);
                        $('.TotalBedCount').html("Ward Total Bed count is " + emp.no_of_beds);
                    });
                }
                else {
                    console.log(data);
                }

            }
        }
    });

}

function ShowBed() {
    var Beddata = {

        Dml_Indicator: "S",
        Ward_ID: $('#HBWardID').val()
    }

    $.ajax({
        async: true,
        type: 'POST',
        url: 'BedManagement_Ins_Upd',
        contentType: 'application/json; charset=UTF-8',
        data: JSON.stringify(Beddata),
        success: function (data) {
            $('#tblBedManagement').empty();
            var data2 = JSON.parse(data);
            if (jQuery.isEmptyObject(data)) {

            }
            else {

                if (data2.msg == "Success") {
                    var data1 = data2.data;

                    var BedStatus = '', BedAct_INAct = '', Delete = '';

                    tr = $('<table id="example1" class="table table-responsive table-bordered table-striped dataTable" />');

                    tr.append("<thead><tr><th>Ward ID / Name</th><th>Bed ID</th><th>Bed Name</th><th>Bed Description</th><th>Floor Name</th><th>Bed Status</th><th>Action</th></tr></thead><tbody>");

                    $.each(data1, function (i, emp) {

                        var view = '';



                        if (emp.Bed_Status == 'Active') {
                            BedStatus = '<span class="label label-success">Active</span>';
                            BedAct_INAct = "<a href=#  data-toggle='tooltip data-placement='bottom' title='Make In Active!' class='btn btn-info btn-xs' data-id='BD_E1' data-type='role_rights_edit' data-nav='sp_div' data-name='edit_Bed_form' onclick=BedAct_INAct('" + emp.bedid + "','inactive');><i class=' fa fa-minus-square-o' aria-hidden='true'></i></a>";
                            Delete = '<button type="button" class="btn btn-delete btn-xs" data-id="CD_D1" data-toggle="tooltip" data-placement="bottom" title="Delete" data-type="role_rights_delete" data-nav="sp_div" data-name="delete_ward_form" onclick="DeleteBed(' + emp.bedid + ');"><i class="fa fa-trash-o" aria-hidden="true"></i></button>';
                        }
                        else if (emp.Bed_Status == 'Inactive') {
                            BedStatus = '<span class="label label-danger">Inactive</span>';
                            BedAct_INAct = "<a href=#  data-toggle='tooltip data-placement='bottom' title='Make Active!' class='btn btn-info btn-xs' data-id='BD_E1' data-type='role_rights_edit' data-nav='sp_div' data-name='edit_Bed_form' onclick=BedAct_INAct('" + emp.bedid + "','active');><i class='fa fa-check-square-o' aria-hidden='true'></i></a>";
                            Delete = '<button type="button" class="btn btn-delete btn-xs" data-id="CD_D1" data-toggle="tooltip" data-placement="bottom" title="Delete" data-type="role_rights_delete" data-nav="sp_div" data-name="delete_ward_form" onclick="DeleteBed(' + emp.bedid + ');"><i class="fa fa-trash-o" aria-hidden="true"></i></button>';
                        }
                        else if (emp.Bed_Status == 'Occupied') {
                            //BedStatus = emp.Bed_Status;
                            BedStatus = '<span class="label btn-primary">Occupied</span>';
                            BedAct_INAct = "";
                            Delete = "";
                        }

                        if (emp.Bedstatus_id != 2) {
                            view = "<a href=# data-id='BD_E1' data-type='role_rights_edit' data-nav='sp_div' data-name='edit_bed_form' class='label label-success'onclick=loadBed(this,'" + emp.bedid + "');>Edit</a>";
                        }

                        //Del = "<span class='label label-danger'><a href=#  onclick=DeledeBed('" + emp.Bed_ID + "');>Delete</span></a>";

                        row_data = "<tr><td>" + emp.Ward_ID + " / " + emp.Ward_Name + "</td><td>" + emp.Bed_ID + "</td><td>" + emp.Bed_Name + "</td><td>" + emp.Bed_Description + "</td><td>" + emp.floor_name + "</td><td>" + BedStatus + "</td><td>" + view + " " + BedAct_INAct + " " + Delete + "</td></tr>";
                        tr.append(row_data);
                    });
                    tr.append("</tbody></table>");
                    $('#tblBedManagement').html(tr);

                    var table = $('#example1').DataTable({

                    });
                    $('a.toggle-vis').on('click', function (e) {
                        e.preventDefault();

                        var column = table.column($(this).attr('data-column'));
                        column.visible(!column.visible());
                    });
                }
                else {
                    console.log(data);
                }

            }
        },
        error: function (data) {
            toastr.warning('some issue');
        }
    });
}

function clearBed() {
    $('#txtBedName').val(""),
    $('#txtBedDescription').val(""),
    $('#ddBedStatus').val("1"),
    $('#btnBedAdd').val(""),
    $('#HBedID').val(''),
    $('#ddFloor').val('')
}

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

    if ($.trim($('#txtBedName').val()) == "") {
        $('#PtxtBedName').show();
        $('#PtxtBedName').fadeOut(8000);
        $('#PtxtBedName').html('Enter The Bed Name');
        $('#txtBedName').focus();
        $('#txtBedName').val('');
        return false;
    }

    var Beddata = {
        Ward_ID: $('#HBWardID').val(),
        Bed_ID: $('#HBedID').val(),
        Bed_Name: $('#txtBedName').val(),
        Bed_Description: $('#txtBedDescription').val(),
        Bed_Status: $('#ddBedStatus').val(),
        Dml_Indicator: "I",
        Ward_category: $('#HBWard_category').val(),
        floorid: $('#ddFloor').val()
    }

    var WardBedCount = parseInt($('#HWardBedCount').val());
    var BedIDCont = parseInt($('#HBedIDCont').val());

    if ((WardBedCount > BedIDCont) || ($('#btnBedAdd').val() == "update")) {
        $.ajax({
            async: true,
            type: 'POST',
            url: 'BedManagement_Ins_Upd',
            contentType: 'application/json; charset=UTF-8',
            data: JSON.stringify(Beddata),
            success: function (data) {

                var data2 = JSON.parse(data);
                if (data2.msg == "Success") {
                    debugger;
                    var data1 = data2.data;
                    var Error = '';

                    $.each(data1, function (i, emp) {
                        Error = emp.Message;
                    });

                    if (Error == 'Already Exists') {
                        toastr.warning('Bed Name Already Exists',
                            {
                                //closeButton: false,
                                progressBar: true,
                                allowHtml: true,
                                timeOut: 0,
                            });
                        return false;
                    }

                    if ($('#btnBedAdd').val() == "update") {
                        toastr.success('Bed Details Updated Successfully',
                        {
                            //closeButton: false,
                            progressBar: true,
                            allowHtml: true,
                            timeOut: 0,
                        });
                    }
                    else {
                        toastr.success('Bed Details Added Successfully',
                       {
                           //closeButton: false,
                           progressBar: true,
                           allowHtml: true,
                           timeOut: 0,
                       });
                    }
                    clearBed();
                    loadBedPage();
                    ShowBed();
                    
                }
                else {
                    console.log(data);
                }   
            },
            error: function (data) {
            }
        });
    }
    else {
        toastr.warning("Bed limit exceeded for this ward.");
    }

});

function DeleteBed(bedid) {


    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>", 'Are You sure,You want to Delete the Bed?',
        {
            closeButton: true,
            progressBar: true,
            allowHtml: true,
            timeOut: 0,

            onShown: function (toast) {
                $("#confirmationRevertYes").click(function () {

                    var AR_data = {
                        Bed_ID: bedid,
                        Dml_Indicator: "BMDEL",
                    }

                    $.ajax({
                        async: true,
                        type: 'POST',
                        url: 'BedManagement_Ins_Upd',
                        contentType: 'application/json; charset=UTF-8',
                        data: JSON.stringify(AR_data),
                        success: function (data) {

                            var data1 = JSON.parse(data);
                            if (jQuery.isEmptyObject((data1))) {
                            }
                            else {

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

                                    toastr.success('Bed Deleted Successfully',
                                     {
                                         //closeButton: false,
                                         progressBar: true,
                                         allowHtml: true,
                                         timeOut: 0,
                                     });
                                    loadBedPage();
                                    ShowBed();
                                }
                                else {
                                    console.log(data);
                                }
                            }
                        }
                    });
                });
            }
        });

}

function BedAct_INAct(val, Dml_Indicator) {
    debugger;

    var status = "";
    if (Dml_Indicator == 'active') {
        status = "Are You Sure, You Want to Activate Bed?";
    }
    else {

        status = "Are You Sure, You Want to In-activate Bed?";
    }
    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: 0,

          onShown: function (toast) {
              debugger
              $("#confirmationRevertYes").click(function () {
                  debugger
                  var Parameter = {
                      Bed_ID: val,
                      Dml_Indicator: Dml_Indicator,
                  }

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

                          }
                          else {

                              if (data2.msg == "Success") {
                                  var data1 = data2.data;

                                  if (Dml_Indicator == 'active') {
                                      toastr.success("Bed Activated Successfully");
                                      setTimeout(function () {

                                      }, 1000);
                                  }
                                  else {
                                      toastr.success("Bed In-activated Successfully");
                                      setTimeout(function () {

                                      }, 1000);
                                  }

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

              });
          }
      });

}

function LoadFloor() {
    var Warddata = {
        Dml_Indicator: "WFS",
        //branch_id: $('#ip_branch_id').val()//Medway all branch concept
    }

    $.ajax({
        async: true,
        type: 'POST',
        url: '/Ipmanagement/WardManagement_Ins_Upd_sel',
        contentType: 'application/json; charset=UTF-8',
        data: JSON.stringify(Warddata),
        success: function (data) {
            $('#ddFloor').empty();
            var data2 = JSON.parse(data);
            if (jQuery.isEmptyObject((data2.data))) {

            }
            else {

                if (data2.msg == "Success") {
                    var data1 = data2.data;
                    var Floor;


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

                        Floor = Floor + '<option value="' + emp.master_servie_type_id + '">' + emp.master_service_name + '</option>';

                    });
                    $('#ddFloor').append(default_opt + Floor);
                    if ($('#HWardID').val() != '') {
                        $('#ddFloor').val($('#Hdnfloorid').val());
                    }
                }
                else {
                    console.log(data);
                }
            }
        }
    });
}