$(function() {

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

	$('#close-deliveries').on('click', function(e) {
		e.preventDefault();
		$('.modal-deliveries').hide(200);
		$('#qtd_deliveries').val('');
		$('#date_first_deliverie').val('');
		$('#daysPayment').val('');

		$('#qtd_deliveries').attr('data-status', false);
		$('#date_first_deliverie').attr('data-status', false);
		$('#daysPayment').attr('data-status', false);
	});

	$('#show_products a.deliveires, a.deliveires').on('click', function(e) {
		e.preventDefault();

		if($(this).attr('data-type') == 'single_delivery') {

			// $('#date_first_deliverie').attr('placeholder', 'Data da entrega');
			$('#qtd_deliveries, #daysPayment, h4.qtd_days, hr.qtd_days, p.next_deliveries_msg').hide();
			$('#amount_balance').attr('readonly', true);
			$('.edit-charge').show();

		} else {

			$('#qtd_deliveries, #daysPayment, h4.qtd_days, hr.qtd_days, p.next_deliveries_msg').show();
			$('.modal-deliveries').show(200);
			$('.modal-deliveries #qtd_deliveries').focus();
			
		}

		$('input[name="type_delivery"]').val($(this).attr('data-type'));
		$('input[name="id_product_delivery"]').val($(this).attr('id'));
	});

	$('#qtd_deliveries').on('keyup', function() {

		if($(this).val() > 0 && $(this).val() < 101) {
			utils.errorImputs('input', 'qtd_deliveries', '#ced4da');
			$(this).attr('data-status', 'true');			

		} else {
			utils.errorImputs('input', 'qtd_deliveries', '#FF0000');
			utils.showAlerts('.message-add', 'Min. 1 e Máx. 100');
			$(this).attr('data-status', 'false');
		}
	});


	// Verificar data do primeiro pagamento
	$('#date_first_deliverie').on('keyup', function() {
		let date = $(this).val();
		let ref = $(this).attr('id');

		if(date.length == 10) {
			utils.verifyDateFirthDelivery(date, 'input', 'date_first_deliverie', 'Data do primeiro pagamento incorreta!');
		} else {
			$('#'+ref).attr('data-status', false);
		}
	});
	// Fim Verificar data do primeiro pagamento

	$('#daysPayment').on('keyup', function() {

		if($(this).val() > 0 && $(this).val() < 61) {
			utils.errorImputs('input', 'daysPayment', '#ced4da');
			$(this).attr('data-status', true);
		} else {
			utils.errorImputs('input', 'daysPayment', '#FF0000');
			utils.showAlerts('.message-add', 'Min. 1 e Máx. 60');
			$(this).attr('data-status', false);
		}
	});

	// Verificação antes de criação de entregas
	$('#go_deliveries').on('click', function(e) {		
		e.preventDefault();

		let type_delivery = $('input[name="type_delivery"]').val();

		if(type_delivery == 'separate_deliveries') {

			if(verifyAllInputsDelivery()) {
				$(this).attr('disabled', true);

				let array = getInfoInitDelivery();
				request.initDeliveries(array);
			}

		} else if(type_delivery == 'single_delivery') {

			if(verifyDateDelivery()) {
				$(this).attr('disabled', true);
				let array = getInfoInitDelivery();

				request.initDeliveries(array);
			}
		}	
	});

	function verifyAllInputsDelivery() {
		let response = false;
		if($('input[name="qtd_deliveries"]').attr('data-status') == 'true') {

			if($('input[name="date_first_deliverie"]').attr('data-status') == 'true') {

				if($('input[name="daysPayment"]').attr('data-status') == 'true') {

					response = true;

				} else {
					utils.showAlerts('.message-add', 'Verifique o intervalo entre os pagamentos!');	
				}

			} else {
				utils.showAlerts('.message-add', 'Verifique a data da primeira entrega!');	
			}

		} else {
			utils.showAlerts('.message-add', 'Verifique a quantidade de entregas!');
		}
		return response;
	}

	function verifyDateDelivery() {
		let response = false;
		if($('input[name="date_first_deliverie"]').attr('data-status') == 'true') {

			response = true;

		} else {
			utils.showAlerts('.message-add', 'Verifique a data da primeira entrega!');
		}
		return response;
	}

	function getInfoInitDelivery() {
		$('#go_deliveries, #delivery-complete').addClass('loading');
		// Verificação e adição de informações em entregas com estoque
		var date_delivery = '';
		let group_delivery = parseInt($('input[name="product_selected_group"]').val());

		if(group_delivery == 2) {
			date_delivery = $('#delivery_date').val();
		} else {
			date_delivery = $('#date_first_deliverie').val();
		}
		// Fim Verificação e adição de informações em entregas com estoque

		var delivery = {
			type_delivery:$('input[name="type_delivery"]').val(),
			id_request:$('input[name="id_request"]').val(),
			id_client:$('input[name="client_selected"]').val(),
			id_product:$('input[name="id_product_delivery"]').val(),
			product_group:$('input[name="product_group"]').val(),
			qtd_deliveries:$('#qtd_deliveries').val(),
			date_first_deliverie:date_delivery,
			daysPayment:$('#daysPayment').val(),
			shipping_invoice:$('#shipping_invoice').val(),
			note:$('textarea[name="note_delivery"]').val()
		};

		return delivery;
	}

	// Tela de programação de entregas com estoque

	$('#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) {
    		request.verifyDate(date, '', 'delivery_date');
    	} else {
    		$('input[name="delivery_date"]').attr('status', false);
    	}
    });

    // Verificar se nota fiscal já está cadastrada
    $('#shipping_invoice').on('keyup', function() {    	
    	let number = $('#shipping_invoice').val();
    	
    	if(number != '') {    		
    		delivery.existsShippingInvoice(number);
		} else {
			$('#shipping_invoice').attr('status', false);
		}
    });

    // Entregar com estoque, botão.
    $('#delivery-complete').on('click', function(e) {
    	e.preventDefault();

    	let date = $('input[name="delivery_date"]').attr('status');

    	if(date == 'true') {
    		let shipping = $('input[name="shipping_invoice"]').attr('status');

    		if(shipping == 'true') {

    			let array = getInfoInitDelivery();

				request.initDeliveries(array);

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

    	} else {
    		utils.showAlerts('.message-add', 'Verifique a data da entrega!');
    	}
    });

    // Cancelar pedido
	$('#close_cancel').on('click', function(e) {
		e.preventDefault();
		$('.modal-stock').hide(300);
		$('#reason_canceled').val('');
	});

    $('#cancel_request, #cancel_request_1').on('click', function(e) {
		e.preventDefault();
		$('.modal-stock').show(300);
	});

    $('#confirm_cancel').on('click', function(e) {
    	e.preventDefault();

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

    	if(reason_canceled.length > 2) {
    		$('#confirm_cancel').addClass('loading');
    		request.cancelRequest(reason_canceled, requestId);
    	} else {
    		utils.showAlerts('.message-add', 'Qual o motivo do cancelamento?')
    	}

    });
});