<template>
	<view class="container">
		<view v-if="pinyin" class="pinyin">{{pinyin}}</view>
		<view class="canvas-box">
			<SvgIcon icon-class="hanzi-writer-bg" class="character-target-bg" :size="300" />
			<canvas :canvas-id="canvasId" ref="canvas" class="canvas" @touchstart.prevent="handleTouchStart"
				@touchmove.prevent="handleTouchMove" @touchend.prevent="handleTouchEnd"></canvas>
		</view>
		<view class="btn-list">
			<view class="btn-box" @click="resetHanzi" :style="{'opacity':disabled?'0.5':'1'}">
				<SvgIcon icon-class="reset" class="reset-btn" :size="18" />
				<text class="btn-text">重写</text>
			</view>
			<view class="btn-box" @click="play()">
				<SvgIcon icon-class="triangle" class="reset-btn" :size="14" />
				<text :class="['btn-text',currenHzData && currenHzData.history ? '' : 'disabled']">笔迹</text>
			</view>
			<view class="btn-box" @click="saveImage" :style="{'opacity':disabled?'0.5':'1'}">
				<SvgIcon icon-class="save" class="reset-btn" :size="14" />
				<text class="btn-text">保存</text>
			</view>
		</view>
	</view>
</template>

<script>
	export default {
		name: 'FreeWrite',
		props: {
			width: {
				type: Number,
				default: 308,
			},
			height: {
				type: Number,
				default: 308,
			},
			lineWidth: {
				type: Number,
				default: 4,
			},
			lineColor: {
				type: String,
				default: '#000000',
			},
			bgColor: {
				type: String,
				default: '',
			},
			isCrop: {
				type: Boolean,
				default: false,
			},
			pinyin: {
				type: String,
				default: '',
			},
			canvasId: {
				type: String,
				default: '',
			},
			mark: {
				type: String,
				default: '',
			},
			answerIndex: {
				type: Number,
				default: -1,
			},
			userAnswerList: {
				type: Array,
				default: () => [],
			},
			disabled: {
				type: Boolean,
				default: false,
			},
		},
		data() {
			return {
				ctx: null,
				isWriting: false,
				lastLoc: {
					x: 0,
					y: 0
				},
				currenHzData: {
					strokes_image_url: '',
					history: [], // 存储路径坐标
				},
				hasPlay: false
			};
		},
		watch: {
			userAnswerList: {
				handler(val, oldVal) {
					this.setUserAnswer();
				},
				immediate: true,
				deep: true,
			},
		},
		created() {
			this.ctx = uni.createCanvasContext(this.canvasId, this);
			this.ctx.setLineWidth(4);
			this.ctx.setStrokeStyle('#000');
			this.ctx.lineCap = 'round'; //表示线条的末端以圆形结束
			this.ctx.lineJoin = 'round'; //表示线条的相交处为圆弧
		},
		methods: {
			handleTouchStart(e) {
				if (this.disabled) return;
				this.isWriting = true;
				this.lastLoc = {
					x: Math.round(e.mp.touches[0].x),
					y: Math.round(e.mp.touches[0].y)
				};
				e.preventDefault();
			},
			handleTouchMove(e) {
				if (this.disabled) return;
				if (this.isWriting) {
					let curLoc = {
						x: Math.round(e.mp.touches[0].x),
						y: Math.round(e.mp.touches[0].y)
					}; // 获得当前坐标
					this.draw(this.ctx, this.lastLoc, curLoc);
					this.currenHzData.history.push([this.lastLoc, curLoc]);
					this.lastLoc = Object.assign({}, this.lastLoc, curLoc);
				}
				e.preventDefault();
			},
			handleTouchEnd(e) {
				this.isWriting = false;
				e.preventDefault();
			},
			draw(context, lastLoc, curLoc) {
				if (context) {
					context.beginPath();
					context.moveTo(lastLoc.x, lastLoc.y);
					context.lineTo(curLoc.x, curLoc.y);
					context.stroke();
					context.draw(true);
				}
			},
			//播放笔画
			play() {
				let that = this;
				if (this.currenHzData && this.currenHzData.history) {
					this.ctx.clearRect(0, 0, 320, 320);
					let history = null;
					history = that.currenHzData.history;
					const len = history.length;
					let i = 0;
					const runner = () => {
						i += 1;
						if (i < len) {
							that.draw(that.ctx, history[i][0], history[i][1]);
							requestAnimationFrame(runner);
						} else {
							that.hasPlay = false;
						}
					};
					requestAnimationFrame(runner);
				}
			},
			//重写
			resetHanzi() {
				if (this.disabled) return;
				this.ctx.clearRect(0, 0, 300, 300);
				// 绘制完成
				this.ctx.draw();
				this.currenHzData.strokes_image_url = '';
				this.currenHzData.history = [];
				this.$emit("saveStrock", this.mark, null, '', this.answerIndex);
			},
			//存储文字图片路径
			saveImage() {
				if (this.disabled) return;
				var that = this;
				this.ctx.draw(true, () => {
					if (that.currenHzData.history.length) {
						uni.canvasToTempFilePath({
							canvasId: this.canvasId,
							success(res) {
								//tempFilePath  路径
								that.currenHzData.strokes_image_url = res.tempFilePath;
								that.$emit("saveStrock", that.mark, that.currenHzData.history, that.currenHzData
									.strokes_image_url, that.answerIndex);
							}
						}, this);
					}
				});
			},
			setUserAnswer() {
				var curAns = this.userAnswerList.find(p => p.mark == this.mark);
				if (!curAns) return;
				var ans_index_en = curAns.strokes_content_list[this.answerIndex];
				if (!ans_index_en) return;
				ans_index_en = JSON.parse(ans_index_en);
				this.ctx = uni.createCanvasContext(this.canvasId, this);
				this.ctx.setLineWidth(4);
				this.ctx.setStrokeStyle('#000');
				this.ctx.lineCap = 'round'; //表示线条的末端以圆形结束
				this.ctx.lineJoin = 'round'; //表示线条的相交处为圆弧
				this.currenHzData.history = JSON.parse(ans_index_en.strokes_content);
				this.play();
			},
		}
	};
</script>

<style lang="scss" scoped>
	.container {
		width: 308px;
		height: 760rpx;
		margin: 0px auto 24rpx auto;
		display: flex;
		flex-direction: column;
		align-items: center;
		row-gap: 24rpx;

		.pinyin {
			font-size: 32px;
		}

		.canvas-box {
			position: relative;
			border: 4px solid #E81B1B;

			.character-target-bg {
				color: #DEDEDE;
			}

			.canvas {
				width: 100%;
				height: 100%;
				position: absolute;
				top: 0;
				left: 0;
			}
		}

		.btn-list {
			width: 100%;
			display: flex;
			justify-content: space-evenly;
			column-gap: 30rpx;

			.btn-box {
				display: flex;
				justify-content: center;
				align-items: center;
				column-gap: 16rpx;

				.btn-text {
					margin-top: -2rpx;
					font-size: 32rpx;
				}
			}
		}
	}
</style>