<template>
	<div style="cursor: default">
		<el-breadcrumb separator-class="el-icon-arrow-right">
			<el-breadcrumb-item>农场管理</el-breadcrumb-item>
			<el-breadcrumb-item :to="{ path: '/index/farmBaseManger' }"
				>基地管理</el-breadcrumb-item
			>
			<el-breadcrumb-item>添加基地</el-breadcrumb-item>
		</el-breadcrumb>
		<el-card class="box-card">
			<el-form
				ref="addBaseFormRef"
				:model="addBaseForm"
				label-width="120px"
				:rules="addBaseFormRules"
			>
				<el-form-item label="基地名称 : " prop="farmname">
					<el-input v-model="addBaseForm.farmname"></el-input>
				</el-form-item>
				<el-form-item label="基地面积(亩) : " prop="farmarea">
					<el-input type="number" min="0" v-model="addBaseForm.farmarea"></el-input>
				</el-form-item>
				<!-- <el-form-item label="基地地址 : " prop="farmaddr">
					<el-input v-model="addBaseForm.farmaddr"></el-input>
				</el-form-item> -->
				<el-form-item label="基地描述 : " prop="farmdesc">
					<el-input type="textarea" v-model="addBaseForm.farmdesc"></el-input>
				</el-form-item>
				<el-form-item label="负责人 : " prop="username">
					<el-input v-model="addBaseForm.username"></el-input>
				</el-form-item>
				<el-form-item label="基地位置 : " class="map-box" prop="farmframe">
					<el-input
						style="width: 380px; cursor: pointer"
						size="small"
						@change="addrChange()"
						clearable
						placeholder="请输入地区检索"
						v-model="addr"
					>
						<i slot="suffix" class="el-input__icon el-icon-search"></i>
					</el-input>
					{{polygonPath.paths}}
					{{overlays}}
					<button style="cursor: pointer" @click.prevent="toggle('polygonPath')">
						{{ polygonPath.editable ? '停止绘制' : '开始绘制' }}
					</button>
					<el-amap
						class="bm-view"
						vid="amapDemo"
						:center="center"
						:amap-manager="amapManager"
						style="height: 400px"
						:zoom="zoom"
						:plugin="plugin"
        				:events="mapEvents"
					>
						<el-amap-polygon 
							:path="polygonPath.paths"
							:editable="true"
							stroke-color="blue"
							fill-color="red"
							:fill-opacity="0.8"
							:stroke-opacity="0.5"
							:stroke-weight="2"
							@click="alertpath"
						></el-amap-polygon>
						
						<el-amap-marker v-if="componentMarker.position.length" vid="component-marker" :position="componentMarker.position"  ></el-amap-marker>
					</el-amap>
					<!-- <baidu-map
						class="bm-view"
						:center="center"
						:zoom="zoom"
						:map-click="false"
						@mousemove="syncPolygon"
						@ready="handler"
						style="height: 400px"
						@click="paintPolygon"
						@rightclick="newPolygon"
					>
						<bm-polygon
							:path="path"
							v-for="path of polygonPath.paths"
							:key="path.toString()"
							stroke-color="blue"
							fill-color="red"
							:fill-opacity="0.8"
							:stroke-opacity="0.5"
							:stroke-weight="2"
							@click="alertpath"
						/>
						<bm-control>
							<button style="cursor: pointer" @click.prevent="toggle('polygonPath')">
								{{ polygonPath.editable ? '停止绘制' : '开始绘制' }}
							</button>
						</bm-control>
					</baidu-map> -->
				</el-form-item>
				<el-form-item>
					<el-button type="primary" @click="addBaseSubm">添加</el-button>
					<el-button @click="cancleaddBase">取消</el-button>
				</el-form-item>
			</el-form>
		</el-card>
	</div>
</template>

<script>
import VueAMap from "vue-amap";
let amapManager = new VueAMap.AMapManager();
export default {
	data() {
		return {
			amapManager,
			mapEvents: { 
				init: (o) => {
				// console.log(o.getCenter())
				// console.log(this.$refs.map.$$getInstance())
				// o.getCity(result => {
				//   console.log(result)
				// })
				},
				'moveend': () => {
				},
				'zoomchange': () => {
				},
				'click': (e) => {
				},
				'mousemove': (e) => {
				},
			},
			plugin: [
				{
				pName: "ToolBar",
				events: {
					init(instance) {
					console.log(instance);
					}
				}
				},
				{
				pName: "Scale",
				events: {
					init(instance) {
					console.log(instance);
					}
				}
				},
				// {
				//     pName: 'MapType',
				//     defaultType: 0,
				//     events: {
				//       init(instance) {
				//         console.log(instance);
				//       }
				//     }
				//   }
			],
			addBaseForm: {
				farmname: '',
				username: '',
				farmdesc: '',
				farmaddr: '',
				farmarea: ''
			},
			addBaseFormRules: {
				farmname: [
					{ required: true, message: '请填写基地名称', trigger: 'blur' }
				],
				username: [
					{ required: true, message: '请填写负责人', trigger: 'blur' }
				],
				farmaddr: [
					{ required: true, message: '请填写基地地址', trigger: 'blur' }
				],
				farmdesc: [
					{ required: true, message: '请填写基地描述', trigger: 'blur' }
				],
				farmarea: [
					{ required: true, message: '请填写基地面积', trigger: 'blur' }
				]
			},
			center: [116.412732,39.911707 ],
			zoom: 13,
			overlays:[],//存储矢量图形
			mouseTool:null,
			polygonPath: {
				editable: false,
				paths: []// 绘制完成后的经纬度，其实是在画的时候动态push的，因为在点击的时候触发了 paintPolygon 函数
			},
			componentMarker:{
				position:[]
			},
			addr: ''
		}
	},
	methods: {
		addBaseSubm() {
			this.$refs.addBaseFormRef.validate((valid) => {
				if (!valid) {
					return
				}
				let farmframe =
					this.polygonPath.paths[0] &&
					this.polygonPath.paths[0]
						.map((item) => {
							return item.lng + ',' + item.lat
						})
						.join(';')
				this.$axios({
					url: '/api/api_gateway?method=ascend.ascend_manage.add_base',
					method: 'POST',
					data: this.qs.stringify({
						farmname: this.addBaseForm.farmname,
						farmdesc: this.addBaseForm.farmdesc,
						username: this.addBaseForm.username,
						farmaddr: this.addBaseForm.farmaddr,
						farmframe,
						farmarea: this.addBaseForm.farmarea
					})
				}).then((res) => {
					if (res.data.message == '') {
						this.$message.success('添加基地成功！')
						this.$router.go(-1)
					} else {
						this.$message.error('添加基地失败！')
					}
				})
			})
		},
		cancleaddBase() {
			this.$router.go(-1)
		},
		getClickInfo(e) {
			console.log(e.point.lng)
			console.log(e.point.lat)
		},
		// 开启多边形绘制
		toggle(name) {
			this[name].editable = !this[name].editable
			// 在这里做一步判断，如果有路径且开启绘制就把原来的路径清空
			if (this.polygonPath.paths && this.polygonPath.editable) {
				this.polygonPath.paths = []
			}
			if(this[name].editable){
				this.paintPolygon()
			}else{
				this.mouseTool.close(true)//关闭，并清除覆盖物
			}
		},
		addrChange() {
			this.geocoder = new AMap.Geocoder({
				city: "全国", //城市设为北京，默认：“全国”
			});
			var _this = this;
			if(!this.addr){
				this.componentMarker.position = []
				return false;
			}
			this.geocoder.getLocation(this.addr, function(status, result) {
				if (status === 'complete'&&result.geocodes.length) {
					var lnglat = result.geocodes[0].location
					_this.center = [lnglat.lng,lnglat.lat]
					_this.componentMarker.position = [lnglat.lng,lnglat.lat];
				}else{
					log.error('根据地址查询位置失败');
				}
			});
		},
		// 鼠标多边形绘制
		paintPolygon() {
			var _this = this;
			let o = amapManager.getMap();
			var polyArr = o.getAllOverlays('polygon');	
			if(polyArr.length){
				o.remove(polyArr)
			};
			this.mouseTool = new AMap.MouseTool(o)
			this.drawPolygon()
			this.mouseTool.on('draw', function(e) {
				// e.obj 为绘制出来的覆盖物对象
				console.log(e.obj)
				console.log(e.obj.getPath())
				_this.mouseTool.close(false)//关闭
				_this.polygonPath.editable = !_this.polygonPath.editable
			})
		},
		drawPolygon () {
			this.mouseTool.polygon({
				strokeColor: "#FF33FF", 
				strokeOpacity: 1,
				strokeWeight: 6,
				strokeOpacity: 0.2,
				fillColor: '#1791fc',
				fillOpacity: 0.4,
				// 线样式还支持 'dashed'
				strokeStyle: "solid",
				// strokeStyle是dashed时有效
				// strokeDasharray: [30,10],
			})
		},
		alertpath(e) {
			// console.log(this.polygonPath.paths)
		},
	}
}
</script>

<style lang='less' scoped>
// .el-form{width:500px;}
.bm-view {
	// height: 400px;
	overflow: hidden;
	　/deep/ .anchorBL {
		display: none;
	}
}
.el-form-item {
	width: 500px;
}
.map-box {
	width: 100%;
}
</style>