<template>
	<div class="page-bgc1 monitor-point cm-layout flex-col">
		<div class="title-w">
			<h3>监测点配制</h3>
		</div>
		<div class="mnt-view flex-disf-rel a-2">
			<div class="a2-1 flex-disf fix-rc">
				<div class="a21 rel-flex fun-area" id="funArea">
					<div class="points">
						<ul>
							<li v-for="(item, i) in pointDict" :class="item.type" draggable="true"></li>
							<!-- <li class="d_02" draggable="true"></li>
							<li class="d_03" draggable="true"></li> -->
						</ul>
					</div>
					<div class="viewArea" style="width:10.50rem;height:8.81rem;">
						<div class="figure">
							<div class="img-box" id="pictureArea">
								<img id="drawingImg">
							</div>
							<div class="upload-layer">
								<label class="upload-area el-icon-picture" for="imgUpload">
									<input type="file" style="display:none" id="imgUpload" @change="cropUpload">
								</label>
							</div>
							<div id="pointsLayer" class="points-layer wkk-ctn">
								<ul>
								</ul>
							</div>
							<i class="delete el-icon-delete" @click="deleteBg"></i>
						</div>
					</div>
					<div class="a2-2">
						<el-form :model="form2" ref="form2" :inline="true" size="small" label-width="100%">
							<el-form-item label="监测点名称">
								<el-input v-model="focusPoint.name" style="width:2.5rem" @input="input"></el-input>
							</el-form-item>
							<el-form-item label="信息框方位" >
								<el-button-group @click="setPosition">
									<el-button :type="focusPoint.infoseat==='up' ? 'primary' : ''" icon="el-icon-top" @click="setPosition('up')"></el-button>
									<el-button :type="focusPoint.infoseat==='right' ? 'primary' : ''" icon="el-icon-right" @click="setPosition('right')"></el-button>
									<el-button :type="focusPoint.infoseat==='down' ? 'primary' : ''" icon="el-icon-bottom" @click="setPosition('down')"></el-button>
									<el-button :type="focusPoint.infoseat==='left' ? 'primary' : ''" icon="el-icon-back" @click="setPosition('left')"></el-button>
								</el-button-group>
							</el-form-item>
							<el-form-item label="设置监测项" >
								<el-select v-model="form2.monitorValues" multiple placeholder="请选择" @change="selectChange($event, _self)" :disabled="!focusPoint.config">
									<el-option
										v-for="item in form2.monitorItems"
										:label="item.name"
										:value="item.id">
									</el-option>
								</el-select>
							</el-form-item>
						</el-form>
						<div class="btn-group">
							<el-button type="danger" class="el-icon-delete" :disabled="!focusPoint.element" @click="deletePoint()">删除监测点</el-button>
							<el-button :loading="false" type="primary" @click="submit()">保存信息</el-button>
						</div>
					</div>
				</div>
			</div>
		</div>
	</div>
</template>

<script>
import { reqApi, Config } from '@/assets/js/httpApi.js';
import { Tools } from '@/assets/js/common.js';
export default {
	name: 'Dashboard',
	components: {
	},
	data() {
		return {
			pointDict:{
				/* 'd_01':{
					type:'d_01',
					width:30,
					height:	65,
				}, */
			},
			focusPoint:{},
			form2:{
				monitorItems:[],
				monitorValues:[],
			},
		}
	},
	mounted() {
		// 获取基本信息
		this.pageApi = Config.getModuleInfo(this);

		this.$nextTick(() => {
			var that = this;
			this.loadData();

			var EventKeys = {
				mstart: 'mousedown',
				mmove: 'mousemove',
				mend: 'mouseup',
				resize: 'resize',
				dragStart: 'dragstart',
				drag: 'drag',
				dragEnd: 'dragend',
				dragEnter: 'dragenter',
				dragOver: 'dragover',
				dragLeave: 'dragleave',
				drop: 'drop',
			};

			// 视图区功能
			var dragWidget = function(){
				var self = this;
				var funArea = that.$el.querySelector("#funArea");
				this.iconBox = funArea.firstElementChild;
				this.menusEl = this.iconBox.firstElementChild;
				this.pointsLayer = funArea.querySelector("#pointsLayer");
				this.pointsCtn = this.pointsLayer.firstElementChild;
				this.pictureArea = funArea.querySelector("#pictureArea");;
				
				// drag 事件临时缓存
				var dragTarget = {};
				var menuColumn = this.menuColumn =  new function(){
					var menuObj = this;
					var mConfig = {
						dragValidDist: 10,		// 有效拖曳距离
						eventAddMark:null,		// 菜单栏的 m, e, 事件绑定状态
					};
			
					return function(menuBox){
						var that = this;
						menuBox.onclick = function(e){
							var tag = e.target || e.srcElement;
						};

						// dragStart
						this.eventHandler.addEvent(EventKeys.dragStart, menuBox, function(e){
							var tag = e.target || e.srcElement;
							dragTarget = {
								start:{
									offsetX: e.offsetX,
									offsetY: e.offsetY,
								},
								target: tag,
							};
							// 激活目标区域事件
							that.movementHandlers.dragTrigger(self.pointsLayer);
						});

						// 结束拖曳事件
						this.eventHandler.addEvent(EventKeys.dragEnd, menuBox, function(e){
							let tag = e.target || e.srcElement;
							that.movementHandlers.dragRemove(self.pointsLayer);		// 清除画布兼听事件
						});
						return menuObj;
					}
				};

				// 事件控制
				this.movementHandlers = function(self){
					this.start = function(e) {
						var tag = e.target || e.srcElement, mouseInfo = self.mouseInfo;
						if(tag.nodeName === 'I' && e.button === 0){
							self.switchActive(tag.parentNode);
							mouseInfo.dragFlag = !0;		// 修改事件状态
							mouseInfo.start = {
								pageX: e.pageX,
								pageY: e.pageY,
							}
							this.eventTrigger(self.pointsLayer)
						}else{
							self.cancelActive();
						};
					};
					this.move = function(e) {
						var mouseInfo = self.mouseInfo;
						if(mouseInfo.dragFlag){
							mouseInfo.dragFlag = e.type;
							var absX = e.pageX - mouseInfo.start.pageX;
							var absY = e.pageY - mouseInfo.start.pageY;
							mouseInfo.move = {
								absX: absX,
								absY: absY,
							}
							mouseInfo.target.style.transform = 'matrix(1, 0, 0, 1, '+absX+', '+absY+')';
						};
					};
					this.end = function(e) {
						var	mouseInfo = self.mouseInfo;
						if(mouseInfo.dragFlag === EventKeys.mmove){
							var target = mouseInfo.target,
								left = target.offsetLeft + mouseInfo.move.absX ,
								top = target.offsetTop + mouseInfo.move.absY;
							var x = qf.parseWpx(left);
							var y = qf.parseWpx(top);
							target.style.transform = 'matrix(1, 0, 0, 1, 0, 0)';
							target.style.left = qf.parseRem(x)+ 'rem';
							target.style.top = qf.parseRem(y) + 'rem';
							var guid = target.dataset.id;
							that.focusPoint = self.pointList[guid];
							that.focusPoint.config.x = x;
							that.focusPoint.config.y = y;
						};
						mouseInfo.dragFlag = null;
						//mouseInfo.target = null;
						this.eventRemove(self.pointsLayer)
					};
					this.eventTrigger = function(el){
						self.eventHandler.addEvent(EventKeys.mmove, el);
						self.eventHandler.addEvent(EventKeys.mend, el);
					};
					this.eventRemove = function(el){
						self.eventHandler.removeEvent(EventKeys.mmove, el);
						self.eventHandler.removeEvent(EventKeys.mend, el);
					};

					this.dragEnter = function(e){
						var tag = e.target || e.srcElement;
					};
					this.dragOver = function(e){
						e.preventDefault();
					};
					this.dragDrop = function(e){
						var wpr = qf.envir.wpr;
						var elLeft = e.offsetX / wpr  - dragTarget.start.offsetX;
						var elTop = e.offsetY / wpr - dragTarget.start.offsetY;
						var target = dragTarget.target || e.srcElement;
						var cionName = target.className;
						var point = that.pointDict[cionName];

						console.log('point ________________ ', point);

						var param = {
							x: elLeft,
							y: elTop,
							type:point.type,
							height:point.height,
							width:point.width,
							angle:~~point.angle,
							start: dragTarget.start,
							//className:cionName,
							//target:dragTarget.target,
						};
						self.createPoint(param, 'drop');
					};
					this.dragTrigger = function(el){
						self.eventHandler.addEvent(EventKeys.dragEnter, el);
						self.eventHandler.addEvent(EventKeys.dragOver, el);
						//self.eventHandler.addEvent(EventKeys.dragLeave, el);
						self.eventHandler.addEvent(EventKeys.drop, el);
					};
					this.dragRemove = function(el){
						self.eventHandler.removeEvent(EventKeys.dragEnter, el);
						self.eventHandler.removeEvent(EventKeys.dragOver, el);
						//self.eventHandler.removeEvent(EventKeys.dragLeave, el);
						self.eventHandler.removeEvent(EventKeys.drop, el);
					};
					this.mouse = {};
					return this;
				}.call({}, this);
				
				// 增删事件
				this.eventHandler = function(that){
					this.addEvent = function(type, el, call){
						call = call || that;
						el.addEventListener(type, call, false);
					};
					this.removeEvent = function(type, el, call){
						call = call || that;
						el.removeEventListener(type, call, false);
					};
					return this;
				}.call({}, this);

				this.initialize();
				this.mouseInfo = {};
				this.pointList = {};
				return self;
			};
			dragWidget.prototype = {
				handleEvent : function(e){;
					var movement = this.movementHandlers;
					switch(e.type){
						case EventKeys.mstart : movement.start(e); break;
						case EventKeys.mmove : movement.move(e); break;
						case EventKeys.mend : movement.end(e); break;
						case EventKeys.resize: movement.resize(); break;
						case EventKeys.dragEnter: movement.dragEnter(e); break;
						case EventKeys.dragOver: movement.dragOver(e); break;
						case EventKeys.dragLeave: movement.dragLeave(e); break;
						case EventKeys.drop: movement.dragDrop(e); break;

					}
				},
				initialize: function(requisite){
					/* if(!requisite.drawArea || requisite.drawArea.constructor.name !== "HTMLDivElement"){
						return new Error('drawArea not a div Element');
					}*/

					this.eventHandler.addEvent(EventKeys.mstart, this.pointsLayer);

					var param = {		// 需要创建图形的参数
						width: 100,
						height: 75,
						top: 280,
						left: 150,
					};
					// 菜单栏激活
					let menuObj = this.menuColumn.call(this, this.menusEl);
				},
				setBackground: function(picture){
					var upload = this.pictureArea.nextElementSibling;
					var bgBtn = this.pointsLayer.nextElementSibling;
					if(picture){
						this.pictureArea.firstElementChild.src = picture;
						this.pictureArea.classList.add('show');
						bgBtn.classList.add('show');
						this.pointsLayer.classList.add('show');
						upload.classList.remove('show');
					}else{
						 this.pictureArea.classList.remove('show');
						 bgBtn.classList.remove('show');
						 this.pointsLayer.classList.remove('show');
						 upload.classList.add('show');
					};
				},
				
				/*
					param[object]	元素的尺寸
				*/ 
				createPoint: function(param, event){
					var config = param;
					var title = param.name || '';
					var direction = param.infoseat || 'up';
					var point = document.createElement("li");
					var guid = param.guid || qf.getGuid();
					point.className = param.type;
					point.dataset.id = guid;
					point.style.diesplay = 'none';
					point.style.top = qf.parseRem(param.y) + 'rem';
					point.style.left = qf.parseRem(param.x) + 'rem';
					point.style.width = qf.parseRem(config.width) + 'rem';
					point.style.height = qf.parseRem(config.height) + 'rem';
					// point.style.fontSize = qf.parseRem(fontSize || (12 * this.wRatio)) + 'rem';
					point.innerHTML = '<i style="transform:rotate('+(~~config.angle)+'deg)"></i><div class="'+direction+'"><div class="text"><h4>'+title+'</h4><dl></dl></div></div>';
					this.pointsCtn.appendChild(point);
					config.guid = guid;

					// 绑定对象属性
					var pointUnit = {
						config:config,
						element:point,
					};
					this.setBindAttr(pointUnit, point.lastElementChild);

					// 设置监测值
					pointUnit.items = config.items || [];

					// 记录信息
					this.pointList[guid] = pointUnit;

					if(event === 'drop'){
						this.switchActive(point);
					};
				},

				createPoints: function(points){
					for(var point of points){
						this.createPoint(point);
					};
				},
				switchActive: function(target){
					var mouseInfo = this.mouseInfo;
					mouseInfo.target && mouseInfo.target.classList.remove('active');
					target.classList.add('active');
					mouseInfo.target = target;
					var guid = target.dataset.id;
					that.focusPoint = this.pointList[guid];
					that.form2.monitorValues = that.focusPoint.values || [];
				},
				cancelActive: function(){
					var mouseInfo = this.mouseInfo;
					mouseInfo.target && mouseInfo.target.classList.remove('active');
					that.focusPoint = {};
					that.form2.monitorValues = [];
				},
				setBindAttr: function(pointUnit, infoEl){
					var titleEl = infoEl.firstElementChild.firstElementChild;
					var items = infoEl.firstElementChild.lastElementChild;
					Object.defineProperty(pointUnit, 'infoseat', { // bind
						set:function(value){
							infoEl.className = value;
						},
						get:function(){
							return infoEl.className
						},
					});
					Object.defineProperty(pointUnit, 'name', { // bind
						set:function(value){
							titleEl.innerText = value;
						},
						get:function(){
							return titleEl.innerText
						},
					});
					Object.defineProperty(pointUnit, 'items', { // bind
						set:function(list){
							var dds = '', values = [];
							for(var item of list){
								var id = item.id || item.value;
								dds += '<dd data-id="'+id+'">'+item.name+'</dd>';
								values.push(id);
							};
							items.innerHTML = dds;
							pointUnit.values = values;
						},
					});
				},
				getPointDataList: function(){
					var points = this.pointList, list = [];
					for(var key in points){
						var point = points[key];
						list.push({
							id: point.config.id || '',
							type: point.config.type,
							guid: point.element.dataset.id,
							name: point.name,
							x: point.config.x,
							y: point.config.y,
							height: point.config.height,
							width: point.config.width,
							angle: point.config.angle,
							infoseat: point.infoseat,
							items:point.values,
						});
					};
					return list;
				},
				removePoint: function(){
					var mouseInfo = this.mouseInfo;
					var target = mouseInfo.target;
					var guid = target.dataset.id;
					var point = this.pointList[guid];
					this.pointsCtn.removeChild(target);
					delete mouseInfo.target;
					delete this.pointList[guid];
					return point;
				},
			};

			this.dragWidget = new dragWidget();
		})
	},
	methods: {
		loadData() {
			this.pageApi.getMonitorPoints({}).then((res)=>{
				var body = res.body, chart = body.chart || {};
				this.form2.monitorItems = body.devices;
				this.dragWidget.setBackground(chart.picture);
				this.dragWidget.createPoints(body.points);
				this.chart = chart;
				var pointDict = {};
				for(var item of body.icons){
					pointDict[item.type] = item;
				};
				this.pointDict = pointDict;
			});
		},
		cropUpload(e){
			var tag = e.target || e.srcElement, self = this;
			Tools.fileElTobase64(tag).then(function(res){
				var base64 = res.base64;
				if(base64){
					var imgBox = tag.parentNode.parentNode.previousElementSibling;
					imgBox.style.display = 'block';
					var height = imgBox.offsetHeight;
					var width = imgBox.offsetWidth;
					//var pictureEl = self.dragWidget.iconBox.nextElementSibling
					//var height1 = qf.parsePixel(parseFloat(pictureEl.style.height));
					//var width1 = qf.parsePixel(parseFloat(pictureEl.style.width));

					var param = {height:height, width:width, picture:base64};
					self.pageApi.postBackground(param).then((res)=>{
						var body = res.body;
						if(res.code === 200){
							self.$notify({
								title: '图片上传成功！',
								type: 'success',
								duration: 2500
							});
							
							// 显示
							self.dragWidget.setBackground(base64);
						};
					});
				};
				tag.value = '';
			}).catch(function(err){
				var errText = '请上传后缀名为“jpg”或“png”格式的图片';
				self.$notify({
					title: errText,
					type: 'error',
					duration: 3500
				});
			});
		},

		submit(){
			var points = this.dragWidget.getPointDataList();
			if(points[0]){
				var pictureArea = this.dragWidget.pictureArea;
				var param = {
					points:points,
					/* chart:{
						height:qf.parsePixel(parseFloat(pictureEl.style.height)),
						width:qf.parsePixel(parseFloat(pictureEl.style.width)),
					}, */
					chart:{
						id:this.chart.id,
						height:qf.parseWpx(pictureArea.offsetHeight),
						width:qf.parseWpx(pictureArea.offsetWidth),
					},
				};
				this.pageApi.submitInfos(param).then((res)=>{
					if(res.code === 200){
						this.$notify({
							title: '保存成功！',
							type: 'success',
							duration: 2500
						});
					};
				});
			};
		},
		input(){
			this.$forceUpdate();
		},
		setPosition(val){
			this.focusPoint.infoseat = val;
			this.$forceUpdate();
		},
		selectChange(values){
			var that = this;
			return qf.vue.onEventInfos(function(val, items){
				that.focusPoint.items = items;
			});
		},
		// 删除背景图片
		deleteBg(e){
			this.$confirm('确定要删除尾矿库图片吗？', '提示', {
				confirmButtonText: '确定',
				cancelButtonText: '取消',
				type: 'warning'
			}).then((e) => {
				var param = {height:0, width:0, picture:''};
				this.pageApi.postBackground(param).then((res)=>{
					if(res.code === 200){
						this.dragWidget.setBackground('');
						this.$notify({
							title: '删除成功！',
							type: 'success',
							duration: 2500
						});
					};
				});
			})
		},
		deletePoint(){
			this.$confirm('确定要删除该监测点吗？', '提示', {
				confirmButtonText: '确定',
				cancelButtonText: '取消',
				type: 'warning'
			}).then((e) => {
				var point = this.dragWidget.removePoint();
				if(point.config.id){
					this.pageApi.deletePoints([point.config.guid]).then((res)=>{
						if(res.code === 200){
							this.focusPoint = {};
							this.$notify({
								title: '删除成功！',
								type: 'success',
								duration: 2500
							});
						};
					});
				}else{
					this.focusPoint = {};
				};
			})
		},
	}
}
</script>

<style rel="stylesheet/scss" lang="scss">
	.monitor-point{
		.title-w{
			line-height:.50rem;text-align:center;font-size:.20rem;background-color:#fff;margin-bottom:10px;
			border-bottom:1px solid #aaa;
		}

		.a2-1{
			.a21{
				//width:10.50rem;height:8.81rem;
				height: max-content;
			}
		}
		.a2-2{
			border:1px solid pink;
			width:4rem;
			.el-form{
				.el-form-item{
					margin-top:20px;text-align:center;
					label{text-align:center;}
				}
				.el-button-group{
					.el-button{
						font-size:.30rem;
					}
				}
			}
			.btn-group{text-align:center;}
		}

		.fun-area{
			.points{
				position:absolute;top:0;left:-.60rem;height:auto;width:.70rem;
				li{
					height:.60rem;width:100%;cursor:move;
					border-style:solid;border-color:#999;border-width:1px 0 0 1px;
					background-repeat:no-repeat;background-position:center bottom;background-size:auto 95%;
				}
				li.d_01{background-image:url('~@/assets/images/icon/d_01.png');}
				li.d_02{background-image:url('~@/assets/images/icon/d_02.png');}
				li.d_03{background-image:url('~@/assets/images/icon/d_03.png');}
				li.d_04{background-image:url('~@/assets/images/icon/d_04.png');}
				li.d_05{background-image:url('~@/assets/images/icon/d_05.png');}
				li.d_06{background-image:url('~@/assets/images/icon/d_06.png');}
				li.d_07{background-image:url('~@/assets/images/icon/d_07.png');}
				li.d_08{background-image:url('~@/assets/images/icon/d_08.png');}
				li:last-child{
					border-width:1px;
				}
			}

			.viewArea{
				max-height:800px;

				.figure{
					border:1px solid #999;width:100%;height:100%;position:relative;
					.img-box{
						position:absolute;top:0;left:0;height:100%;width:100%;z-index:10;display:none;
						&.show{display:block;}
						img{display:block;border:0;height:100%;width:100%;}
					}
					.upload-layer{
						position:absolute;top:0;left:0;height:100%;width:100%;z-index:80;display:none;justify-content:center;align-items:center;
						background-color:#fff;
						.upload-area{
							min-width:40%;padding:.50rem;border:1px dashed rgba(0, 0, 0, 0.1);background-color:rgba(0, 0, 0, 0.05);z-index:0;
							text-align:center;cursor:pointer;color:#999;
							&:before{display:block;font-size:.54rem;}
							&:after{display:block;content:"上传尾矿库全景图片";margin-top:20px;line-height:22px;}
						}
						&.show{display:flex;}
					}
					.points-layer{
						user-select:none;font-family:serif;color:#444;z-index:20;display:none;overflow:hidden;
						&.show{display:block;}
					}
					.delete{
						position:absolute;top:0;right:0;height:auto;width:auto;z-index:21;color:#fff;cursor:pointer;
						display:none;
						&.show{display:block;}
					}

					.wkk-ctn{position:absolute;top:0;left:0;height:100%;width:100%;}
					.wkk-ctn li{position:absolute;}
					.wkk-ctn li::marker{content:close-quote;}
					.wkk-ctn li i{
						position:absolute;top:0;left:0;height:100%;width:100%;
						background-repeat:no-repeat;background-position:center bottom;
						//background-size:100% auto;
						background-size:contain;
					}
					.wkk-ctn li.active i{border:1px dashed red;}
					.wkk-ctn li.d_01 i{background-image:url('~@/assets/images/icon/d_01.png');}
					.wkk-ctn li.d_02 i{background-image:url('~@/assets/images/icon/d_02.png');}
					.wkk-ctn li.d_03 i{background-image:url('~@/assets/images/icon/d_03.png');}
					.wkk-ctn li.d_04 i{background-image:url('~@/assets/images/icon/d_04.png');}
					.wkk-ctn li.d_05 i{background-image:url('~@/assets/images/icon/d_05.png');}
					.wkk-ctn li.d_06 i{background-image:url('~@/assets/images/icon/d_06.png');}
					.wkk-ctn li.d_07 i{background-image:url('~@/assets/images/icon/d_07.png');}
					.wkk-ctn li.d_08 i{background-image:url('~@/assets/images/icon/d_08.png');}
					.wkk-ctn li>div{position:absolute;display:flex;align-items:center;justify-content:center;}
					.wkk-ctn li>div .text{position:absolute;padding:0.0402rem;background-color:#aac0da;border-radius:0.0643rem;line-height:1.2;}
					.wkk-ctn li>div .text:before{content:'';position:absolute;height:0;width:0;border-style:solid;border-width:0.0643rem;border-color:transparent;}
					.wkk-ctn li .text{text-align:center;}
					.wkk-ctn .up{top:0;left:0;height:0;width:100%;}
					.wkk-ctn .up .text{bottom:0.0804rem;width:max-content;}
					.wkk-ctn .up .text:before{bottom:-0.1287rem;left:50%;margin-left:-0.0643rem;border-color:white transparent transparent transparent;}
					.wkk-ctn .down{bottom:0;left:0;height:0;width:100%;}
					.wkk-ctn .down .text{top:0.0804rem;width:max-content;}
					.wkk-ctn .down .text:before{top:-0.1287rem;left:50%;margin-left:-0.0643rem;border-color:transparent transparent white transparent;}
					.wkk-ctn .left{top:0;left:0;height:100%;width:0;}
					.wkk-ctn .left .text{right:0.0804rem;width:max-content;}
					.wkk-ctn .left .text:before{top:50%;right:-0.1287rem;margin-top:-0.0643rem;border-color:transparent transparent transparent white;}
					.wkk-ctn .right{top:0;right:0;height:100%;width:0;}
					.wkk-ctn .right .text{left:0.0804rem;width:max-content;}
					.wkk-ctn .right .text:before{top:50%;left:-0.1287rem;margin-top:-0.0643rem;border-color:transparent white transparent transparent;}
				}
			}
		}
	}

</style>
