{% extends 'pos_base.html' %}
{% block tailhead %}
<script src="https://cdn.jsdelivr.net/npm/chart.js"></script>
<script type="text/javascript" src="https://cdn.jsdelivr.net/jquery/latest/jquery.min.js"></script>
<script type="text/javascript" src="https://cdn.jsdelivr.net/momentjs/latest/moment.min.js"></script>
<script type="text/javascript" src="https://cdn.jsdelivr.net/npm/daterangepicker/daterangepicker.min.js"></script>
<link rel="stylesheet" type="text/css" href="https://cdn.jsdelivr.net/npm/daterangepicker/daterangepicker.css" />
{% endblock tailhead %}
{% block content %}
{% include 'navbar.html' %}
<div class="container">
  <div class='row'>
    <div class="col-8 ">
      <div class="dropdown">
        <button class="btn btn-secondary dropdown-toggle" type="button" id="dropdownMenuButton" data-toggle="dropdown" aria-haspopup="true" aria-expanded="false">
          ยอดรวมวันนี้
        </button>
        <div class="dropdown-menu" aria-labelledby="dropdownMenuButton" id='areaDropdown'>
          <a class="dropdown-item" id='week' href="#" onclick='setshow(this)'>1สัปดาห์(7วันก่อนหน้า)</a>
          <a class="dropdown-item" id='month' href="#" onclick='setshow(this)'>1เดือน(30วันก่อนหน้า)</a>
          {% comment %} 
          no onclick send param by postMethod ,no recive postMethod to make something in views.py
          <a class="dropdown-item" href="#" onclick='showOption(this)'>เลือกช่วงเวลา</a> {% endcomment %}
        </div>
      </div>
    </div>
    <div class="col-4 ">
       
                <a class="nav-link" href="{% url 'download' today_filename%}" id='download'>download</a>
    </div>
  </div>
</div>



<div class="container">

  <div class='d-none' id="reportrange" style="background: #fff; cursor: pointer; padding: 5px 10px; border: 1px solid #ccc; max-width: 250px">
      <i class="fa fa-calendar"></i>&nbsp;
      <span></span> 
      <i class="fa fa-caret-down"></i>
      
  </div>
  
</div>

<div class="px-5 mx-5">
  <div class="px-5 mx-5 d-none" id='divChart'>
    <div>
      <canvas id="myChart"></canvas>
    </div>
  </div>

  <table class="table" id='todayTable'>
      <thead>
          <tr>
              <th onclick="sortTodayTable(0)" class='w-20'>รหัสสินค้า
                  {% comment %} <i class="bi bi-chevron-down"></i> {% endcomment %}
                  {% comment %} <i class="bi bi-chevron-up"></i> {% endcomment %}
              </th>
              <th onclick="sortTodayTable(1)" class='w-20'>ชื่อสินค้า</th>
              <th onclick="sortTodayTable(2)" class='w-20'>ราคาขาย</th>
              <th onclick="sortTodayTable(3)" class='w-20'>จำนวนการขาย</th>
              <th onclick="sortTodayTable(4)" class='w-20'>มูลค่า</th>
          </tr>
      </thead>
      <tbody>
          {% for key,value in today.items %}
              <tr>
                  <td> {{ value.id }} </td>
                  <td> {{ value.name }} </td>
                  <td> {{ value.price }} </td>
                  <td> {{ value.sold }} </td> 
                  <td> {{ value.value }} </td> 
              </tr>
          {% endfor %}
      </tbody>
  </table>

  <table class="table d-none" id='weekTable'>
      <thead>
          <tr>
              <th onclick="sortWeekTable(0)" class='w-20 p-0'>รหัสสินค้า</th>
              <th onclick="sortWeekTable(1)" class='w-20 p-0'>ชื่อสินค้า</th>
              <th onclick="sortWeekTable(2)" class='w-10 p-0'>ราคาขาย</th>
              <th onclick="sortWeekTable(3)" class='w-10 p-0'>จำนวนการขาย</th>
              <th onclick="sortWeekTable(4)" class='w-10 p-0'>มูลค่า</th>
              <th onclick="sortWeekTable(5)" class='w-20 p-0'>จำนวนการขายเฉลี่ยต่อวัน</th>
              <th onclick="sortWeekTable(6)" class='w-10 p-0'>มูลค่าเฉลี่ยต่อวัน</th>
          </tr>
      </thead>
      <tbody>
          {% for key,value in week.dataProduct.items %}
              <tr>
                  <td> {{ value.id }} </td>
                  <td> {{ value.name }} </td>
                  <td> {{ value.price }} </td>
                  <td> {{ value.sold }} </td>
                  <td> {{ value.value }} </td> 
                  <td> {{ value.soldperday}} </td> 
                  <td> {{ value.valueperday }} </td> 
              </tr>
          {% endfor %}
      </tbody>
  </table> 

  <table class="table d-none" id='monthTable'>
      <thead>
          <tr>
              <th onclick="sortMonthTable(0)" class='w-20 p-0'>รหัสสินค้า
                  {% comment %} <i class="bi bi-chevron-down"></i> {% endcomment %}
                  {% comment %} <i class="bi bi-chevron-up"></i> {% endcomment %}
              </th>
              <th onclick="sortMonthTable(1)" class='w-20 p-0'>ชื่อสินค้า</th>
              <th onclick="sortMonthTable(2)" class='w-10 p-0'>ราคาขาย</th>
              <th onclick="sortMonthTable(3)" class='w-10 p-0'>จำนวนการขาย</th>
              <th onclick="sortMonthTable(4)" class='w-10 p-0'>มูลค่า</th>
              <th onclick="sortMonthTable(5)" class='w-20 p-0'>จำนวนการขายเฉลี่ยต่อวัน</th>
              <th onclick="sortMonthTable(6)" class='w-10 p-0'>มูลค่าเฉลี่ยต่อวัน</th>
          </tr>
      </thead>
      <tbody>
          {% for key,value in month.dataProduct.items %}
              <tr>
                  <td> {{ value.id }} </td>
                  <td> {{ value.name }} </td>
                  <td> {{ value.price }} </td>
                  <td> {{ value.sold }} </td>
                  <td> {{ value.value }} </td> 
                  <td> {{ value.soldperday}} </td> 
                  <td> {{ value.valueperday }} </td> 
              </tr>
          {% endfor %}
      </tbody>
  </table>

</div>


<script src="https://cdn.jsdelivr.net/npm/chart.js"></script>
<script type="text/javascript" src="https://cdn.jsdelivr.net/jquery/latest/jquery.min.js"></script>
<script type="text/javascript" src="https://cdn.jsdelivr.net/momentjs/latest/moment.min.js"></script>
<script type="text/javascript" src="https://cdn.jsdelivr.net/npm/daterangepicker/daterangepicker.min.js"></script>
<script>
var atoday = $('<a class="dropdown-item" href="' + {% url 'dashboard' %} + '">ยอดรวมวันนี้</a>');
var tmpa = ''



var start = moment().subtract(1, 'months');
var end = moment();

function cb(start, end) {
    $('#reportrange span').html(start.format('MMMM D, YYYY') + ' - ' + end.format('MMMM D, YYYY'));
}

$('#reportrange').daterangepicker({
    startDate: start,
    endDate: end,
    
}, cb);

cb(start, end);

function managebtnDropdown(element){
  if (tmpa == ''){
  $('#areaDropdown').append(atoday)
  tmpa = element.cloneNode(true)
  }else{
    $('#areaDropdown').append(tmpa)
    tmpa = element.cloneNode(true)
  }
  $('#dropdownMenuButton').text(element.innerHTML)
  element.remove()
}

function setshow(element){
  // data and hide table 4 column show table by id
  console.log(element.id)
  managebtnDropdown(element)
  $('#todayTable').addClass('d-none')

  $('table').each( function(){
    var t = $(this);
    var idChart = '#'+t.attr('id').replace('Table','Chart');
    //console.log(idChart)
    if(t.attr('id') == element.id+'Table'){
      t.removeClass('d-none');
      //$(idChart).removeClass('d-none');

      if(element.id=='week'){
        showChart(w_labels,w_data,w_avg)
        $('#download').attr('href',"{% url 'download' last_week_filename%}")

      }
      if(element.id=='month'){
        showChart(m_labels,m_data,m_avg)
        $('#download').attr('href',"{% url 'download' last_month_filename%}")
      }
    }else{
      t.addClass('d-none')
      //$(idChart).addClass('d-none')
    }
  })
  
  $('#'+element.id+'table').removeClass('d-none')
  $("#reportrange").addClass('d-none')
}

function showOption(element){
  managebtnDropdown(element)
  $("#reportrange").removeClass('d-none')
  }

function sortTodayTable(n){
  sortTable('todayTable',n)
  }
function sortWeekTable(n){
  sortTable('weekTable',n)
  }
function sortMonthTable(n){
  sortTable('monthTable',n)
  }
function sortTable(idTable,n) {
  var table, rows, switching, i, x, y, shouldSwitch, dir, switchcount = 0;
  table = document.getElementById(idTable);
  switching = true;


  $('.bi-chevron-down').remove();
  $('.bi-chevron-up').remove();

  //Set the sorting direction to ascending:
  dir = "asc"; 
  /*Make a loop that will continue until
  no switching has been done:*/
  while (switching) {
    //start by saying: no switching is done:
    switching = false;
    rows = table.rows;
    
    /*Loop through all table rows (except the
    first, which contains table headers):*/
    for (i = 1; i < (rows.length - 1); i++) {
      //start by saying there should be no switching:
      shouldSwitch = false;
      /*Get the two elements you want to compare,
      one from current row and one from the next:*/
      x = rows[i].getElementsByTagName("TD")[n];
      y = rows[i + 1].getElementsByTagName("TD")[n];
      

      /*check if the two rows should switch place,
      based on the direction, asc or desc:*/
      if (dir == "asc") {
        if (Number(x.innerHTML)) {
            if (Number(x.innerHTML) > Number(y.innerHTML)) {
            shouldSwitch = true;
            break;
            }
        }else{
            if (x.innerHTML.toLowerCase() > y.innerHTML.toLowerCase()) {
            //if so, mark as a switch and break the loop:
            shouldSwitch = true;
            break;
            }
        }
      } else if (dir == "desc") {
        if (Number(x.innerHTML)) {
            if (Number(x.innerHTML) < Number(y.innerHTML)) {
            shouldSwitch = true;
            break;
            }
        }else{
            if (x.innerHTML.toLowerCase() < y.innerHTML.toLowerCase()) {
            //if so, mark as a switch and break the loop:
            shouldSwitch = true;
            break;
            }
        }
      }
    }
    if (shouldSwitch) {
      /*If a switch has been marked, make the switch
      and mark that a switch has been done:*/
      rows[i].parentNode.insertBefore(rows[i + 1], rows[i]);
      switching = true;
      //Each time a switch is done, increase this count by 1:
      switchcount ++;      
      
    } else {
      /*If no switching has been done AND the direction is "asc",
      set the direction to "desc" and run the while loop again.*/
      if (switchcount == 0 && dir == "asc") {
        dir = "desc";
        switching = true;
      }else{
        if (dir=='desc'){
          rows[0].getElementsByTagName('th')[n].innerHTML += '<i class="bi bi-chevron-down"></i>' 
        }else{
          rows[0].getElementsByTagName('th')[n].innerHTML += '<i class="bi bi-chevron-up"></i>'
        }
        
      }
    }
  }
  }
var myChart = null;
function showChart(l,d,a){
  
  const labels = l
  const data = {
  labels: labels,
  datasets: [{
    label: 'มูลค่าการขาย',
    backgroundColor: 'rgb(255, 99, 132)',
    borderColor: 'rgb(255, 99, 132)',
    borderColor: 'rgb(255, 99, 132)',
    pointBackgroundColor:'rgb(0,0,255)',
    data: d,
    },{
      label: 'มูลค่าการขายเฉลี่ย',
      backgroundColor: 'rgb(204, 204, 204)',
      //borderColor: 'rgb(0, 0, 255)',
      pointBackgroundColor:'rgb(51,51,51)',
      borderColor: 'rgb(51,51,51)',
      fill: true,
      data: a,
      borderDashOffset:5,
      borderDash:[10]
    },]
  };
  const config = {
    type: 'line',
    data,
    options: {}
  };
  try {
      myChart = new Chart(
        document.getElementById('myChart'),
        config
      );
    }
    catch(err) {
      myChart.destroy();
      myChart = new Chart(
        document.getElementById('myChart'),
        config
      );
    }
  $('#divChart').removeClass('d-none')

}

const w_labels = {{week.labels|safe}};
const w_data = {{week.data}};
const w_avg = {{week.avgSoldValue}};


const m_labels = {{month.labels|safe}};
const m_data = {{month.data}};
const m_avg = {{month.avgSoldValue}};



</script>

{% endblock content %}