<template>
	<div class="common-page">
		<div class="option page-row">
			<!--工具栏-->
			<div class="head-container">
				<!-- 搜索 -->
				<label class="el-form-item-label" style="font-weight: 500;">项目名称</label>
				<el-input v-model="query.name" clearable size="small" placeholder="请输入项目名称" style="width:140px;" @clear="clearLimit"/>

				<el-button size="mini" type="success" icon="el-icon-search" @click="toSearch">搜索</el-button>
			</div>
		</div>
		<div class="panel-bottom page-row">
			<h3>设备管理列表</h3>
			<div class="ctin-box">
				<div class="content-within">
					<div class="content-fix">
						<div class="toolbar">
							<el-button size="mini" type="primary" icon="el-icon-plus" @click="toAdd">新增</el-button>
						</div>
						<div class="content">
							<el-table :data="tableData" v-loading="loading" border style="width:auto" :row-class-name="tableRowClassName">
								<el-table-column prop="id" label="ID" width="80px"></el-table-column>
								<el-table-column prop="name" label="项目名称"></el-table-column>
								<el-table-column prop="content" label="图纸" width="200px;">
									<template slot-scope="scope">
										<img :src="scope.row.content" style="width:100%;border:0;height:120px;"/>
									</template>
								</el-table-column>
								<el-table-column prop="updateTime" label="更新时间"></el-table-column>
								<el-table-column prop="createTime" label="上传时间"></el-table-column>
								<el-table-column prop="remark" label="备注"></el-table-column>
								<el-table-column label="操作" width="130px" align="center" fixed="right">
									<template slot-scope="scope">
										<el-button size="mini" type="primary" icon="el-icon-edit" @click="toEdit(scope.row)"></el-button>
										<el-button size="mini" type="danger" icon="el-icon-delete" @click="toDelete(scope.row)"></el-button>
									</template>
								</el-table-column>
							</el-table>
							<!--分页组件-->
							<el-pagination :total="total" :current-page="page" style="margin-top: 8px;" layout="total, prev, pager, next, sizes" @size-change="sizeChange" @current-change="pageChange" />
						</div>
					</div>
				</div>
			</div>
		</div>

		<!-- 表单渲染 -->
		<el-dialog class="draw-dialog" append-to-body :close-on-click-modal="false" :before-close="cancelForm" :visible.sync="form.visible">
			<el-form :model="form.item" :rules="rules" ref="form1" :inline="true" size="small" label-width="80px">
				<el-form-item prop="eprogramid" >
					<el-select v-model="form.item.eprogramid" placeholder="请选择项目" :disabled="form.reqType==='edit'" @change="programSelectChanged">
						<el-option v-for="obj in form.projectSelectList" :label="obj.name" :value="obj.id"></el-option>
					</el-select>
				</el-form-item>
				<el-form-item >
					<el-select v-model="form.item.deviceid" placeholder="请选择设备" size="small" @change="deviceSelectChanged">
						<el-option v-for="obj in form.deviceSelectList" :label="obj.ename" :value="obj.id"></el-option>
					</el-select>
				</el-form-item>
				<el-form-item >
					<el-button type="primary" :disabled="(form.addBtn || !form.item.content)" @click="addDevicePoint">添加设备</el-button>
					<el-button type="danger" :disabled="!form.delBtn" @click="deleteDevicePoint">删除设备</el-button>
				</el-form-item>
				<el-form-item prop="content" style="display:block;" >
					<div class="img-upload">
						<div class="img-box" v-show="form.item.content">
							<img :src="form.item.content" v-model="form.item.content" id="drawingImg">
						</div>
						<div class="upload-layer" :class="{'show':!form.item.content}">
							<label class="upload-area el-icon-plus" for="imgUpload">
								<input type="file" style="display:none" id="imgUpload" @change="cropUpload">
							</label>
						</div>
						<div id="pointsLayer" class="points-layer" :class="{'show':form.item.content}">
						</div>
					</div>
				</el-form-item>
				<el-form-item label="备注" prop="remark" >
					<el-input v-model="form.item.remark" style="width:260px;" placeholder="备注名称"/>
				</el-form-item>
			</el-form>
			<div slot="footer" class="dialog-footer">
				<el-button type="text" @click="cancelForm">取消</el-button>
				<el-button :loading="form.status.cu === 2" type="primary" @click="submitForm('form1', form.item)">确认</el-button>
			</div>
		</el-dialog>
	</div>
</template>

<script>
//import myUpload from 'vue-image-crop-upload'
import { Tools, HttpReq } from '@/assets/js/common.js';
import DateRangePicker from '@/components/DateRangePicker';
import {Layers} from '@/components/Layers';
import { getToken } from '@/utils/auth'
// style
import '@/assets/styles/common.css';

export default {
	name: 'Dashboard',
	components: {
		DateRangePicker,
	},
	data() {
		return {
			loading: false,
			page: 1,
			size: 10,
			total: 0,
			query:{},
			tableData: [],
			form: {
				title:'添加图纸', visible:false, reqType:'add',
				status:{cu:0},
				projectSelectList:[],
				deviceSelectList:[],
				addBtn:true,
				delBtn:false,
				item:{
					eprogramid:'',
					deviceid:'',
					content:'',
					remark:'',
				},
			},
			rules: {
				eprogramid: [
					{required: true, message: '请选择项目', trigger: 'blur' }
				],
				content: [
					{required: true, message: '请选择图片', trigger: 'blur' }
				],
			},
			headers: {
				'Authorization': getToken()
			},
			updateAvatarApi:'',
			show:true,
		}
	},
	mounted() {
		var that = this;

		this.$nextTick(() => {
			this.loadData();
		})
	},
	methods: {
		tableRowClassName({row, rowIndex}) {
			if (rowIndex === 1) {
				return 'warning-row';
			} else if (rowIndex === 3) {
				return 'success-row';
			}
			return '';
		},
		// 点击搜索
		toSearch() {
			this.page = 1
			this.loadData()
		},
		clearLimit(){		// 清除限制
			this.loadData()
		},
		loadData() {
			var that = this, sort = 'date,desc';
			var param = this.query;
			param.page = this.page - 1;
			param.size = this.size;
			param.sort = sort;

			// 按时间过滤
			var param2 = {};
			var Time = param.createTime || [];
			if(Time[0]){
				var date1 = new Date(Time[0]).getTime();
				var date2 = new Date(Time[1] || Time[0]).getTime();
				param2 = {date1:date1, date2:date2}
			};
			this.loading = true;

			HttpReq.drawing.getItemSubProgram(param).then((res) => {
				this.loading = false;
				if(res.head.code === '0000'){
					var body = res.body || {};
					var list = body.list || [];
					this.tableData = list;
					this.total = body.total
				};
			}).catch(function(error) {
				this.loading = false;
			})
		},
		
		toAdd() {
			// 请除表单验证
			this.$refs['form1'] && this.$refs['form1'].clearValidate();
			this.form.title = '添加图纸';
			this.form.status.cu = 0;
			this.form.visible = true;
			this.form.reqType = 'add';
			this.form.deviceSelectList = [];
			this.form.item = {
				eprogramid:'',
				deviceid:'',
				content:'',
				remark:'',
			};

			// 请求项目列表
			this.reqProjectsSimple().then((list) => {
				this.form.projectSelectList = list
			});
			
			this.$nextTick(() => {
				// 激活图形事件
				this.figureEvent();

				// 清除坐标点
				this.sliderPanel.clearPoint()
			});
		},
		toEdit(item) {
			this.reqPointByProjectId(item).then((body) => {
				var pointList = body.list || [];
				this.$refs['form1'] && this.$refs['form1'].clearValidate();
				this.form.title = '编辑图纸';
				this.form.status.cu = 0;
				this.form.visible = true;
				this.form.reqType = 'edit';

				this.form.item = {
					eprogramid:item.name,
					edeviceid: item.id,
					content: item.content,
					remark: item.remark,
					name: item.name,
					programid:item.programid,
				};

				// 请求图纸设备列表
				this.reqNotInDeviceSelectList(item.programid);

				// 功能
				this.$nextTick(() => {
					// 激活图形事件
					var sliderPanel = this.figureEvent();

					// 清除坐标点
					sliderPanel.clearPoint();
					
					for(var pitem of pointList){
						item.x = pitem.x;
						item.y = pitem.y;
						item.deviceid = pitem.deviceid;
						var param = {x:pitem.x, y:pitem.y, deviceid:pitem.deviceid, eprogramid:item.programid};
						sliderPanel.createPoint(param).then((item) => {});
					};
				});
			});
		},
		cancelForm(){
			this.form.visible = false;
			// 清除事件
			Tools.removeMoveEvent(this.sliderPanel);
		},
		toDelete(item) {
			this.$confirm('确认删除该条数据吗?', '提示', {
				confirmButtonText: '确定',
				cancelButtonText: '取消',
				type: 'warning'
			}).then((e) => {
				this.reqRemoveProject({programid:item.programid})
			}).catch((e) => {
			})
		},
		pageChange(e) {
			this.page = e
			this.loadData()
		},
		sizeChange(e) {
			this.page = 1
			this.size = e
			this.loadData()
		},
		submitForm(validateName, item){
			if(!this.form.status.cu){
				this.$refs[validateName].validate(valid => {
					if(valid){
						this.form.status.cu = 2;
						if(this.form.reqType === 'add'){
							// 添加图纸
							this.reqAddItem({programid:item.eprogramid, content:item.content, remark:item.remark}).then((res) => {
								// 更新设备标记
								var pointsParam = this.sliderPanel.getPointParam();
								this.reqUpdateItem({programid:item.eprogramid}, pointsParam)
							});
						}else{
							// 添加图纸设备
							var pointsParam = this.sliderPanel.getPointParam();

							// 更新设备标记
							this.reqUpdateItem(item, pointsParam)
						}
					}else{
						this.form.status.cu = 0
					}
				});
			};
		},

		reqProjectsSimple(){
			return HttpReq.drawing.getNotInProgramSelectList().then((res) => {
				if(res.head.code === '0000'){
					return res.body.list;
				}else{
					return []
				}
			})
		},
		reqNotInDeviceSelectList(id){	// 请求图纸设备列表
			return HttpReq.drawingpoint.getNotInDeviceSelectList({eprogramid:id}).then((res) => {
				if(res.head.code === '0000'){
					return this.form.deviceSelectList = res.body.list
				}else{
					return []
				}
			})
		},
		reqAddItem(item){
			return HttpReq.drawing.saveItem(item).then((res) => {
				this.form.visible = false;
				if(res.head.code === '0000'){
					this.$notify({
						title: '添加成功！',
						type: 'success',
						duration: 2500
					});
					this.loadData()
				}else{
					this.$notify({
						title: res.head.message,
						type: 'error',
						duration: 2500
					})
				}
			}).catch(function(error) {
				this.form.status.cu = 0
			});
		},
		reqUpdateItem(item, list){
			return HttpReq.drawingpoint.updateItem({programid:item.programid, list:list}).then((res) => {
				this.form.visible = false;
				if(res.head.code === '0000'){
					/* this.$notify({
						title: '修改成功！',
						type: 'success',
						duration: 2500
					}); */
				}else{
					/* this.$notify({
						title: res.head.message,
						type: 'error',
						duration: 2500
					}) */
				}
			}).catch(function(error) {
				this.form.status.cu = 0
			});
		},
		reqRemoveProject(item){
			return HttpReq.drawing.removeItem(item).then((res) => {
				if(res.head.code === '0000'){
					this.$notify({
						title: '删除成功！',
						type: 'success',
						duration: 2500
					});
					this.loadData()
				}else{
					this.$notify({
						title: res.head.message,
						type: 'error',
						duration: 2500
					})
				};
				this.loadData()
			});
		},
		reqPointByProjectId(item){
			return HttpReq.drawingpoint.getItem({programid:item.programid}).then((res) => {
				if(res.head.code === '0000'){
					return res.body
				}else{
					this.$notify({
						title: res.head.message,
						type: 'error',
						duration: 2500
					});
				}
			})
		},

		// 项目 select 事件
		programSelectChanged(val){
			// 请求图纸设备列表
			this.reqNotInDeviceSelectList(val);
		},
		// 设备 select 事件
		deviceSelectChanged(val){
			this.form.currentDevice = val;
			this.form.addBtn = !val;
		},
		// 添加设备标记
		addDevicePoint(){
			var item = this.form.item;
			var programid = this.form.reqType === 'add' ? item.eprogramid : item.programid;
			var param = {deviceid:item.deviceid, eprogramid:programid};
			this.sliderPanel.createPoint(param).then((point) => {
				var deviceSelectList = this.form.deviceSelectList, len = deviceSelectList.length;
				for(var i=0; i<len; i++){
					var obj = deviceSelectList[i];
					if(obj && obj.id === point.deviceid){
						deviceSelectList.splice(i, 1);
						item.deviceid = '';
					};
				};
				this.form.addBtn = true;
			});
		},
		// 删除设备标记
		deleteDevicePoint(){
			this.sliderPanel.removePoint(this.form.delBtn);
			this.form.delBtn = false;

			// 请求图纸设备列表
			this.reqNotInDeviceSelectList(this.form.item.programid);
		},

		cropUpload(e){
			var tag = e.target || e.srcElement;
			var that = this, file = tag.files[0];

			if(!this.form.item.eprogramid){
				tag.value = '';
				return this.$notify({
					title: '请选择项目',
					type: 'warning',
					duration: 2500
				})
			};

			if(!file)return ;
		
			if(file.name.indexOf(".jpg") > 0){
				var img = new Image();
				var blob = (typeof file === 'string') ? file : URL.createObjectURL(file);
				img.src = blob;
				img.crossOrigin = "*";
				img.onerror = function() {
					var error = new Error('图片加载失败');
				};
				img.onload = function(){
					var w = img.width, h = img.height;
					/* if(w < 800 || w > 1024){
						return that.$notify({
							title: '图片宽度不在800~1024之间',
							type: 'warning',
							duration: 2500
						})
					};

					if(h < 600 || h > 768){
						return that.$notify({
							title: '图片高度不在600~768之间',
							type: 'warning',
							duration: 2500
						})
					}; */
					
					// 显示大小 2MB
					var fileSize = file.size / 1024;	// kb
					if(fileSize > 2048){
						return that.$notify({
							title: '图片不能大于2M',
							type: 'warning',
							duration: 2500
						})
					};

					// canvas
					var canvas = document.createElement('canvas');
					canvas.width = w;
					canvas.height = h;
					var ctx = canvas.getContext('2d');
					ctx.fillStyle = 'transparent';
					ctx.fillRect(0, 0, w, h);
					ctx.drawImage(img, 0, 0, w, h);
					// 生成结果
					var results = {};
					results.origin = file;
					results.base64 = canvas.toDataURL('image/jpeg', 0.7);
					results.base64Len = results.base64.length;
					// 释放内存
					canvas = null;
					img = null;
	
					var imgBox = tag.parentNode.parentNode.previousElementSibling;
					imgBox.style.display = 'block';
					that.form.item.content = results.base64;
					tag.value = '';

					// 重设比例
					that.sliderPanel.setCoordRatio();
				}
			}else{
				this.$notify({
					title: '只支持JPG格式图片',
					type: 'warning',
					duration: 2500
				})
			}
		},

		figureEvent(){
			var that = this, pointsLayer = document.getElementById("pointsLayer");
			var mouseDewn, device, x, y;
			var drawingImg = document.getElementById("drawingImg");
			var wRatio = 1, hRatio = 1;

			that.sliderPanel && that.sliderPanel.eventHandler.removeEvent();

			var sliderPanel = Tools.registerSlider(pointsLayer, {
				disc:'x',
				event:true,
				start: function(e){
					var tag = e.target || e.srcElement;
					device = tag.nodeName === 'A' ? tag.parentNode : tag.className === 'point' ? tag : void 0;
					if(device){
						x = device.offsetLeft;
						y = device.offsetTop;
					}else{
						x = 0, y = 0;
					};
					this.activePoint(device);
					mouseDewn = true
				},
				move: function(e){
					if(mouseDewn && device){
						that.sliderPanel.setMoveAbs.call(device, e.distX + x, e.distY + y);
					}else{
						
					};
				},
				end: function(e){
					if(mouseDewn && device){
						var absX = e.distX + x, absY = e.distY + y;
						//device.dataset.naturalX = absX * wRatio;
						//device.dataset.naturalY = absY * hRatio;
						that.sliderPanel.setEndAbs.call(device, absX, absY);
					};
					mouseDewn = false;
				},
				activePoint: function(el){
					var active = pointsLayer.querySelector('.active');
					if(el && !el.classList.contains('active')){
						active && active.classList.remove('active');
						el.classList.add('active');
						that.form.delBtn = el;
					}else{	// null
						active && active.classList.remove('active');
						that.form.delBtn = false;
					};
				},
			});

			// 设置比例
			(sliderPanel.setCoordRatio = function(){
				var w = drawingImg.offsetWidth, h = drawingImg.offsetHeight, 
					nw = drawingImg.naturalWidth, nh = drawingImg.naturalHeight;
				wRatio = nw / w, hRatio = nh / h;

				drawingImg.onload = function(){
					var w = drawingImg.offsetWidth, h = drawingImg.offsetHeight, 
						nw = drawingImg.naturalWidth, nh = drawingImg.naturalHeight;
					wRatio = nw / w, hRatio = nh / h;
				};
			})();

			sliderPanel.createPoint = function(item){
				return new Promise(function (resolve, reject){
					var point = document.createElement("div");
					point.dataset.deviceid = item.deviceid;
					point.dataset.eprogramid = item.eprogramid;
					point.className = 'point';
					point.innerHTML = '<a>'+item.deviceid+'</a>';
					item.x && (point.style.left = item.x / wRatio + 'px');
					item.y && (point.style.top = item.y / hRatio + 'px');
					pointsLayer.appendChild(point)	
					resolve(item);
				})
			};
			sliderPanel.clearPoint = function(item){
				pointsLayer.innerHTML = '';
			};

			sliderPanel.removePoint= function(el){
				el && pointsLayer.removeChild(el)
			};

			sliderPanel.getPointParam = function(item){
				var points = pointsLayer.children;
				var params = [];
				for(var point of points){
					var x = ~~(point.offsetLeft * wRatio), y = ~~(point.offsetTop * hRatio);
					params.push({programid:point.dataset.eprogramid, deviceid:point.dataset.deviceid, x:x, y:y})
				};
				return params;
			};
			return that.sliderPanel = sliderPanel
		},
	}
}
</script>

<style rel="stylesheet/scss" lang="scss" scope>
	.el-table .warning-row {
		background: oldlace;
	}

	.el-table .success-row {
		background: #f0f9eb;
	}
	
	.draw-dialog{
		display:flex;align-items:center;
		.el-dialog{
			margin-top:inherit !important;display:table !important;width:fit-content;
			.el-form-item{margin-right:0;}
		}

		.el-dialog__header{display:none;}

		.img-upload{
			border:1px solid #999;width:800px;height:500px;position:relative;

			.img-box{position:absolute;top:0;left:0;height:100%;width:100%;z-index:10;}
			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{
					width:50%;padding:50px;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:34px;}
					&:after{display:block;content:"上传图片,只支持宽度在800~1024之间,且小于2MB的图片";margin-top:20px;line-height:22px;}
				}
			}
			.upload-layer.show{display:flex;}
			.points-layer{
				user-select:none;
				position:absolute;top:0;left:0;height:100%;width:100%;z-index:50;border:1px solid green;display:none;overflow:hidden;
				&.show{display:block;}

				.point{position:absolute;}
				.point a{
					margin:0;padding:39px 0 0;min-height:40px;min-width:20px;cursor:default;display:block;
					background:no-repeat top center url('~@/assets/images/point.png');background-size:auto;
					line-height:11px;color:#000;text-align:center;
				}
				.active{border:2px solid green;}
			}
		}
	}
</style>
