<template>
	<view class="setbox">
		<map
			id="container"
			class="map"
			:latitude="center.lat"
			:longitude="center.lng"
			@poitap="onClcikImgMap"
			@tap="onClcikImgMap"
			:markers="covers"
			scale="15"
			:style="'width: 750rpx;height:' + mapheight + 'px;'"
		></map>

		<view class="maptop">
			<view class="maptopflex">
				<image :src="serimg" class="maptopimg"></image>
				<input  class="maptopint" id="tipInputs" v-model="searchtxt"  @input="searchKeyword" placeholder="请输入地点进行查找" />
			</view>
			<!-- 地图联想 -->
			<view class="addrSearch_list" >
				<view class="addrSearch_item" v-for="(item, index) in searchList" :key="index" @click="handleAddrClick(item)" >
					<view class="wrap_name">
						<!-- #ifdef H5 -->
						<text class="wrap_text">{{item.name.substring(0, item.name.indexOf(searchtxt))}}</text>
							<text class="wrap_text" style="color: #2797FF;">{{searchtxt}}</text>
							<text class="wrap_text">{{item.name.substring(item.name.indexOf(searchtxt) + searchtxt.length)}}</text>
						<!-- #endif -->
						<!-- #ifndef H5 -->
						<rich-text :nodes="richNodes(item)"></rich-text>
						<!-- #endif -->
					</view>
					<view class="wrap_addr">
						<text class="wrap_addrs">{{ item.addr }}</text>
					</view>
				</view>
			</view>
		</view>

		<view class="mapfot">
			<view class="mapfott"><text class="mapfottit">标点位置</text></view>
			<view class="mapfotx">
				<image :src="adrimg" class="mapfotimg"></image>
				<text class="mapfottxt" v-if="address">{{ address }}</text>
			</view>
			<view class="mapfotn" @click="getSureFn"><text class="mapfotntit">确定</text></view>
		</view>
	</view>
</template>

<script>
import myAmapFun from '@/utils/initmap.js';
import self from "@/utils/location.js"

	export default{
		data(){
			return{
				serimg:require("@/work/static/search.png"),
				adrimg:require("@/work/static/adress.png"),
				mapimg:require("@/work/static/map.png"),
				// center:{
				// 	lng:'117.211954',
				// 	lat:'31.839676',
				// },
				center:{
					lng:'',
					lat:'',
				},
				mapflag:false,
				// userId: this.$store.state.user.userId,
				// deptId: this.$store.state.user.deptId,
				address:'',
				searchtxt:'',
				type:'add',//新增还是修改,
				placeSearchComponent:'',
				autoCompleteComponent:'',
				map:'',
				covers: [{
					id:0,
					latitude: '',
					longitude: '',
					width:68,   //宽
					height:68,   //高
					iconPath: require("@/work/static/map.png"),
					anchor:{x: 0.5, y: 0.5}
				}],
				mapheight:0,
				mapContext:"",
				searchList:[],
				focus:false,
				location:'',
				setflag:false,
			}
		},
		onReady() {
			this.getcreateMap()
		},
		onLoad(e) {
			if(e.type=='update'){
				this.type='update'
				this.center.lng=e.lng;
				this.center.lat=e.lat;
				this.address=e.address;
			}else{
				if(e.address){
					this.type='update'
					this.center.lng=e.lng;
					this.center.lat=e.lat;
					this.address=e.address;
				}else{
					this.type='add';
				}
				
			}
			if(e.fromurl){
				this.fromurl=e.fromurl
			}
		},
		onShow() {
			var that=this;
			if(this.setflag){
				this.setflag=false;
				// #ifndef H5
				this.getlocationadr()
				// uni.getSetting({
				// 	success(res) {
				// 		if(res.authSetting['scope.userLocation'] != undefined){
				// 			if (res.authSetting['scope.userLocation']) {
				// 				// 已经授权，可以直接调用 getLocation 获取地理位置
				// 				that.getlocation()
				// 				that.setflag=false;
				// 			} else {
				// 				that.$modal.confirm('确定开启定位授权？').then(() => {
				// 					that.setflag=true;
				// 				  uni.openSetting({
				// 				  	success(res2) {
				// 				  		if (res2.authSetting['scope.userLocation']) {
								  			
				// 				  		}
				// 				  	}
				// 				  });
				// 				})
				// 			};
				// 		}
				// 	},
				// 	fail(err) {
				// 	},
				// })
				// #endif
			}
		},
		mounted() {
			var that=this;
			this.getinfo();
			if(this.type=='add'){
				// #ifndef H5
				this.getlocationadr()
				// #endif
			}else{				
				var lng=this.center.lng;
				var lat=this.center.lat;
				that.covers = [];
				that.covers = [{
					id:1,
					latitude: lat,
					longitude: lng,
					width:68,   //宽
					height:68,   //高
					iconPath: that.mapimg,
					anchor:{x: 0.5, y: 0.5}
				}]
				// #ifdef MP-WEIXIN
				that.getCity(lat,  lng)
				// #endif
			}
		},
		methods:{
			// 获取定位
			getlocationadr(){
				var that=this;
				self.getLocation(function(res){
					if(res==-1){
						that.setflag=true
					}else{
						that.center.lng=res.lng;
						that.center.lat=res.lat;
						that.address=res.address;
						that.covers = [];
						that.covers = [{
							id:4,
							width:68,   //宽
							height:68,   //高
							latitude: res.lat,
							longitude: res.lng,
							iconPath: that.mapimg,
							anchor:{x: 0.5, y: 0.5}
						}]
						var newobj={
							lng:res.lng,
							lat:res.lat,
							address:res.address
						}
						self.setUxLocation(newobj)
					}	
				})
			},
			getSureFn(){
				var address={
					address:this.address,
					lng:this.center.lng,
					lat:this.center.lat,
				}
				uni.$emit('refreshaddr',address);
				uni.navigateBack({delta: 1});	
			},
			searchKeyword(){
				var that=this;
				if(this.searchtxt){
					// #ifdef H5
					AMap.plugin('AMap.PlaceSearch', function(){
						let autoOptions = {
							city:'全国',
							citylimit: true,
							pageIndex: 1,
							pageSize: 20,
						}
						let placeSearch = new AMap.PlaceSearch(autoOptions);
						placeSearch.search(that.searchtxt, function(status, result) {
							// 搜索成功时，result即是对应的匹配数据
							if (status === 'complete' && result.info === 'OK') {
								let items = result.poiList.pois;
								if(items.length > 0){
									var pois = [];
									for (let i in items) {
										var obj = {
											"name": items[i].name,
											"addr": items[i].address,
											"lng": items[i].location.lng,
											"lat": items[i].location.lat
										};
										pois.push(obj);
									}
									that.searchList = pois;
								}
							}else{
								that.searchList = [];
							}
						})
					})
					// #endif

					// #ifndef H5
					myAmapFun.getInputtips({
						keywords: that.searchtxt,
						city: '全国',
						citylimit: true,
						success: function(result){
							console.log(result,124)
							if(result.tips.length > 0){
								let pois = [];
								let items = result.tips;
								for (let i in items) {
									if(items[i].location&&items[i].location.length>0){
										var lnglat = items[i].location.split(',');
										var obj = {
											"name": items[i].name,
											"addr": items[i].district + items[i].address,
											"lng": lnglat[0],
											"lat": lnglat[1]
										};
										pois.push(obj);
									}
								}
								that.searchList = pois;
							}else{
								that.searchList = [];
							}
						},
						fail: function(info){
							that.searchList = [];
							console.log('fail-search', info)
						}
					})
					// #endif
				}
			},
			handleAddrClick(addr){
				var that=this;
				var lng=addr.lng;
				var lat=addr.lat;
				that.center.lng=lng;
				that.center.lat=lat;
				that.covers = [];
				that.covers = [{
					id:2,
					width:68,   //宽
					height:68,   //高
					latitude: addr.lat,
					longitude: addr.lng,
					iconPath: that.mapimg,
					anchor:{x: 0.5, y: 0.5}
				}]
				// that.address=addr.name || addr.addr;
				that.address=addr.addr + addr.name;
				that.searchList=[];
				// #ifdef MP-WEIXIN
				that.getCity(lat,  lng)
				// #endif
			},
			richNodes(item){
			return [{
				children: [
					{
				type: 'text',
				attrs: {
				class:'wrap_text'
				},
				text: item.name.substring(0, item.name.indexOf(this.searchtxt))
				},
				{
				type: 'text',
				attrs: {
				class:'wrap_texts'
				},
				text: this.searchtxt
				},
				{
				type: 'text',
				attrs: {
				class:'wrap_text'
				},
				text: item.name.substring(item.name.indexOf(this.searchtxt) + this.searchtxt.length)
				}
				]
			}]
			},
			// 获取当前屏幕信息
			getinfo(){
				var that=this;
				uni.getSystemInfo({
					success(e) {
						that.mapheight=e.windowHeight;
					},
				})
			},
			getcreateMap(){
				//mapId 就是你在 map 标签中定义的 id
				this.mapContext = uni.createMapContext('container', this);
			},
			onClcikImgMap(e) {
				var that=this;
				var lng=e.detail.longitude;
				var lat=e.detail.latitude;
				that.center.lng=lng;
				that.center.lat=lat;
				that.covers = [];
				that.covers = [{
					id:3,
					width:68,   //宽
					height:68,   //高
					latitude: e.detail.latitude,
					longitude: e.detail.longitude,
					iconPath: that.mapimg,
					anchor:{x: 0.5, y: 0.5}
				}]
				// #ifdef MP-WEIXIN
				that.getCity(lat,  lng)
				// #endif
			},
			//获取中心点
			getCenterLanLat() {
				var that = this;
					this.mapContext.getCenterLocation({
					  type: 'gcj02',
					  success: res => {
					    that.center.lng=res.longitude;
					    that.center.lat=res.latitude;
						that.covers = [];
						that.covers = [{
							id:4,
							width:68,   //宽
							height:68,   //高
							latitude: e.detail.latitude,
							longitude: e.detail.longitude,
							iconPath: that.mapimg,
							anchor:{x: 0.5, y: 0.5}
						}]
					    // #ifdef MP-WEIXIN
						
					    that.getCity(res.latitude,  res.longitude)
					    // #endif
					  },
					  fail: err => {
					    console.log('获取当前地图中心的经纬度2', err);
					  },
					});

			},
			getCity(latitude, longitude,idx) {
				var that = this;
				that.location = `${longitude},${latitude}`

				myAmapFun.getRegeo({
				//如果经纬度有问题会导致不进入回调方法，从而报错
					location: that.location,
					success: function(e) {
						//成功回调
						that.address='';
						that.address = e[0].regeocodeData.formatted_address; //详细地址
						// 存起来
						if(idx&&idx==1){
							var newobj={
								lng:longitude,
								lat:latitude,
								address:that.address
							}
							self.setUxLocation(newobj)
						}
					},
					fail: function(info) {
						//失败回调
						console.log(info)
					}
				})
			},
			// 获取定位
			getlocation(){
				var that = this;
				uni.getLocation({
					type: 'gcj02',
					geocode: true,
					success: function(res) {
						that.center.lng=res.longitude;
						that.center.lat=res.latitude;
						that.covers = [];
						that.covers = [{
							id:4,
							width:68,   //宽
							height:68,   //高
							latitude: res.latitude,
							longitude: res.longitude,
							iconPath: that.mapimg,
							anchor:{x: 0.5, y: 0.5}
						}]
						// #ifdef MP-WEIXIN
						that.getCity(res.latitude,  res.longitude,1)
						// #endif
						
						// #ifdef H5
						var adr= address.province+address.city+address.district+address.street+address.streetNum+address.poiName
						// that.address=res.longitude
						that.address=adr
						// #endif

					},
					fail: function(red) {
						uni.showToast({
							title:"获取定位失败"
						})
					},
				})
			},
			// 点击刷新方法
			refresh(e){
				this.getlocation();
			},

		}
	}
</script>

<style lang="scss" scoped>
.maptop {
	position: fixed;
	left: 34rpx;
	right: 34rpx;
	top: 24rpx;
}
.maptopflex {
	display: flex;
	align-items: center;
	padding: 0 32rpx;
	box-sizing: border-box;
	flex-direction: row;
	width: 684rpx;
	height: 84rpx;
	background: #ffffff;
	box-shadow: 0px 0px 12rpx 0px rgba(75, 75, 75, 0.35);
	border-radius: 6rpx;
	margin-bottom: 10rpx;
}
.maptopimg {
	width: 36rpx;
	height: 38rpx;
	margin-right: 16rpx;
}
.maptopint {
	font-size: 32rpx;
	color: #666666;
	flex: 1;
	height: 84rpx;
}
.mapfot {
	position: fixed;
	left: 34rpx;
	right: 34rpx;
	bottom: 24rpx;
	background: #fff;
	box-shadow: 0px 0px 12rpx 0px rgba(75, 75, 75, 0.35);
	border-radius: 6rpx;
	padding: 40rpx 32rpx 32rpx;
	min-height: 300rpx;
}
.mapfott {
	margin-bottom: 28rpx;
}
.mapfottit {
	font-size: 33rpx;
	font-weight: bold;
	color: #343434;
}
.mapfotx {
	display: flex;
	margin-bottom: 32rpx;
	min-height: 70rpx;
	flex-direction: row;
}

.mapfotimg {
	width: 26rpx;
	height: 28rpx;
	flex: 0 0 auto;
	margin-right: 12rpx;
}
.mapfottxt {
	flex: 1;
	font-size: 32rpx;
	color: #343434;
	line-height: 32rpx;
}
.mapfotn {
	width: 618rpx;
	height: 76rpx;
	background: #1678ff;
	border-radius: 6rpx;
	display: flex;
	align-items: center;
	justify-content: center;
}
.mapfotntit {
	font-size: 34rpx;
	color: #fff;
}

.addrSearch_item {
	border-bottom: 2upx solid #f5f5f5;
	padding: 4upx;
	background: #ffffff;
}
.addrSearch_item .wrap_name {
	display: flex;
	flex-direction: row !important;
}
.wrap_text {
	font-size: 34upx;
	color: #151515;
	line-height: 40upx;
}
.wrap_texts{
	font-size: 34upx;
	color: #2797FF;
	line-height: 40upx;
}
.addrSearch_item .wrap_addr {
	margin-top: 2upx;
}
.wrap_addrs {
	font-size: 28upx;
	color: #999;
	line-height: 32upx;
}
</style>
