var formatResult = function (data) {
    return  data.text;
};
function initializeInSelect2(itr) {
    $("#product" + itr).select2({
        placeholder: "إسم المنتج",
        minimumInputLength: document.getElementById("searchvalue").value,
        //minimumInputLength: 3,
        multiple: false,
        quietMillis: 100,
        ajax: {
            url: "sellbillAjaxController.php?do=getProducts",
            dataType: 'json',
            data: function (term, page) {
                return {
                    term: term, //search term
                    page_limit: 10, // page size
                    storeid: document.getElementById("inStore").value,
                    //hiddenpricetype: document.getElementById("pricetypepro" + n).value, //pricetype
                    //suppplier: document.getElementById("supplier").value,
                    searchWithCatAndProductNameOnly: 0, //document.getElementById("searchWithCatAndProductNameOnly").value,
                };
            },
            results: function (data) {
                return {results: data};
            }
        },
        formatResult: formatResult,
        initSelection: function (element, callback) {
            var item = element.val().split(':');
            //  var data = {id: item[0], text: item[1]};
            var data = {id: item[0], text: item[1], productquantity: item[2], price: item[3]};
            callback(data);
        }
    }).on('change', function () {
        //var theselectedvalue = $(this).val();
        var n = $(this).data('itr');
        $('#unitId' + itr).val('').change();
        $('#price' + n).val('').change();
    })
    $("#unitId" + itr).select2({
        placeholder: "وحدة القياس",
        minimumInputLength: 0, //document.getElementById("searchvalue").value,
        //minimumInputLength: 3,
        multiple: false,
        quietMillis: 100,
        ajax: {
            url: "damagedProductAjaxController.php?do=unitsAjax",
            dataType: 'json',
            data: function (term, page) {
                return {
                    term: term, //search term
                    page_limit: 10, // page size
                    product: $('#product' + itr).val(),
                };
            },
            results: function (data) {
                return {results: data};
            }
        },
        formatResult: formatResult,
        initSelection: function (element, callback) {
            var item = element.val().split(':');
            //  var data = {id: item[0], text: item[1]};
            var data = {id: item[0], text: item[1], productquantity: item[2], price: item[3]};
            callback(data);
        }
    }).on('change', function () {
        var n = $(this).data('itr');
        var p = $("#product" + n).select2('data').price;
        var pnum = $("#unitId" + n).select2('data').pnum;
        if ((Number($("#product" + n).val()) > 0 || $("#product" + n).val().includes("hasSizeColor")) && Number($("#unitId" + n).val()) > 0) {
            var tp = Number((p * pnum).toFixed(2));
            $('#price' + n).val(tp).keyup();
        } else {
            $('#price' + n).val(.0).keyup();
        }
    });

    //
    if ($('#oldproductid' + itr).length > 0 && $('#oldproductname' + itr).length > 0)
        $('#product' + itr).select2('data', {id: $('#oldproductid' + itr).val(), text: $('#oldproductname' + itr).val()});
    //
    if ($('#oldunitid' + itr).length > 0 && $('#oldunitname' + itr).length > 0)
        $('#unitId' + itr).select2('data', {id: $('#oldunitid' + itr).val(), text: $('#oldunitname' + itr).val()});
}


$(document).ready(function (e) {
    $(".select2Supp").select2({
        placeholder: "المورد",
        minimumInputLength: document.getElementById("searchvalue").value,
        //inimumInputLength: 0,
        multiple: false,
        quietMillis: 100,
        ajax: {
            url: "supplierAjaxController.php?do=select2supplier",
            dataType: 'json',
            data: function (term, page) {
                return {
                    term: term, //search term
                    page_limit: 7, // page size
                    withAddOption: 0,
                    withNakdi: 0,
                    //jsonRowRet: 1,
                };
            },
            results: function (data) {
                return {results: data};
            }
        },
        formatResult: function (data) {
            if (Number(data.id) == -2) {
                return  '<span class="newoption">' + data.text + '</span >';
            } else {
                return  '<span>' + data.text + '</span >';
            }
        },
        initSelection: function (element, callback) {
            var item = element.val().split(':');
            var data = {id: item[0], text: item[1]};
            callback(data);
        },
        //dropdownCssClass: "bigdrop", // apply css that makes the dropdown taller
    })
//    .on('select2-loaded', function (e) {// not "select2-open" nor "select2-opening" //http://mkurz.github.io/select2/index.html
//        $('.newoption').parent().addClass('newoption');
//    }).on('change', function () {
//        supplierDebt($(this).val());
//    })
    $('#supplier').select2('data', {id: $('#oldsupplierid').val(), text: $('#oldsuppliername').val()});
    $(".select2productout").select2({
        placeholder: "إسم المنتج",
        minimumInputLength: document.getElementById("searchvalue").value,
        //minimumInputLength: 3,
        multiple: false,
        quietMillis: 100,
        ajax: {
            url: "sellbillAjaxController.php?do=getProducts",
            dataType: 'json',
            data: function (term, page) {
                return {
                    term: term, //search term
                    page_limit: 10, // page size
                    storeid: document.getElementById("outStore").value,
                    //hiddenpricetype: document.getElementById("pricetypepro" + n).value, //pricetype
                    //suppplier: document.getElementById("supplier").value,
                    searchWithCatAndProductNameOnly: 0, //document.getElementById("searchWithCatAndProductNameOnly").value,
                };
            },
            results: function (data) {
                return {results: data};
            }
        },
        formatResult: formatResult,
        initSelection: function (element, callback) {
            var item = element.val().split(':');
            //  var data = {id: item[0], text: item[1]};
            var data = {id: item[0], text: item[1], productquantity: item[2], price: item[3]};
            callback(data);
        }
    });
    if ($('#oldproductOutid').length > 0 && $('#oldproductOutname').length > 0)
        $('#productOut').select2('data', {id: $('#oldproductOutid').val(), text: $('#oldproductOutname').val()});

    $(document).on('click', '.addInPro', function () {
        var itr = $('#inProItr').val();
        itr++;
        $('#inTabletb').append('<tr>'
                + '<td><input type="hidden" id="product' + itr + '" name="product' + itr + '" data-itr="' + itr + '" class="select2productin wdt100" tabindex="7" /></td>'
                + '<td><input type="hidden" name="unitId' + itr + '"  id="unitId' + itr + '" class="select2_unit" data-itr="' + itr + '"></td>'
                + '<td><input type="text" name="price' + itr + '" id="price' + itr + '" min="0" class="form-control inPrice inCalc positivefloat" data-itr="' + itr + '" value=""/></td>'
                + '<td><input type="text" name="quantity' + itr + '" id="quantity' + itr + '" min="0" class="form-control inQuantity inCalc positivefloat" data-itr="' + itr + '" value="" /></td>'
                + '<td><span class="inTotalCost" id="inTotalCost' + itr + '"></span></td>'
                + '<td class="noprint"><button id="remove' + itr + '" type="button" class="close flt-none removeicon removeproduct" aria-hidden="true">&times;</button></td>');
        $('.positivefloat').forcepositivefloat();
        initializeInSelect2(itr);
        $('#inProItr').val(itr);
    });
    $(document).on('click', '.removeicon', function () {
        $(this).parent().parent().remove();
        //
        var total = 0
        $('.inTotalCost').each(function () {
            total += Number($(this).html());
        })
        $('#allCost').html(total);
        calcOutAllCostTot();
        return false;
    });


    $('.outCalc').on('keyup', function () {
        var q = Number($('#outQuantity').val());
        var c = Number($('#outUnitCost').val());
        var t = Number((q * c).toFixed(2));
        $('#outAllCost').val(t);
        calcOutAllCostTot();
    })
    $(document).on('keyup', '.inCalc', function () {
        var n = $(this).data('itr');
        var q = Number($('#quantity' + n).val());
        var p = Number($('#price' + n).val());
        var t = Number((q * p).toFixed(2));
        $('#inTotalCost' + n).html(t);

        //
        var total = 0
        $('.inTotalCost').each(function () {
            total += Number($(this).html());
        })
        $('#allCost').html(total);
        calcOutAllCostTot();
    })

    function calcOutAllCostTot() {
        var q = Number($('#outQuantity').val());
        if (q != 0) {
            var c = Number($('#outUnitCost').val());
            var ac = Number($('#allCost').html());
            var outAllCostTot = (ac / q) + c;
            outAllCostTot = Number(outAllCostTot.toFixed(3));
        } else {
            outAllCostTot = '';
        }
        $('#outAllCostTot').val(outAllCostTot);
        $('#outAllCostTot_h').val(outAllCostTot);
    }
    //stop default action of form if {no equation name} or (total percentage !=100) or {one of products list with choice = -1}
    $("#saveBtn").click(function (event) {
        if (!$('#form1').hasClass('processing...')) {
            $('#form1').addClass('processing...');

            if (Number($('#supplier').val()) > 0) {
            } else {
                alert('اختر مورد اولا');
                $('#form1').removeClass('processing...');
                return false;
            }
            if (Number($('#productOut').val()) > 0 || $("#productOut").val().includes("hasSizeColor")) {
            } else {
                alert('اختر المنتج المخرج اولا');
                $('#form1').removeClass('processing...');
                return false;
            }
            if (Number($('#outQuantity').val()) > 0) {
            } else {
                alert('ادخل كمية المنتج المخرج اولا');
                $('#form1').removeClass('processing...');
                return false;
            }
            if (Number($('#outUnitCost').val()) >= 0) {
            } else {
                alert('ادخل تكلفة تصنيع الوحدة اولا');
                $('#form1').removeClass('processing...');
                return false;
            }
            if (Number($('#allCost').html()) > 0) {
            } else {
                alert('اختر بيانات المدخلات اولا');
                $('#form1').removeClass('processing...');
                return false;
            }

            $('#form1').submit();
        }
    });



    if ($('#inProItr').length > 0) {
        //edit page
        var inProItr = Number($('#inProItr').val());
        if (inProItr > 0) {
            //edit page
            for (var i = 0; i <= inProItr; i++) {
                initializeInSelect2(i);
            }
        } else {
            //add page
            $('.addInPro').click();
        }
    }

});
