Untitled

mail@pastecode.io avatar
unknown
plain_text
3 years ago
17 kB
2
Indexable
Never
define([
	"jquery",
	"bootstrap",
	"moment",
	"daterangepicker",
	"gtmTrack",
	"authentication",
], function ($, bootstrap, moment, daterangepicker) {
	const EPProspectScheduleCalendar =
		"https://api-hml.skybr.digital/Prospect/v1/calendar";
	const EPProspectScheduleOrderStatus =
		"https://api-hml.skybr.digital/Prospect/v1/order/status";
	const EPProspectReschedule =
		"https://api-hml.skybr.digital/Prospect/v1/order/reschedule";

	//TAGUEMAENTO ASSINATURAS
	let sessionsVars = {
		SESSION_KEY_USERDATA_ASSISELECT: "P_uDSelectAssi",
		SESSION_KEY_USERDATA_ASSI: "SESSION_KEY_USERDATA_ASSI",
	};

	let v_status_assinatura = "nao-logado";

	if (acc.authentication.isAuthenticated()) {
		let assinaturaAtual = sessionStorage.getItem(
			sessionsVars.SESSION_KEY_USERDATA_ASSISELECT
		);
		let assinaturas = localStorage.getItem(
			sessionsVars.SESSION_KEY_USERDATA_ASSI
		)
			? JSON.parse(localStorage.getItem(sessionsVars.SESSION_KEY_USERDATA_ASSI))
			: null;
		if (assinaturas) {
			for (let x = 0; x < assinaturas.length; x++) {
				if (assinaturaAtual == assinaturas[x].id) {
					//
					v_tipo_assinatura = assinaturas[x].tipo;
					let v_plano = assinaturas[x].planoCliente;
					let v_plano_id = assinaturas[x].idPlanoCliente;
					let v_assinatura = assinaturas[x].id;
					let v_status_assinatura = assinaturas[x].statusAssinatura;
				}
			}
		}
		//tipo assinatira
		if (v_tipo_assinatura == 0 || v_tipo_assinatura == 1) {
			v_tipo_assinatura = "pos";
		} else if (v_tipo_assinatura == 2) {
			v_tipo_assinatura = "pre-livre";
		} else if (v_tipo_assinatura == 3) {
			v_tipo_assinatura = "pre";
		} else if (v_tipo_assinatura == 4) {
			v_tipo_assinatura = "bl";
		}

		//status assinatura
		if (v_status_assinatura == 0) {
			v_status_assinatura = "inativa";
		} else if (v_status_assinatura == 1) {
			v_status_assinatura = "ativa";
		} else if (v_status_assinatura == 2) {
			v_status_assinatura = "cancelada";
		} else if (v_status_assinatura == 3) {
			v_status_assinatura = "nao-habilitada";
		} else if (v_status_assinatura == 4) {
			v_status_assinatura = "desenhocida";
		}
	}

	/*GTM hashs data*/
	let gtmHashData = $(".meus-pedidos").data(),
		componentIdcms = gtmHashData.gtmCommonfield,
		componentObj = gtmHashData.gtmObj,
		objParse =
			componentObj != undefined
				? eval("(" + componentObj.replace(/'/g, '"') + ")")
				: "";

	/*RECUPERA numero da proposta*/
	const numberReq = sessionStorage.getItem("_proposalNumber");

	/*Initial pageview*/
	acc.gtmTrack.pageView(
		{
			hash: objParse["x200"],
			v_status_assinatura,
			idcms: "minha-sky/pedido/agendar-visita/",
			v_id_pedido: numberReq,
		},
		null,
		"minha-sky/pedido/agendar-visita/"
	);
	let nomesDias = ["Dom", "Seg", "Ter", "Qua", "Qui", "Sex", "Sab"],
		nomesDias1 = ["D", "S", "T", "Q", "Q", "S", "S"],
		nomesMeses = [
			"Janeiro",
			"Fevereiro",
			"Março",
			"Abril",
			"Maio",
			"Junho",
			"Julho",
			"Agosto",
			"Setembro",
			"Outubro",
			"Novembro",
			"Dezembro",
		];

	var arrayAgenda = [];
	var novoArray = [];
	var dataList = [];

	/*send data*/
	$("[name=optiontime]").on("change", function () {
		$(".wrap-option").removeClass("error");

		acc.gtmTrack.trackEvent(
			{
				hash: objParse[1],
				idcms: componentIdcms,
				v_status_assinatura,
				v_id_pedido: numberReq,
				v_periodo: $(this).val(),
			},
			null
		);
	});

	//gtm events click success page
	$(".agendamento-confirm .btnSkyPlay").on("click", function (e) {
		acc.gtmTrack.trackEvent(
			{
				hash: objParse[3],
				idcms: componentIdcms,
				v_status_assinatura,
				v_id_pedido: numberReq,
			},
			null
		);
	});

	$(".agendamento-confirm .btnInitial").on("click", function (e) {
		acc.gtmTrack.trackEvent(
			{
				hash: objParse[4],
				idcms: componentIdcms,
				v_status_assinatura,
				v_id_pedido: numberReq,
			},
			null
		);
	});

	//GTM CLICKS EVENTS - Voltar
	$(".btnReturn").on("click", function (e) {
		acc.gtmTrack.trackEvent(
			{
				hash: objParse[6],
				idcms: componentIdcms,
				v_status_assinatura,
				v_id_pedido: numberReq,
			},
			null
		);
	});

	//gtm events click error page
	$("#modalError .btnAgain").on("click", function (e) {
		acc.gtmTrack.trackEvent(
			{
				hash: objParse[5],
				idcms: componentIdcms,
				v_status_assinatura,
				v_id_pedido: numberReq,
			},
			null
		);
	});
	var calendar;
	$(".agendamento-wrap form").on("click", "button", function (e) {
		e.preventDefault();
		let hasError = false;

		let formData = {
			date: calendar.data("daterangepicker").startDate.format("YYYY/MM/DD"),
			time: $("[name=optiontime]:checked").val(),
		};

		let formDataBr = {
			date: calendar.data("daterangepicker").startDate.format("DD/MM/YYYY"),
		};

		/*validação*/
		$(".calendar-wrap, .wrap-option").removeClass("error");

		if ($('[name="date"]').val() == "") {
			$(".calendar-wrap").addClass("error");
			hasError = true;
		}

		if (!$("[name=optiontime]:checked").length) {
			$(".wrap-option").addClass("error");
			hasError = true;
		}

		if (!hasError) {
			//
			$(".agendamento-wrap").addClass("hide");
			$(".agendamento-confirm").removeClass("hide");

			$(".info-data .dateHour .date").html(formDataBr.date);

			if (formData.time == "Morning") {
				$(".info-data .dateHour .manha").removeClass("hide");
			} else if (formData.time == "Afternoon") {
				$(".info-data .dateHour .tarde").removeClass("hide");
			}

			acc.gtmTrack.pageView(
				{
					hash: objParse["x201"],
					v_status_assinatura,
					idcms: "minha-sky/pedido/agendamento-sucesso/",
					v_id_pedido: numberReq,
				},
				null,
				"minha-sky/pedido/agendamento-sucesso/"
			);
		} else {
			modalError(1);

			acc.gtmTrack.pageView(
				{
					hash: objParse["x202"],
					v_status_assinatura,
					idcms: "minha-sky/pedido/agendamento-erro/",
					v_id_pedido: numberReq,
				},
				null,
				"minha-sky/pedido/agendamento-erro/"
			);
		}

		acc.gtmTrack.trackEvent(
			{
				hash: objParse[2],
				idcms: componentIdcms,
				v_status_assinatura,
				v_id_pedido: numberReq,
			},
			null
		);
	});

	/*modal error*/
	function modalError(type) {
		/*
			type:
			1=erro data não disponível
			2=erro no pedido
			3=erro sem data no momento
			4=erro no sistema
			5=timeout 3 minutos
		*/

		let modalE = $("#modalError");

		modalE.find(".modal-body div").addClass("hide");
		modalE.find(".modal-body [data-error=" + type + "]").removeClass("hide");

		modalE.modal();
	}

	//** integracao  */

	function eDataValida(dates) {
		dates.filter((dataAtual) => {
			if (dataAtual.scheduleDate === dataSelecionada) {
				switch (periodoSelecionado.toLowerCase()) {
					case "morning":
						if (dataAtual.morning.available === true) {
							//chamar Reschedule
							return reagendamento();
							break;
						} else {
							// preencheCalendario(dataAtual.slice(-2));
							//seta erro no modal
							modalError(3);
							break;
						}
					case "afternoon":
						if (dataAtual.afternoon.available === true) {
							//chamar

							return reagendamento();
							break;
						} else {
							// preencheCalendario(dataAtual.slice(-2));
							//seta erro no modal
							modalError(3);
							break;
						}
					default:
						modalError(4);
						break;
				}
			}
		});
	}

	function degustacaoSkyPlay(dataPagamento, tipoProduto) {
		if (
			dataPagamento !== null &&
			dataPagamento !== undefined &&
			tipoProduto === "POS"
		) {
			dataPagamento = dataPagamento.slice(0, 10);
			let contadorDias = moment(dataPagamento).fromNow();
			let diaFuturo = contadorDias.contains("in");
			if (diaFuturo !== true) {
				contadorDias = contadorDias.replace(/([^\d])+/gim, "");
				if (contadorDias >= 7) {
					//Exibir opcao de degustacao
				} else {
					//Não exibir a opcao de degustacao
				}
			} else {
				//Nao exibir a opcao de degustacao
			}
		}
	}

	function validaMeioPagamento(tipoPagamento, isCancelledOrderService) {
		let isCancelled = isCancelledOrderService;
		if (tipoPagamento === "Crédito" && isCancelled !== true) {
			//Agenda liberada para reagendamento
			return true;
		} else {
			modalError(3);
			// Exibir erro de indisponibilidade de Data
		}
	}

	var tokenApi = sessionStorage.getItem("_tMeusPedidos");
	//PROPOSALRESUME
	var itemID;
	var proposalNumber = sessionStorage.getItem("_proposalNumber");
	//Get Status Order

	var radioValue = "";

	// function to get status from button
	$(document).on("click", "input[name='optiontime']", function (e) {
		// verifying if radios is unchecked
		$("#radioCheck").val("true");
		radioValue = $(this).val();

		if (
			$("#datepickerSelected").val() == "true" &&
			$("#radioCheck").val() == "true"
		) {
			$("#buttonConfirmSchedule").prop("disabled", false);
		}
	});

	//GET CALENDAR
	let getCallendarSuccess = function getCallendarSuccess(dataSuccess, valor) {
		$("#countTimes").val(parseInt($("#countTimes").val()) + 1);

		function pegarTodasDatas() {
			if (!dataSuccess.data.response.agenda.schedulePlanning) {
				proposalsResumeSuccess;
			}

			var dataMes =
				dataSuccess.data.response.agenda.schedulePlanning.scheduleEntry;
			var AgendaDisponivel = dataMes.filter(
				(element) =>
					element.morning.available ||
					element.afternoon.available ||
					element.evening.available
			);
			arrayAgenda.push(...AgendaDisponivel);
			arrayDatas = arrayAgenda.map((item) => item.scheduleDate);

			return arrayDatas;
		}

		if ($("#countTimes").val() == 1) {
			// hiding loading
			$(".meus-pedidos").removeClass("load-cicle");
			/*embeda calendário*/
			calendar = $(".agendamento-wrap").daterangepicker({
				singleDatePicker: true,
				parentEl: ".calendar-wrap",
				autoApply: true,
				startDate: moment(),
				minDate: moment(),
				maxDate: moment().add(3, "M"),
				locale: {
					format: "DD/MM/YYYY",
					daysOfWeek: nomesDias1,
					monthNames: nomesMeses,
				},
				isInvalidDate: function (date) {
					if (!pegarTodasDatas().includes(date.format("YYYY-MM-DD"))) {
						$("#datepickerSelected").val("true");

						// show radio buttons
						$(".wrap-option").removeClass("hide");
						return true;
					}
				},
			});

			/* range update listener */
			calendar.on("apply.daterangepicker", function (ev, picker) {
				$('[name="date"]').val(picker.startDate.format("YYYY-MM-DD"));
				$(".calendar-wrap").removeClass("error");
			});

			/* prevent hide after range selection */
			calendar.data("daterangepicker").hide = function () {};

			/* show picker on load */
			calendar.data("daterangepicker").show("slow");

			// at this point, confirm button is disabled
			$("#buttonConfirmSchedule").prop("disabled", true);
		}

		let datasDisponiveis;
		if (dataSuccess.data.response.status !== "error") {
			datasDisponiveis =
				dataSuccess.data.response.agenda.schedulePlanning.scheduleEntry;
			if (datasDisponiveis === null || datasDisponiveis === undefined) {
				modalError(3);
			} else {
				eDataValida(datasDisponiveis);
			}
		} else {
			modalError(3);
		}
	};

	let getCallendarError = function getCallendarError(dataError) {
		console.error("else getCalendar ", dataError.message);
		modalError(4);
	};

	var statusOrdersSuccess = async function statusOrderSuccess(dataSuccess) {
		if (dataSuccess.data.response.length !== 0) {
			itemID = dataSuccess.data.response[0].items[0].itemID;
			$("#itemID").val(itemID);

			let dataCriacao = dataSuccess.data.response[0].items[0].itemCreationDate;
			let diaDoAgendamento = dataCriacao.slice(0, 10);
			if (diaDoAgendamento !== moment().format("YYYY-MM-DD")) {
				return itemID;
			} else {
				modalError(2);
			}
		}
	};

	var statusOrdersError = async function statusOrderError(dataError) {
		//Modal de erro
		modalError(2);
		console.error("statusOrderError -> ", dataError);
	};

	let proposalsResumeSuccess = function proposalsResumeSuccess(dataSuccess) {
		let tipoPagamento = dataSuccess.data.proposal.payments.type;
		let isCancelledOrderService = dataSuccess.data.proposal.isCancelled;
		let dataPagamento = dataSuccess.data.proposal.payments.processingDate;
		let tipoProduto = dataSuccess.data.proposal.product.group;

		//Chamada statusOrder
		var EPStatusOrders =
			EPProspectScheduleOrderStatus + "?proposalNumber=" + proposalNumber;
		skyacc.ajax(
			"GET",
			EPStatusOrders,
			null,
			null,
			statusOrdersSuccess,
			statusOrdersError
		);

		var monthCurrent = moment().format("MM");
		var yearCurrent = moment().format("YYYY");

		//GET CALLENDAR VERIFICA CALENDARIO DISPONIVEL
		var EPGetCallendar =
			EPProspectScheduleCalendar +
			"?month=" +
			monthCurrent +
			"&year=" +
			yearCurrent;
		var callendarObjHeader = { authorization: "Bearer " + tokenApi };

		skyacc.ajax(
			"GET",
			EPGetCallendar,
			null,
			callendarObjHeader,
			getCallendarSuccess,
			getCallendarError
		);

		var monthCurrent = moment().add(1, "M").format("MM");
		var yearCurrent = moment().format("YYYY");
		//GET CALLENDAR VERIFICA CALENDARIO DISPONIVEL
		var EPGetCallendar =
			EPProspectScheduleCalendar +
			"?month=" +
			monthCurrent +
			"&year=" +
			yearCurrent;
		var callendarObjHeader = { authorization: "Bearer " + tokenApi };

		skyacc.ajax(
			"GET",
			EPGetCallendar,
			null,
			callendarObjHeader,
			getCallendarSuccess,
			getCallendarError
		);
		var monthCurrent = moment().add(2, "M").format("MM");
		var yearCurrent = moment().format("YYYY");

		//GET CALLENDAR VERIFICA CALENDARIO DISPONIVEL
		var EPGetCallendar =
			EPProspectScheduleCalendar +
			"?month=" +
			monthCurrent +
			"&year=" +
			yearCurrent;
		var callendarObjHeader = { authorization: "Bearer " + tokenApi };

		skyacc.ajax(
			"GET",
			EPGetCallendar,
			null,
			callendarObjHeader,
			getCallendarSuccess,
			getCallendarError
		);

		degustacaoSkyPlay(dataPagamento, tipoProduto);
		//validaMeioPagamento(tipoPagamento, isCancelledOrderService);

		return true;
	};
	let proposalsResumeError = function proposalsResumeError(dataErro) {
		if (dataErro.status === 403) {
			modalError(5);
		} else {
			modalError(4);
		}
	};
	var EPProposalsResume = EPSalesProspectProposalsResume; //Mais complemento
	var objetoHeaderAjax = { authorization: "Bearer " + tokenApi };
	//body sempre no json.stringfy()

	//PROPOSALRESUME
	skyacc.ajax(
		"GET",
		EPProposalsResume,
		null,
		objetoHeaderAjax,
		proposalsResumeSuccess,
		proposalsResumeError
	);

	//Reagendar ordem de servico

	var rescheduleSuccess = function rescheduleSuccess(dataSuccess) {
		if (dataSuccess.data.response.code != "0") {
			debugger;
			modalError(4);
			throw new Error("Agendamento nao realizado", dataSuccess);
		} else {
			$(".meus-pedidos").removeClass("load-cicle");
			$(".agendamento-wrap").hide();
			$(".agendamento-confirm").removeClass("hide");
			$(".numero-protocolo").text(itemID);

			return true;
		}
	};

	var rescheduleError = async function rescheduleError(dataError) {
		//ativar Modal de erro 1
		modalError(1);
		console.error("resultado do erro -> ", dataError);
	};

	function reagendamento() {
		var EPRescheduleOrder = EPProspectReschedule;
		//PRECISA Pegar ITEMID - SCHEDULEDATE - PERIOD
		var bodyRescheduleOrder = JSON.stringify({
			itemId: $("#itemID").val(),
			observation: "Reagendado-Solic. pelo ass", //Por hora valor tem q ser fixo
			updateReasonId: "829", //Por hora valor tem q ser fixo
			schedule: {
				period: radioValue,
				scheduleDate: $('[name="date"]').val(),
			},
		});
		skyacc.ajax(
			"PATCH",
			EPRescheduleOrder,
			bodyRescheduleOrder,
			null,
			rescheduleSuccess,
			rescheduleError
		);
	}

	$(".btn-block").on("click", function () {
		$(".meus-pedidos").addClass("load-cicle");
		reagendamento();
	});
	// timeout de sessao
	$(function timeOut() {
		setTimeout(function () {
			modalError(5);
		}, 180000);
	});

	//remove barra superior - ASSINAR
	$("#header-sky-uno").on("DOMNodeInserted", function (e) {
		$(".alert-comunication").html("");
	});

	//add class prev next calendar
	$(".prev.available")
		.find("span")
		.addClass("sky_icon sky-icon-line-arrow-right-ios icon_xs");
	$(".next.available")
		.find("span")
		.addClass("sky_icon sky-icon-line-arrow-left-ios icon_xs");
	$(".calendar-wrap").on("DOMNodeInserted", function (e) {
		$(".prev.available")
			.find("span")
			.addClass("sky_icon sky-icon-line-arrow-right-ios icon_xs");
		$(".next.available")
			.find("span")
			.addClass("sky_icon sky-icon-line-arrow-left-ios icon_xs");
	});

	if (sessionStorage.getItem("_statusLabel") != "equipamento instalado") {
		$("#subMenuMinhaSKY")
			.parents("ul")
			.first()
			.addClass("hide")
			.find("li")
			.addClass("hide");
	}
});