<template>
	<el-dialog :append-to-body="true" :close-on-click-modal="false" :before-close="cancel" top="4vh" :visible.sync="dialog" :title="isAdd ? '新增' : '编辑'" width="50%" id="form1Dialog">
		<el-form ref="form" :model="form" :rules="rules" size="small" label-width="100px">
			<el-form-item label="项目">
				<!--<el-input v-model="form.company" style="width: 370px;"/>-->
				<el-select v-model="valueProjectName" placeholder="请选择">
					<el-option v-for="project in projectFormUser" :key="project.id" :label="project.proname" :value="project.id" />
				</el-select>
				<el-button type="primary" @click="createDialog">新增项目</el-button>
			</el-form-item>
			<el-form-item label="二维码">
				<el-input v-model.trim="form.qrcode" :disabled="isAdd ? false : true" />
			</el-form-item>
			<el-form-item label="名称(非必填)">
				<el-input v-model.trim="form.name" />
			</el-form-item>
			<el-form-item label="输入地区：">
				<label style="z-index: 999999"><input v-model="keyword" style="width: 100%; height: 3vh; border-radius: 3px; outline:none;border: 1px solid #DCDFE6;"/></label>
				<!--<label>地区：<input v-model="location"></label>-->
				<baidu-map :center="center" :zoom="zoom" :scroll-wheel-zoom="true" :key="menuKey" style="height: 400px;" @ready="handler" @click="clickEvent" id="baiduMap">
					<bm-geolocation :show-address-bar="true" :auto-location="true" anchor="BMAP_ANCHOR_BOTTOM_RIGHT" />
					<bm-local-search :keyword="keyword" :auto-viewport="true" :location="location" />
				</baidu-map>
			</el-form-item>
		</el-form>
		<div slot="footer" class="dialog-footer">
			<el-button type="text" @click="cancel">取消</el-button>
			<el-button :loading="loading" type="primary" @click="doSubmit">确认</el-button>
		</div>
		<el-dialog :visible.sync="createProjectDialog" :before-close="cancelProject" width="40%" title="新增项目" center append-to-body>
			<el-form ref="form" :model="projectForm" :rules="rules" size="small" label-width="80px">
				<el-form-item label="项目名">
					<el-input v-model="projectForm.proname" />
				</el-form-item>
			</el-form>
			<div slot="footer" class="dialog-footer">
				<el-button type="text" @click="cancelProject">取消</el-button>
				<el-button :loading="loading" type="primary" @click="submitProject">确认</el-button>
			</div>
		</el-dialog>
	</el-dialog>
</template>

<script>
import { edit, bindingDevice } from '@/api/sDevice'
import { addProject, findProjectByUserid } from '@/api/sProject'
import Vue from 'vue'
import BaiduMap from 'vue-baidu-map'
Vue.use(BaiduMap, {
	// ak 是在百度地图开发者平台申请的密钥 详见 http://lbsyun.baidu.com/apiconsole/key */
	ak: 'GIpUncIwoaK7BjBZdrpOs0ytywLippwu',
})
export default {
	props: {
		isAdd: {
			type: Boolean,
			required: true,
		},
	},
	data() {
		return {
			location: '北京',
			keyword: '',
			menuKey: 1,
			BMap: '',
			map: '',
			center: { lng: 0, lat: 0 },
			zoom: 10,
			loading: false,
			dialog: false,
			createProjectDialog: false,
			valueProjectName: '',
			form: {
				id: '',
				jd: '',
				wd: '',
				qrcode: '',
				name: '',
				nt: '',
			},
			projectForm: {
				proname: '新建项目',
			},
			rules: {},
			projectFormUser: [],
		}
	},
	watch: {
		menuTree() {
			++this.menuKey
		},
	},
	methods: {
		cancel() {
			this.resetForm()
			// window.location.reload()
		},
		cancelProject() {
			this.resetProjectForm()
		},
		getLocation() {
			// console.log(this.location)
			const local = new this.BMap.LocalSearch(this.map, {
				renderOptions: { map: this.map },
			})
			local.search(this.location)
		},
		doSubmit() {
			this.loading = true
			this.form.nt = this.valueProjectName
			if (this.form.qrcode === '') {
				this.loading = false
				this.$notify({
					title: '请输入二维码信息！',
					type: 'warning',
					duration: 2500,
				})
				return
			}
			if (this.form.jd === '') {
				this.loading = false
				this.$notify({
					title: '请点击地图选择位置！',
					type: 'warning',
					duration: 2500,
				})
				return
			}
			if (this.isAdd) {
				this.doAdd()
			} else this.doEdit()
		},
		doAdd() {
			bindingDevice(this.form)
				.then(res => {
					this.resetForm()
					this.$notify({
						title: '添加成功',
						type: 'success',
						duration: 2500,
					})
					this.loading = false
					this.$parent.init()
					// window.location.reload()
				})
				.catch(err => {
					this.loading = false
					console.log(err.response.data.message)
				})
		},
		doEdit() {
			edit(this.form)
				.then(res => {
					this.resetForm()
					this.$notify({
						title: '修改成功',
						type: 'success',
						duration: 2500,
					})
					this.loading = false
					this.$parent.init()
					// window.location.reload()
				})
				.catch(err => {
					console.log(err.response.data.message)
				})
		},
		resetForm() {
			this.dialog = false
			this.$refs['form'].resetFields()
			this.$parent.getProjects()
			this.keyword = ''
			this.form = {
				id: '',
				jd: '',
				wd: '',
				qrcode: '',
				nt: '',
			}
		},
		resetProjectForm() {
			this.createProjectDialog = false
			this.projectForm = {
				proname: '新建项目',
			}
		},
		handler({ BMap, map }) {
			this.map = map
			this.BMap = BMap;
			const _this = this;

			if (this.isAdd) {
				const geolocation = new BMap.Geolocation()
				geolocation.getCurrentPosition(
					function getinfo(position) {
						_this.center = { lng: position.longitude, lat: position.latitude }
					},
					function(e) {},
					{ provider: 'baidu' }
				)
			} else {
				map.clearOverlays()
				var marker = new BMap.Marker(new BMap.Point(this.form.jd, this.form.wd)) // 创建点
				map.addOverlay(marker)
				// _this.autoLocationPoint = { lng: this.form.jd, lat: this.form.wd }
				_this.center = { lng: this.form.jd, lat: this.form.wd }
			};

			this.$nextTick(() => {
				var baiduMap = this.$el.querySelector("#baiduMap");
				var form1Dialog = document.getElementById("form1Dialog");
				baiduMap.onclick = function(e){
					var tag = e.target || e.srcElement;
					e.stopPropagation ? e.stopPropagation() : window.event.cancelBubble = true;
				};
				form1Dialog.onclick = function(e){
					var tag = e.target || e.srcElement;
					var mapSearchEl = baiduMap.lastElementChild;
					mapSearchEl.firstElementChild && (mapSearchEl.innerHTML = '');
				};
			})
		},

		// 点击地图监听
		clickEvent(e, map) {
			this.map.clearOverlays()
			var marker = new this.BMap.Marker(new this.BMap.Point(e.point.lng, e.point.lat)) // 创建点
			this.map.addOverlay(marker)
			this.form.jd = e.point.lng
			this.form.wd = e.point.lat
			// console.log(e.point.lng, e.point.lat)
		},
		createDialog() {
			this.createProjectDialog = true;
		},
		submitProject() {
			addProject(this.projectForm).then(response => {
				this.$notify({
					title: '添加成功',
					type: 'success',
					duration: 2500,
				})
				this.createProjectDialog = false
				this.initProjectUser()
				this.resetProjectForm()
			})
		},
		menuKeyPlus() {
			this.menuKey = this.menuKey + 1
		},
		initProjectUser() {
			findProjectByUserid().then(response => {
				if (response.length === 0) {
					this.createProjectDialog = true
				} else {
					this.projectFormUser = response
					if (this.isAdd) {
						this.valueProjectName = this.projectFormUser[0].id
					} else {
						this.valueProjectName = parseInt(this.form.nt)
					}
				}
			})
		},
	},
}
</script>

<style scoped>
.map {
	width: 100%;
	height: 400px;
}
</style>
