$(function() {

	// Somente números e (.) quantidade da balança
    $('#amount_balance, #charge_quantity').on('keypress', function(ev) {
        if(ev.key.match(/[^\d\,]/)) {
            ev.preventDefault();
        }
    });

	// Somente números Nota Fiscal
    $('#shipping_invoice').on('keypress', function(ev) {
        if(ev.key.match(/[^\d\.]/)) {
            ev.preventDefault();
        }
    });

	// Abrir modal nova carga
	$('button#new-charge').on('click', function() {
        $('.modal-new-charge').show(200);
    });

	// Fechar modal nova carga
    $('.modal-new-charge #close_cancel').on('click', function() {
        $('.modal-new-charge').hide(200);
    });

    // Validar data Entrega
	$('#date_delivery').on('keyup', function() {
		let date = $(this).val();
		let ref = $(this).attr('id');

		if(date.length == 10) {
			utils.verifyDateFirthDelivery(date, 'input', 'date_delivery', 'Data da entrega não é válida!');
		} else {
			$('#'+ref).attr('data-status', false);
		}
	});

	// Criar nova Entrega
    $('#confirm_charge').on('click', function(e) {
    	e.preventDefault();
    	let charge_quantity = $('#charge_quantity').val();

    	if(charge_quantity != 0 && charge_quantity != '') {
    		let status_date_delivery = $('#date_delivery').attr('data-status');

    		if(status_date_delivery == 'true') {
                $('#confirm_charge').addClass('loading');
    			let new_charge = {
    				charge_quantity:charge_quantity,
                    date_delivery:$('#date_delivery').val(),
                    nc_id_delivery:$('input[name=nc_id_delivery]').val(),
                    nc_id_request:$('input[name=nc_id_request]').val(),
                    nc_id_product:$('input[name=nc_id_product]').val(),
                    nc_id_provider:$('input[name=nc_id_provider]').val(),
                    nc_id_client:$('input[name=nc_id_client]').val(),
                    nc_product_group:$('input[name=nc_product_group]').val()
    			}

    			delivery.createNewCharge(new_charge);

    		} else {
    			utils.showAlerts('.message-add', 'Data da entrega não é válida!');
    		}

    	} else {
    		utils.showAlerts('.message-add', 'Digite a quantidade da carga!');
    	}
    });


    // Busca de informações de entrega, (Entregar ou editar)
    $('table#deliveryItems button.view-edit').on('click', function() {
    	let ref = parseInt($(this).attr('data-ref'));
    	
    	delivery.getInfoDelivery(ref);
    });

    // Fechar modal informações
    $('#close-delivery-info').on('click', function() {
    	$('.edit-charge').hide(100);
    });

    // Validar data de entrega
    $('input[name="delivery_date"]').on('keyup', function() {
    	let date = $(this).val();

    	if(date.length == 10) {
    		delivery.verifyDateDelivery(date);
    	} else {
    		$('input[name="delivery_date"]').attr('status', false);
    	}

    });

    // Salvar alterações da entrega
    $('#save-info-delivery').on('click', function() {
    	let date_delivery_status = $('input[name="delivery_date"]').attr('status');

    	if(date_delivery_status == 'true') {

    		let data = {
    			id:$('input[name="id_item_delivery"]').val(),
    			date_delivery:$('input[name="delivery_date"]').val(),
    			shipping_invoice:$('input[name="shipping_invoice"]').val(),
    			note:$('textarea[name="note"]').val()
    		}

    		delivery.saveDeliveryInfo(data);

    	} else {
    		utils.showAlerts('.message-add', 'Data da entrega não é válida!');
    	}
    });

    // Quantidade da balança    
    $('#amount_balance').on('keyup', function() {    	
    	let quantity = $('#amount_balance').val();
    	
    	if(quantity != '') {
    		let refDelivery = parseInt($('input[name="id_item_delivery"]').val());
    		delivery.getUpdatedValueDelivery(quantity, refDelivery);
		} else {
			$('input[name="amount_balance"]').attr('status', false);
			utils.showAlerts('.message-add', 'Quantidade da balança não é válido!');
		}
    });

    // Verificar se nota fiscal já está cadastrada
    $('#shipping_invoice').on('keyup', function() {    	
    	let number = $('#shipping_invoice').val();
        let provider = parseInt($('input[name="nc_id_provider"]').val());
    	
    	if(number != '') {    		
    		delivery.existsShippingInvoice(number, provider);
		} else {
			$('#shipping_invoice').attr('status', false);
		}
    });
    
    // Atualizar para entrega realizada
    $('#delivery-complete').on('click', function() {
        let date_delivery_status = $('input[name="delivery_date"]').attr('status');

        if(date_delivery_status == 'true') {
            let p_group = parseInt($('input[name="product_selected_group"]').val());

            if(p_group == 2) {
                shipping_status = $('input[name="shipping_invoice"]').attr('status');           

                if(shipping_status == 'true') {
                    let shipping_invoice = $('input[name="shipping_invoice"]').val();
                    let dateDelivery = $('input[name="delivery_date"]').val();
                    let refDelivery = parseInt($('input[name="id_item_delivery"]').val());
                    let amount_balance = '';
                    let total_value = '';
                    let note = $('textarea[name="note"]').val();

                    delivery.setDeliveryComplete(refDelivery, p_group, amount_balance, total_value ,shipping_invoice, dateDelivery, note);

                } else {
                    utils.showAlerts('.message-add', 'Nr da Nota Fiscal inválida e/ou já cadastrada!'); 
                }

            } else {
                let status_balance = $('input[name="amount_balance"]').attr('status');

                if(status_balance == 'true') {
                    shipping_status = $('input[name="shipping_invoice"]').attr('status');               

                    if(shipping_status == 'true') {
                        let shipping_invoice = $('input[name="shipping_invoice"]').val();
                        let dateDelivery = $('input[name="delivery_date"]').val();
                        let refDelivery = parseInt($('input[name="id_item_delivery"]').val());
                        let amount_balance = $('#amount_balance').val();
                        let total_value = $('input[name="total_balance"]').val();
                        let note = $('textarea[name="note"]').val();

                        delivery.setDeliveryComplete(refDelivery, p_group, amount_balance, total_value ,shipping_invoice, dateDelivery, note);

                    } else {
                        utils.showAlerts('.message-add', 'Nr da Nota Fiscal inválida e/ou já cadastrada!'); 
                    }

                } else {
                    utils.showAlerts('.message-add', 'Quantidade da balança não é válido!');
                }
            }

        } else {
            utils.showAlerts('.message-add', 'Data da entrega não é válida!');
        }
    });

    // Cancelar entrega
	$('button.cancel').on('click', function() {
		let clicked = parseInt($(this).attr('data-ref'));

		$('input[name="cancel_clicked_item"]').val(clicked);

		$('.modal-stock').show(100);
    });

    // Fechar Cancelar entrega
	$('#close_cancel_deliverie').on('click', function(e) {
		e.preventDefault();
		$('.modal-stock').hide(100);
    });

    // Confirmar cancelamento
    $('#confirm_cancel_deliverie').on('click', function(e) {
        e.preventDefault();

        let item = $('input[name="cancel_clicked_item"]').val();
        let reason_canceled = $('#reason_canceled').val();

        delivery.setDeliverieCanceled(item, reason_canceled);
    });

    // Zerar saldo - Zerar Balança

    $('.modal-balance-zero #close_cancel').on('click', function() {
        $('.modal-balance-zero').hide(200);
    });

    $('#zero_balance').on('click', function() {
        $('.modal-balance-zero').show(200);
    });

    $('#confirm_zero_balance').on('click', function() {
        let zb_id_delivery = $('input[name=zb_id_delivery]').val();
        $(this).addClass('loading');
        
        delivery.zeroBalance(zb_id_delivery);
    });


});