let utils = {
	getListCity:(state, inputRef) => {
		$.ajax({
			url:BASE_URL+'getcitylist',
			type:'POST',
			data:{state:state},
			dataType:'json',
			success:function(json) {
				var html = '';
				for(let i in json) {
					html += '<option value="'+json[i].id+'">'+json[i].name+'</option>';
				}
				$('select[name='+inputRef+']').html(html);
			}
		});
	},
	changeEnder:(cep, inputRef) => {
		$.ajax({
			url:'http://api.postmon.com.br/v1/cep/'+cep,
			type:'GET',
			dataType:'jsonp',
			success:function(jsonp){
				if(typeof jsonp.logradouro != 'undefined') {
					$('input[name='+inputRef+']').val(jsonp.logradouro);
				}
			}
		});
	},
	verifyExistsRg:(rg, ref) => {
		$.ajax({
			url:BASE_URL+'verifyexists',
			type:'POST',
			data:{
				value:rg,
				ref:'rg'
			},
			dataType:'json',
			success:function(json) {
				if(json == true) {
					$('button[type="submit"]').attr('disabled', true);
					utils.clearErrors();
					utils.showError(ref, 'Rg já cadastrado!');
				} else {
					$('button[type="submit"]').attr('disabled', false);
					utils.clearErrors();
				}
			}
		});
	},
	verifyExistsCpf:(cpf, ref) => {
		$.ajax({
			url:BASE_URL+'verifyexists',
			type:'POST',
			data:{
				value:cpf,
				ref:'cpf'
			},
			dataType:'json',
			success:function(json) {
				if(json == true) {
					$('button[type="submit"]').attr('disabled', true);
					utils.clearErrors();
					utils.showError(ref, 'CPF já cadastrado!');
				} else {
					$('button[type="submit"]').attr('disabled', false);
					utils.clearErrors();
				}
			}
		});
	},
	verifyExistsCnpj:(cnpj, ref) => {
		$.ajax({
			url:BASE_URL+'verifyexists',
			type:'POST',
			data:{
				value:cnpj,
				ref:'cnpj'
			},
			dataType:'json',
			success:function(json) {
				if(json == true) {
					$('button[type="submit"]').attr('disabled', true);
					utils.clearErrors();
					utils.showError(ref, 'CNPJ já cadastrado!');
				} else {
					$('button[type="submit"]').attr('disabled', false);
					utils.clearErrors();
				}
			}
		});
	},
	verifyExistsStateRegistration:(value, ref) => {
		$.ajax({
			url:BASE_URL+'verifyexistsfarm',
			type:'POST',
			data:{
				value:value
			},
			dataType:'json',
			success:function(json) {
				if(json == true) {
					$('button[type="submit"]').attr('disabled', true);
					utils.clearErrors();
					utils.showError(ref, 'Insc. Estadual já cadastrada!');
				} else {
					$('button[type="submit"]').attr('disabled', false);
					utils.clearErrors();
				}
			}
		});
	},
	deleteAtt:(data, farm) => {
		$.ajax({
			url:BASE_URL+'deleteattfarm',
			type:'POST',
			data:{
				value:data,
				farm:farm
			},
			dataType:'json',
			success:function(json) {
				if(json == true) {
					$('#attArchive, #deleteAtt').hide();
				}
			}
		});
	},
	updateStatus:(ref, astatus, where) => {
		$.ajax({
			url:BASE_URL+'activeinactive',
			type:'POST',
			data:{
				ref:ref,
				status:astatus,
				where:where
			},
			dataType:'json',
			success:function(json) {
				if(json == true) {
					location.reload();
				}
			}
		});
	},
	updateStatusProduct:(ref, astatus) => {
		$.ajax({
			url:BASE_URL+'activeinactiveprod',
			type:'POST',
			data:{
				product:ref,
				status:astatus
			},
			dataType:'json',
			success:function(json) {
				if(json == true) {
					location.replace(location.pathname);
				}
			}
		});
	},
	getListProvider:(inputRef) => {
		$.ajax({
			url:BASE_URL+'getlistprovider',
			type:'POST',
			dataType:'json',
			success:function(json) {
				var html = '';
				for(var i in json.providersList) {
					html += '<option value="'+json.providersList[i].id+'">'+json.providersList[i].company_name+'</option>';
				}
				$('#'+inputRef).html(html);

				$('#'+inputRef+' option').each(function() {
					// se localizar a frase, define o atributo selected
					if($(this).val() == $('input[name="pro_selected"]').val()) {
						$(this).attr('selected', true);
					} else {
						$(this).attr('selected', false);
					}
				});
			}
		});
	},
	verifyExistsSalesman:(value, ref, message) => {
		$.ajax({
			url:BASE_URL+'verifyexistssalesman',
			type:'POST',
			data:{
				value:value,
				ref:ref
			},
			dataType:'json',
			success:function(json) {
				if(json == true) {
					$('button[type="submit"]').attr('disabled', true);
					utils.errorImputs('input', ref, '#FF0000');
					utils.messageErrorImputs('.val_salesman', message, true);
				} else {
					$('button[type="submit"]').attr('disabled', false);
					utils.errorImputs('input', ref, '#ced4da');
					utils.messageErrorImputs('.val_salesman', '', false);
				}
			}
		});
	},
	updateStatusSalesman:(ref, astatus) => {
		$.ajax({
			url:BASE_URL+'activeinactivesalesman',
			type:'POST',
			data:{
				salesman:ref,
				status:astatus
			},
			dataType:'json',
			success:function(json) {
				if(json == true) {
					location.replace(location.pathname);
				}
			}
		});
	},
	updateStatusProvider:(ref, astatus, provider_of) => {
		$.ajax({
			url:BASE_URL+'activeinactiveprovider',
			type:'POST',
			data:{
				provider:ref,
				status:astatus,
				provider_of:provider_of
			},
			dataType:'json',
			success:function(json) {
				if(json == true) {
					location.replace(location.pathname);
				}
			}
		});
	},
	updateStatusShipping:(ref, astatus) => {
		$.ajax({
			url:BASE_URL+'activeinactiveshipping',
			type:'POST',
			data:{
				shipping:ref,
				status:astatus
			},
			dataType:'json',
			success:function(json) {
				if(json == true) {
					location.replace(location.pathname);
				}
			}
		});
	},
	getListProductsProvider:(inputRef, provider) => {
		$.ajax({
			url:BASE_URL+'getproductsprovider',
			type:'POST',
			data: {
				provider:provider
			},
			dataType:'json',
			success:function(json) {
				var html = '';
				html += '<option value="0">Selecionar</option>';
				for(var i in json) {
					html += '<option value="'+json[i].id+'">'+json[i].name+'</option>';
				}
				$('#'+inputRef).html(html);
			}
		});
	},
	getInfoProduct:(product) => {
		$.ajax({
			url:BASE_URL+'getinfoproduct',
			type:'POST',
			data:{
				product:product
			},
			dataType:'json',
			success:function(json) {
				$('input[name="group"]').val(json.group.id);
				$('input[name="unity"]').val(json.unity.id);
				$('input[name="presentation"]').val(json.presentation.id);
				$('input[name="groupName"]').val(json.group.name);
				$('input[name="unityName"]').val(json.unity.name);
				$('input[name="presentationName"]').val(json.presentation.name);

				if(json.group.id == 3 && json.product.amount > 0) {
					let html = "O "+json.product.name+" Possui saldo de "+json.product.amount+" "+json.unity.name+"(s)!";
					$('.modal-stock #msg-stock').html(html);
					$('.modal-stock').css('display', 'flex');
				}
			}
		});
	},
	verifyExistsNotePurchase:(ref, value) => {
		$.ajax({
			url:BASE_URL+'verifynotepurchase',
			type:'POST',
			data:{
				note:value
			},
			dataType:'json',
			success:function(json) {
				if(json == true) {
					utils.clearErrors();
					utils.showError(ref, 'Nota já cadastrada!');
					$('input[name="'+ref+'"]').attr('status', false);
				} else {
					utils.clearErrors();
					$('input[name="'+ref+'"]').attr('status', true);
				}
			}
		});
	},
	verifyPurchaseNoteDate:(ref, value) => {
		$.ajax({
			url:BASE_URL+'verifynotedate',
			type:'POST',
			data:{
				date:value
			},
			dataType:'json',
			success:function(json) {
				if(json == false) {
					utils.clearErrors();
					utils.showError(ref, 'Data Inválida!');
					$('input[name="'+ref+'"]').attr('status', false);
				} else {
					utils.clearErrors();
					$('input[name="'+ref+'"]').attr('status', true);
				}
			}
		});
	},
	getTotal:(qt, value, inputRef) => {
		$.ajax({
			url: BASE_URL+'totalvalue',
			type:'POST',
			data: {
				qt:qt,
				value:value
			},
			dataType:'json',
			success:function(json){
				$('input[name='+inputRef+']').val(json);
			}
		});		
	},
	addProductPurchase:(item) => {
		$.ajax({
			url: BASE_URL+'addproductinpurchase',
			type:'POST',
			data: {
				item:item
			},
			dataType:'json',
			success:function(json) {
				if(json.status == true) {
					utils.clearToNewProduct();
					utils.addProductToList(json.items_show);					
					$('input[name="total_amount"]').val(json.total_amount);
					utils.showAlerts('.message-add', 'Produto adicionado!');

					if(json.count > 0) {
						$('input[name="can_proceed"]').val(1);
					} else {
						$('input[name="can_proceed"]').val('');
					}
				}
			}
		});		
	},
	removeItemPurchase:(item) => {
		$.ajax({
			url: BASE_URL+'removeproductpurchase',
			type:'POST',
			data: {
				product:item
			},
			dataType:'json',
			success:function(json) {
				if(json.status == true) {
					$('#insert_products table tr#remove').remove();
					$('input[name="total_amount"]').val(json.total_amount);

					if(json.count > 0) {
						$('input[name="can_proceed"]').val(1);
					} else {
						$('input[name="can_proceed"]').val('');
					}
				}
			}
		});		
	},
	getPurchaseAdvanceValue:(value) => {
		$.ajax({
			url: BASE_URL+'getadvancepurchase',
			type:'POST',
			data: {
				advance:value
			},
			dataType:'json',
			success:function(json) {
				$('input[name="total_advance"]').val(json)
			}
		});		
	},
	verifyAndCompareDate:(firstdate, secondedate, delimiter, message, ref, refmodify) => {
		$.ajax({
			url: BASE_URL+'verifycomparedate',
			type:'POST',
			data: {
				date1:firstdate,
				date2:secondedate,
				delimiter:delimiter
			},
			dataType:'json',
			success:function(json) {
				if(json == true) {
					$(ref).html('');
					$(refmodify).attr('status', true);
				} else{
					$(ref).html(message);
					$(refmodify).attr('status', false);
				}
			}
		});		
	},
	clearToNewProduct:() => {
		let ref = ['product', 'group', 'groupName', 'unity', 'unityName', 'presentation', 'presentationName', 'quantity', 'product_price', 'total'];

		for(let i in ref) {
			$('input[name="'+ref[i]+'"]').val('');
			$('select[name="'+ref[i]+'"]').val('0');
		}
	},
	addProductToList:(items_show) => {
		let html = '';
		html += '<table class="table table-bordered">';
		html += '<tbody>';
		html += '<tr>';
		html += '<th scope="col">Produto</th> <th scope="col">Quantidade</th> <th scope="col">Valor unitário</th> <th scope="col">Total</th> <th scope="col">Grupo</th> <th scope="col">Unidade</th> <th scope="col">Apresentação</th> <th scope="col">Ação</th>';
		for(let i in items_show) {
			html += '<tr>';
			html += '<td>'+items_show[i].productName+'</td>';
			html += '<td>'+items_show[i].quantity+'</td>';
			html += '<td>'+items_show[i].priceItem+'</td>';
			html += '<td>'+items_show[i].total+'</td>';
			html += '<td>'+items_show[i].group.name+'</td>';
			html += '<td>'+items_show[i].unity.name+'</td>';
			html += '<td>'+items_show[i].presentation.name+'</td>';
			html += '<td><a href="#" class="btn btn-danger" id='+items_show[i].productId+'>remover</a></td>';
			html += '</tr>';
		}
		html += '</tr>';
		html += '</tbody>';
		html += '</table>';

		$('#insert_products').html(html);
	},
	deletePurchase:(ref) => {
		$.ajax({
			url: BASE_URL+'deletepurchase',
			type:'GET',
			data: {
				purchase:ref
			},
			dataType:'json',
			success:function(json) {
				if(json == true) {
					location.reload();
				}
			}
		});		
	},
	searchRequestBy:(ref, text, showresult) => {
		$.ajax({
			url: BASE_URL+ref,
			type:'POST',
			data: {
				text:text
			},
			dataType:'json',
			success:function(json) {
				if(json != '') {
					$('div.'+showresult).html(json);
					$('div.'+showresult).show(100);
				} else {
					$('div.'+showresult).hide(100);
				}
			}
		});		
	},
	verifyDateFirthDelivery:(date, type_input, ref_input, msg) => {
		$.ajax({
			url: BASE_URL+'verifydate',
			type:'POST',
			data: {
				date:date
			},
			dataType:'json',
			success:function(json) {
				if(json) {
					utils.errorImputs(type_input, ref_input, '#ced4da');
					$('input[name="'+ref_input+'"]').attr('data-status', true);
				} else {
					utils.errorImputs(type_input, ref_input, '#FF0000');
					utils.showAlerts('.message-add', msg);
					$('input[name="'+ref_input+'"]').attr('data-status', false);
				}
			}
		});		
	},
	showError:(input, error) => {
		let box = $('input[name="'+input+'"]');
        box.css('border-color', '#FF0000');
        let errorElement = '<div class="error">'+error+'</div>';
        $(box).parent().append(errorElement);
    },
    clearErrors:() => {
        let inputs = form.querySelectorAll('input');
        for(let i=0;i<inputs.length;i++) {
            inputs[i].style = '';
        }

        let errorElements = document.querySelectorAll('.error');
        for(let i=0;i<errorElements.length;i++) {
            errorElements[i].remove();
        }
    },
    errorImputs:(type, ref, value) => {
		$(type+'[name="'+ref+'"]').css({'border-color': value});
	},
	messageErrorImputs:(ref, value, type) => {
		$(ref).html(value);

		if(type) {
			$(ref).show();
		} else {
			$(ref).hide();
		}
	},
	showAlerts:(ref, msg) => {
		$(ref).html(msg);
		$(ref).css('top', '20px');
		setTimeout(function(){
			$(ref).css('top', '-100%');
		}, 4000);
	}
}