<template>
	<view>


		<map id="map" :longitude="longitude" :latitude="latitude" :polyline="polyline" scale="14" :polygons="polygons"
		 show-location style="width: 100%; height:100vh;" :markers="markers" @markertap="markertap" :data-markers="markers"
		 :enable-satellite="satellite" @controltap="controltap" :controls="controls">
			<cover-view @click="again" v-if="mapclick" class="again" style="left: 5%; border-radius: 15upx;">重绘</cover-view>
			<cover-view @click="cancelBtn" v-if="mapclick" class="cancelBtn">取消</cover-view>
			<cover-view @click="finish" v-if="mapclick" class="finish">完成</cover-view>
			<view class="info" v-if="markShow">
				<view class="infoCon">
					<view class='flexB'>
						<view style="font-size:32upx;">区域名称：{{detail.name}}</view>
						<view class="flex" style="margin-top:15upx;align-items:center;">
							<!-- <van-switch style="margin:0 15upx;" checked="detail.status==1 ? true:false " size="18px" bind:change="switchCon"
						 active-color="#07c160" inactive-color="#f00" /> -->
							<text style="margin-bottom:7upx;">{{detail.status==1 ? '已开启':'已禁用'}}</text>
						</view>
					</view>
					<view class="deleted" @click="remove" :data-detail="detail">
						<text>删除</text>
					</view>
				</view>
			</view>
			<cover-image src="http://resource.weilaibike.com/bike_yunwei/ref.png" @click="refresh" class="ref" style="bottom: 17%;"></cover-image>
			<cover-image src="http://resource.weilaibike.com/change.png" @click="sateposi" class="satellite flexCC"></cover-image>
				<cover-view id="top" @click="push" v-if="!mapclick" style="background: #18d5b9">添加区域</cover-view>
			<cover-image src="http://resource.weilaibike.com/bike_yunwei/location.png" @click="posi" class="position"></cover-image>
		</map>
	</view>
</template>

<script>
	const app = getApp();
	export default {
		data() {
			return {
				latitude: "",
				longitude: "",
				markers: [], //点
				polyline: [], //线
				polygons: [], //区域
				controls: [],
				list: [],
				fence: [], //点击地图获取的经纬度
				type: '', //停车区类型
				parkName: '', //停车区名称
				markShow: false, //是否显示停车点名称
				parkId: '', //停车点/禁停区id
				detail: [],
				showPop: false, //是否显示弹窗
				areaList: [], //选择所属大区列表
				typeList: [{ //区域类型选项
					type: 1,
					name: '禁停区'
				}, {
					type: 2,
					name: '停车区'
				}],
				options: '',
				parkNum: 0, //停车上限
				mapclick: false, //是否执行地图点击事件
				areaChecked: true, //弹窗区域的状态
				areaId: '', //区域id
				btnShow: false, //重绘  取消
				pushShow: true,
				areaName: '',
				satellite: false, //是否显示卫星地图
				newArea: {}, // 新添加的停车点或者禁停区
				areaID: 0,
				value1: 0, //第一个显示什么
				option1: [],
				rideArea: [], //骑行区
				screenHeight: '', //屏幕可视高度
				showArea: '',
				showType: ''
			}
		},
		methods: {
			//重绘
			again: function() {
				console.log('重绘')
				this.getArea();
				this.polygons = [];
				this.markers = [];
				this.polyline = [];
				this.list = [];
				this.btnShow = false;
				this.park();
			},
			cancelBtn: function() {
				console.log('取消')
				this.mapclick = false;
				this.markers = [];
				this.pushShow = true;
				this.controls = []
				this.polygons = []
				this.polyline = []
				this.list = []
				this.park();
			},
			//完成
			finish: function() {
				let that = this;
				if (that.fence.length >= 3) {
					let state = JSON.parse(that.areaChecked);
					let parking_fence = []
					that.fence.map(i => {
						parking_fence.push({
							lat: i.latitude,
							lng: i.longitude
						})
					})
					if (state) {
						state = 1
					} else {
						state = 0
					}
					let data = {
						parking_fence: JSON.stringify(parking_fence),
						area_id: that.areaId,
						max_number: that.parkNum,
						name: that.parkName,
						status: state,
						type: that.type,
					}
					app.request('parking', data, 'POST').then(res => {
						if (res.statusCode == 201) {
							console.log(that.type, 555)
							console.log(res, '添加');
							uni.showToast({
								title: '添加成功',
								icon: 'none',
								duration: 3000,
								success: function() {
									that.mapclick = false;
									that.pushShow = true;
									that.controls = [];
									that.list = [];
									that.polygons = [];
									that.polyline = [];
									that.markers = [];
									that.park();
								}
							})
						}
					})
				} else {
					uni.showToast({
						title: '请至少选择三个点',
						icon: 'none'
					})
				}

			},

			//添加还车点、禁停区
			push: function() {
				// this.showPop = true;
				// this.parkName = '';
				// this.parkNum = 0;
				// this.areaChecked = true;
				// this.markShow = false;
				// this.areaName = this.option1[0].text;
				// this.typeName = this.typeList[1].name;
				// this.type = this.typeList[1].type;
				// this.areaId = this.option1[0].areaID;
				uni.navigateTo({
					url: "./add_park"
				})
			},
			posi: function() {
				//点击定位  
				console.log(12)
				uni.getLocation({
					type: 'gcj02',
					success: (res) => {
						console.log(res)
						this.longitude = res.longitude;
						this.latitude = res.latitude;
					}
				})
			},
			refresh: function() {
				uni.showLoading({
					title: '刷新中...',
				})
				this.markShow = false;
				this.park();
			},
			sateposi: function() {
				this.satellite = !this.satellite
			},
			//选择区域类型
			choiceType: function() {
				this.showType = !this.showType;
			},
			// 改变区域状态
			changeState: function() {
				this.areaChecked = !this.areaChecked;
			},
			//绘制围栏
			draw: function() {
				let that = this;
				uni.getSystemInfo({
					success: (res) => {
						console.log(1111)
						this.controls = [{
							id: 1,
							iconPath: '/static/img/lock.png', //  中心点图片
							position: {
								left: res.windowWidth / 2 - 9,
								top: res.windowHeight / 2 - 27,
								width: 45,
								height: 45
							},
							clickable: true
						}]
					}
				})
				this.showPop = false;
				this.mapclick = true;
				this.pushShow = false;
				uni.showToast({
					title: '请点击地图进行绘制',
					icon: 'none'
				})
			},
			//地图上绘制停车区
			controltap: function(e) {
				let that = this;
				let mapCtx = uni.createMapContext("map");
				let arr = that.list;
				mapCtx.getCenterLocation({
					success: function(res) {
						console.log(res.latitude, '经纬度')
						var latitude = res.latitude
						var longitude = res.longitude
						var color = '';
						var bgColor = '';
						var iconPath = '';
						if (that.type == 1) { //禁停区
							iconPath = "http://resource.weilaibike.com/redStop.png";
							color = "#FF0000";
							bgColor = "#FF000002";
						} else if (that.type == 2) { //停车区
							iconPath = "http://resource.weilaibike.com/stop1.png";
							color = "#ff00ff";
							bgColor = "#ff00ff02"
						}
						let obj = {
							latitude,
							longitude
						};
						arr.push(obj);
						console.log(arr, 'arr')
						if (arr.length == 1) {
							console.log('1')
							let dot = {}
							dot.latitude = arr[0].latitude;
							dot.longitude = arr[0].longitude;
							dot.width = 28;
							dot.height = 28;
							dot.iconPath = iconPath;
							let dotArr = [];
							dotArr.push(dot)
							that.markers = that.markers.concat(dotArr)
						}
						if (arr.length == 2) {
							console.log('2')
							let line = {};
							line.points = arr;
							line.width = 4;
							line.borderWidth = 3;
							line.borderColor = color;
							line.color = color;
							let lineArr = [];
							lineArr.push(line);
							console.log(lineArr)
							that.markers.splice(that.markers.length - 1, 1)
							that.polyline = lineArr;
							that.markers = that.markers;
							// console.log(lineArr)
						}
						if (arr.length == 3) {
							console.log('==3')
							let line = {};
							line.points = arr;
							let lineArr = [];
							lineArr.push(line);
							let area = {};
							that.fence = arr;
							that.btnShow = true;
							area.points = arr;
							let areaArr = [];
							areaArr.push(area)
							console.log(areaArr)
							var areaPoly = areaArr[0].points[0];
							var areaPons = areaArr[0].points.concat(areaPoly);
							console.log(areaPons)
							var obj2 = {
								'points':areaPons,
								'fillColor':bgColor,
								'strokeColor':color,
								'strokeWidth':4,
								'zIndex':1,
								'id':99
							}
							that.polygons = that.polygons.concat(obj2);
							var poly = lineArr[0].points[0];
							var polylines = lineArr[0].points.concat(poly);
							var obj1 = {
								'points':polylines,
								'width':4,
								'borderWidth':3,
								'borderColor':color,
								'color':color
							}
							var arr1 = []
							arr1.push(obj1)
							that.polyline = arr1;
							console.log(that.polyline)
							console.log(that.polygons)
						}
						if(arr.length>=4){
							console.log(that.polygons)
							var arr5 = that.polygons[0].points;
							var arr6 = that.deWeight(arr5)
							that.polygons[0].points = arr6
							console.log(that.polygons)
							let line = {};
							line.points = arr;
							let lineArr = [];
							lineArr.push(line);
							let area = {};
							that.fence = arr;
							that.btnShow = true;
							area.points = arr;
							let areaArr = [];
							areaArr.push(area)
							console.log(areaArr)
							var areaPoly = areaArr[0].points[0];
							var areaPons = areaArr[0].points.concat(areaPoly);
							console.log(areaPons)
							var obj2 = {
								'points':areaPons,
								'fillColor':bgColor,
								'strokeColor':color,
								'strokeWidth':4,
								'zIndex':1,
								'id':99
							}
							var poly2 = that.polygons.concat(obj2)
							that.polygons = poly2;
							var poly = lineArr[0].points[0];
							var polylines = lineArr[0].points.concat(poly);
							var obj1 = {
								'points':polylines,
								'width':4,
								'borderWidth':3,
								'borderColor':color,
								'color':color
							}
							var arr1 = []
							arr1.push(obj1)
							that.polyline = arr1;
							console.log(that.polyline)
							console.log(that.polygons)
						}
					}
				})
			},
			//停车点和禁停点
			park: function() {
				uni.showLoading({
					title: '加载中...',
				})
				var that = this;
				console.log(that.areaID)
				let url = 'parking?area_id=1'
				that.getArea();
				app.request(url, '', 'GET').then(res => {
					uni.hideLoading();
					// console.log(res)
					let polygons = res.data.parking_area.concat(that.rideArea);
					that.markers = res.data.point;
					that.polygons = polygons;
					that.polyline = that.polygons;
					console.log(that.polygons, '停车区和禁停区')
					console.log(that.markers, 'markers')
				})
			},
			 deWeight:function(arr) {
			    for (var i = 0; i < arr.length - 1; i++) {
			        for (var j = i + 1; j < arr.length; j++) {
			            if (arr[i].longitude == arr[j].longitude) {
			                arr.splice(j, 1);
			                //因为数组长度减小1，所以直接 j++ 会漏掉一个元素，所以要 j--
			                j--;
			            }
			        }
			    }
			    return arr;
			},
			// 获取骑行区
			getArea: function() {
				var that = this;
				let url = 'getAreas?put_area_id=' + that.areaID + "&&is_with_parking=" + 0
				app.request(url, '', 'GET').then(res => {
					console.log(res);
					that.rideArea = res.data.ridding_area
				})
			},
			//停车（禁停）图标点击事件
			markertap: function(e) {
				console.log(e)
				this.getPark_info(e.detail.markerId)
				this.parkId = e.detail.markerId;
			},
			//获取停车（禁停）点信息
			getPark_info: function(parkId) {
				var that = this;
				uni.showLoading({
					title: '加载中...',
				})
				console.log(parkId)
				app.request('parking/' + parkId.slice(1), '', 'GET').then(res => {
					uni.hideLoading();
					console.log(res.data)
					this.detail = res.data;
					this.markShow = true;
					var status = ''
					if (res.data.status == 1) {
						status = '已启用'
					} else {
						status = '已禁用'
					}
					console.log(status, 'status')
					uni.showActionSheet({
						itemList: ['禁用/启用，当前' + status, '删除', '取消'],
						success: function(res) {
							console.log('选中了第' + (res.tapIndex + 1) + '个按钮');
							if (res.tapIndex + 1 == 2) {
								//删除
								that.remove()
							}
							if (res.tapIndex + 1 == 1) {
								//禁用或者启用
								that.switchCon()
							}
						},
						fail: function(res) {
							console.log(res.errMsg);
						}
					});
				})
			},
			//删除当前停车（禁停点）
			remove: function(e) {
				console.log(e);
				var that = this;
				console.log(that.parkId, 'parkId')
				uni.showModal({
					title: '提示',
					content: '确定删除该区域吗？',
					success: function(res) {
						if (res.confirm) {
							app.request('parking/' + that.parkId.slice(1), '', 'DELETE').then(res => {
								if (res.statusCode == 204) {
									that.park();
									uni.showToast({
										title: '删除成功',
										icon: 'none',
										duration: 2000,
									})
									that.markShow = false;
								}
							})
						}
					}
				})
			},
			//停车区状态
			switchCon: function() {
				uni.showLoading({
					title: '修改中...',
				})
				var that = this;
				console.log(that)
				let detail = that.detail
				detail.status = !detail.status;
				let status = '';
				if (detail.status == true) {
					status = 1
				} else {
					status = 0
				}
				that.detail = detail;
				let data = {
					status,
					id: that.parkId
				}
				app.request('parking/status', data, 'POST').then(res => {
					uni.hideLoading();
					if (res.statusCode == 200) {
						uni.showToast({
							title: '修改成功',
							icon: 'none'
						})
					}
				})
			},
		},
		onLoad(options) {
			this.park(); // 获取停车区
			this.getArea(); //获取骑行区
			// this.controltap()

		},
		onShow: function() {
			console.log(this.areaId)
			console.log(this.parkName)
			console.log(this.parkNum)
			console.log(this.type)
			if (this.mapclick) {
				this.draw()
			}
			uni.getLocation({
				type: 'gcj02',
				success: (res) => {
					console.log(res)
					this.longitude = res.longitude;
					this.latitude = res.latitude;
				}
			})
		}
	}
</script>

<style>
	.info {
		font-size: 28upx;
		width: 100%;
		height: 76upx;
		position: absolute;
		left: 0;
		top: 12%;
	}

	.info .infoCon {
		background: #fff;
		width: 90%;
		margin: 0 auto;
		padding: 10upx;
		border-radius: 10upx;
		display: flex;
		justify-content: space-between;
		align-items: center;
	}

	.info .infoCon .flexB {
		display: flex;
		flex-direction: column;
		align-items: flex-start;
	}

	.info .deleted {
		display: flex;
		align-items: center;
		justify-content: center;
		background: #f00;
		color: #fff;
		font-size: 26upx;
		padding: 10upx 30upx;
		border-radius: 25upx;
		margin-right: 15upx;
		height: 35upx;
	}

	#top {
		position: absolute;
		width: 300upx;
		height: 70upx;
		z-index: 999;
		bottom: 17%;
		left: 50%;
		margin-left: -150upx;
		border-radius: 15upx;
		background: #18d5b9;
		font-size: 28upx;
		color: #fff;
		text-align: center;
		line-height: 60upx;
	}

	.position,
	.ref {
		position: absolute;
		left: 10%;
		bottom: 27%;
		display: flex;
		align-items: center;
		justify-content: center;
		height: 72upx;
		width: 72upx;
	}

	.satellite {
		position: absolute;
		left: 80%;
		bottom: 17%;
		height: 40upx;
		width: 40upx;
	}

	.again {
		position: absolute;
		bottom: 100upx;
		width: 27%;
		height: 70upx;
		line-height: 60upx;
		text-align: center;
		background: #18d5b9;
		color: white;
		font-size: 30upx;
		border-radius: 15upx;
		z-index: 999;
	}

	.cancelBtn {
		width: 27%;
		border-radius: 15upx;
		position: absolute;
		bottom: 100upx;
		height: 70upx;
		left: 37% !important;
		font-size: 30upx;
		background: #18d5b9;
		color: #FFFFFF;
		text-align: center;
		line-height: 60upx;
	}

	.finish {
		border-radius: 15upx;
		width: 27%;
		position: absolute;
		bottom: 100upx;
		font-size: 30upx;
		height: 70upx;
		right: 5% !important;
		color: #FFFFFF;
		text-align: center;
		background: #18d5b9;
		line-height: 60upx;
	}

	.bt {
		height: 70upx;
		line-height: 70upx;
		width: 25%;
		background-color: #007AFF;
		color: #FFFFFF;
		border-radius: 10upx;
		font-size: 28upx;
	}
</style>
