var myApp = angular.module('myApp', []);

myApp.controller('myCtrlItem_1', function($scope,$rootScope,$compile,$filter) {
    $scope.updateHTML = function (html,div_element) {
        let comp = $scope.compile = $compile(html)($scope);
        $(div_element+" div.row-category-items").append(comp);
    }
    
    $scope.createScopeAdditional = function (item_additional_id,item_id) {
        //let priceAdditional = Number($("#inputItemAdditionalPaid_"+item_additional_id+"_"+item_id).val());
        let priceAdditional = Number($scope["inputItemAdditionalPaid_"+item_additional_id+"_"+item_id]);
        let hideFreeName = Number($scope["inputItemAdditionalPaidHideFreeName_"+item_additional_id+"_"+item_id]);
        
        if (priceAdditional > 0) {
            $("#textPriceAdditional_"+item_additional_id+'_'+item_id).removeClass("text-light-green-2");
            $scope['currentValueAdditional_'+item_additional_id+'_'+item_id] = Number(priceAdditional).toLocaleString(company_currency, { style: "currency" , currency:currency});
        }
        else {
            $("#textPriceAdditional_"+item_additional_id+'_'+item_id).addClass("text-light-green-2");
            //$scope['currentValueAdditional_'+item_additional_id+'_'+item_id] = 'Grátis';
            $scope['currentValueAdditional_'+item_additional_id+'_'+item_id] = (!hideFreeName ? 'Grátis' : '');
        }
    }
    
    $scope.updateScopeAdditional = function (item_additional_id,item_id,amount) {
        let priceAdditional = Number($("#inputItemAdditionalPaid_"+item_additional_id+"_"+item_id).val());
        priceAdditional = priceAdditional * amount;
        console.log(priceAdditional);
        
        let hideFreeName = ($("#inputItemAdditionalPaidHideFreeName_"+item_additional_id+"_"+item_id).length > 0 ? true : false);
        
        if (priceAdditional > 0) {
            $("#textPriceAdditional_"+item_additional_id+'_'+item_id).removeClass("text-light-green-2");
            console.log($scope['currentValueAdditional_'+item_additional_id+'_'+item_id]);
            $scope['currentValueAdditional_'+item_additional_id+'_'+item_id] = Number(priceAdditional).toLocaleString(company_currency, { style: "currency" , currency:currency});
            console.log($scope['currentValueAdditional_'+item_additional_id+'_'+item_id]);
        }
        else {
            $("#textPriceAdditional_"+item_additional_id+'_'+item_id).addClass("text-light-green-2");
            //$scope['currentValueAdditional_'+item_additional_id+'_'+item_id] = 'Grátis';
            $scope['currentValueAdditional_'+item_additional_id+'_'+item_id] = (!hideFreeName ? 'Grátis' : '');
        }
    }
    
    $scope.checkItemOptions = function (flavor_id,item_id) {
        if (Number($scope['inputItemFlavorAmount_'+item_id]) != -1) {
            itemOptions = $scope.itemOption !== undefined ? $scope.itemOption : false;
            //itemOptionsAmount = 0;
            itemOptionsAmount = $scope.sumFlavorsAmount(item_id);
            /*Object.keys(itemOptions).forEach((key) => {
                if (itemOptions[key] === true) {
                    itemOptionsAmount++;
                }
            });*/
            
            if (itemOptionsAmount > $scope['inputItemFlavorAmount_'+item_id]) {
                $("#itemOption_"+flavor_id).addClass("shake-element");
                
                setTimeout(function (id = flavor_id) {
                    $("#itemOption_"+id).removeClass("shake-element");
                }, 1000);
                
                $scope.itemOption[flavor_id] = false;
                return;
            }
            
            if (Number($("#inputItemOption_"+flavor_id).val()) > 0) {
                if ($scope.itemOption[flavor_id] == true) {
                    $("#amountFlavor_"+flavor_id+"_"+item_id).removeClass("d-none");
                }
                else {
                    $("#amountFlavor_"+flavor_id+"_"+item_id).addClass("d-none");
                }
            }
            
            $scope.updateValue(item_id);
        }
    }
    
    $scope.checkItemAdditionals = function (additional_id,additional_category_id,item_id) {
        if (Number($scope['inputItemAdditionalAmount_'+additional_category_id+'_'+item_id]) != -1) {
            itemAdditionalsPaid = $scope.additionals !== undefined ? $scope.additionals : false;
            itemAdditionalsAmount = $(".additional-category-"+additional_category_id+"_"+item_id+" .form-check-input:checked").length;
            
            //console.log($(".additional-category-"+additional_category_id+"_"+item_id+" .form-check-input:checked").length);
            
            if (itemAdditionalsAmount > $scope['inputItemAdditionalAmount_'+additional_category_id+'_'+item_id]) {
                $("#itemAdditionals_"+additional_id+"_"+item_id).addClass("shake-element");
                
                setTimeout(function (id = additional_id, itemId = item_id) {
                    $("#itemAdditionals_"+id+"_"+itemId).removeClass("shake-element");
                }, 1000);
                
                $scope.additionals[additional_id] = false;
                return;
            }
            
            /*if (Number($("#inputItemAdditionalPaid_"+additional_id+"_"+item_id).val()) > 0) {
                if ($scope.additionals[additional_id] == true) {
                    $("#amountAdditional_"+additional_id+"_"+item_id).removeClass("d-none");
                }
                else {
                    $("#amountAdditional_"+additional_id+"_"+item_id).addClass("d-none");
                }
            }*/
            
            if ($scope.additionals[additional_id] == true) {
                $("#amountAdditional_"+additional_id+"_"+item_id).removeClass("d-none");
            }
            else {
                $("#amountAdditional_"+additional_id+"_"+item_id).addClass("d-none");
            }
            
            $scope.updateValue(item_id);
        }
    }
    
    $scope.sumFlavorsAmount = function (item_id) {
        $scope.itemPriceTypeValue = $scope["inputItemPriceType_"+item_id] ? $scope["inputItemPriceType_"+item_id] : 0;
        if ($scope.itemPriceTypeValue > 0) {
            itemOptionsAmount = 0;
            itemOptions = $scope.itemOption !== undefined ? $scope.itemOption : false;
            Object.keys(itemOptions).forEach((key) => {
                if (itemOptions[key] === true) {
                    itemOptionsAmount += $scope["inputAmountFlavor_" + key + "_" + item_id];
                }
            });
            
            console.log(itemOptionsAmount);
            return itemOptionsAmount;
        }
    }
    
    $scope.updateValue = function (item_id) {
        $scope.additionalsPaidValue = 0;
        itemAdditionalsPaid = $scope.additionals !== undefined ? $scope.additionals : false;
        Object.keys(itemAdditionalsPaid).forEach((key) => {
            if (itemAdditionalsPaid[key] === true) {
                //$scope.additionalsPaidValue = $scope.additionalsPaidValue + Number($("#inputItemAdditionalPaid_"+key+"_"+item_id).val());
                
                //$scope.additionalsPaidValue = $scope.additionalsPaidValue + (Number($("#inputItemAdditionalPaid_"+key+"_"+item_id).val()) * Number($("#inputAmountAdditional_"+key+"_"+item_id).val()));
                $scope.additionalsPaidValue = $scope.additionalsPaidValue + (Number($("#inputItemAdditionalPaid_"+key+"_"+item_id).val()) * Number($scope['inputAmountAdditional_'+key+'_'+item_id]));
                
                let priceAdditional = (Number($("#inputItemAdditionalPaid_"+key+"_"+item_id).val()) * Number($scope['inputAmountAdditional_'+key+'_'+item_id]));
                let hideFreeName = ($("#inputItemAdditionalPaidHideFreeName_"+key+"_"+item_id).length > 0 ? true : false);
                $scope['currentValueAdditional_'+key+'_'+item_id] = priceAdditional > 0 ? priceAdditional.toLocaleString(company_currency, { style: "currency" , currency:currency}) : (!hideFreeName ? 'Grátis' : '');
            }
        });
        
        //$scope.itemSizeValue = $scope['itemSize_'+item_id] !== undefined ? $("#inputItemSize_"+$scope['itemSize_'+item_id]).val() : 0;
        $scope.itemSizeValue = $scope['itemSize_'+item_id] !== undefined ? $scope['inputItemSize_'+$scope['itemSize_'+item_id]] : 0;
        
        $scope.itemPriceValue = 0;
        //$scope.itemPriceTypeValue = $("#inputItemPriceType_"+item_id).length > 0 ? $("#inputItemPriceType_"+item_id).val() : 0;
        $scope.itemPriceTypeValue = $scope["inputItemPriceType_"+item_id] ? $scope["inputItemPriceType_"+item_id] : 0;
        if ($scope.itemPriceTypeValue > 0) {
            itemOptionsAmount = 0;
            itemOptions = $scope.itemOption !== undefined ? $scope.itemOption : false;
            Object.keys(itemOptions).forEach((key) => {
                if (itemOptions[key] === true) {
                    switch (Number($scope.itemPriceTypeValue)) {
                        /*case 1: $scope.itemPriceValue = $scope.itemPriceValue > Number($("#inputItemOption_"+key).val()) || $scope.itemPriceValue === 0 ? Number($("#inputItemOption_"+key).val()) : $scope.itemPriceValue; break;
                        case 2: $scope.itemPriceValue = $scope.itemPriceValue < Number($("#inputItemOption_"+key).val()) ? Number($("#inputItemOption_"+key).val()) : $scope.itemPriceValue; break;
                        case 3: $scope.itemPriceValue = $scope.itemPriceValue + Number($("#inputItemOption_"+key).val()); break;*/
                        case 1: $scope.itemPriceValue = $scope.itemPriceValue > Number($scope["inputItemOption_"+key]) || $scope.itemPriceValue === 0 ? Number($scope["inputItemOption_"+key]) : $scope.itemPriceValue; break; // Menor valor dos sabores
                        case 2: $scope.itemPriceValue = $scope.itemPriceValue < Number($scope["inputItemOption_"+key]) ? Number($scope["inputItemOption_"+key]) : $scope.itemPriceValue; break; // Maior valor dos sabores
                        case 3: $scope.itemPriceValue = $scope.itemPriceValue + Number($scope["inputItemOption_"+key]); break; // Média dos valores dos sabores
                        case 4: $scope.itemPriceValue = $scope.itemPriceValue + Number($scope["inputItemOption_"+key]); break; // Soma todos os sabores
                    }
                    itemOptionsAmount++;
                }
            });
            
            $scope.itemPriceValue = $scope.itemPriceTypeValue == 3 && itemOptionsAmount > 0 ? $scope.itemPriceValue / itemOptionsAmount : $scope.itemPriceValue;
        }
        
        //console.log('Antes:' + $scope['amountItem_'+item_id]);
        //console.log('Depois:' + parseFloat($scope['amountItem_'+item_id]).toString());
        
        let valor = $scope['amountItem_'+item_id].toString();
        $scope['amountItem_'+item_id] = applyMask(valor);
        
        //console.log('Depois_2222:' + $scope['amountItem_'+item_id]);
        //console.log('Depois_3333:' + $("#amountItem_"+item_id).val());
        
        $scope.currentValue = Number($scope.itemPriceTypeValue) === 0 ? $scope['priceItem_'+item_id] : $scope.itemPriceValue;
        $scope.currentValue = Number($scope.currentValue) + Number($scope.additionalsPaidValue);
        $scope.currentValue = Number($scope.currentValue) + Number($scope.itemSizeValue);
        $scope.currentValue = Number($scope.currentValue) * Number($scope['amountItem_'+item_id]);
        $scope.currentValue = parseFloat((Math.round($scope.currentValue * 1000) / 1000).toFixed(3));
        $scope.currentValue = ($scope.currentValue != "undefined" && $scope.currentValue != "" && !isNaN($scope.currentValue) ? $scope.currentValue.toLocaleString(company_currency, { style: "currency" , currency:currency}) : 'R$ 0,00');
    }
})

myApp.directive('dynamic', ['$compile', function($compile){
    return{
      replace: true,
      link: function($scope, ele, attrs) {
          $scope.$watch(attrs.dynamic, function(html){
             if(!html)
                return;
             ele.html((typeof(html) === 'string') ? html : html.data);
             $compile(ele.contents())($scope);
    });
    }
    }
}]);

function applyMask(value) {
    //console.log(value);
    
    // Remove qualquer caractere que não seja número
    value = value.replace(/\D/g, '');

    // Inverter a string
    var reverseValue = value.split('').reverse().join('');

    // Adicionar os pontos
    var maskedValue = reverseValue.replace(/(\d{3})(?=\d)/g, '$1.');

    // Inverter novamente para o formato original
    maskedValue = maskedValue.split('').reverse().join('');

    return maskedValue;
}