$(function() {
	// 轮播图
	// var id = getQueryString("id")
	var id =''
	if(getQueryString("id")){
		id = getQueryString("id");
	}else{
		id = sessionStorage.getItem('newcardetailId');
	}
	function initSlick() {
		$(".rental-slider").slick({
			slidesToShow: 1,
			slidesToScroll: 1,
			arrows: false,
			fade: true,
			asNavFor: ".as-nav-slider",
		});
		$(".as-nav-slider").slick({
			slidesToShow: 5,
			slidesToScroll: 1,
			// slide: true,
			asNavFor: ".rental-slider",
			dots: false,
			arrows: false,
			centerMode: false,
			variableWidth: true,
			focusOnSelect: true,
			responsive: [{
					breakpoint: 1200,
					settings: {
						slidesToShow: 4,
					},
				},
				{
					breakpoint: 1025,
					settings: {
						slidesToShow: 3,
					},
				},
			],
		});
	}
	// 生成HTML
	function generateslide(product) {
		if (product.pic_full == '') {
			return ''
		}
		return `
					<div class="rental-slide">
						<img src="${product.pic_full}" alt="banner">
					</div>
			    `;
	}

	function generateslide1(product) {
		if (product.pic_full == '') {
			return ''
		}
		return `
					<div class="img-box">
					    <img src="${product.pic_full}" alt="car">
					</div>
			    `;
	}
	// 渲染轮播图
	function renderbanner(lbdata) {
		const rentalslider = document.getElementById('rental-slider');
		rentalslider.innerHTML = lbdata.map(product =>
			generateslide(product)
		).join('');
		const asnavslider = document.getElementById('as-nav-slider');
		asnavslider.innerHTML = lbdata.map(product =>
			generateslide1(product)
		).join('');
		initSlick()
	}
	// Introduction
	function Introductionhtml(data){
		$(".nav-menu").append(
			`<li class="nav-item"><a href="#section1" class="nav-link" data-i18n="newcars.Introduction"></a></li>`
		);
		var html='';
		html+='<section id="section1" class="section"> <h2 class="wp-block-heading" data-i18n="newcars.Introduction"></h2> <ul class="wp-block-list unstyled" >'
		$.each(data,function(){
			html+="<li>"+this.content+"</li>"
		});
		html+='</ul></section>'
		$(".content").append(html)
		
	}
	// Highlighted
	function Highlightedhtml(data){
		var html='';
		$(".nav-menu").append(
			`<li class="nav-item"><a href="#section2" class="nav-link" data-i18n="newcars.Highlighted"></a></li>`
		);
		html+='<section id="section2" class="section"> <h2 class="wp-block-heading"  data-i18n="newcars.Highlighted"></h2> <ul class="wp-block-list unstyled" >'
		
		$.each(data,function(){
			html+="<li><strong>"+this.title+"</strong><br>"+this.content+"</li>"
		});
		html+='</ul></section>'
		$(".content").append(html)
	}
	// video
	function videohtml(data){
		$(".nav-menu").append(
			`<li class="nav-item"><a href="#section3" class="nav-link" data-i18n="newcars.video"></a></li>`
		);
		var html=`<section id="section3" class="section"> <h2 class="wp-block-heading" data-i18n="newcars.video"></h2> <iframe width="100%" src="${data}" title="YouTube video player" frameborder="0" allow="accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture; web-share" referrerpolicy="strict-origin-when-cross-origin" allowfullscreen=""></iframe></section>`
		$(".content").append(html)
	}
	
	// FAQ
	function FAQhtml(data){
		var html='';
		$(".nav-menu").append(
			`<li class="nav-item"><a href="#section4" class="nav-link" data-i18n="newcars.FAQ"></a></li>`
		);
		html+='<section id="section4" class="section"> <h2 class="wp-block-heading pcontenth2" data-i18n="newcars.FAQ"></h2> <div class="schema-faq wp-block-yoast-faq-block" id="faqs">'
		
		$.each(data,function(){
			html+=`<div class="schema-faq-section" >
				<strong class="schema-faq-question">${this.title}</strong>
				<p class="schema-faq-answer">${this.content}</p>
			</div>`
		});
		html+='</div></section>'
		$(".content").append(html)
	}
	
	// 处理导航和滚动
	function initNavigation() {
		// 获取内容区域
		const contentScroll = document.querySelector('.content');
		// 更新导航选中状态的函数
		function updateNavState(targetId) {
			$('.nav-item').removeClass('current');
			$(`.nav-link[href="#${targetId}"]`).parent().addClass('current');
		}
		
		// 使用jQuery事件委托处理点击事件
		$('.nav-menu').off('click', '.nav-link').on('click', '.nav-link', function(e) {
			e.preventDefault();
			const targetId = $(this).attr('href').substring(1);
			const targetElement = document.getElementById(targetId);
			
			if (targetElement) {
				// 获取目标元素相对于视口的位置
				const targetPosition = targetElement.getBoundingClientRect().top + window.pageYOffset;
				
				// 立即更新选中状态
				updateNavState(targetId);
				
				// 使用window.scrollTo方法实现滚动
				window.scrollTo({
					top: targetPosition,
					behavior: 'smooth'
				});
			}
		});

		// 监听滚动事件
		let scrollTimeout;
		$(window).on('scroll', function() {
			// 清除之前的定时器
			if (scrollTimeout) {
				clearTimeout(scrollTimeout);
			}
			
			// 设置新的定时器，避免频繁触发
			scrollTimeout = setTimeout(function() {
				const sections = document.querySelectorAll('[id^="section"]');
				const scrollTop = window.pageYOffset;
				
				// 找到当前可见区域内的section
				let currentSection = null;
				sections.forEach(section => {
					const sectionTop = section.getBoundingClientRect().top + window.pageYOffset;
					const sectionBottom = sectionTop + section.offsetHeight;
					
					if (scrollTop >= sectionTop - 100 && scrollTop < sectionBottom) {
						currentSection = section;
					}
				});
				
				// 更新导航选中状态
				if (currentSection) {
					updateNavState(currentSection.id);
				}
			}, 100);
		});

		// 页面加载时激活第一个导航链接
		$('.nav-item:first').addClass('current');
	}

	// 获取数据并初始化
	AjaxUtils.get('apis/vehicle/new/'+id+'/detail', {
		id: id
	}).done(function(data) {
		var carinfo = data.data
		$(".carname").html(carinfo.name)
		$(".carpice").html(carinfo.price)
		$(".carbrand").html(carinfo.brand_name)
		$(".carstype").html(carinfo.type_name)
		$(".careng").html(carinfo.energy_name)
		$(".carstatus").html(carinfo.store_status_name)
		$(".carkm").html(carinfo.mileage)
		$(".carage").html(carinfo.vehicle_age)
		$(".condition_desc").html(carinfo.condition_desc)
		$(".Locations").html(carinfo.location_name)
		$(".views").html(carinfo.views)
		$("#brands").html('<a href="brand.html?id='+carinfo.brand+'">'+carinfo.brand_name+'</a>')
		renderbanner(carinfo.album)
		
		Introductionhtml(carinfo.content)
		Highlightedhtml(carinfo.trait)
		if(carinfo.video!=''){
			videohtml(carinfo.video)
		}
		FAQhtml(carinfo.asked)
		
		// 初始化导航
		i18n.loadLanguage(localStorage.getItem('lang')?localStorage.getItem('lang'): 'en')
		// 确保在内容加载完成后再初始化导航
		setTimeout(initNavigation, 100);
		
		// console.log(data);
	}).fail(function(error) {
		// console.error(error);
	});
	
	


	$("#subbtn").click(function() {
		var name = $("#name").val()
		var phone = $("#Phone").val()
		var content = $("#content").val()
		var Email = $("#Email").val()

		AjaxUtils.post('apis/contact/add', {
			name: name,
			phone: phone,
			content: content,
			email: Email,
			vehicle_id: id
		}).done(function(result) {
			alert(result.data.message)
			// console.log(result);
		}).fail(function(error) {
			// console.error(error);
		});
	})
})