<template>
	<div class="app-container">
		<div id="container" ref="container" class="container" />
	</div>
</template>

<script>
	import Konva from 'konva'

	export default {
		name: 'DragAndDrop',
		props: {
			image: {
				required: false,
				type: [String],
				default: null
			},

			options: { //配置项
				required: false,
				type: [Object],
				default: () => null
			},
		},
		data() {
			return {
				myStage: null,
				myLayer: null,
				isText: false,
				mode: 'paint',
				config: {
					textColor: 'red',
					textSize: 16,
					isDpr: false, //是否使用dpr兼容高分屏 [Boolean] 可选
					lastWriteSpeed: 1, //书写速度 [Number] 可选
					lastWriteWidth: 2, //下笔的宽度 [Number] 可选
					lineCap: 'round', //线条的边缘类型 [butt]平直的边缘 [round]圆形线帽 [square]	正方形线帽
					lineJoin: 'round', //线条交汇时边角的类型  [bevel]创建斜角 [round]创建圆角 [miter]创建尖角。
					canvasWidth: 1200, //canvas宽高 [Number] 可选
					canvasHeight: 600, //高度  [Number] 可选
					isShowBorder: true, //是否显示边框 [可选]
					bgColor: '#fcc', //背景色 [String] 可选 注:这背景色仅仅只是canvas背景,保存的图片仍然是透明的
					borderWidth: 1, // 网格线宽度  [Number] 可选
					borderColor: "#ff787f", //网格颜色  [String] 可选
					writeWidth: 5, //基础轨迹宽度  [Number] 可选
					maxWriteWidth: 30, // 写字模式最大线宽  [Number] 可选
					minWriteWidth: 5, // 写字模式最小线宽  [Number] 可选
					writeColor: 'red', // 轨迹颜色  [String] 可选
					isSign: false, //签名模式 [Boolean] 默认为非签名模式,有线框, 当设置为true的时候没有任何线框
					imgType: 'png' //下载的图片格式  [String] 可选为 jpeg  canvas本是透明背景的
				},
			}
		},
		created() {
			this.$nextTick(() => {
				this.initStage()
			})
		},
		methods: {
			initStage() {
				let that = this
				var stage = new Konva.Stage({
					container: 'container',
					width: this.config.canvasWidth,
					height: this.config.canvasHeight
				});
				this.$refs.container.style.width = this.config.canvasWidth + 'px'
				var layer = new Konva.Layer();

				var isPaint = false;
				var mode = 'brush';
				var lastLine;

				stage.on('mousedown.1 touchstart.1', function(e) {
					if (that.isText || that.mode === 'text') {
						that.isText = false
						that.mode = 'paint'
						let textNode = new Konva.Text({
							text: "",
							x: stage.getPointerPosition().x,
							y: stage.getPointerPosition().y,
							fontSize: that.config.textSize,
							fill: that.config.textColor,
							draggable: true,
							width: 200,
							// height: 50,
							name: "text",
						});
						layer.add(textNode);
						let tr = new Konva.Transformer({
							node: textNode,
							// enabledAnchors: ["middle-left", "middle-right"],
							centeredScaling: true,
							anchorStroke: "#808080",
							anchorFill: "#fff",
							anchorSize: 12,
							anchorCornerRadius: 5,
							anchorStrokeWidth: 2,
							borderStroke: "#000000",
							borderStrokeWidth: 2,
							borderDash: [3, 3],
							padding: 10,
						});
						layer.add(tr);
						textNode.on("transformstart", function() {
							that.isPaint = false
							that.mode = 'transform'
						});
						textNode.on("transform", function() {
							that.isPaint = false
							textNode.setAttrs({
								width: Math.max(textNode.width() * textNode.scaleX(), 20),
								height: Math.max(textNode.height() * textNode.scaleY(), 20),
								scaleX: 1,
								scaleY: 1
							})
						});
						textNode.on("transformend", function() {
							that.isPaint = true
							that.mode = 'paint'
						});
						layer.draw();
						textNode.on("click", (e) => {
							e.evt.preventDefault();
							that.$parent.curMode = 'text'
							that.isPaint = false
							textNode.hide();
							tr.show();
							layer.draw();
							let textPosition = textNode.absolutePosition();
							let stageBox = stage.container().getBoundingClientRect();
							let areaPosition = {
								x: stageBox.left + textPosition.x,
								y: stageBox.top + textPosition.y,
							};
							let textarea = document.createElement("textarea");
							document.body.appendChild(textarea);
							textarea.value = textNode.text();
							textarea.style.position = "absolute";
							textarea.style.top = areaPosition.y + "px";
							textarea.style.left = areaPosition.x + "px";
							textarea.style.width = textNode.width() - textNode.padding() * 2 + "px";
							textarea.style.height = textNode.height() - textNode.padding() * 2 + 5 + "px";
							textarea.style.fontSize = textNode.fontSize() + "px";
							textarea.style.border = "none";
							textarea.style.padding = "0px";
							textarea.style.margin = "0px";
							textarea.style.overflow = "hidden";
							textarea.style.background = "none";
							textarea.style.zIndex = "9999999";
							textarea.style.outline = "none";
							textarea.style.resize = "none";
							textarea.style.lineHeight = textNode.lineHeight();
							textarea.style.fontFamily = textNode.fontFamily();
							textarea.style.transformOrigin = "left top";
							textarea.style.textAlign = textNode.align();
							textarea.style.color = textNode.fill();
							let rotation = textNode.rotation();
							let transform = "";
							if (rotation) {
								transform += "rotateZ(" + rotation + "deg)";
							}

							let px = 0;
							let isFirefox =
								navigator.userAgent.toLowerCase().indexOf("firefox") > -1;
							if (isFirefox) {
								px += 2 + Math.round(textNode.fontSize() / 20);
							}
							transform += "translateY(-" + px + "px)";
							textarea.style.transform = transform;
							// reset height
							textarea.style.height = "auto";
							// after browsers resized it we can set actual value
							textarea.style.height = textarea.scrollHeight + 3 + "px";
							textarea.focus();

							function removeTextarea() {
								textarea.parentNode.removeChild(textarea);
								window.removeEventListener("click", handleOutsideClick);
								textNode.show();
								console.log(layer)
								console.log(tr)
								tr.hide();
								tr.forceUpdate();
								layer.draw();
								
							}

							function setTextareaWidth(newWidth) {
								if (!newWidth) {
									// set width for placeholder
									newWidth = textNode.placeholder.length * textNode.fontSize();
								}
								// some extra fixes on different browsers
								let isSafari = /^((?!chrome|android).)*safari/i.test(
									navigator.userAgent
								);
								let isFirefox =
									navigator.userAgent.toLowerCase().indexOf("firefox") > -1;
								if (isSafari || isFirefox) {
									newWidth = Math.ceil(newWidth);
								}

								let isEdge =
									document.documentMode || /Edge/.test(navigator.userAgent);
								if (isEdge) {
									newWidth += 1;
								}
								textarea.style.width = newWidth + "px";
							}

							console.log(textarea)
							textarea.addEventListener("keydown", function(e) {
								if (e.keyCode === 27) {
									removeTextarea();
								}
							});

							textarea.addEventListener("keydown", function(e) {
								that.$parent.curMode = 'move'
								that.mode = 'move'
								that.isText = false
								let scale = textNode.getAbsoluteScale().x;
								setTextareaWidth(textNode.width() * scale);
								textarea.style.height = "auto";
								textarea.style.height =
									textarea.scrollHeight + textNode.fontSize() + "px";
							});

							function handleOutsideClick(e) {
								if (e.target !== textarea) {
									textNode.text(textarea.value);
									that.$parent.curMode = 'move'
									that.mode = 'move'
									removeTextarea();
								}
							}
							setTimeout(() => {
								window.addEventListener("click", handleOutsideClick);
							});
						});
					} else if(that.mode === 'paint') {
						console.log('进入绘制')
						isPaint = true;
						var pos = stage.getPointerPosition();
						lastLine = new Konva.Line({
							stroke: that.config.writeColor,
							strokeWidth: that.config.writeWidth,
							globalCompositeOperation: mode === 'brush' ? 'source-over' : 'destination-out',
							points: [pos.x, pos.y],
							draggable:true
						});
						layer.add(lastLine);
					}else{
						// 如果是点击的变形框 则不处理
						console.log('move')
					}

				});

				stage.on('mouseup touchend', function() {
					isPaint = false;
				});

				stage.on('mousemove touchmove', function(e) {
					// e.evt.stopPropagation();
					if (!isPaint || that.mode === 'text') {
						return;
					}
					const pos = stage.getPointerPosition();
					var newPoints = lastLine.points().concat([pos.x, pos.y]);
					lastLine.points(newPoints);
					layer.batchDraw();
				});

				stage.add(layer);
				this.myLayer = layer
				this.myStage = stage
			},
			
			/* 渲染背景图 */
			doRenderImg(src){
				//console.log(src)
				const image = new Image()
				image.src = src
				image.setAttribute('crossOrigin', 'anonymous')
				image.onload = () => {
					const renderWidth = image.width > 1200 ? 1200 : image.width
					const renderHeight = (image.height / image.width) * renderWidth
					this.config.canvasWidth = renderWidth
					this.config.canvasHeight = renderHeight
					this.initStage()
					const graph = new Konva.Image({
						x: (this.myStage.attrs.width - renderWidth) / 2,
						y: (this.myStage.attrs.height - renderHeight) / 2,
						image: image,
						width: renderWidth,
						height: renderHeight
					})
					this.myLayer.add(graph)
					this.myLayer.batchDraw()
				}
			},

			/*白板缩放后 重新获取新的坐标未知*/
			getRelativePointerPosition(node) {
				// 函数将返回相对于传递的节点的指针位置
				var transform = node.getAbsoluteTransform().copy();
				// 为了检测相对位置，需要进行逆变换
				transform.invert();
				// 获取指针(如鼠标或触摸)位置
				var pos = node.getStage().getPointerPosition();
				// now we find relative point
				return transform.point(pos);
			},

			/* 撤销操作 */
			doUndo() {
				this.myLayer.children.pop()
				this.myLayer.draw()
			},

			/* 绘制输入的文本 */
			doAddText(val) {
				this.isText = true
			},

			/* 清屏操作 */
			canvasClear() {
				this.initStage()
			},

			/* 截图保存图片 */
			saveAsImg() {
				return new Promise(async (r, j) => {
					console.log(this.myStage)
					const image = new Image();
					let compressImg = await this.$editorTools.compressImg(this.myStage.toDataURL(),
						this.myStage.attrs.width, this.myStage.attrs.height)
					r({
						base64: compressImg,
						width: this.myStage.attrs.width,
						height: this.myStage.attrs.height
					})
				})
			}
		},

		watch: {
			'options.writeWidth': {
				handler(n) {
					this.config.writeWidth = n
				},
				immediate: true
			},
			'options.writeColor': {
				handler(n) {
					this.config.writeColor = n
				},
				immediate: true
			},
			'options.textColor': {
				handler(n) {
					this.config.textColor = n
				},
				immediate: true
			},
			'options.textSize': {
				handler(n) {
					this.config.textSize = n
				},
				immediate: true
			},
			// 'options.canvasWidth': {
			// 	handler(n) {
			// 		this.config.canvasWidth = n
			// 		this.initStage();
			// 	},
			// },
			// 'options.canvasHeight': {
			// 	handler(n) {
			// 		this.config.canvasHeight = n
			// 		this.initStage();
			// 	},
			// },
		},
	}
</script>
<style>
	.container {
		max-width: 1200px;
		margin: 0 auto;
		background-color: #dadada;
	}
</style>
