<template>
	<view>
		<view class="canvas-container">
			<canvas canvas-id="canvas" id="canvas" :disable-scroll="true" style="width: 100%; height: 200px;background-color: #FFFFFF;"
				@touchstart="handleTouchStart($event)" @touchmove="handleTouchMove($event)" @touchend="handleTouchEnd($event)"
				@touchcancel="handleEnd($event)"></canvas>
		</view>
		<view class="btn-container">
			<button class="cu-btn lg bg-blue" @click="handleConfirm()">确定</button>
			<button class="cu-btn lg line-gray" @click="reset()">重置</button>
		</view>
	</view>
</template>

<script>
	var context = null
	export default {
		props: {
			dialogVisiable: {
				type: Boolean,
				default: false
			}
		},
		data() {
			return {
				canvasData: []
			};
		},
		watch: {
			dialogVisiable() {
				if (this.dialogVisiable === true) {
					context = uni.createCanvasContext('canvas')
					context.setLineWidth(3)
					context.setStrokeStyle("#000000")
					this.reset()
				}
			},
			canvasData() {
				context.moveTo(this.canvasData[0].x, this.canvasData[0].y)
				for (let i = 0; i < this.canvasData.length; i++) {
					context.lineTo(this.canvasData[i].x, this.canvasData[i].y)
				}
				context.stroke()
				context.draw(true)
			}
		},
		methods: {
			reset() {
				context.draw()
			},
			hideModal() {
				this.$emit('update:dialogVisiable', false)
			},
			handleTouchStart(e) {
				this.canvasData = []
				const a = e.changedTouches[0]
				this.canvasData.push({
					x: a.x,
					y: a.y
				})
			},
			handleTouchMove(e) {
				const a = e.changedTouches[0]
				this.canvasData.push({
					x: a.x,
					y: a.y
				})
			},
			handleTouchEnd(e) {
				const a = e.changedTouches[0]
				this.canvasData.push({
					x: a.x,
					y: a.y
				})
			},
			handleEnd() {
				context.stroke()
				context.draw(true)
			},
			handleConfirm() {
				uni.canvasToTempFilePath({
					canvasId: 'canvas',
					success: res => {
						this.$emit('success', res.tempFilePath)
					}
				})
			}
		}
	}
</script>

<style lang="scss" scoped>
	.canvas-container {
		width: 400px;
	}
	.btn-container {
		padding-bottom: 20rpx;
		display: flex;
		justify-content: space-around;
	}
</style>
