$(function() {
	Vue.component('v-select', VueSelect.VueSelect);
	console.log(getQueryString("type"))
	var brand = getQueryString("brand") ? Number(getQueryString("brand")) : ''
	var model = getQueryString("model") ? Number(getQueryString("model")) : ''
	var energy = getQueryString("energy") ? Number(getQueryString("energy")) : ''
	var store_status = getQueryString("store_status") ? Number(getQueryString("store_status")) : ''
	var min_price = getQueryString("min_price") ? Number(getQueryString("min_price")) : ''
	var max_price = getQueryString("max_price") ? Number(getQueryString("max_price")) : ''
	var price = getQueryString("price") ? getQueryString("price") : ''
	var mileage = getQueryString("mileage") ? getQueryString("mileage") : ''
	var min_mileage=getQueryString("min_mileage") ? Number(getQueryString("min_mileage")) : ''
	var max_mileage=getQueryString("max_mileage") ? Number(getQueryString("max_mileage")) : ''
	var types = getQueryString("type") ? Number(getQueryString("type")) : ''
	var vm = new Vue({
		el: '#app',
		data: {
			currentPage: 1, // 当前页码
			pageSize: 12, // 每页条数
			totalItems: 0, // 总数据量（后端分页用）
			dataList: [],
			isshow:false,
			model: [],
			brandlist: [],
			energy: [],
			mileage: [],
			pricemin: [],
			pricemax: [],
			mileagemin: [],
			mileagemax: [],
			score_status: [],
			licklist:[],
			type: [],
		
			
			select: {
				brand: brand,
				model: model,
				energy: energy,
				store_status: store_status,
				min_price: min_price,
				max_price: max_price,
				price:price,
				mileage:mileage,
				start_year: '',
				end_year: '',
				min_mileage: min_mileage,
				max_mileage:max_mileage,
				type: types,
			},
		},
		computed: {
			// 当前页数据（前端分页）
			currentPageData() {
				const start = (this.currentPage - 1) * this.pageSize;
				return this.allData.slice(start, start + this.pageSize);
			},
			// 总页数
			totalPages() {
				return Math.ceil(this.totalItems / this.pageSize);
			},
			// 动态页码范围
			visiblePages() {
				const maxVisible = 5;
				let start = Math.max(1, this.currentPage - 2);
				let end = Math.min(start + maxVisible - 1, this.totalPages);
				return Array.from({
					length: end - start + 1
				}, (_, i) => start + i);
			}
		},
		watch: {
			currentPage() {
				this.fetchData(); // 后端分页时触发数据更新
			}
		},
		created: function() {
			this.getbrand()
			this.fetchData()
		},
		methods: {
			getbrand(brand_id) {
				var that = this
				AjaxUtils.get('apis/search/options', {}).done(function(data) {
					var datas = data.data
					that.brandlist = datas.brand
					that.energy = datas.energy
					that.mileage = datas.price
					that.pricemin = datas.mileage
					that.mileagemin = datas.mileage
					that.score_status = datas.score_status
					that.type = datas.type
				}).fail(function(error) {
					// console.error(error);
				});
			},
			licklistfn(){
				var that = this
				that.licklist=[]
				AjaxUtils.get('apis/vehicle/random', {}).done(function(data) {
					var data = data.data
					that.licklist.push(data)
				}).fail(function(error) {
					// console.error(error);
				});
			},
			//获取品牌类型
			getmodels(brand_id) {
				var that = this
				AjaxUtils.get('apis/get/models', {
					brand_id: brand_id
				}).done(function(data) {
					that.model = data.data
				}).fail(function(error) {
					// console.error(error);
				});
				// fetch(baseURL+'apis/get/models?brand_id='+brand_id,options)
				//   .then(response => {
				//     if (!response.ok) {
				//       throw new Error('Network response was not ok');
				//     }
				//     return response.json();
				//   })
				//   .then(data => {
				//     that.model = data.data
				// 	// console.log(that.model)
				//   })
				//   .catch(error => {
				//     this.error = error.message;
				//     this.loading = false;
				// });
			},
			//品牌选择
			onSelectbrand(item) {
				if (item == null) {
					item = ''
				}
				this.select.brand = item
				this.fetchData()
				if (item != '') {
					this.getmodels(item)
				}
				// console.log('Selected item:', item);
			},
			//类型
			onSelectmodel(item) {
				if (item == null) {
					item = ''
				}
				this.select.model = item
				this.fetchData()
			},
			onSelectengineType(item) {
				if (item == null) {
					item = ''
				}
				// min_price:'',
				// max_price:'',
				this.select.energy = item
				this.fetchData()
			},
			onSelectinventoryStatus(item) {
				if (item == null) {
					item = ''
				}
				this.select.store_status = item
				this.fetchData()
			},
			onSelectpriceFromLow(item) {
				var min=''
				var max=''
				if (item == null) {
					item = ''
				}else{
					min = item.split(/\s*-\s*/).map(Number)[0];
					max = item.split(/\s*-\s*/).map(Number)[1];
				}
				this.select.min_price = min
				this.select.max_price = max
				this.select.price = item
				this.fetchData()
			},
			onSelectmileageRange(item) {
				var min=''
				var max=''
				if (item == null) {
					item = ''
				}else{
					min = item.split(/\s*-\s*/).map(Number)[0];
					max = item.split(/\s*-\s*/).map(Number)[1];
				}
				this.select.min_mileage = min
				this.select.max_mileage = max
				this.select.mileage = item
				this.fetchData()
			},
			onSelectvehicleType(item) {
				if (item == null) {
					item = ''
				}
				this.select.type = item
				this.fetchData()
			},
			onSelectstartYear(item) {
				this.fetchData()
			},
			onSelectendYear(item) {
				this.fetchData()
			},
			fetchData() {
				// 新的参数对象
				const newParams = {
					param2: 'value2'
				};

				// 创建新的查询字符串
				const newQueryString = new URLSearchParams(this.select).toString();

				// 新的完整URL
				const newUrl = `${window.location.pathname}?${newQueryString}`;
				// console.log(newUrl)
				// 使用pushState改变URL
				history.pushState(null, null, newUrl);
				// console.log(params.toString())
				// window.location.search = `?${params.toString()}`;
				var that = this
				AjaxUtils.get('apis/vehicle/list', {
					page: this.currentPage,
					per_page: this.pageSize,
					brand: this.select.brand,
					model: this.select.model,
					energy: this.select.energy,
					store_status: this.select.store_status,
					min_price: this.select.min_price,
					max_price: this.select.max_price,
					start_year: this.select.start_year,
					end_year: this.select.end_year,
					min_mileage: this.select.min_mileage,
					max_mileage: this.select.max_mileage,
					type: this.select.type,
				}).done(function(data) {
					that.dataList = data.data.list
					that.allData = data.data.list; // 前端分页时存储所有数据
					that.totalItems = data.data.meta.total; // 后端分页时更新总数
					if(that.dataList.length<=0){
						that.isshow = true
						that.licklistfn()
					}else{
						that.isshow = false
					}
					// console.log(data.data.list);
				}).fail(function(error) {
					// console.error(error);
				});


			},
			prevPage() {
				if (this.currentPage > 1) this.currentPage--;
				$('html, body').animate({
					scrollTop: $('.navs').offset().top - 0
				}, 0);
			},
			nextPage() {
				if (this.currentPage < this.totalPages) {
					this.currentPage++
				};
				$('html, body').animate({
					scrollTop: $('.navs').offset().top - 0
				}, 0);
			},
			gotoPage(page) {
				this.currentPage = page;
			},
			godetil(item) {
				window.location.href = 'vehicle-details.html?id=' + item.id
			},
			clearfn() {
				for (const key in this.select) {
					if (this.select.hasOwnProperty(key)) {
						this.select[key] = '';
					}
				}
				this.fetchData()
			},
			contentbtn(){
				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: 0
				}).done(function(result) {
					alert(result.data.message)
					// console.log(result);
				}).fail(function(error) {
					// console.error(error);
				});
			}
		},
	})
})