<template>
	<el-dialog :title="modalTitle" :visible.sync="modalVisible" :width="formLabelWidth" top="2vh" @close="handleCancel">
		<div class="gardenMobile">
			<el-tabs :tab-position="tabPosition" :stretch="true" style="height:600px;" v-model="activePlanName">
				<el-tab-pane label="园区基本信息" name="baseinfo" style="height:600px;overflow-y:auto;">
					<div class="wrap">
						<h3 class="title">园区基本信息</h3>
						<el-form label-width="80px" :model="form" :rules="rules" label-position="top" ref="baseinfo" class="gardenFrom">
							<el-row :gutter="20">
								<el-col :span="8">
									<el-form-item label="园区编码" prop="orchardCode">
										<el-input v-model="form.orchardCode" :disabled="limit.isRead"></el-input>
									</el-form-item>
								</el-col>
								<el-col :span="8">
									<el-form-item label="园区名称" prop="orchardName">
										<el-input v-model="form.orchardName" :disabled="limit.isRead"></el-input>
									</el-form-item>
								</el-col>
								<el-col :span="8">
									<el-form-item label="园区规模（平方米）" prop="orchardArea">
										<el-input v-model="form.orchardArea" :disabled="limit.isRead"></el-input>
									</el-form-item>
								</el-col>
							</el-row>
							<el-row :gutter="20">
								<el-col :span="8">
									<el-form-item label="行业类型" prop="induType">
										<el-select v-model="form.induType" placeholder="请选择" :disabled="limit.isRead">
											<el-option v-for="item in agriTypeList" :key="item.id" :label="item.name" :disabled="limit.isRead" :value="item.id"></el-option>
										</el-select>
									</el-form-item>
								</el-col>
								<el-col :span="8">
									<el-form-item label="人员数" prop="workerCount"><el-input v-model="form.workerCount" :disabled="limit.isRead"></el-input></el-form-item>
								</el-col>
								<el-col :span="8">
									<el-form-item label="建园日期">
										<el-date-picker
											:disabled="limit.isRead"
											v-model="form.beginDate"
											type="date"
											start-placeholder="请选择日期"
											value-format="yyyy-MM-dd"
											align="left"
										></el-date-picker>
									</el-form-item>
								</el-col>
							</el-row>
							<el-row :gutter="20">
								<el-col :span="8">
									<el-form-item label="负责人">
										<el-input v-model="form.leaderName" :disabled="limit.isRead"></el-input>
									</el-form-item>
								</el-col>
								<el-col :span="8">
									<el-form-item label="联系方式" prop="telNo">
										<el-input v-model="form.telNo" :disabled="limit.isRead"></el-input>
									</el-form-item>
								</el-col>
								<el-col :span="8">
									<el-form-item label="海拔">
										<el-input v-model="form.elevation" :disabled="limit.isRead"></el-input>
									</el-form-item>
								</el-col>
							</el-row>
							<el-row :gutter="20">
								<el-col :span="24">
									<el-form-item label="园区简介">
										<el-input type="textarea" :rows="2" placeholder="请输入内容" v-model="form.orchardDesc" :disabled="limit.isRead"></el-input>
									</el-form-item>
								</el-col>
							</el-row>
							<h3 class="title">产出管理</h3>
							<el-table :data="form.products" border style="width: 100%">
								<el-table-column type="index" width="50" label="序号" align="center"></el-table-column>
								<el-table-column label="产出物">
									<template slot-scope="scope">
										<span v-if="!scope.row.editing">{{ scope.row.prodName }}</span>
										<span v-else><el-input size="mini" placeholder="请输入内容" v-model="scope.row.prodName"></el-input></span>
									</template>
								</el-table-column>
								<el-table-column label="产出面积（亩）">
									<template slot-scope="scope">
										<span v-if="!scope.row.editing">{{ scope.row.prodArea }}</span>
										<span v-else><el-input type="number" size="mini" placeholder="请输入内容" v-model="scope.row.prodArea"></el-input></span>
									</template>
								</el-table-column>
								<el-table-column label="产量估算（公斤）">
									<template slot-scope="scope">
										<span v-if="!scope.row.editing">{{ scope.row.prodVol }}</span>
										<span v-else><el-input type="number" size="mini" placeholder="请输入内容" v-model="scope.row.prodVol"></el-input></span>
									</template>
								</el-table-column>
								<el-table-column fixed="right" label="操作" align="center">
									<template slot-scope="scope">
										<el-button type="primary" size="mini" v-if="!scope.row.editing" :disabled="limit.isRead" icon="el-icon-edit-outline" @click="handleRowEdit(scope.$index, scope.row)">
											编辑
										</el-button>
										<el-button type="primary" size="mini" v-if="scope.row.editing" :disabled="limit.isRead" icon="el-icon-success" @click="handleRowSave(scope.$index, scope.row)">
											保存
										</el-button>
										<el-button size="mini" type="warning" v-if="scope.row.editing" :disabled="limit.isRead" icon="el-icon-warning" @click="handleRowCancel(scope.$index, scope.row)">
											取消
										</el-button>
										<el-button size="mini" type="danger" v-if="!scope.row.editing" :disabled="limit.isRead" icon="el-icon-delete" @click="handleRowDelete(scope.$index, scope.row)">
											删除
										</el-button>
									</template>
								</el-table-column>
							</el-table>
							<a class="addCcw" @click="addProduct" v-if="!limit.isRead">
								<i class="el-icon-plus"></i>
								新增产出物
							</a>
						</el-form>
					</div>
				</el-tab-pane>
				<el-tab-pane label="园区地理配置" name="mapConfig" style="height:600px;overflow-y:auto;">
					<div class="wrap">
						<h3 class="title">园区地理配置</h3>
						<div class="aMap">
							<el-card v-if="!limit.isRead" class="box-card" style="position: absolute;width:390px;top:60px;right: 30px;z-index: 9999;">
								<div slot="header" class="clearfix"><span>操作说明</span></div>
								<div>1、圆和矩形通过拖拽来绘制</div>
								<div>2、其他覆盖物通过点击来绘制、双击结束绘制</div>
								<div style="color: red;">3、右键单击图形清除绘制</div>
								<div style="color: red;">4、双击左键选定中心点</div>
								<div>
									<el-radio v-model="coversType" label="marker">画点</el-radio>
									<el-radio v-model="coversType" label="polyline">画折线</el-radio>
									<el-radio v-model="coversType" label="polygon">画多边形</el-radio>
									<el-radio v-model="coversType" label="rectangle">画矩形</el-radio>
									<el-radio v-model="coversType" label="circle">画圆</el-radio>
								</div>
							</el-card>
							<div ref="amap" style="width:100%;height:100%;position:relative;"></div>
						</div>
						<el-form label-width="80px" :model="form" :rules="rules" label-position="top" ref="mapConfig" class="gardenFrom">
							<el-row :gutter="20">
								<el-col :span="24">
									<el-form-item label="详细地址">
										<el-select
											v-model="citySelected.ids.provinceId" 
											placeholder="请选择" 
											@change="getCityList('add')">
											<el-option 
												v-for="item in provinceList" 
												:key="item.code"
												:label="item.name"
												:disabled="limit.isRead"
												:value="item.code"></el-option>
										</el-select>
										<el-select 
											v-if="citySelected.ids.provinceId"
											v-model="citySelected.ids.cityId"
											placeholder="请选择" 
											@change="getCountyList('add')">
											<el-option 
												v-for="item in cityList" 
												:key="item.code" 
												:label="item.name"
												:disabled="limit.isRead"
												:value="item.code"></el-option>
										</el-select>
										<el-select
											v-if="citySelected.ids.cityId"
											v-model="citySelected.ids.countyId" 
											placeholder="请选择" 
											@change="getTownList('add')"
											>
											<el-option 
												v-for="item in countyList" 
												:key="item.code" 
												:label="item.name"
												:disabled="limit.isRead"
												:value="item.code"></el-option>
										</el-select>
										<el-select 
											v-if="citySelected.ids.countyId"
											v-model="citySelected.ids.townId" 
											placeholder="请选择"
											@change="getAllAddress"
											>
											<el-option 
												v-for="item in townList" 
												:key="item.code" 
												:label="item.name"
												:disabled="limit.isRead"
												:value="item.code"></el-option>
										</el-select>
									</el-form-item>
									<el-input 
										v-model="citySelected.ids.address" 
										placeholder="详细地址" 
										:disabled="limit.isRead"
										class="address"></el-input>
								</el-col>
							</el-row>
						</el-form>
					</div>
				</el-tab-pane>
			</el-tabs>
		</div>
		<div slot="footer" class="dialog-footer">
			<el-button @click="submit" v-if="!limit.isRead">保 存</el-button>
			<el-button type="primary" v-if="!limit.isRead" @click="handelNext">{{ activePlanName == 'baseinfo' ? '下一步' : '上一步' }}</el-button>
		</div>
	</el-dialog>
</template>

<script>
import { globalReg } from '@/api/CONST';
export default {
	name: 'userMobiel',
	props: {
		visible: {
			type: Boolean,
			default: false
		},
		title: {
			type: String,
			default: 'title'
		},
		action: {
			type: String,
			default: 'add'
		},
		selectRow: {
			type: Object,
			default: {}
		}
	},
	watch: {
		visible(newVal, oldVal) {
			this.modalVisible = newVal;
		},
		title(newVal, oldVal) {
			this.modalTitle = newVal;
		},
		action(newVal, oldVal) {
			this.modalAction = newVal;
		},
		selectRow(newVal, oldVal) {
			this.modalSelectRow = newVal;
		},
		activePlanName(newVal,oldVal){
			console.log(newVal)
		}
	},
	data() {
		return {
			modalTitle: this.title,
			modalVisible: this.visible,
			modalAction: this.action,
			modalSelectRow: this.selectRow,
			formLabelWidth: '80%',
			tabPosition: 'left',
			activePlanName: 'baseinfo',
			agriTypeList: [], //涉及农业
			provinceList:[],
			cityList:[],
			countyList:[],
			townList:[],
			citySelected:{
				ids:{
					provinceId:'',
					cityId:'',
					countyId:'',
					townId:'',
					address:''
				}
			},
			limit: {
				isRead: false,
				isAdd: false
			},
			rules: {
				orchardCode: [
					{ required: true, message: '园区编码不能为空!', trigger: 'blur' },
					{ pattern: /^[0-9a-zA-Z]*$/g, message: '编码格式不正确，只能输入数字或字母!' },
				],
				orchardName: [
					{ required: true, message: '园区名称不能为空!', trigger: 'blur' },
				],
				orchardArea: [
					{ required: true, message: '园区规模不能为空!', trigger: 'blur' }, 
					{ pattern: /^\d+(\.\d+)?$/, message: '园区规模格式不正确，只能输入数字和小数!' },
				],
				induType: [
					{ required: true, message: '行业类型不能为空!', trigger: 'blur' },
				],
				workerCount: [
					{ required: true, message: '人员数不能为空!', trigger: 'blur' }, 
					{ pattern: /^[0-9]*$/g, message: '人员格式不正确，只能输入数字!' },
				],
				telNo: [
					{ required: false, validator: this.validateTel, trigger: 'blur' },
				],
				address: [
					{ required: true, message: '地址不能为空!', trigger: 'blur' },
				]
			},
			form: {
				products: [],
				orchardBorder:[]
			},
			//覆盖物绘画类型
			coversType: 'polygon',
			mouseTool: null,
			overlaysId: [],
			path:[],
		};
	},
	created() {
		this.getAgriType()
		this.getProvince() //城市初始化
		switch (this.modalAction) {
			case 'add':
				this.limit.isAdd = true;
				break;
			case 'edit':
				this.getDetail(this.modalSelectRow.id);
				break;
			case 'view':
				this.getDetail(this.modalSelectRow.id);
				this.limit.isRead = true;
				break;
			default:
				break;
		}
	},
	mounted() {
		this.initmap();
	},
	watch: {
		coversType(n, v) {
			this.mouseTool[n]();
		}
	},
	methods: {
		//获取省
		getProvince(){
			this.$port.getProvince()
				.then(res=>{
					this.provinceList = res.list
				}) 
		},
		//获取市
		getCityList(status){
			if(status === 'add'){
				this.reSelCityAll()
			}
			let params = {
				id:this.citySelected.ids.provinceId
			}
			this.$port.getCity(params)
				.then(res=>{
					this.cityList = res.list
				})
		},
		//获取县区
		getCountyList(status){
			if(status === 'add'){
				this.citySelected.ids.countyId = ''
				this.citySelected.ids.townId = ''
			}
			let params = {
				id:this.citySelected.ids.cityId
			}
			this.$port.getCounty(params)
				.then(res=>{
					this.countyList = res.list
				})
		},
		//获取乡镇
		getTownList(status){
			if(status === 'add'){
				this.citySelected.ids.townId = ''
			}
			let params = {
				id:this.citySelected.ids.countyId
			}
			this.$port.getTown(params)
				.then(res=>{
					this.townList = res.list
				})
		},
		//重置城市选中
		reSelCityAll(){
			this.citySelected.ids.cityId = ''
			this.citySelected.ids.countyId = ''
			this.citySelected.ids.townId = ''
			this.citySelected.ids.address = ''
		},
		//获取选中对应城市的名称
		findCityName(type){
			let arr,activeId,obj = {};
			switch(type){
				case 'province':
					arr = this.provinceList
					activeId = this.citySelected.ids.provinceId
					break;
				case 'city':
					arr = this.cityList
					activeId = this.citySelected.ids.cityId
					break;
				case 'county':
					arr = this.countyList
					activeId = this.citySelected.ids.countyId
					break;
				case 'townList':
					arr = this.townList
					activeId = this.citySelected.ids.townId
				default:	
			}
			obj = arr.find((item)=>{
				return item.code === activeId
			})
			return obj.name
		},
		//获取选择全地址
		getAllAddress(){
			let str;
			let province = this.findCityName('province')
			let city = this.findCityName('city')
			let county = this.findCityName('county')
			let townList = this.findCityName('townList')
			str = province+city+county+townList
			this.setMapCenter(str)
		},
		//地图操作 -> 检索切换城市
		setMapCenter(data){
			let params = {
				keywords:data,
				key:'952c5bea7e4b38bc32e1aa3beef06130',
				extensions: 'all'
			}
			this.$port.serachAmap(params)
				.then(res=>{
					if(res.data.status == 1){
						let center = res.data.pois[0].location.split(',');
						let [lng,lat] = center
						let position = new AMap.LngLat(lng,lat);
						this.mapObject.setZoomAndCenter(15, position);
						this.setAmapArea(this.path)
					}else{
						console.log("请求失败，请注意!")
					}
				})
		},
		//获取行业类型
		getAgriType() {
			this.$port.getAgriTypeList().then(res => {
				this.agriTypeList = res.list;
			});
		},
		//地图组件初始化
		initmap() {
			this.getAMap().then(res => {
				this.mapObject = new AMap.Map(res, {
					layers: [new AMap.TileLayer.RoadNet()],
					resizeEnable: true, //是否监控地图容器尺寸变化
					zoom: 13 //初始化地图层级
				});
				AMap.plugin('AMap.ToolBar', () => {
					this.mapObject.addControl(
						new AMap.ToolBar()
					);
				});
				//异步加载鼠标工具插件
				AMap.plugin('AMap.MouseTool', () => {
					//添加轮廓绘画工具
					this.mouseTool = new AMap.MouseTool(this.mapObject);
					//监听draw事件可获取画好的覆盖物
					if(!this.limit.isRead){
						this.mouseTool.on('draw', e => {
							const type = e.obj.CLASS_NAME.split('.')[1],
								  id = e.obj._amap_id;
							switch (type) {
								case 'Marker':
									const position = e.obj.getPosition();
									this.path.push({
										id,
										type,
										position
									});
									break;
								case 'Circle':
									//获取中心
									const center = e.obj.getCenter(),
										//获取半径
										radius = e.obj.getRadius();
									this.path.push({
										id,
										type,
										center,
										radius,
									});
									break;
								case 'Polygon':
								case 'Polyline':
									const path = e.obj.getPath().map(x => {
										return [x.lng, x.lat];
									});
									this.path.push({
										id,
										type,
										path,
									});
									break;
							}
							this.overlaysId.push(id);
							//对画好的覆盖物绑定事件
							e.obj.on('rightclick', e => {
								if(!this.limit.isRead){
									this.mapObject.remove(e.target);
									const idIndex = this.overlaysId.indexOf(id);
									idIndex > -1 && this.path.splice(idIndex, 1);
									idIndex > -1 && this.overlaysId.splice(idIndex, 1);
								}
							});
						});
						this.mouseTool[this.coversType]();
					}
				});
			});
		},
		getAMap(i = 0) {
			if (this.$refs.amap) {
				return new Promise(r => {
					r(this.$refs.amap);
				});
			} else if (i < 5) {
				return new Promise(r => {
					setTimeout(() => {
						r(this.getAMap(i++));
					}, 500);
				});
			}
		},
		//回填地图边界
		setAmapArea(data){
			//同步数据ID
			const fgw = data.map((x, i) => {
				const id = x.id || i;
				this.overlaysId.includes(id) || this.overlaysId.push(id);
				let m = null;
				switch (x.type) {
					case 'Marker':
						m = new AMap[x.type]({
							position: x.position,
							icon: x.icon
						});
						break;
					case 'Circle':
						m = new AMap[x.type]({
							center: { ...x.center },
							radius: x.radius,
							...x.style
						});
						break;
					case 'Polygon':
					case 'Polyline':
						m = new AMap[x.type]({
							path: [...x.path],
							...x.style
						});
						break;
				}
				m && m.on('rightclick', e => {
					if(!this.limit.isRead){
						this.mapObject.remove(e.target);
						const idIndex = this.overlaysId.indexOf(id);
						idIndex > -1 && this.path.splice(idIndex, 1);
						idIndex > -1 && this.overlaysId.splice(idIndex, 1);
					}
				});
				m && this.mapObject.add(m);
				return m;
			});
		},
		//获取园区详情
		getDetail(id) {
			let params = {
				id: id
			};
			this.$port.getOrchard(params).then(res => {
				this.form = Object.assign({},res)
				// let timerArr = [this.form.beginDate]
				// this.form.createData = timerArr
				this.path = JSON.parse(this.form.orchardBorder)
				this.citySelected.ids['provinceId'] = this.form.provinceId
				this.citySelected.ids['cityId'] = this.form.cityId
				this.citySelected.ids['countyId'] = this.form.countyId
				this.citySelected.ids['townId'] = this.form.townId
				this.citySelected.ids['address'] = this.form.address
				this.getCityList();
				this.getCountyList();
				this.getTownList();
				setTimeout(()=>{
					this.getAllAddress()
				},2000)
			});
		},
		//切换表单
		handelNext() {
			this.activePlanName = this.activePlanName === 'baseinfo' ? 'mapConfig' : 'baseinfo';
		},
		//创建产出物
		addProduct() {
			let lineData = {
				prodName: '',
				prodArea: '',
				prodVol: '',
				editing: true
			};
			this.form.products = this.form.products || [];
			if (this.form.products.length == 0) {
				this.form.products.push(lineData);
			} else {
				for (let i of this.form.products) {
					if (i.editing) return this.$message.warning('请先保存当前编辑项目!');
				}
				this.form.products.push(lineData);
			}
		},
		//确定产出物
		handleRowSave($index, row) {
			this.$set(this.form.products[$index], 'editing', false);
		},
		//编辑产出物
		handleRowEdit($index, row) {
			this.$set(this.form.products[$index], 'editing', true);
		},
		//取消编辑产出物
		handleRowCancel($index, row) {
			this.$set(this.form.products[$index], 'editing', false);
		},
		//删除产出物
		handleRowDelete($index, row) {
			this.$confirm('此操作将永久删除该条数据, 是否继续?', '提示', {
				confirmButtonText: '确定',
				cancelButtonText: '取消',
				type: 'warning'
			})
				.then(() => {
					this.form.products.splice($index, 1);
					this.$message({
						type: 'success',
						message: '删除成功!'
					});
				})
				.catch(err => {
					this.$message({
						type: 'error',
						message: err
					});
				});
		},
		//提交前校验一把
		submit() {
			if (this.activePlanName === 'baseinfo') {
				this.$refs.baseinfo.validate(valid => {
					if (valid) {
						this.slUpSource();
					} else {
						return false;
					}
				});
			} else {
				// this.$refs.mapConfig.validate(valid => {
				// 	if (valid) {
				// 		console.log(this.form);
				// 		console.log(this.$refs.cityAddress.selected)
						this.slUpSource();
				// 	} else {
				// 		return false;
				// 	}
				// });
			}
		},
		//判断数据提交方式
		slUpSource() {
			switch (this.modalAction) {
				case 'add':
					this.add();
					break;
				case 'edit':
					this.update();
					break;
				default:
					break;
			}
		},
		//数据新增
		add() {
			this.form.orchardBorder = JSON.stringify(this.path)
			let params = Object.assign({},this.form,this.citySelected.ids)
			console.log(params)
			// if(params.createData){
				// params.beginDate = params.createData[0]
				// params.endDate   = params.createData[1]
				// delete params.createData;
			// }
			this.$port.addOrchard(params).then(res => {
				if (!res.code) {
						this.form.id = res.id
						this.$message.success("操作成功！")
						this.handleCancel()
						this.$emit('closeModal',true)
				}
			});
		},
		//数据修改
		update() {
			this.form.orchardBorder = JSON.stringify(this.path)
			let params = Object.assign({},this.form,this.citySelected.ids)
			// if(params.createData){
				// params.beginDate = params.createData[0]
				// params.endDate   = params.createData[1]
				// delete params.createData;
			// }
			this.$port.updateOrchard(params).then(res => {
				if (!res.code) {
						this.form.id = res.id
						this.$message.success("操作成功！")
						this.handleCancel()
						this.$emit('closeModal',true)
				}
			});
		},
		//自定义校验 -> 电话号码校验
		validateTel(rule, value, callback) {
			if (value === undefined || value === '' || value === null) {
				return callback();
				// new Error('请输入11位手机号,座机以 - 隔开')
			}
			let str = value.trim();
			if (globalReg.regPhone.test(str) || globalReg.regTel.test(str)) {
				callback();
			} else {
				callback(new Error('请输入11位手机号,座机以 - 隔开'));
			}
			callback();
		},
		//窗口关闭
		handleCancel() {
			this.$emit('closeModal', false);
		}
	}
};
</script>

<style scoped lang="less">
.gardenMobile {
	.wrap {
		width: 100%;
		padding: 0 15px;
		.title {
			display: block;
			padding: 15px 0;
			margin-bottom: 15px;
			border-bottom: 1px solid #dcdfe6;
		}
		.gardenFrom {
			.el-col {
				padding-right: 75px !important;
				&:last-child {
					padding-right: 0 !important;
				}
			}
		}
		.addCcw {
			display: block;
			cursor: pointer;
			margin-top: 15px;
			border: 1px dashed #ddd;
			padding: 13px 0;
			text-align: center;
			&:hover {
				border-color: #409eff;
				color: #409eff;
			}
		}
		.aMap {
			width: 100%;
			height: 350px;
			margin-bottom: 20px;
			background: #ddd;
		}
	}
}

.amap-maps .amap-icon img {
	width: 25px;
	height: 34px;
}
</style>
