
function showInputView(){
	const box = document.getElementById("search-box");
	box.style.display = "block"; //设置样式为不显示（隐藏）
	// const citys = document.getElementById("citys");
	// citys.style.display = "block"; //设置样式为不显示（隐藏）
}

function hidInputView(){
	const box = document.getElementById("search-box");
	box.style.display = "none"; //设置样式为不显示（隐藏）
	// const citys = document.getElementById("citys");
	// citys.style.display = "none"; //设置样式为不显示（隐藏）
}


document.addEventListener('UniAppJSBridgeReady', function() {
var lats = getQueryVariable('lat') * 1;
var lngs = getQueryVariable('lng') * 1;
var latn = getQueryVariable('nlat') * 1;
var lngn = getQueryVariable('nlng') * 1;
var sstate = getQueryVariable('sstate') * 1;
var lg = getQueryVariable('lg') * 1;
var zoom = 15; //地图缩放比例
var coords = "";
var startAddr="";
var endcoords = "";
var endAddr="";
var mpcenter = "";
var searchmarker = "";



var showinput=false;


var map; //地图
var drawRouteMarker = []; //路线marker
var directionsRendererArr = []; //地图路线
/**
 * 初始化
 * 
 */
function initMap() {
	if (lats && lngs) {
		coords = {
			lat: lats,
			lng: lngs
		};
		mpcenter = {
			lat: lats,
			lng: lngs
		};
	} else {
		navigator.geolocation.getCurrentPosition(function(position) {
			coords = {
				lat: position.coords.latitude,
				lng: position.coords.longitude
			};
			mpcenter = {
				lat: position.coords.latitude-0.001,
				lng: position.coords.longitude
			};
			lats = position.coords.latitude;
			lngs = position.coords.longitude
		});
	}
	map = new google.maps.Map(document.getElementById('map'), {
		zoom: zoom,
		center: mpcenter,
		mapId: MAPID,
		animation: 'BOUNCE'
	});
	if(latn!=0 && lngn!=0){
		endcoords ={
			lat: latn,
			lng: lngn
		};
		drawRoute();
	}
	else{
		searchmarker = new google.maps.Marker({
			map: map,
			position: coords,
			title: '',
		});
		getAddress(coords,'',0);
	}
	
	if(sstate==0){
		const box = document.getElementById("search-box");
		box.style.display = "none"; //设置样式为不显示（隐藏）
		const posl = document.getElementById("pos");
		posl.style.display = "none"; //设置样式为不显示（隐藏）
	}
	else if(sstate==1){
		const box = document.getElementById("search-box");
		if(lg==1){
			box.placeholder='Vui lòng nhập điểm đến...';
		}
		if(lg==2){
			box.placeholder='请输入目的地...';
		}
		if(lg==3){
			box.placeholder='請輸入目的地...';
		}
		
		Repositioning();
		ListeningInputBox();
	}
	else if(sstate==2){
		const box = document.getElementById("search-box");
		box.style.display = "none"; //设置样式为不显示（隐藏）
		const posl = document.getElementById("pos");
		posl.style.display = "none"; //设置样式为不显示（隐藏）
		
	}
	
	setTimeout(() => {
		LoadAnimation(false)
	}, 500)
	
}

/**
 * 监听输入框 输入事件
 * 
 * */
function ListeningInputBox() {
	// 创建 Autocomplete 实例

	const input = document.getElementById("search-box");
	const autocomplete = new google.maps.places.Autocomplete(input);
	// 设置 Autocomplete 参数
	autocomplete.setFields(["geometry", "name"]);
	// 添加事件监听器，当用户选择某个地点时，在地图上标记出所选位置
	LoadAnimation(true)
	autocomplete.addListener("place_changed", function() {
		const place = autocomplete.getPlace();
		var latlng = JSON.parse(JSON.stringify(place.geometry.location));
		var placename = document.getElementById("search-box").value;
		getAddress(latlng,placename,1);
		if (!place.geometry) {
			console.log("返回的地理信息无效！");
			return;
		}
		
		// 将地图中心点指向用户所选位置，并设置标记
		map.setCenter(place.geometry.location);
		if (searchmarker) { //去除marker标记点
			searchmarker.setMap(null)
			searchmarker = ""
		}
		searchmarker = new google.maps.Marker({
			map: map,
			position: place.geometry.location,
			title: place.name,
		});
		
		//以搜索地址为目的地规划路径
		// endcoords = place.geometry.location;
		// drawRoute();
		setTimeout(() => {
			LoadAnimation(false)
		}, 1000)
		
	});
}
/**
 * 根据经度纬度获取相对应的地址信息
 *  提取 国家 省/州 市 区/县 路 门牌号  
 * 
 * */
function getAddress(latlng,name,mark) {
	
	// 根据经纬度发起 Reverse Geocoding API 请求，获取地址信息
	var geocoder = new google.maps.Geocoder();
	var cityInfo = {
		country: "", //国家
		province: "", //省
		city: "", //市
		district: "", //区
		street: "", //街道	
		door: "", //门牌号
		address: "", //详细地址
		name:name//地址名称
	}
	geocoder.geocode({
		location: latlng
	}, function(results, status) {
		if (status === 'OK') {
			if (results[0]) {
				console.log(results[0])
				for (var i = 0; i < results.length; i++) {
					var components = results[i].address_components;
					for (var j = 0; j < components.length; j++) {
						var component = components[j];
						if (component.types.includes("country")) {
							console.log("国家:  ====>" + component.long_name);
							cityInfo.country = component.long_name || '暂无';
						} else if (component.types.includes("administrative_area_level_1")) {
							console.log("省/州:  ====>" + component.long_name);
							cityInfo.province = component.long_name || '暂无';
						} else if (component.types.includes("locality")) {
							console.log("城市: ====> " + component.long_name);
							cityInfo.city = component.long_name || '暂无';
						} else if (component.types.includes("sublocality_level_1")) {
							console.log("区/县: ====>" + component.long_name);
							cityInfo.district = component.long_name || '暂无';
						} else if (component.types.includes("route")) {
							console.log("路/街道名: ====> " + component.long_name);
							cityInfo.street = component.long_name || '暂无';
						} else if (component.types.includes("street_number")) {
							console.log("门牌号: ====> " + component.long_name);
							cityInfo.door = component.long_name || '暂无';
						}
					}
				}
				cityInfo.address = results[0].formatted_address;
				returngeocode(latlng,cityInfo,mark);
				// console.log("cityInfo==========", cityInfo)
				// addInfo(cityInfo)
				
			} else {
				//alert('找不到地址信息');
				returngeocode(latlng,cityInfo,mark);
			}
		} else {
			//alert('获取地址信息失败：' + status);
			returngeocode(latlng,cityInfo,mark);
		}
	});
}

function returngeocode(location,cityInfo,type){
	uni.postMessage({
		data: {
			position:location,
			cityInfo:cityInfo,
			type:type
		}
	});
}

function addInfo(cityInfo) {
	// 获取子节点并设置新的文本内容
	const child1 = document.getElementById('country');
	child1.textContent = cityInfo.country;
	const child2 = document.getElementById('province');
	child2.textContent = cityInfo.province;
	const child3 = document.getElementById('city');
	child3.textContent = cityInfo.city;
	const child4 = document.getElementById('district');
	child4.textContent = cityInfo.district;
	const child5 = document.getElementById('street');
	child5.textContent = cityInfo.street;
	const child6 = document.getElementById('door');
	child6.textContent = cityInfo.door;
	const child7 = document.getElementById('address');
	child7.textContent = cityInfo.address;

}

/**
 * 画路线图
 *  经度纬度加了随机函数 故 起始点和终点 各不一致
 *  需要用到此功能自行调整
 * 
 * */
function drawRoute() {
	LoadAnimation(true)
	clearDrawRoute()
	const directionsService = new google.maps.DirectionsService();
	var TravelMode = [{
			id: 1,
			name: "DRIVING",
			color: "#ea4335"
		},
		{
			id: 2,
			name: "WALKING",
			color: "#7825fa"
		},
		{
			id: 3,
			name: "BICYCLING",
			color: "#fa6200"
		},
		{
			id: 4,
			name: "TRANSIT",
			color: "#ff00ff"
		}
	];
	startDrawRoute(directionsService, TravelMode[0]);
	
}

/**
 * 清除路线
 * 
 * */
function clearDrawRoute() {
	if (directionsRendererArr) { //清空线
		for (var i = 0; i < directionsRendererArr.length; i++) {
			directionsRendererArr[i].setMap(null);
		}
		// 清空数组
		directionsRendererArr = [];
	}
	if (drawRouteMarker) { //清空标记点
		for (var i = 0; i < drawRouteMarker.length; i++) {
			drawRouteMarker[i].setMap(null);
		}
		// 清空数组
		drawRouteMarker = [];

	}

}

/**
 * 
 * 开始绘制以下路线图
 *	DRIVING：驾车模式。这是默认的出行方式，计算出行路线时考虑当时的实时交通情况。
 *可用  WALKING：步行模式。计算步行路线时会考虑人行道、人行横道等规则，因此得到的路线可能与驾车路线不同。
 *可用  BICYCLING：骑行模式。计算骑行路线时，避开了折返点和拥堵路段，提供了适合骑自行车的路线。
 * TRANSIT：公共交通模式。在城市间导航中被广泛使用，提供了乘坐公共交通工具（如公交车、地铁、火车和轻轨）的路线方案。
 * FLIGHTS：飞行模式。在 Google Maps 平台上无法使用，此模式只适用于各大航空公司网站等其他服务商范畴内。
 * 
 * */
function startDrawRoute(directionsService, travelMode) {
	// 随机数字而已  动态数字  方便查询效果
	// let min = 5000;
	// let max = 10000;
	// let randomNum = (Math.floor(Math.random() * (max - min + 1)) + min) / 500000;
	// 起点坐标

	/**
	 * lat 和lng数据为随机数据  运行时 调整为自己所在位置坐标
	 * 
	 * */
	const origin = {
		lat: coords.lat,
		lng: coords.lng
	};
	// 终点坐标
	const destination = {
		lat: endcoords.lat,
		lng: endcoords.lng
	};
    
	var directionsRenderer = new google.maps.DirectionsRenderer({
		map: map,
		suppressMarkers: true, // 关闭默认图标
		polylineOptions: {
			strokeColor: travelMode.color, //设置路线颜色
			strokeWeight: 5 //设置路线宽度
		},
		// draggable: true //允许用户拖动路线

	});
	const request = {
		origin: origin,
		destination: endcoords,
		travelMode: travelMode.name, //绘制路线的模式
	};
	directionsService.route(request,
		(result, status) => {
			if (status === "OK") {
				directionsRenderer.setDirections(result);
				directionsRenderer.setMap(map);
				// 获取起点和终点的信息并添加标记
				var startMarker = new google.maps.Marker({
					position: result.routes[0].legs[0].start_location,
					map: map,
					icon: {
						url: "https://maps.gstatic.com/mapfiles/ms2/micons/pink.png",
						scaledSize: new google.maps.Size(50, 50),
					},
				});
				drawRouteMarker.push(startMarker)
				var endMarker = new google.maps.Marker({
					position: result.routes[0].legs[0].end_location,
					map: map,
					icon: {
						url: "https://maps.gstatic.com/mapfiles/ms2/micons/orange.png",
						scaledSize: new google.maps.Size(50, 50),
					},
				});
				drawRouteMarker.push(endMarker)
				directionsRendererArr.push(directionsRenderer)
				//显示路线的总距离
				// console.log('距离===', directionsRenderer.directions.routes[0].legs[0].distance.text)
				// console.log('时间===', directionsRenderer.directions.routes[0].legs[0].duration.text)
				// for (var k = 0; k < directionsRenderer.directions.routes[0].legs[0].steps.length; k++) {
				// 	console.log(directionsRenderer.directions.routes[0].legs[0].steps[k].instructions)
				// }
				if (searchmarker) { //去除marker标记点
					searchmarker.setMap(null)
					searchmarker = ""
				}
				uni.postMessage({
					data: {
						distance:directionsRenderer.directions.routes[0].legs[0].distance.text,
						duration:directionsRenderer.directions.routes[0].legs[0].duration.text,
						type:2
					}
				});
			} else {
				// console.log(travelMode, "绘制失败===", result)
				uni.postMessage({
					data: {
						drawRoute:result
					}
				});
			}
		}
	);

	LoadAnimation(false)
}

/**
 * 重新定位
 * 
 * 
 * */
function Repositioning() {
	LoadAnimation(true)
	var element = document.getElementById('pos');
	element.addEventListener("click", function() {
		if (navigator.geolocation) {
			navigator.geolocation.getCurrentPosition(function(position) {
				// lats = position.coords.latitude;
				// lngs = position.coords.longitude;
				var pos = {
					lat: position.coords.latitude,
					lng: position.coords.longitude
				};
				LoadAnimation(false)
				map.setCenter(pos); // 将地图中心置于当前位置
				// 将地图中心点指向用户所选位置，并设置标记
				if (searchmarker) { //去除marker标记点
					searchmarker.setMap(null)
					searchmarker = ""
				}
				searchmarker = new google.maps.Marker({
					map: map,
					position: pos,
					title:'location',
				});
				getAddress(pos,'',0);
			}, function() {
				console.log("无法获取地理位置信息");
			});
		} else {
			console.log("浏览器不支持Geolocation API");
		}


	});
}

LoadAnimation(true)
window.initMap = initMap;
});