{% extends 'base.html' %}
{% load crispy_forms_tags %}
{% load humanize %}
{% block title %}Invoice{% endblock title %}

{% block body %}
 

    <div class="container-fluid">
        <form action="" method="POST" class="card border-info-subtle p-3 mt-2" autocomplete="off" id="form">
            {% csrf_token %}
            <div class="row">
            </div>
            <!-- <input name="customer_fullname" type='text' list='itemname' onchange='changeitem(event)' value='{{customer_name}}' class='textinput form-control'> -->
            <input name="customerreffullname" type='text' list='itemname'  value='{{customer_name}}' id='id_CustomerRefFullName' class='textinput form-control' placeholder="Choose Customer" autofocus>
                    
            <button type="submit" class="btn btn-primary mt-2 me-2 ms-2" id="id_btnsave" onclick="checksubmit(event)">Save</button>
            <!-- <button type="submit" class="btn btn-primary mt-2 me-2 ms-2" id="id_btnsave" >Save</button> -->
        </form>
    </div>
           
    <datalist id='itemname'>
        {% for customer in customers %}
        <option value="{{customer|first}}" data-pk="{{customer|first}}" data-desc="{{customer|first}}" data-rate="{{customer|first}}">
        {% endfor %}
    </datalist>

<!-- 
<script>
  document.getElementById('id_CustomerRefFullName').addEventListener('focusout', function() {
    console.log(this.value);
    if (this.value == '') {
      return};
    let str='';
    let url="{% url 'Invoice:getpricelist' %}"+this.value
    console.log(url)
    fetch(url)
      .then((response) => {
        return response.json(); 
      })
      .then((data) => {
        //console.log(data);
        data=JSON.parse(data);
        let dt=JSON.parse(data['itemdatalist']);
        console.log(dt)
        console.log(dt.length)

        for (let k=0;k<dt.length;k++){
          //console.log(dt[k]);
          //console.log("dt[k]")
          if (dt[k].itempricelevel__Price) {
            str+='<option value="' + dt[k].FullName + '" data-pk="' + dt[k].id + '" data-desc="' + dt[k].SalesDesc + '" data-rate="' + dt[k].itempricelevel__Price + '">';
          } else {
            str+='<option value="' + dt[k].FullName + '" data-pk="' + dt[k].id + '" data-desc="' + dt[k].SalesDesc + '" data-rate="' + dt[k].SalesPrice + '">';
          }
        }
        //console.log(str);
        dt=JSON.parse(data['obj']);
        console.log(dt)
        console.log(dt.length)
        document.getElementById('itemname').innerHTML = str;

        str='';
        for (let k=0;k<dt.length;k++){
          console.log(dt[0].pk);
          console.log(dt[0].fields.BillAddr1);
          
          str= dt[0].fields.BillAddr1;
          if (dt[0].fields.BillAddr2) {str+="\n"+dt[0].fields.BillAddr2}
          if (dt[0].fields.BillAddr3) {str+="\n"+dt[0].fields.BillAddr3}
          if (dt[0].fields.BillAddr4) {str+="\n"+dt[0].fields.BillAddr4}
          if (dt[0].fields.BillAddr5) {str+="\n"+dt[0].fields.BillAddr5}
          document.getElementById('id_BillAddr1').value = str
          str=dt[0].fields.ShipAddr1;
          if (dt[0].fields.ShipAddr2) {str+="\n"+dt[0].fields.ShipAddr2}
          if (dt[0].fields.ShipAddr3) {str+="\n"+dt[0].fields.ShipAddr3}
          if (dt[0].fields.ShipAddr4) {str+="\n"+dt[0].fields.ShipAddr4}
          if (dt[0].fields.ShipAddr5) {str+="\n"+dt[0].fields.ShipAddr5}
          document.getElementById('id_ShipAddr1').value = str;
          //document.getElementById('id_ShipAddr1').value = dt[0].fields.ShipAddr1;
        }

      });
    console.log(str)
    //for (let i=0;i<12;i++){
    //  str+= '<option value="' + i + '">';
    //}
    //document.getElementById('itemname').innerHTML = str;
  });
  function customerChanged(e){
    console.log(e)
  }
</script> -->
<script>
  function number_format( number, decimals, dec_point, thousands_sep ) {
    // http://kevin.vanzonneveld.net
    // +   original by: Jonas Raoni Soares Silva (http://www.jsfromhell.com)
    // +   improved by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)
    // +	 bugfix by: Michael White (http://crestidg.com)
    // +	 bugfix by: Benjamin Lupton
    // +	 bugfix by: Allan Jensen (http://www.winternet.no)
    // +	revised by: Jonas Raoni Soares Silva (http://www.jsfromhell.com)
    // *	 example 1: number_format(1234.5678, 2, '.', '');
    // *	 returns 1: 1234.57
  
    var n = number, c = isNaN(decimals = Math.abs(decimals)) ? 2 : decimals;
    var d = dec_point == undefined ? "," : dec_point;
    var t = thousands_sep == undefined ? "." : thousands_sep, s = n < 0 ? "-" : "";
    var i = parseInt(n = Math.abs(+n || 0).toFixed(c)) + "", j = (j = i.length) > 3 ? j % 3 : 0;
  
    return s + (j ? i.substr(0, j) + t : "") + i.substr(j).replace(/(\d{3})(?=\d)/g, "$1" + t) + (c ? d + Math.abs(n - i).toFixed(c).slice(2) : "");
  }
</script>
<script>
    var totalAmount = 0;
    var boloktosave = 0;

    function revert(){
      document.getElementById("form").reset();
      findTotalAmount()
    }

    function numberOnly(event){
      //console.log(event.cancelable);
      if ((event.charCode >= 48 && event.charCode <= 57) || event.charCode==46) {
        //console.log("true");
        return true;
      } else {
        //console.log("false");
        event.preventDefault();
        return false;
      }
    }

    function checksubmit(e){
      console.log('boloktosave:' + boloktosave);
    //   if (boloktosave==0) {
    //     console.log("prevented")
    //     e.preventDefault();
    //     return false;
    //   }
      const customerreffullname = document.getElementById('id_CustomerRefFullName');
      if (!customerreffullname.value){
        console.log('customer is empty');
        e.preventDefault();
        return false

      }
      const inputitem = document.getElementsByClassName('inputitem');
      const inputValue=document.getElementById('id_CustomerRefFullName').value;
      const dtlist = document.getElementById('itemname');
      console.log(inputValue)
      const selectedOption = dtlist.querySelector('option[value="' + inputValue + '"]');
      console.log("selected option:")
      console.log(selectedOption);
      if (!selectedOption) {
        console.log("not correct custname")
        e.preventDefault();
        return false
      }
      

    //   for (let i=0; i<inputitem.length;i++) {
    //     if (!inputitem[i].value){
    //       console.log(getElementByElEventClass(inputitem[i], "checkboxinput").checked)
    //       if (getElementByElEventClass(inputitem[i], "checkboxinput").checked==true) {
    //         continue;
    //       };
    //       //console.log()
    //       console.log("ItemRefFullName cannot be empty");
    //       alert('ItemRefFullName cannot be empty');
    //       console.log(i);
    //       console.log(inputitem[i]);
    //       inputitem[i].focus();
    //       e.preventDefault();
    //       return false
    //     }
    //   }
      console.log("submitted")
    }

    function changeitem(e) {
        console.log(e.cancelable);
        const inputValue=e.target.value;
        console.log("inputval="+inputValue);
        const dtlist = document.getElementById('itemname');
        const selectedOption = dtlist.querySelector('option[value="' + inputValue + '"]');
        console.log(selectedOption)
        
        if (!selectedOption && e.target.value!="") {
          console.log("cannot find item")
          //e.preventDefault;
          boloktosave=0;
          e.target.focus();
          e.target.onblur= function() {
            setTimeout(function() {
                e.target.focus();
            }, 0);
          };
          return false;
        }
        if (e.target.value=="" || !e.target.value){
          boloktosave=0;
          return false;
        }
        e.target.onblur="";
        boloktosave=1;
        const datasetPK = selectedOption.dataset.pk;
        const datasetDesc = selectedOption.dataset.desc;
        const datasetRate = selectedOption.dataset.rate;
        console.log(datasetPK, datasetDesc, datasetRate);
        const targetELParent = e.target.parentElement.parentElement.parentElement;
        console.log(targetELParent);
        //const targetELParent = e.target.parentElement.parentElement;
        //const targetELItemRef = targetELParent.nextElementSibling.children[0].children[1];
        const targetELItemRef = targetELParent.getElementsByClassName('itemreffullname')[0];
        console.log(targetELItemRef);
        targetELItemRef.value = datasetPK;
        //const targetELDesc = targetELParent.nextElementSibling.nextElementSibling.children[0].children[1];
        const targetELDesc = getElementByElEventClass(e, "desc");
        //const targetELDesc = targetELParent.getElementsByClassName('desc')[0];
        console.log(targetELDesc);
        targetELDesc.value = datasetDesc;
        //const targetELRate = targetELParent.nextElementSibling.nextElementSibling.nextElementSibling.nextElementSibling.nextElementSibling.children[0].children[1];
        const targetELRate = getElementByElEventClass(e, "rate");
        //const targetELRate = targetELParent.getElementsByClassName('rate')[0];
        console.log(targetELRate);
        targetELRate.value = parseFloat(datasetRate).toFixed(2);
        //const targetELAmount = targetELParent.nextElementSibling.nextElementSibling.nextElementSibling.nextElementSibling.nextElementSibling.nextElementSibling.children[0].children[1];
        const targetELAmount = getElementByElEventClass(e, "amount");
        //const targetELAmount = targetELParent.getElementsByClassName('amount')[0];
        //const qty = targetELParent.nextElementSibling.nextElementSibling.nextElementSibling.children[0].children[1].value;
        const qtyEL = getElementByElEventClass(e, "quantity");
        //const qtyEL = targetELParent.getElementsByClassName('quantity')[0];
        console.log(qtyEL.value);
        if (!qtyEL.value){
          qtyEL.value=1;
        }
        targetELAmount.value=(qtyEL.value*parseFloat(datasetRate)).toFixed(2)
        findTotalAmount();
    }

    function findTotalAmount() {
      let arr=document.getElementsByClassName('amount');
      let tot=0;
      for(let i=0;i<arr.length;i++){
        if(parseFloat(arr[i].value)) {
          tot += parseFloat(arr[i].value);
        }
      }
      console.log(tot);
      const totalamountEL=document.getElementById('id_TotalAmount');
      const dividtotalamountEL = document.getElementById('div_id_TotalAmount');
      const totFormated = number_format(tot,"2",".",",");
      console.log(totFormated);
      console.log(dividtotalamountEL)
      dividtotalamountEL.innerHTML = totFormated;
      console.log(dividtotalamountEL.innerHTML)
      totalamountEL.value=tot;
    }

    function descchanged(e) {
      boloktosave=1;
    }
    function qtychanged(e) {
      console.log(e);
      let qty=e.target.value;
      console.log(qty);
      if (!qty) {
        qty=1;
        e.target.value=qty;
      } else if (qty<0) {
        qty=0;
        e.target.value=qty;
      }
      const rate=getElementByElEventClass(e, "rate").value;

      //const rate=e.target.parentElement.parentElement.nextElementSibling.nextElementSibling.children[0].children[1].value;
      console.log(rate * qty);
      let amountValue=rate*qty;
      const amount=getElementByElEventClass(e, "amount")
      //let amount=e.target.parentElement.parentElement.nextElementSibling.nextElementSibling.nextElementSibling.children[0].children[1];
      console.log(amount);
      amount.value=amountValue.toFixed(2);
      findTotalAmount();
      boloktosave=1;
    }

    function ratechanged(e) {
      console.log(e);
      let rate=e.target.value;
      console.log(rate);
      if (!rate){
        rate=0;
        e.target.value=0;
      } else if(rate<0){
        rate=0;
        e.target.value=0;
      }
      const qty=getElementByElEventClass(e, "quantity").value;
      //const qty=e.target.parentElement.parentElement.previousElementSibling.previousElementSibling.children[0].children[1].value;
      console.log("qty"+qty);
      let amountValue=rate*qty;
      console.log(amountValue);
      const amount=getElementByElEventClass(e,"amount");
      //const amount=e.target.parentElement.parentElement.nextElementSibling.children[0].children[1];
      console.log(amount);
      amount.value=amountValue.toFixed(2);
      console.log(amount.value);
      findTotalAmount();
      boloktosave=1;
    }

    function amountchanged(e) {
      console.log(e);
      let amount=e.target.value;
      if (!amount){
        amount=0;
        e.target.value=0;
      } else if(amount<0){
        amount=0;
        e.target.value=0;
        alert("Amount cannot be a negative value.")
      }
      const qty=getElementByElEventClass(e, "quantity");
      console.log(qty.value);
      if (qty.value){
        const rateEL=getElementByElEventClass(e, "rate")
        if (qty.value>0){
          rateEL.value=(amount/qty.value).toFixed(2)
          
        } else {
          qty.value=(amount/rateEL.value).toFixed(2)
        }
        findTotalAmount();
        boloktosave=1;
      }
    }

    function getElementByElEventClass(e, classname){
      let parent;
      console.log("eventclaaaaaaasss");
      console.log("eventclass",e,classname)
      if (e.target){
        parent = e.target.parentElement;
      }
      else {
        parent = e.parentElement;
      }
      console.log(parent);
      console.log(e, classname);
      while (!parent.classList.contains('parentrow')){
        parent = parent.parentElement;
      }
      console.log(parent);
      //const parent=e.target.parentElement.parentElement.parentElement;
      console.log(parent);
      const el=parent.getElementsByClassName(classname)[0];
      console.log(el);
      return el;
    }

    function deletechanged(e){
      console.log("DELETEEEEE")
      boloktosave=1;
      findTotalAmount();
    }
</script>
<script>
    document.addEventListener('click', (event)=>{
        if (event.target.id == 'add-more') {
            console.log("addmore clicked")
            add_new_form(event);
        }
    })
    function add_new_form(e) {
        if (e) {
            e.preventDefault();
        }
        const totalNewForms = document.getElementById('id_invoiceitemline_set-TOTAL_FORMS'); //'id_invoiceitemline_set-TOTAL_FORMS' 'id_form-TOTAL_FORMS'
        const curItemLineForms = document.getElementsByClassName('itemline-form');
        const curFormCount = curItemLineForms.length;
        console.log('curformcount=' + curFormCount);
        const formCopyTarget = document.getElementById('itemline-form-list');
        const copyEmptyFormEl = document.getElementById('empty-form').cloneNode(true);
        copyEmptyFormEl.setAttribute('class', 'itemline-form');
        copyEmptyFormEl.setAttribute('id', `form-${curFormCount}`);
        const regex = new RegExp('__prefix__', 'g');
        copyEmptyFormEl.innerHTML = copyEmptyFormEl.innerHTML.replace(regex, curFormCount);
        totalNewForms.setAttribute('value', curFormCount + 1);
        formCopyTarget.append(copyEmptyFormEl);

    }
</script>
{% endblock body %}