//高德key
const key = 'c6a3302bff3ffc7462fa6eb69c3f002e';

const amapFile = require('./amap-uni.js');

const icon = "/static/home/icon-yb.png";
/*
调用高德地图api进行路线规划时,
高德对途经点的坐标格式如下:

116.441063,39.91903;
116.39622,39.912057;
116.39622,39.912057;
116.39622,39.912057;
116.39622,39.912057;
116.39622,39.912057;
116.39622,39.912057;
116.39622,39.912057

也就是说每个点的经纬度之间用;分隔,所以请提前格式化好您的坐标格式

*/

function getWeather(callback) {
	var myAmapFun = new amapFile.AMapWX({
		key: key
	});
	myAmapFun.getWeather({
		// city : "天河区",
		success: function(data) {
			callback(data);
		},
		fail: function(info) {
			//失败回调
			uni.$u.toast("获取天气失败,请确保打开定位权限");
		}
	})
}


function PlanningRoute(start, end, _waypoints, result, fail) {
	let that = this;
	var myAmapFun = new amapFile.AMapWX({
		key: key
	});

	myAmapFun.getDrivingRoute({
		origin: start,
		destination: end,
		waypoints: _waypoints,
		success: function(data) {
			console.log(data);
			var points = [];
			if (data.paths && data.paths[0] && data.paths[0].steps) {
				var steps = data.paths[0].steps;
				for (var i = 0; i < steps.length; i++) {
					var poLen = steps[i].polyline.split(';');
					for (var j = 0; j < poLen.length; j++) {
						points.push({
							longitude: parseFloat(poLen[j].split(',')[0]),
							latitude: parseFloat(poLen[j].split(',')[1])
						})
					}
				}
			}
			//这个返回结果就是对应的路线坐标,其他属性页面自己配置,请参照uniapp地图组件一章节
			//https://uniapp.dcloud.io/component/map
			result({
				points: points,
				color: "#289ae6",
				width: 12,
				arrowLine: true
			})
		},
		fail: function(info) {
			fail(info)
		}
	})
}
//标记标记点
function Makemarkers(startpoi, endpoi, waypoints, success) {
	const id = new Date().getTime(); // 拿时间做下id
	let markers = [];

	//起点
	let start = {
		iconPath: icon,
		id: id,
		longitude: startpoi.split(",")[0],
		latitude: startpoi.split(",")[1],
		width: 28,
		height: 34
	}
	markers.push(start);

	let _waypoints = waypoints.split(';');
	if (waypoints) {
		//途经点,先将其分隔成为数组
		for (let i = 0, _len = _waypoints.length; i < _len; i++) {
			let point = {
				iconPath: icon,
				id: id + i + 1,
				longitude: parseFloat(_waypoints[i].split(",")[0]),
				latitude: parseFloat(_waypoints[i].split(",")[1]),
				width: 28,
				height: 34
			}
			markers.push(point)
		}
	}

	if (endpoi) {
		//终点
		let end = {
			iconPath: icon,
			id: id + _waypoints.length + 1,
			longitude: endpoi.split(",")[0],
			latitude: endpoi.split(",")[1],
			width: 28,
			height: 34
		}
		markers.push(end)
	}

	//统一风格为回调方式,也可以直接返回这个markers
	success(markers);

}

module.exports = {
	line: PlanningRoute,
	markers: Makemarkers,
	getWeather : getWeather,
	icon
}
