<template>
	<div class="p-components-map-poi">
		<div id="container"></div>
		<div id="myPageTop" >
			<div class="g_flex_row_center" style="position: relative;">
				<div>
					<input id="tipinput" placeholder="请输入关键词搜索" autocomplete="off" v-model="keyword" />
				</div>
				<div class="btn g_flex_c">
					<svg focusable="false" data-icon="search" width="1em" height="1em" fill="currentColor" aria-hidden="true" viewBox="64 64 896 896"><path d="M909.6 854.5L649.9 594.8C690.2 542.7 712 479 712 412c0-80.2-31.3-155.4-87.9-212.1-56.6-56.7-132-87.9-212.1-87.9s-155.5 31.3-212.1 87.9C143.2 256.5 112 331.8 112 412c0 80.1 31.3 155.5 87.9 212.1C256.5 680.8 331.8 712 412 712c67 0 130.6-21.8 182.7-62l259.7 259.6a8.2 8.2 0 0011.6 0l43.6-43.5a8.2 8.2 0 000-11.6zM570.4 570.4C528 612.7 471.8 636 412 636s-116-23.3-158.4-65.6C211.3 528 188 471.8 188 412s23.3-116.1 65.6-158.4C296 211.3 352.2 188 412 188s116.1 23.2 158.4 65.6S636 352.2 636 412s-23.3 116.1-65.6 158.4z"></path></svg>
				</div>
			</div>
		</div>
		<div class="g_pt_10 g_flex_row_between">
			<div>
				<div class="g_fw_700 g_fs_14">{{mapInfo.name}}</div>
				<div class="g_fs_14">{{mapInfo.address}}</div>
			</div>
			<div class="g_flex_column_center" v-if="mapInfo.name">
				<a-button type="primary" @click="submitForm">确定</a-button>
			</div>
		</div>
	</div>
</template>

<script setup>
	import {
		ref,
		onMounted,
		getCurrentInstance,
		watch,
		defineEmits,
		defineProps
	} from 'vue';
	import { 
		Modal,
		message 
	} from 'ant-design-vue';
	import AMapLoader from "@amap/amap-jsapi-loader";
	import {
		mapConfig
	} from "../../../utils/config.js";
	
	/* #################### 初始化事件 #################### */
	const emits = defineEmits(['submitEvent'])
	const commonJS = getCurrentInstance().appContext.app.config.globalProperties.G;
	const mapInfo = ref({
		name:"",
		address:"",
		lat:"",
		lng:""
	});
	const keyword = ref('');
	const selectInfo = ref({});
	const props = defineProps({
	    info:{
				type: Object,
				default: () => {
					return {
						name:"",
						address:"",
						lat:"",
						lng:""
					}
				}
	    },
	})
	const defaultInfo = ref({
		mdistrict:"",
	});
	onMounted(()=>{
		mapInfo.value = props.info;
		keyword.value = mapInfo.value.name;
	});
	
	/* ############################## 地图配置 ############################## */
	window._AMapSecurityConfig = {
	  securityJsCode: mapConfig.secret,
	};
	AMapLoader.load({
	  key: mapConfig.key, 
	  version: "2.0", 
	  plugins: ["AMap.Scale","AMap.HawkEye","AMap.ToolBar","AMap.ControlBar","AMap.Geocoder"], 
	})
	.then((AMap) => {
		/* ################################# 初始化 ################################# */
	    var map = new AMap.Map("container",{
			zoom: 12,
			resizeEnable: true
		}); //"container"为 <div> 容器的 id
		
		
		/* ################################# 点击事件 ################################# */
		var geocoder = new AMap.Geocoder();
		var marker,lnglat = [];
		map.on("click", function (ev) {
			mapInfo.value = {
				name:'',
				address:'',
				lat:ev.lnglat.lat,
				lng:ev.lnglat.lng
			}
			keyword.value = mapInfo.value.name;
			
			lnglat = [ev.lnglat.lng,ev.lnglat.lat];
			geocoder.getAddress(lnglat, function(status, result) {
				if (marker) {
					marker.setMap(null);
					marker = null;
				}
				setTimeout(()=>{
          console.log('点击点返回结果：',result);
					if (status === 'complete' && result.info === 'OK') {
						let _address = "",
							_district = result.regeocode.addressComponent.province + result.regeocode.addressComponent.city + result.regeocode.addressComponent.district;
						if(result.regeocode.addressComponent.neighborhood){
							_address = result.regeocode.addressComponent.neighborhood;
						}else{
							_address = result.regeocode.formattedAddress.replace(_district + result.regeocode.addressComponent.township,() => '');
						}
						mapInfo.value.name = _address;
						keyword.value = mapInfo.value.name;
						mapInfo.value.address = result.regeocode.formattedAddress;
						
						selectInfo.value = {
							address:result.regeocode.formattedAddress,
							district:_district,
							lat:mapInfo.value.lat,
							lng:mapInfo.value.lng,
							name:mapInfo.value.name,
						}
						
						defaultInfo.value = {
							mdistrict:_district
						}
						
						
						marker = new AMap.Marker({
						  icon: "//a.amap.com/jsapi_demos/static/demo-center/icons/poi-marker-red.png",
						  position: [mapInfo.value.lng, mapInfo.value.lat],
						  offset: new AMap.Pixel(-13, -30)
						});
						marker.setMap(map);
					}
				},10)
			})
		});
		
		/* ################################# 工具条 ################################# */
		var scale = new AMap.Scale({
		        visible: true
		    }),
		    toolBar = new AMap.ToolBar({
		        visible: true,
		        position: {
		          top: '110px',
		          right: '40px'
		        }
		    }),
		    controlBar = new AMap.ControlBar({
		        visible: true,
		        position: {
		          top: '10px',
		          right: '10px'
		        }
		    }),
		    overView = new AMap.HawkEye({
		        visible: true
		    });
		map.addControl(scale);
		map.addControl(toolBar);
		map.addControl(controlBar);
		map.addControl(overView);
		
		
		
		/* ################################# POI搜索与选择 ################################# */
		//输入提示
		var autoOptions = {
			input: "tipinput"
		};
		AMap.plugin(['AMap.PlaceSearch','AMap.AutoComplete'], function(){
			var auto = new AMap.AutoComplete(autoOptions);
			var placeSearch = new AMap.PlaceSearch({
				map: map
			});  //构造地点查询类
			auto.on("select", select);//注册监听，当选中某条记录时会触发
			function select(e) {
				console.log('map 获取下拉选择地址信息：',e)
				placeSearch.setCity(e.poi.adcode);
				placeSearch.search(e.poi.name);  //关键字查询查询
				
				selectInfo.value = e.poi;
				if(e.poi.location){
					mapInfo.value = {
						name:e.poi.name,
						address:e.poi.district + e.poi.address,
						lat:e.poi.location.lat,
						lng:e.poi.location.lng
					}
				}else{
					mapInfo.value = {
						name:e.poi.name,
						address:e.poi.district + e.poi.address,
						lat:'', 
						lng:''
					}
				}
				keyword.value = mapInfo.value.name;
				defaultInfo.value = {
					mdistrict:e.poi.district
				}
			}
		});
	}).catch((e) => {
	    console.log('地图异常状态数据：',e);
	});
	
	const submitForm = ()=>{
		if(mapInfo.value.lat == ""){
			console.log('经纬度：',mapInfo.value)
			message.error('请重新选择')
			return false;
		}
		emits("submitEvent",{
			pointInfo:Object.assign(defaultInfo.value,mapInfo.value),
			initInfo:Object.assign(defaultInfo.value,selectInfo.value)
		});
	}
</script>

<style lang="less">
	.p-components-map-poi{
		#container{
			width: 100%;
			height: calc(100vh - 254px);
		}
		#myPageTop{
			position: absolute;
			top: 106px;
			width: 280px;
			border: none;
			right: 236px;
			padding: 0;
		}
		#myPageTop input{
			-webkit-box-sizing: border-box;
			box-sizing: border-box;
			margin: 0;
			padding: 0;
			font-variant: tabular-nums;
			list-style: none;
			-webkit-font-feature-settings: "tnum";
			font-feature-settings: "tnum";
			position: relative;
			display: inline-block;
			width: 100%;
			height: 32px;
			padding: 4px 11px;
			color: rgba(0,0,0,.65);
			font-size: 14px;
			line-height: 1.5;
			background-color: #fff;
			background-image: none;
			border: 1px solid #d9d9d9;
			border-radius: 4px;
			-webkit-transition: all .3s;
			transition: all .3s;
			width: 280px;
			outline: #1677ff;
		}
		#myPageTop input:focus{
			border-color: #40a9ff;
			border-right-width: 1px!important;
		}
		#myPageTop .btn{
			cursor: pointer;
			width: 32px;
			height: 32px;
			background-color: #1677ff;
			color: #fff;
			position: absolute;
			right: 0;
			top: 0;
			border-top-right-radius: 4px;
			border-bottom-right-radius: 4px;
		}
		.amap-icon img{
			width: 25px;
			height: 34px;
		}
	}
</style>