// import L from 'leaflet'
// import 'leaflet-clipper/dist/L.Clipper'
// import * as turf from '@turf/turf'
import config from '@/utils/map/sub/config'
import global from '@/utils/map/sub/global'

var toggleFlag = false
export default {
	cpMarkLayerGroup: null, // 检查点标记图层组
	cpMemoLayerGroup: null, // 检查点备注图层组
	cpPathLayerGroup: null, // 检查点路线图层组

	init() {
		this.cpMarkLayerGroup = new L.featureGroup()
		this.cpMemoLayerGroup = new L.featureGroup()
		this.cpPathLayerGroup = new L.featureGroup()
	},
	// 即将开始地图缩放时触发本方法
	onZoomStart(e) {
		// this.cpMarkLayerGroup.remove()
		this.cpMemoLayerGroup.remove()
		this.cpPathLayerGroup.remove()
	},
	// 地图发生缩放时触发本方法
	onZoom(e) {},
	// 地图缩放结束时触发本方法
	onZoomEnd(e) {
		if (toggleFlag) {
			this.drawAllPath()
			// this.cpMarkLayerGroup.addTo(global.map)
			this.cpMemoLayerGroup.addTo(global.map)
			this.cpPathLayerGroup.addTo(global.map)

			this.cpMarkLayerGroup.bringToBack()
			this.cpMemoLayerGroup.bringToBack()
			this.cpPathLayerGroup.bringToBack()
		}
	},
	toggle(flag) {
		// console.log('toggle:', flag)
		if (flag != null) {
			toggleFlag = !flag
		}

		if (toggleFlag) {
			this.cpMarkLayerGroup.removeFrom(global.map)
			this.cpMemoLayerGroup.removeFrom(global.map)
			this.cpPathLayerGroup.removeFrom(global.map)

			toggleFlag = false
		} else {
			this.cpMarkLayerGroup.addTo(global.map)
			this.cpMemoLayerGroup.addTo(global.map)
			this.cpPathLayerGroup.addTo(global.map)

			this.cpMarkLayerGroup.bringToBack()
			this.cpMemoLayerGroup.bringToBack()
			this.cpPathLayerGroup.bringToBack()

			toggleFlag = true
		}
	},
	drawAllRoutes() {
		// console.log("[drawAllRoutes] routes", global.routes)
		if (this.cpMarkLayerGroup != null)
			this.cpMarkLayerGroup.clearLayers()
		if (this.cpMemoLayerGroup != null)
			this.cpMemoLayerGroup.clearLayers()

		for (let i = 0; i < global.routes.length; i++) {
			this.drawOneRoute(global.routes[i].id)
		}
	},
	drawOneRoute(rtId) {
		// var that = this
		var cpList = global.getRouteById(rtId).controlPointSortedListList

		if (cpList == null) {
			console.warn('[drawOneRoute] 关键数据为空', cpList)
			return
		}
		// console.warn('[drawOneRoute] cpList', cpList)

		for (var i = 0; i < cpList.length; i++) {
			let res = this.drawOnePoint(cpList[i])
			cpList[i].marker = res.marker
			cpList[i].markerMemo = res.markerMemo
		}
	},
	drawOnePoint(data) {
		// console.warn('[drawOnePoint] data', data)
		if (data == null) {
			console.warn('[drawOnePoint] 关键数据为空', data)
			return
		}

		var position = data.ciposition

		var marker = L.circleMarker([position.latitude, position.longitude], config.gStyle.checkPoint.default)
			.addTo(this.cpMarkLayerGroup)
		// .addTo(global.map)
		// .bindPopup("Hello, I'm a Marker!<br><img src='my-image.png' width='100'>").openPopup();
		// .bindTooltip(`检查点：${route.serial_num}`, config.gStyle.checkPoint.tooltip)

		var myIcon = L.divIcon({
			html: '<div>' + data.sn + '</div>',
			className: 'my-div-icon',
			iconSize: [60, 20], //宽高
			iconAnchor: [30, 35] //文字标注相对位置
		});
		var markerMemo = L.marker([position.latitude, position.longitude], {
				icon: myIcon,
				// zIndexOffset: -100
			})
			.addTo(this.cpMemoLayerGroup)

		// this.cpMarkLayerGroup.addTo(global.map)
		// this.cpMemoLayerGroup.addTo(global.map)
		this.cpMarkLayerGroup.bringToBack()
		this.cpMemoLayerGroup.bringToBack()

		return {
			marker: marker,
			markerMemo: markerMemo
		}
	},
	drawAllPath() {
		// console.log("[drawAllPath] routes", global.routes)
		if (this.cpPathLayerGroup != null) {
			this.cpPathLayerGroup.clearLayers()
		}

		for (let i = 0; i < global.routes.length; i++) {
			this.drawOnePath(global.routes[i].id)
		}
	},
	drawOnePath(rtId) {
		var cpList = global.getRouteById(rtId).controlPointSortedListList
		// console.log("[drawOnePath] cpList", cpList)

		var latlngs = []
		for (var i = 0; i < cpList.length; i++) {
			var position = cpList[i].ciposition
			if (position.latitude != null && position.longitude != null) {
				latlngs.push([position.latitude, position.longitude])
			}
		}

		var radius = config.gStyle.checkPoint.default.radius
		// var Lines = this.getIntersection(latlngs, radius) // 获取（圆与路线的）交叉点坐标

		// // var polyline = L.polyline(latlngs, config.gStyle.checkPointPath.default)
		// var polyline = L.polyline(Lines, config.gStyle.checkPointPath.default)
		// 	.addTo(this.cpPathLayerGroup)

		// // this.cpPathLayerGroup.addTo(global.map)
		// this.cpPathLayerGroup.bringToBack()
	},
	// 获取（圆与路线的）交叉点坐标
	getIntersection(LatLngArry, radius) {
		// var LatLngArry = [
		// 	[36.672562, 117.127572],
		// 	[36.67165, 117.129262],
		// 	[36.671409, 117.126752]
		// ]
		var PointArry = []
		// var Circles = []
		var radius = 20 // 圆的半径 px
		var DistanceArry = []
		var Lines = []
		for (let i = 0; i < LatLngArry.length; i++) {
			// 给定地理坐标，返回相应的像素坐标 (相对于原点像素)
			let point = global.map.latLngToLayerPoint(LatLngArry[i])
			PointArry.push(point)
			// let circle = L.circle(LatLngArry[i], {
			// 	radius: radius
			// }).addTo(global.map);
			// Circles.push(circle)
			if (i > 0) {
				// 计算相邻两个点之间的距离
				let distance = L.point(PointArry[i]).distanceTo(L.point(PointArry[i - 1]))
				DistanceArry.push(distance)

				// 计算圆半径占比
				let per = parseFloat(radius.toFixed(16) / distance.toFixed(16)).toFixed(16)
				// console.log('per:', per, i)
				// console.log('PointArry:', PointArry[i])

				let offsetX = parseFloat((PointArry[i].x.toFixed(16) - PointArry[i - 1].x.toFixed(16)) * per).toFixed(
					16)
				let offsetY = parseFloat((PointArry[i].y.toFixed(16) - PointArry[i - 1].y.toFixed(16)) * per).toFixed(
					16)
				// console.log('offset:', offsetX, offsetY)
				// 给定相对于原点像素的像素坐标， 返回相应的地理坐标（对于当前缩放级别）
				let line = [
					global.map.layerPointToLatLng([
						parseFloat(PointArry[i - 1].x) + parseFloat(offsetX),
						parseFloat(PointArry[i - 1].y) + parseFloat(offsetY)
					]),
					global.map.layerPointToLatLng([
						parseFloat(PointArry[i].x) - parseFloat(offsetX),
						parseFloat(PointArry[i].y) - parseFloat(offsetY)
					])
				]
				Lines.push(line)
			}
		}
		// console.log('DistanceArry', DistanceArry)
		// console.log('Lines', Lines)

		// var polyline = L.polyline(Lines, config.gStyle.checkPointPath.default).addTo(global.map)
		return Lines
	},
	test() {},
	free() {}
}