<template>
	<div class="home_map">
		<div id="container"></div>
		<div v-show="isRight" class="lng_lat">{{ mapLngLat }}</div>

		<div class="base_func">
			<div class="base_func--input">
				<input id="tipinput" placeholder="请搜索查询" type="text" />
				<img src="@/assets/images/func_search.png" alt="" />
			</div>
			<div class="btn" :class="{ isActiveBtn: isActive == 1 }" @click="onMouseTool('rule', 1)">距离测量</div>
			<div class="btn" :class="{ isActiveBtn: isActive == 2 }" @click="onMouseTool('measureArea', 2)">面积测量</div>
			<div class="btn" @click="onClose">关闭</div>
		</div>
	</div>
</template>

<script>
import { dept, getEmergency } from '@/api'

export default {
	name: 'home-map',
	data() {
		return {
			mapLngLat: [], // 鼠标滑动出现坐标
			markerArr: [], // 点坐标数组
			isActive: 0, // 功能键选中
			zoom: 0,
			polygons: [],
			map: '',
		}
	},

	mounted() {
		var map = new AMap.Map('container', {
			zoom: 12,
			layers: [new AMap.TileLayer.Satellite(), new AMap.TileLayer.RoadNet()],
		})

		//输入提示
		var autoOptions = {
			input: 'tipinput',
		}

		var auto = new AMap.Autocomplete(autoOptions)
		var placeSearch = new AMap.PlaceSearch({
			map: map,
		}) //构造地点查询类
		AMap.event.addListener(auto, 'select', select) //注册监听，当选中某条记录时会触发
		function select(e) {
			placeSearch.setCity(e.poi.adcode)
			placeSearch.search(e.poi.name) //关键字查询查询
		}

		AMap.plugin(['AMap.Scale', 'AMap.OverView'], function() {
			map.addControl(new AMap.Scale())
			map.addControl(new AMap.OverView({ isOpen: true }))
		})

		map.on('mousemove', e => {
			let lnglat = e.lnglat
			this.mapLngLat = [lnglat.lng, lnglat.lat]
		})

		// 企业管理
		dept().then(res => {
			let select_item = this.$store.state.select_item
			let arr = [];

			res.content.map(item => {
				for (let i of select_item) {
					if (item.type == i.id) {
						item.typeName = i.label
					}
				}

				if (item.typeName) {
					if(item.jd && !item.jd.match(/°|′/)){
						arr.push({
							title: item.name,
							typeName: item.typeName,
							position: [item.jd, item.wd],
							address: item.address,
							label: {
								tip: [item.typeName],
							},
						});
					};
				}
			});


			//突发事件
			getEmergency({sort: 'emergencyTime,desc'}).then(res => {
				//var select_item = this.$store.state.select_item;
				var list = res.content || [];
				for(var item of list){
					arr.push({
						title: item.emergencyTitle + '（' + item.emergencyContent + '）',
						typeName: item.emergencyContent,
						position: [item.emergencyLng, item.emergencyLat],
						address: item.emergencyPlace,
						label: {
							tip: [item.emergencyTitle],
						},
						type:226,
					})
				};
				this.markerArr = arr

				this.onMarker(map)
			});
		});


		this.$store.commit('SET_APP_MAP', map)

		this.init(map)
	},

	methods: {
		init(map) {
			const opts = {
				subdistrict: 1, // 返回下一级行政区
				extensions: 'all', // 返回完整行政区边界坐标点
				// level: "province", // 行政区级别 省
				showbiz: false, // 是否显示商圈，默认值true
			}

			// 地图初始化
			var district = new AMap.DistrictSearch(opts)
			this.onDistrict(map, district, '152525')
		},

		// 选择区域
		onDistrict(map, district, adcode) {
			for (var i = 0, l = this.polygons.length; i < l; i++) {
				this.polygons[i].setMap(null)
			}
			const THAT = this
			district.search(adcode, function(status, result) {
				if (status == 'complete') {
					THAT.getData(result.districtList[0], map)
				}
			})
		},

		getData(data, map) {
			var THAT = this
			var bounds = data.boundaries
			var arrList = []
			for (let i of bounds) {
				for (let j of i) {
					arrList.push([j.lng, j.lat])
				}
			}
			if (bounds) {
				for (var i = 0, l = bounds.length; i < l; i++) {
					var polygon = new AMap.Polygon({
						map: map,
						bubble: true,
						strokeWeight: 5,
						strokeDasharray: [10, 20],
						strokeColor: 'rgba(7, 247, 247, 1)',
						fillColor: 'rgba(7, 247, 247, 1)',
						fillOpacity: 0.2,
						path: bounds[i],
					})
					THAT.polygons.push(polygon)
				}
				map.setFitView() //地图自适应
				map.zoomIn()
			}
		},

		onMarker(map) {
			var infoWindow = new AMap.InfoWindow({
				offset: new AMap.Pixel(0, -20),
			})

			// 信息窗口
			function openInfo(e) {
				var info = []
				info.push("<p class='input-item'>名称 : " + e.target.title + '</p>')
				info.push("<p class='input-item'>地址 :" + e.target.address + '</p></div></div>')
				infoWindow.setContent(info.join(''))
				infoWindow.open(map, [e.lnglat.lng, e.lnglat.lat])
			}

			// 关闭信息窗口
			function openClose() {
				infoWindow.close()
			}

			this.markerArr.map(item => {
				if (item.typeName) {
					var url
					if (item.typeName == '非煤矿山') {
						url = '/image/fei.png'
					}

					if (item.typeName == '煤矿') {
						url = '/image/mei.png'
					}

					if (item.typeName == '危险化学品企业') {
						url = '/image/hua.png'
					}

					if (item.type == 226) {
						url = 'https://webapi.amap.com/theme/v1.3/markers/n/mark_rs.png'
					};

					var icon = new AMap.Icon({
						image: url,
						size: new AMap.Size(36, 36),
					})

					let marker = new AMap.Marker({
						icon: icon,
						position: item.position,
						offset: new AMap.Pixel(-12, -12),
						map: map,
						title: item.title,
						address: item.address,
					})

					marker.title = item.title
					marker.address = item.address

					marker.on('click', e => {
						const position = [marker.getPosition().lng, marker.getPosition().lat]
						openInfo(e)
						// map.setCenter(position)
						// map.setZoom(14)
					})

					// marker.on('mouseover', openInfo)
					marker.on('mouseout', openClose)
				}
			})
		},

		onMouseTool(type, index) {
			const map = this.$store.state.appMap
			var mouseTool = new AMap.MouseTool(map)
			this.isActive = index

			switch (type) {
				case 'rule': {
					mouseTool.rule({
						startMarkerOptions: {
							//可缺省
							icon: new AMap.Icon({
								size: new AMap.Size(19, 31), //图标大小
								imageSize: new AMap.Size(19, 31),
								image: 'https://webapi.amap.com/theme/v1.3/markers/b/start.png',
							}),
						},
						endMarkerOptions: {
							//可缺省
							icon: new AMap.Icon({
								size: new AMap.Size(19, 31), //图标大小
								imageSize: new AMap.Size(19, 31),
								image: 'https://webapi.amap.com/theme/v1.3/markers/b/end.png',
							}),
							offset: new AMap.Pixel(-9, -31),
						},
						midMarkerOptions: {
							//可缺省
							icon: new AMap.Icon({
								size: new AMap.Size(19, 31), //图标大小
								imageSize: new AMap.Size(19, 31),
								image: 'https://webapi.amap.com/theme/v1.3/markers/b/mid.png',
							}),
							offset: new AMap.Pixel(-9, -31),
						},
						lineOptions: {
							//可缺省
							strokeStyle: 'solid',
							strokeColor: '#FF33FF',
							strokeOpacity: 1,
							strokeWeight: 2,
						},
						//同 RangingTool 的 自定义 设置，缺省为默认样式
					})
					break
				}
				case 'measureArea': {
					mouseTool.measureArea({
						strokeColor: '#80d8ff',
						fillColor: '#80d8ff',
						fillOpacity: 0.3,
						//同 Polygon 的 Option 设置
					})
					break
				}
			}

			this.$store.commit('SET_MOUSETOOL', mouseTool)
		},

		// 关闭距离
		onClose() {
			const mouseTool = this.$store.state.mouseTool
			mouseTool.close(true) //关闭，并清除覆盖物
			this.isActive = 0
		},
	},

	watch: {
		compony_info(e) {
			const map = this.$store.state.appMap
			map.setZoom(11)

			setTimeout(() => {
				map.setCenter([e.jd, e.wd])
				map.setZoom(14)
			}, 300)
		},
	},

	computed: {
		compony_info() {
			return this.$store.state.compony_info
		},

		isRight() {
			return this.$store.state.isRight
		},
	},
}
</script>

<style lang="scss">
.home_map {
	width: 100%;
	height: 100%;
	#container {
		width: 100%;
		height: 100%;
	}

	.base_func {
		color: #01bffd;
		display: flex;
		align-items: center;
		position: fixed;
		top: 8vh;
		right: 20vw;
		width: 35vw;
		height: 4vh;
		z-index: 999;

		&--input {
			position: relative;
			width: 30vw;
			height: 100%;
			background-image: url('~@/assets/images/func_input.png');
			background-size: 100% 100%;
			border-radius: 5px;

			img {
				position: absolute;
				width: 1vw;
				right: 1vw;
				top: 50%;
				transform: translateY(-50%);
				cursor: pointer;
			}

			input {
				height: 100%;
				width: 82%;
				padding-left: 1vw;
				border: none;
				outline: none;
				color: #01a7fd;
				background-color: transparent;
			}

			input::-webkit-input-placeholder {
				color: #01a7fd;
			}
			input::-moz-placeholder {
				color: #01a7fd;
			}
			input:-moz-placeholder {
				color: #01a7fd;
			}
			input:-ms-input-placeholder {
				color: #01a7fd;
			}
		}

		.btn {
			margin-left: 1vw;
			display: flex;
			align-items: center;
			justify-content: center;
			width: 27%;
			height: 100%;
			background-image: url('~@/assets/images/func_btn.png');
			background-size: 100% 100%;
			cursor: pointer;
		}

		.isActiveBtn {
			background-image: url('~@/assets/images/func_btn_active.png');
			background-size: 100% 100%;
			color: #fff;
		}
	}

	.content-window-card {
		position: relative;
		width: 23rem;
		padding: 0.75rem 0 0 1.25rem;
		box-shadow: none;
		bottom: 0;
		left: 0;
	}

	.input-item {
		position: relative;
		display: flex;
		flex-wrap: wrap;
		align-items: center;
		width: 100%;
	}

	.lng_lat {
		position: absolute;
		color: #fff;
		font-size: 2vh;
		z-index: 999;
		bottom: 1vh;
		right: 13%;
	}

	.amap-overviewcontrol {
		bottom: 0vh;
		left: 20vw;

		.amap-overview-main {
			left: 0;
			top: 0;
		}
	}
}
</style>
