Array.prototype.removeByIndex = function (i) {
  if (!Number.isInteger(i) || i < 0) {
    // i must be an integer
    return this;
  }
  return this.filter((f, indx) => indx !== i);
};
let debug = '[{"productCategory":8,"id":1,"productQuantity":1,"productUnit":1,"productName":"Stoller N-Balancer","productPrice":3120,"postedBy":"1","productDesc":"növekedés szabályozó B 9%, Mo 0,03%","quantitity":5,"discount":0,"ekaer":"","delivery":"","status":0,"total":15600},{"productCategory":8,"id":3,"productQuantity":1,"productUnit":1,"productName":"Stoller Bioforge 5 l kanna","productPrice":15830,"postedBy":"1","productDesc":"magasfokú stresszoldás N 10,5%, K2O 5%              Co 0,002%, Mo0,0002%","quantitity":5,"discount":0,"ekaer":"","delivery":"","status":0,"total":79150}]';
//debug = '[]';
let currentPartner = {};
generateProductList();
dategen();
$('div.productList').on('change','select,:not(input[data-type="delivery"])',function(e){
  let target = parseInt($(e.currentTarget).parent().parent().data("product-order"));
  let temp = $(e.currentTarget).data('type');
  if(temp && temp!="ekaer"&&temp!="delivery"&&temp!="discountint"&&temp!="discount"){
    let elem = {};
    productList.forEach(element => {
      if(element.id==target)
        elem=element;
    });
    if(elem[temp] == parseInt($(e.currentTarget).val()))
      return false;
    elem[temp] = parseInt($(e.currentTarget).val());
    elem.total = (temp=='quantitity'||temp=='discount')?(elem.productPrice * elem.quantitity * ((100 - elem.discount)/100)):elem.total;
    generateProductList();
    dategen();
  }else if(temp){
    if(temp=="discountint"){
      productList.forEach(element => {
        if(element.id==target)
          elem=element;
      });
      let base = elem["productPrice"];
      let divider = base-parseInt($(e.currentTarget).val());
      let final = Math.round((100-(divider/base*100))*100)/100;
      console.log($(e.currentTarget));
      let _lol = $(e.currentTarget).find(`input[data-type="discount"]`).val(final)
      elem.discount=final;
      elem.discountint = parseInt($(e.currentTarget).val());
      elem.total = (temp=="discountint")?((elem.productPrice * elem.quantitity * ((100 - elem.discount)/100))).toFixed(2):elem.total.toFixed(2);
      generateProductList();
      dategen();
    }else if(temp=="discount"){
        productList.forEach(element => {
          if(element.id==target)
            elem=element;
        });
        let base = elem["productPrice"];
        let percent = parseInt($(e.currentTarget).val());
        let value = (base*(percent/100)).toFixed(2);
        //let final = Math.round((100-(divider/base*100))*100)/100;
        let _lol = $(e.currentTarget).find(`input[data-type="discountint"]`).val(value);
        console.log(value);
        elem.discount=percent;
        elem.discountint = value;
        elem.total = (temp=='discount')?((elem.productPrice * elem.quantitity * ((100 - elem.discount)/100))).toFixed(2):elem.total.toFixed(2);
        generateProductList();
        dategen();
    }else{
      productList.forEach(element => {
        if(element.id==target)
          elem=element;
      });
      console.log(elem[temp] +' ?= '+ $(e.currentTarget).val())
      console.log(elem[temp] == $(e.currentTarget).val());
      if(elem[temp] == $(e.currentTarget).val())
        return false;
      elem[temp] = $(e.currentTarget).val();
      elem.total = (temp=='quantitity'||temp=='discount')?(elem.productPrice * elem.quantitity * ((100 - elem.discount)/100)):elem.total;
      generateProductList();
      dategen();
    }
  }
});
$('div.productList').on('apply.daterangepicker','input[data-type="delivery"]',function(e){
  let target = parseInt($(e.currentTarget).parent().parent().data("product-order"));
  let data;
  for(elem of productList){
    if(elem.id == target)
      data = elem;
  }
  let temp = $(e.currentTarget).data('type');
  if(temp){
    console.log(data[temp] +' ?= '+ $(e.currentTarget).val())
    console.log(data[temp] == $(e.currentTarget).val());
    if(data[temp] == $(e.currentTarget).val())
      return false;
    data[temp] = $(e.currentTarget).val();
    data.total = (temp=='quantitity'||temp=='discount')?(data.productPrice * data.quantitity * ((100 - data.discount)/100)):data.total;
    generateProductList();
    dategen();
  }
});

$("select.selectProduct").select2({
  width: "200px",
  ajax: {
    url: "/ajax/get/product/frontend/search",
    dataType: "json",
    type: "GET",
    data: function (params) {
      if(currentPriceRange==null){
        var query = {
          productName: params.term,
        };
      }else{
        var query = {
          productName: params.term,
          pricerange:currentPriceRange
        };
      }
      // Query parameters will be ?search=[term]&type=public
      return query;
    },
    processResults: function (data) {
      // Transforms the top-level key of the response object from 'items' to 'results'
      var data = $.map(data, function (obj) {
        obj.id = obj.id || obj.id;
        obj.text = obj.text || obj.productName; // replace pk with your identifier
        //obj.text = obj.text + " - " + obj.id;
        return obj;
      });
      return {
        results: data,
      };
    },
  },
});
$("select.selectPartner").select2({
  width: "200px",
  ajax: {
    url: "/ajax/get/partner/search",
    dataType: "json",
    type: "GET",
    data: function (params) {
      var query = {
        companyName: params.term,
      };

      // Query parameters will be ?search=[term]&type=public
      return query;
    },
    processResults: function (data) {
      // Transforms the top-level key of the response object from 'items' to 'results'
      var data = $.map(data, function (obj) {
        obj.id = obj.id;
        obj.text = obj.text || obj.companyName; // replace pk with your identifier
        //obj.text = obj.text + " - " + obj.id;
        return obj;
      });
      return {
        results: data,
      };
    },
  },
});
$("select.selectPartner").on("change", function (e) {
  console.log(e.target.value);
  let filter = { id: e.target.value };
  console.log(filter);
  $.ajax({
    url: "/ajax/get/partner/short",
    dataType: "json",
    type: "GET",
    data: filter,
  }).done(function (msg) {
    currentPartner = msg[0];
    const payday = moment().add(msg[0].companyPaymentDays, "days").format("MM/DD/YYYY");
    const _payday = moment().add(msg[0].companyPaymentDays, "days");
    //console.log(payday);
    $('input.paymentDueDate').val(payday);
    $("input.paymentDueDate").daterangepicker({
      singleDatePicker: true,
      showDropdowns: true,
      format: "YYYY-MM-DD",
      locale: "hu",
    });
    $('input.paymentDueDate').data('daterangepicker').minDate = moment().add(msg[0].companyPaymentDays, "days");
    let append = `<div>${msg[0].companyName}</div>`;
    append += `<div>${msg[0].companyZip} ${msg[0].companyCity}, ${msg[0].companyAdressLocation} </div>`;
    append += `<div>${msg[0].companyVat} </div>`;
    append += `<div>${msg[0].companyVatEU} </div>`;
    if(msg[0].companyPriceRange!=null){
      currentPriceRange = msg[0].companyPriceRange;
    }else{
      currentPriceRange = null;
      console.log(msg[0].companyPriceRange);
    }
    productList = [];
    generateProductList();
    $("div.card.customerParameters div.card-body").html(append);
    $("div.orderbody").css('display','block');
  });
});
$("button.savedata").on("click", function (e) {
  if(currentPartner=={} || productList.length==0)
    return alert("Nincs kiválasztva termék vagy partner");
  e.preventDefault();
  let filter = prepareForSave();
  $.ajax({
    url: "/ajax/set/order/new",
    dataType: "json",
    type: "POST",
    data: filter,
  }).done(function (msg) {
    let flag = confirm("Sikeresen rögzítetted a megrendelést! Szeretne még egyet rögzíteni?");
    if(flag!=true){
      window.location = "/orders/order";
    }
  });
});
$("button.addToOrder").on("click", function (e) {
  let name = $("select.selectProduct").text();
  let productId = parseInt($("select.selectProduct").val());
  let product;
  var query ={};
      if(currentPriceRange==null){
        query = {
          id:productId,
        };
      }else{
        query = {
          id:productId,
          pricerange:currentPriceRange
        };
      }
  $.ajax({
    url: "/ajax/get/product/frontend/search",
    dataType: "json",
    type: "GET",
    async: true,
    data: query,
    success: function (res) {
      product = res[0];
      let count = $("div.card-footer input.quantitity").val();
      if (count == "") {
        count = 1;
      }else{
        count = parseInt(count);
      }
      product.quantitity = count;
      product.discount = 0;
      product.ekaer = '';
      let today = moment().format("YYYY-MM-DD");
      product.delivery = `${today} - ${today}`;
      product.status = 0;
      product.total = product.productPrice * product.quantitity * ((100 - product.discount)/100);
      productList.push(product);
      generateProductList();
      dategen();
    },
  });
});
$("div.productList").on("click", "i.productInfo", function () {
  let target = $(this).data("product-id");
  let productId = $("select.selectProduct").val();
  let product;
  $.ajax({
    url: "/ajax/get/product",
    dataType: "json",
    type: "GET",
    async: false,
    data: { id: parseInt(target) },
    success: function (res) {
      product = res[0];
    },
  });
  $("div.shadow").css("display", "block");
  console.log(product);
  $("div.popup.card .card-header h3").html(product.productName);
  if (product.productDesc != undefined) {
    $("div.popup.card .productDesc").html(product.productDesc);
  }
  if (product.productPrice != undefined) {
    $("div.popup.card .productPrice").html(product.productPrice + " Ft");
  }
});
$("div.shadow,button.closeWindow").on("click", function () {
  $("div.shadow").css("display", "none");
});
$("input.paymentDueDate").daterangepicker({
  singleDatePicker: true,
  showDropdowns: true,
  format: "YYYY-MM-DD",
  locale: "hu",
});
$('div.productList').on('click','i.fa-times',function(e){
  productList = productList.removeByIndex(parseInt($(e.currentTarget).data('product-order')));
  generateProductList();
});
function getProductListIndexByID(id) {
  let counter = 0;
  for (p of productList) {
    if (p[0] == id) {
      return counter;
    }
    counter++;
  }
  return null;
}
function prepareForSave() {
  /* Prepare order body customer*/
  let order = new Object();
  if (currentPartner == {}) {
    alert("Nincs kiválasztva megrendelő");
    return false;
  } else {
    order.customer = currentPartner;
  }
  /* Prepare order body */

  order.orderAccept = $("select.orderAccept").val();
  order.orderComment = $("textarea.orderComment").val();
  order.salesPerson = user;
  order.orderStatus = $("select.orderStatus").val();
  order.paymentDueDate = $("input.paymentDueDate").val();
  if(productList==[]){
    alert("Nincs feltöltve termék");
    return false;
  }
  order.body = productList;

  return order;
}
function generateProductList(){
  let append = `<table class="table"><thead><tr class="row">
                  <th class="col-lg-1 col-sm-1 text-center">#</th>
                  <th class="col-lg-3 col-sm-11">Termék</th>
                  <th class="col-lg-1">Mennyiség</th>
                  <th class="col-lg-1">K.(%)</th>
                  <th class="col-lg-1">~K.(Ft)</th>
                  <th class="col-lg-1">Ár</th>
                  <th class="col-lg-1">Összesen</th>
                  <th class="col-lg-3">Szállítási dátum</th>
                  <th class="col-lg-1" style="display:none">Ekáer</th>
                  <th class="col-lg-2" style="display:none">Státusz</th>
                </tr></thead><tbody>`;
  for(let i=0;i<productList.length;i++){
    let p = productList[i];
    let price = 0;
    let pid = i;
    if(p.id){
      pid = p.id;
    }
    let productPr = `${p.productPrice} Ft`;
    if(p.productPrice==0)
      productPr = `<input class="form-control productPrice" type="number" value="0" data-type="productPrice">`;
    if(p.discountint||p.discount>0){
      let base = p.productPrice;
      let discounted = (base*((100-p.discount)/100)).toFixed(2);
      productPr = `<del>${p.productPrice} Ft</del></br><ins>${discounted}</ins>`;
    }
    append += `<tr class="row" data-product-order="${pid}">
                <td class="col-lg-1 col-sm-12 text-center"><i class="fas fa-times" data-product-order="${i}"></i></td>
                <td class="col-lg-3 col-sm-11">${p.productName} <i class="fas fa-info productInfo" data-product-id="${p.id}"></i></td>
                <td class="col-lg-1"><input class="form-control quantitity" min="0" type="number" value="${p.quantitity}" data-type="quantitity"></td>
                <td class="col-lg-1"><input class="form-control discount" min="0" type="number" value="${p.discount}" data-type="discount"></td>
                <td class="col-lg-1"><input class="form-control discountint" min="0" type="number" value="${p.discountint}" data-type="discountint"></td>
                <td class="col-lg-1">${productPr}</td>
                <td class="col-lg-1">${p.total} Ft</td>
                <td class="col-lg-3"><input class="form-control delivery" type="text" value="${p.delivery}" data-type="delivery"></td>
                <td class="col-lg-1" style="display:none"><input class="form-control ekaer" type="text" value="${p.ekaer}" data-type="ekaer"></td>
                <td class="col-lg-2" style="display:none"><select class="form-control status" type="number" data-type="status">${generateStatusSelect(p.status)} </select></td>
              </tr>`;
  }
  append += `</tbody></table>`
  $("div.productList").html(append);
}
function generateStatusSelect($id){
  let selected = ($id==0)?'selected':'';
  let html = `<option value="0" ${selected}>Megrendelve</option>`
  selected = ($id==1)?'selected':'';
  html += `<option value="1" ${selected}>Kiszállítás alatt</option>`
  selected = ($id==2)?'selected':'';
  html += `<option value="2" ${selected}>Kiszállítva</option>`
  selected = ($id==3)?'selected':'';
  html += `<option value="3" ${selected}>Számlázva</option>`
  selected = ($id==4)?'selected':'';
  html += `<option value="4" ${selected}>Fizetve</option>`
  selected = ($id==5)?'selected':'';
  html += `<option value="5" ${selected}>Jutalék</option>`
  return html;
}
function removeItemOnce(arr, value) {
  var index = arr.indexOf(value);
  if (index > -1) {
    arr.splice(index, 1);
  }
  return arr;
}
function dategen(){
  $("input.delivery").daterangepicker({
    singleDatePicker: false,
    locale: {
      format: "YYYY-MM-DD",
      separator: " - ",
      applyLabel: "Mentés",
      cancelLabel: "Mégse",
      daysOfWeek: ["V", "H", "K", "Sze", "Cs", "P", "Szo"],
      monthNames: ["Január","Február","Március","Április","Május","Június","Július","Augusztus","Szeptember","Október","November","December"],
      firstDay: 1,
    },
  });
}
