{% include 'base/test_nav_patient.html' %}

<link href="https://unpkg.com/bootstrap-table@1.22.1/dist/bootstrap-table.min.css"   rel="stylesheet">
<link href="https://cdn.jsdelivr.net/npm/bootstrap-icons@1.10.3/font/bootstrap-icons.css"   rel="stylesheet">
<script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
<script src="https://unpkg.com/tableexport.jquery.plugin/tableExport.min.js"  type="text/javascript" ></script>
<script src="https://unpkg.com/bootstrap-table@1.22.1/dist/bootstrap-table.min.js"  type="text/javascript" ></script>
<script src="https://unpkg.com/bootstrap-table@1.22.1/dist/extensions/export/bootstrap-table-export.min.js"  type="text/javascript" ></script> 



    {% comment %} <link rel="stylesheet" href="https://cdn1.ap-south-1.linodeobjects.com/resource/adminlte3/plugins/bootstrap5/css/bootstrap.min.css">
     {% endcomment %}

<style>
  .form-group{ padding-top: 10px;}
  .mar-top{
    margin-top:2rem;
    
   
  }
  .border{
    padding-left:1rem;
    padding-right:1rem;
    line-height: 136%;
  }
  .acc-pad{
    margin-top:11rem;
    padding-left:1rem;
    padding-right:1rem;
  }
  
  .form_align{
    display:flex;
    
    padding-left:1rem;
    padding-right:1rem;
    margin-top:13rem;
    width:auto;
 
  }
  .heading{
    display:flex;
    justify-content:center;

    
  }
  .line {
    line-height: 136%;
  }

  
  .pad{
    padding:1rem;
  }

  

</style>
{% if messages %}

<div class="toast-container position-fixed bottom-0 end-0 p-3">
  {% for message in messages %}
  <div id="liveToast" class="toast toast-entry " role="alert" aria-live="assertive" aria-atomic="true">
    <div class="toast-header">
      <strong class="me-auto">{{title}}</strong>
      <small>Notification</small>
      <button type="button" class="btn-close" data-bs-dismiss="toast" aria-label="Close"></button>
    </div>
    <div class="toast-body btn-{{message.tags}}">
      {{ message|safe }}
    </div>
  </div>
 {% endfor %}
</div> 
<script type="module">
    var toasts = document.getElementsByClassName("toast-entry");
    for (var i = 0; i < toasts.length; i++) {
      const toastLiveExample = toasts.item(i)
      const toastBootstrap = bootstrap.Toast.getOrCreateInstance(toastLiveExample)
      toastBootstrap.show()
    }
</script>  

{% endif %}

{% if 'Mobile' in request.META.HTTP_USER_AGENT %} 
<div class="acc-pad">
  {% if obj_help %}
<div class="accordion " id="accordionExample">
  <div class="accordion-item">
    <h2 class="accordion-header" id="headingOne">
      <button class="accordion-button" type="button" data-bs-toggle="collapse" data-bs-target="#collapseOne" aria-expanded="true" aria-controls="collapseOne">
       <center> {{obj_help.heading}}</center>
      </button>
    </h2>
    <div id="collapseOne" class="accordion-collapse collapse show" aria-labelledby="headingOne" data-bs-parent="#accordionExample">
      <div class="accordion-body">
        {{obj_help.content_HTML|safe}}
      </div>
    </div>
  </div>
  {% endif %}
</div>

<div class="p-2 border mar-top ">
  {% load bootstrap_tags %}

 {% load crispy_forms_tags %} 
   
     {% crispy form %}
     <br>
     <a type="reset" name="reset"  class="btn btn-warning"  href=".">Reset</a>
    </div>
    
</div>



{% else %}
<div class="form_align w-100   ">
  <div class=" w-50 from-margin pad border line " >
  {% load bootstrap_tags %}
  {% load crispy_forms_tags %} 

  {% comment %} <form method="post" enctype="multipart/form-data"> {% endcomment %}
  {% crispy form %}
  {% comment %} </form> {% endcomment %}
  <br>
  <a type="reset" name="reset"  class="btn btn-warning"  href=".">Reset</a>
  </div>

  <div class="border w-50 ">
    <div class="heading mt-3 " >
      <h3><b> {{obj_help.heading}}</b></h3>
    </div>

    <div class="p-4">
        <p>{{obj_help.content_HTML|safe}}<p>
    </div>
  </div>

</div>
{% endif %}


<h2 align="center" class="mt-5"> <b>{{tblname}}</b> </h2>
<div id="toolbar">
  <button id="remove" class="btn btn-danger " disabled>
    <i class="fa fa-trash"></i> Remove from View
  </button>
</div>
<table 
  id="table"
  data-toolbar="#toolbar"
  data-search="true"
  data-show-refresh="true"
  data-show-toggle="true"
  data-show-fullscreen="true"
  data-show-columns="true"
  data-show-columns-toggle-all="true"
  data-detail-view="true"
  data-show-export="true"
  data-click-to-select="true"
  data-detail-formatter="detailFormatter"
  data-minimum-count-columns="2"
  data-show-pagination-switch="true"
  data-pagination="true"
  data-id-field="id"
  data-page-list="[10, 25, 50, 100, all]"
  data-show-footer="true"
  data-side-pagination="server"
  data-url={{baseurl}}
  data-response-handler="responseHandler">
</table>



<script>
  var $table = $('#table')
  var $remove = $('#remove')
  var selections = []

  function getIdSelections() {
    return $.map($table.bootstrapTable('getSelections'), function (row) {
      return row.id
    })
  }

  function responseHandler(res) {
    $.each(res.rows, function (i, row) {
      row.state = $.inArray(row.id, selections) !== -1
    })
    return res
  }

  function detailFormatter(index, row) {
    var html = []
    $.each(row, function (key, value) {
      if(key =='tag_color'){html.push('<p><b>' + key + ':</b> <p style="background: '+ value +';"> ' + value + '</p>')}
      else {html.push('<p><b>' + key + ':</b> ' + value + '</p>')}
    })
    return html.join('')
  }

  function operateFormatter(value, row, index) {
    return [
    {% comment %} '<a class="edit" href="{{editurl}}' ,    row.id,    '"title="Edit">',
      '<i class="fa fa-pencil"></i>',
      '</a>  ',  
      '<a class="download" href="javascript:void(0)" title="download">',
      '<i class="fa fa-download" aria-hidden="true"></i>',
      '</a>  ',  
      '<a class="view" href="javascript:void(0)" title="view">',
        '<i class="fa fa-eye"></i>',
        '</a>  ',         
      '<a class="like" href="javascript:void(0)" title="Like">',
      '<i class="fa fa-heart"></i>',
      '</a>  ',  {% endcomment %}
      
      '<a class="remove" href="javascript:void(0)" title="Remove">',
      '<i class="fa fa-remove"></i>',
      '</a>   ',
      {% comment %} '<a class="delete" href="javascript:void(0)" title="Delete">',
        '<i class="fa fa-trash"></i>',
        '</a>   ' {% endcomment %}
    ].join('')
  }

  window.operateEvents = {
    'click .like': function (e, value, row, index) {
      alert('You click like action, row: ' + JSON.stringify(row))
    },
    'click .remove': function (e, value, row, index) {
      $table.bootstrapTable('remove', {
        field: 'id',
        values: [row.id]
      })
    },
    'click .delete': function (e, value, row, index) {
      if (confirm('{{request.user.username}}, You have requested for delete, Entry #'+ row.id) == true) {
        
       $.ajax({
          url: '{{request.path}}/'.replace('/tbl/','/delete/')+ row.id,
          type: "get", //send it through get method
          success: function(response) {
            if ( response == 'success') { alert('The model has been deleted!' );}
            else if ( response == 'nodata') {alert('The data is not available for deletion!' );}
            else if ( response == 'noauth') {alert('You are not authorized to delete this data!!!' );}
            else{alert('something went wrong, contact admin!' );}
          },
            error: function(xhr) {
              //Do Something to handle error
            }
            });          
    } else {
      alert('delete request canceled!');
    }
    },


  }

  function totalTextFormatter(data) {
    return 'Total'
  }

  function totalNameFormatter(data) {
    return data.length
  }

  function totalPriceFormatter(data) {
    var field = this.field
    return '$' + data.map(function (row) {
      return +row[field].substring(1)
    }).reduce(function (sum, i) {
      return sum + i
    }, 0)
  }

  function initTable() {
    var headers = {{jsoncolumn|safe}};//[{'header': 'state_name', 'title':'State Name'},{'header': 'countrycode', 'title':'countrycode'},{'header': 'country_name', 'title':'country_name'}]
    var column_data = []
    
    $.each(headers, function(i, item) {
        column_data.push({
            field: item.header,
            title: item.title,
            sortable: true,
            align: 'center'
          })
    });    

   var arry_config =   [   {
        field: 'state',
        checkbox: true,
        align: 'center',
        valign: 'middle'
      }, {
        field: 'id',
        title: 'id',
        sortable: true,
        footerFormatter: totalNameFormatter,
        align: 'center'
      }
    ]
    var arry_config2 =   [    {
        field: 'operate',
        title: 'Item Operate',
        align: 'center',
        clickToSelect: false,
        events: window.operateEvents,
        formatter: operateFormatter
      }
    ]    
    var arry_config3 =   arry_config.concat(column_data);
    var finalObj =   arry_config3.concat(arry_config2);
    $table.bootstrapTable('destroy').bootstrapTable({

      height: 550,
      locale: 'en-US',
      columns: finalObj,
      exportTypes: [ 'csv', 'txt', 'excel'],
      exportOptions: {
             fileName: function () {
            var currentdate = new Date(); 
          var datetime =    currentdate.getDate() + "_"
                          + (currentdate.getMonth()+1)  + "_" 
                          + currentdate.getFullYear() + "_"  
                          + currentdate.getHours() + "-"  
                          + currentdate.getMinutes() + "-" 
                          + currentdate.getSeconds();
           return '{{tblname}}' + '_export_'  + datetime;
        }
     },
    })
    $table.on('check.bs.table uncheck.bs.table ' +
      'check-all.bs.table uncheck-all.bs.table',
    function () {
      $remove.prop('disabled', !$table.bootstrapTable('getSelections').length)

      // save your data, here just save the current page
      selections = getIdSelections()
      // push or splice the selections if you want to save all data selections
    })
    $table.on('all.bs.table', function (e, name, args) {
      console.log(name, args)
    })
    $remove.click(function () {
      var ids = getIdSelections()
      $table.bootstrapTable('remove', {
        field: 'id',
        values: ids
      })
      $remove.prop('disabled', true)
    })
  }

  $(function() {
initTable()
  })
</script>



