const programs_with_catalog = ["la", "lkt"];

var preapproval_selected_program = undefined;
var preapproval_selected_brand = undefined;
var preapproval_exists = false;
var preapproval_payload = {
	vat: "", 
	program: "", 
	brand: "", 
	model: "", 
	price: "", 
	name: "", 
	phone: "", 
};

var leasing_form_submitting = false;

function preapproval_object_check_errors()
{
	var valid = true;
	console.log({ preapproval_payload })

	if(preapproval_payload.vat === "")
	{
		valid = false;
		console.log("preapproval_vat");
		$("#preapproval_vat_wrapper").addClass("error").attr("data-error", "Пожалуйста, укажите ИНН организации");
	}
	else
	{
		if(preapproval_payload.vat.toString().length < 10)
		{
			$("#preapproval_vat_wrapper").addClass("error").attr("data-error", "Пожалуйста, укажите корректный ИНН");
		}
	}

	if(preapproval_payload.price === "")
	{
		valid = false;
		console.log("preapproval_price");
		$("#preapproval_price_wrapper").addClass("error").attr("data-error", "Пожалуйста, укажите цену объекта лизинга");
	}

	if(preapproval_payload.program === "")
	{
		valid = false;
		console.log("preapproval_program_wrapper");
		$("#preapproval_program_wrapper").addClass("error").attr("data-error", "Пожалуйста, укажите выберите программу");
	}

	if(preapproval_payload.brand === "")
	{
		valid = false;
		if(programs_with_catalog.indexOf(preapproval_selected_program) > -1)
		{
			console.log(1);
			$("#preapproval_brand_select_wrapper").addClass("error").attr("data-error", "Пожалуйста, укажите марку");
		}
		else
		{
			console.log(2);
			$("#preapproval_brand_input_wrapper").addClass("error").attr("data-error", "Пожалуйста, укажите марку");
		}
	}

	if(preapproval_payload.model === "" && preapproval_payload.brand !== "Другая марка")
	{
		valid = false;
		if(programs_with_catalog.indexOf(preapproval_selected_program) > -1)
		{
			console.log(3);
			if(preapproval_payload.brand !== "")
			{
				$("#preapproval_model_select_wrapper").addClass("error").attr("data-error", "Пожалуйста, укажите модель");
			}
		}
		else
		{
			console.log(4);
			$("#preapproval_model_input_wrapper").addClass("error").attr("data-error", "Пожалуйста, укажите марку");
		}
	}

	return valid;
}

function preapproval_form_check_errors()
{
	console.log("preapproval_form_check_errors()", { preapproval_payload });

	var valid = true;

	if(preapproval_payload.name === "")
	{
		valid = false;
		$("#preapproval_name_wrapper").addClass("error").attr("data-error", "Пожалуйста, укажите с кем связаться");
	}

	if(preapproval_payload.phone === "")
	{
		valid = false;
		$("#preapproval_phone_wrapper").addClass("error").attr("data-error", "Пожалуйста, укажите номер телефона");
	}

	if(!$("#preapproval_form_policy_checkbox").is(':checked'))
	{
		valid = false;
		$("#preapproval_form_policy_wrapper").addClass("error");		
	}

	return valid;
}

(function InitAprrove() 
{
	console.log("OF", window.innerWidth);
	if(window.innerWidth > 540)
	{
		$("#preapproval_block").find(".block_toggle")
		.on("mouseenter", function() { 
			$("#preapproval_block_span_wrapper").css("margin-left", "-20px" );
			$("#preapproval_block_span").removeClass("span_hidden").css("transform", "translate(0px, 0px)");
		})
		.on("mouseleave", function() { 
			$("#preapproval_block_span_wrapper").css("margin-left", "-500px");
			$("#preapproval_block_span").add("span_hidden").css("transform", "translate(-500px, 0px)");
		});

		setTimeout(function()
		{
			$("#preapproval_block_span_wrapper").css("margin-left", "-500px");
			$(".span_animate_out").removeClass("span_animate_out").addClass("span_hidden");
		}, 2000);
	}

	const wrap = $("#preapproval_block");
	const form = $(wrap).find("form");

	const checkFields = () => 
	{
		var currentStep = $(".step.active");
		var inputsFilled = currentStep.find("input, select").filter(function() 
		{
			return $(this).val() === ""|| $(this).val() === null;
		}).length === 0; 

		if(!inputsFilled) 
		{
			alert("Пожалуйста, заполните все поля.");
		}
		return inputsFilled;
	}

	$(wrap).on("click", ".block_toggle", function(e) 
	{
		$(".preapproval_exists").css("display", "none");
		$(".preapproval_new").css("display", "none");

		e.preventDefault();
		$(wrap).toggleClass("active");
		$(wrap).find(".block_title").text("Получите предварительное одобрение за 1 минуту");
		$(wrap).find(".step").eq(0).addClass("active").siblings().removeClass("active");
	});

	$(wrap).on("change", "#preapproval_program", function(e)
	{
		console.log(e.target);
		preapproval_selected_program = e.target.value;
		preapproval_payload.program = $(this).find("option:selected").text();
		$("#preapproval_program_wrapper").removeClass("error").removeAttr("data-error");
		preapproval_payload.brand = "";
		preapproval_payload.model = "";
		$("#preapproval_brand_input").val("");
		$("#preapproval_model_input").val("");

		$("#preapproval_brand_select").attr("disabled", true);
		$("#preapproval_brand_select").empty();
		$("#preapproval_brand_select").append('<option selected disabled value="">Марка</option>');

		$("#preapproval_model_select").attr("disabled", true);
		$("#preapproval_model_select").empty();
		$("#preapproval_model_select").append('<option selected disabled value="">Модель</option>');

		if(programs_with_catalog.indexOf(preapproval_selected_program) > -1)
		{
			$("#preapproval_brand_select_wrapper").css("display", "block");
			$("#preapproval_model_select_wrapper").css("display", "block");
			$("#preapproval_brand_input_wrapper").css("display", "none");
			$("#preapproval_model_input_wrapper").css("display", "none");

			$.get("/api/programs/brands/", { "PROGRAM": preapproval_selected_program }, function(response)
			{
				if(response.brands !== undefined)
				{
					if(response.brands.length > 0)
					{
						for(let i in response.brands)
						{
							$("#preapproval_brand_select").append('<option value="'+response.brands[i].id+'">'+response.brands[i].text+'</option>');
						}
						$("#preapproval_brand_select").append('<option value="Другая марка">Другая марка</option>');

						$("#preapproval_brand_select").attr("disabled", false);
					}
				}
			});
		}
		else
		{
			$("#preapproval_brand_select_wrapper").css("display", "none");
			$("#preapproval_model_select_wrapper").css("display", "none");
			$("#preapproval_brand_input_wrapper").css("display", "block");
			$("#preapproval_model_input_wrapper").css("display", "block");
		}
	});

	$(wrap).on("change", "#preapproval_brand_select", function(e)
	{
		preapproval_selected_brand = e.target.value;
		preapproval_payload.brand = $(this).find("option:selected").text();
		$("#preapproval_brand_select_wrapper").removeClass("error").removeAttr("data-error");
		$("#preapproval_brand_input_wrapper").removeClass("error").removeAttr("data-error");

		if(preapproval_selected_brand === "Другая марка")
		{
			$("#preapproval_model_select").attr("disabled", true);
			$("#preapproval_model_select").empty();
			$("#preapproval_model_select").append('<option selected disabled value="">Модель</option>');
			preapproval_payload.model = "";
		}
		else
		{
			$.get("/api/programs/models/", { "PROGRAM": preapproval_selected_program, "BRAND_ID": preapproval_selected_brand }, function(response)
			{
				$("#preapproval_model_select").attr("disabled", true);
				$("#preapproval_model_select").empty();
				$("#preapproval_model_select").append('<option selected disabled value="">Модель</option>');

				if(response.models !== undefined)
				{
					if(response.models.length > 0)
					{
						for(let i in response.models)
						{
							$("#preapproval_model_select").append('<option value="'+response.models[i].id+'">'+response.models[i].text+'</option>');
						}
						$("#preapproval_model_select").append('<option value="Другая модель">Другая модель</option>');

						$("#preapproval_model_select").attr("disabled", false);
					}
				}
			});
		}
	});

	$(wrap).on("change", "#preapproval_model_select", function(e)
	{
		preapproval_payload.model = $(this).find("option:selected").text();
		$("#preapproval_model_select_wrapper").removeClass("error").removeAttr("data-error");
		$("#preapproval_model_input_wrapper").removeClass("error").removeAttr("data-error");
	});

	$("#preapproval_vat").on("input", function(e)
	{
		preapproval_payload.vat = e.target.value;
		$("#preapproval_vat_wrapper").removeClass("error").removeAttr("data-error");
	});

	$("#preapproval_price").on("input", function(e)
	{
		preapproval_payload.price = e.target.value;
		$("#preapproval_price_wrapper").removeClass("error").removeAttr("data-error");
	});

	$("#preapproval_brand_input").on("input", function(e)
	{
		preapproval_payload.brand = e.target.value;
		$("#preapproval_brand_input_wrapper").removeClass("error").removeAttr("data-error");
	});

	$("#preapproval_model_input").on("input", function(e)
	{
		preapproval_payload.model = e.target.value;
		$("#preapproval_model_input_wrapper").removeClass("error").removeAttr("data-error");
	});

	$("#preapproval_name").on("input", function(e)
	{
		preapproval_payload.name = e.target.value;
		$("#preapproval_name_wrapper").removeClass("error").removeAttr("data-error");
	});

	$(wrap).on("click", ".next", function(e) 
	{
		e.preventDefault();
		var currentStep = $(".step.active");

		if(preapproval_object_check_errors())
		{
			console.log({ preapproval_payload });

			currentStep.removeClass("active");
			currentStep.next(".step").addClass("active");
//			$(wrap).find(".block_title").text("Вам предварительно одобрено всё");

			$.post("/api/preapproval/", { vat: preapproval_payload.vat }, function(response)
			{
				console.log("/api/preapproval/", { response });

				$(".loading_spinner").css("display", "none");
				$("#preapproval_form").css("display", "block");

				if(response.client === "partner")
				{
					preapproval_exists = true;
					$("#preapproval_status").text("Мы Вас узнали 😊");
					$(".preapproval_exists").css("display", "block");
				}
				else
				{
					$("#preapproval_status").text("Вам предварительно одобрено финансирование");
					$(".preapproval_new").css("display", "block");
				}

				//$(form).reset();
				//$(wrap).find(".block_close").click();
			});
		}
	});

	$(form).on("submit", function(e) 
	{
		e.preventDefault();
		var currentStep = $(".step.active");

		if(preapproval_form_check_errors()) 
		{
			console.log({ preapproval_payload });

			$(".loading_spinner").css("display", "inline-block");
			currentStep.removeClass("active");
			currentStep.next(".step").addClass("active");

			var formData = new FormData($("#form_leasing_request")[0]);
			formData.append("form", "FORM_LEASING_REQUESTS");
			formData.append("FORM_FIELD_FIO", preapproval_payload.name);
			formData.append("FORM_FIELD_PHONE", preapproval_payload.phone);
			formData.append("FORM_FIELD_PAGE_NAME", document.title);
			formData.append("FORM_FIELD_PAGE_URL", window.location.href);
			formData.append("FORM_FIELD_BRAND", preapproval_payload.brand);
			formData.append("FORM_FIELD_MODEL", preapproval_payload.model);
			formData.append("FORM_FIELD_PRICE", preapproval_payload.price);
			formData.append("FORM_FIELD_PROGRAM", preapproval_payload.program);
			formData.append("FORM_FIELD_INN", preapproval_payload.vat);

			grecaptcha.ready(function() 
			{
				grecaptcha.execute($("meta[name=recaptcha_site_key]")
				.attr("content"), { action: 'submit' })
				.then(function(token)
				{
					formData.append("recaptcha_token", token);

					$.ajax(
					{
						url: "/api/forms/", type: 'POST', success: function(response)
						{
							$(".loading_spinner").css("display", "none");

							if(response.status === "complete")
							{
								try
								{
									ym(66905533,'reachGoal','leasingform')
								}
								catch(e)
								{
									console.error(e);
								}

								if(preapproval_exists)
								{
									$(".preapproval_exists_success").css("display", "block");
								}
								else
								{
									$(".preapproval_new_success").css("display", "block");			
								}
							}
							else if(response.status === "error")
							{
								if(response.message === "recaptcha_error")
								{
									$(".preapproval_error_recaptcha_message").css("display", "block");
								}
								else
								{
									$(".preapproval_error_message").css("display", "block");
								}
							}
						}, data: formData,
						dataType: "json",
						cache: false, contentType: false, processData: false
					});
				});
			});

			/*
			$.post("/api/preapproval/send/", preapproval_payload, function(response)
			{
			});
			*/

			/*
			$.post("/api/preapproval/", preapproval_payload, function(response)
			{
				console.log("send");
				$(form).reset();
				$(wrap).find(".block_close").click();
				$("#approval_status").text("Вам предварительно одобрено всё");
				$("#approval_status").text("Мы Вас узнали 😊");
				$("#approval_comment").text("Оставьте контактные данные и мы свяжемся с Вами");
				$("#approval_comment").text("Ваш менеджер по лизингу свяжется с Вами в ближайшее время");	
			});
			*/
		}
	})

	$("#preapproval_form_policy_checkbox").on("change", function(e)
	{
		if($(this).is(':checked'))
		{
			$("#preapproval_send_button").attr("disabled", false);
		}
		else
		{
			$("#preapproval_send_button").attr("disabled", true);
		}
	});
}());

$(document).ready(function()
{
	$("#preapproval_phone").inputmask('+7 (999) 999-9999', { 
		oncomplete: function(event) {
			const phone = event.target.value.replace(/\D/g, "");
			preapproval_payload.phone = phone;
			$("#preapproval_phone_wrapper").removeClass("error").removeAttr("data-error");
		}, 
		onincomplete: function(event) {
			preapproval_payload.phone = event.target.value.replace(/\D/g, "");
		}, 
		onBeforePaste: function(pastedValue, opts) {
			preapproval_payload.phone = pastedValue;
			$("#preapproval_phone_wrapper").removeClass("error").removeAttr("data-error");
			return pastedValue;
		}, 
		onBeforeMask: function(value, opts)
		{
			const phone = value.replace(/\D/g, "");
			if(phone.length === 11)
			{
				preapproval_payload.phone = phone;
				$("#preapproval_phone_wrapper").removeClass("error").removeAttr("data-error");
			}
		}, 
	});
});
