<template>
	<view class="signature-container">
		<!-- 第一阶段：显示品项信息 -->
		<view class="signature-px-info" v-if="currentStage === 'info'">
			<view class="px-info-title">{{ infoTitle }}</view>
			<view class="px-info-list">
				<view class="px-info-row" v-for="(item, index) in pxInfoList" :key="index">
					<text class="px-name">{{ item.name }}</text>
					<view class="px-info-right">
						<text class="px-type" v-if="item.type">{{ item.type }}</text>
						<text class="px-count">数量：{{ item.count }}</text>
					</view>
				</view>
			</view>
			<view class="px-info-total">
				<text class="total-label">{{ amountLabel }}：</text>
				<text class="total-value">¥{{ pxInfo.actualPrice || '0.00' }}</text>
			</view>
			<view class="px-info-action">
				<button @click="startSign" class="btn-start-sign">开始签字</button>
			</view>
		</view>

		<!-- 第二阶段：签字 -->
		<template >
			<view class="signature-header" v-if="currentStage === 'sign'">
				<text class="signature-title">会员签字</text>
				<view class="signature-actions">
					<button @click="clearSignature" class="btn-clear">清除</button>
					<button @click="confirmSignature" class="btn-confirm">确认</button>
				</view>
			</view>
			<!-- 第三阶段：显示提示信息 -->
			<view class="signature-confirm-tips" v-if="currentStage === 'confirm'">
				<text class="confirm-tips-text">离店前，请检查一下是否带好了：手机、钥匙、钱包和那份美丽的心情。</text>
			</view>
			<!-- 签字区域 -->
			<view class="signature-pad" id="signaturePad">
				<canvas canvas-id="signature-canvas" style="width: 100%; height: 100%;" @touchstart="startDrawing"
					@touchmove="draw" @touchend="stopDrawing" class="signature-canvas"></canvas>
			</view>
			<view class="signature-tips" v-if="currentStage === 'sign'">
				<text class="tips-text">请在上方区域进行签字</text>
			</view>
		</template>

	
	</view>
</template>

<script>
	export default {
		name: 'SignaturePad',
		props: {
			width: {
				type: Number,
				default: 300
			},
			height: {
				type: Number,
				default: 150
			},
			lineWidth: {
				type: Number,
				default: 2
			},
			strokeColor: {
				type: String,
				default: '#000000'
			},
		pxInfo: {
			type: Object,
			default: null
		},
		signatureType: {
			type: String,
			default: 'order' // 'order' 开单, 'consume' 耗卡, 'refund' 退卡
		}
		},
		data() {
			return {
				canvasWidth: 300,
				canvasHeight: 150,
				isDrawing: false,
				lastX: 0,
				lastY: 0,
				ctx: null,
				hasSignature: false,
				// 存储所有绘制的路径点
				paths: [],
				currentStage: 'info' // 当前阶段：'info' 显示品项信息, 'sign' 签字, 'confirm' 显示提示
			}
		},
	computed: {
		// 格式化品项列表，每条显示品项名、类型和数量
		pxInfoList() {
			if (!this.pxInfo || !this.pxInfo.items || this.pxInfo.items.length === 0) {
				return [];
			}
			return this.pxInfo.items.map(item => ({
				name: item.name || '无',
				count: item.count || 0,
				type: item.type || ''
			}));
		},
		// 根据类型显示不同的标题
		infoTitle() {
			if (this.signatureType === 'consume') {
				return '耗卡信息';
			} else if (this.signatureType === 'refund') {
				return '退卡信息';
			}
			return '订单信息';
		},
		// 根据类型显示不同的金额标签
		amountLabel() {
			if (this.signatureType === 'consume') {
				return '耗卡金额';
			} else if (this.signatureType === 'refund') {
				return '退卡金额';
			}
			return '实付金额';
		}
	},
		mounted() {
			// 初始阶段是显示品项信息，不需要初始化画布
			// 只有在进入签字阶段时才初始化画布
		},
		methods: {
			// 初始化画布
			initCanvas() {
				// this.canvasWidth = this.width;
				// this.canvasHeight = this.height;
				// 获取signature-pad的宽高
				const query = uni.createSelectorQuery().in(this);
				// 选择需要查询的元素（支持类名、ID等选择器）
				query.select('#signaturePad')
					.boundingClientRect(data => {
						if (data) {
							this.canvasWidth = data.width;
							this.canvasHeight = data.height;
						} else {
							console.log('未找到元素');
						}
					})
					.exec(); // 执行查询

				// console.error(this.canvasWidth, this.canvasHeight);
				this.$nextTick(() => {
					this.ctx = uni.createCanvasContext('signature-canvas', this);
					this.drawBackground();
				});
			},

			// 绘制背景
			drawBackground() {
				if (!this.ctx) return;

				// 清除画布
				this.ctx.clearRect(0, 0, this.canvasWidth, this.canvasHeight);

				// 设置背景色
				this.ctx.fillStyle = '#ffffff';
				this.ctx.fillRect(0, 0, this.canvasWidth, this.canvasHeight);

				// 绘制边框
				this.ctx.strokeStyle = '#e0e0e0';
				this.ctx.lineWidth = 2;
				this.ctx.strokeRect(0, 0, this.canvasWidth, this.canvasHeight);

				// 绘制提示文字
				this.ctx.fillStyle = '#999';
				this.ctx.font = '16px Arial';
				// this.ctx.fillText('请在此区域签字', 20, 30);

				// 重新绘制所有已保存的路径
				this.redrawPaths();

				// 显示
				this.ctx.draw();
			},

			// 重新绘制所有路径
			redrawPaths() {
				if (!this.ctx || this.paths.length === 0) return;

				this.ctx.strokeStyle = this.strokeColor;
				this.ctx.lineWidth = this.lineWidth;
				this.ctx.lineCap = 'round';
				this.ctx.lineJoin = 'round';

				this.paths.forEach(path => {
					if (path.length < 2) return;

					this.ctx.beginPath();
					this.ctx.moveTo(path[0].x, path[0].y);

					for (let i = 1; i < path.length; i++) {
						this.ctx.lineTo(path[i].x, path[i].y);
					}

					this.ctx.stroke();
				});
			},

			// 开始签字阶段
			startSign() {
				this.currentStage = 'sign';
				this.$nextTick(() => {
					this.initCanvas();
				});
			},

			// 开始绘制
			startDrawing(e) {
				// 如果不在签字阶段，不允许绘制
				if (this.currentStage !== 'sign') {
					return;
				}

				this.isDrawing = true;
				this.hasSignature = true;

				const touch = e.touches[0];
				const x = touch.x;
				const y = touch.y;

				// 开始新的路径
				this.paths.push([{
					x,
					y
				}]);

				this.lastX = x;
				this.lastY = y;
			},

			// 绘制
			draw(e) {
				// 如果不在签字阶段，不允许绘制
				if (this.currentStage !== 'sign' || !this.isDrawing) return;

				const touch = e.touches[0];
				const x = touch.x;
				const y = touch.y;

				// 添加点到当前路径
				this.paths[this.paths.length - 1].push({
					x,
					y
				});

				// 重新绘制整个画布
				this.drawBackground();

				this.lastX = x;
				this.lastY = y;
			},

			// 停止绘制
			stopDrawing() {
				this.isDrawing = false;
			},

			// 清除签字
			clearSignature() {
				this.paths = [];
				this.hasSignature = false;
				this.drawBackground();
				this.$emit('clear');
			},

			// 确认签字
			confirmSignature() {
				if (!this.hasSignature) {
					uni.showToast({
						title: '请先进行签字',
						icon: 'none'
					});
					return;
				}

				this.getSignatureData().then(dataUrl => {
					// 进入确认阶段，显示提示信息
					this.currentStage = 'confirm';
					this.$emit('confirm', {
						dataUrl: dataUrl,
						hasSignature: this.hasSignature
					});
					// 延迟2秒后触发确认事件，让用户看到提示信息
					// setTimeout(() => {
					// 	this.$emit('confirm', {
					// 		dataUrl: dataUrl,
					// 		hasSignature: this.hasSignature
					// 	});
					// }, 2000);
				}).catch(error => {
					console.error('获取签字数据失败:', error);
					uni.showToast({
						title: '获取签字数据失败',
						icon: 'none'
					});
				});
			},

			// 获取签字数据
			getSignatureData() {
				return new Promise((resolve, reject) => {
					uni.canvasToTempFilePath({
						canvasId: 'signature-canvas',
						success: (res) => {
							// 在H5环境下，直接使用tempFilePath
							// #ifdef H5
							const dataUrl = res.tempFilePath;
							resolve(dataUrl);
							// #endif

							// 在微信小程序环境下，需要读取文件
							// #ifdef MP-WEIXIN
							uni.getFileSystemManager().readFile({
								filePath: res.tempFilePath,
								encoding: 'base64',
								success: (fileRes) => {
									const dataUrl =
									`data:image/png;base64,${fileRes.data}`;
									resolve(dataUrl);
								},
								fail: reject
							});
							// #endif

							// 在APP环境下，使用plus.io读取文件并转换为base64
							// #ifdef APP-PLUS
							try {
								// 使用plus.io读取文件
								plus.io.resolveLocalFileSystemURL(res.tempFilePath, (entry) => {
									entry.file((file) => {
										const reader = new plus.io.FileReader();
										reader.onloadend = (e) => {
											// readAsDataURL返回的结果已经是完整的data URL格式
											const dataUrl = e.target.result;
											resolve(dataUrl);
										};
										reader.onerror = (error) => {
											reject(new Error('读取文件失败: ' + (error.message || '未知错误')));
										};
										reader.readAsDataURL(file);
									}, (error) => {
										reject(new Error('获取文件对象失败: ' + (error.message || '未知错误')));
									});
								}, (error) => {
									reject(new Error('解析文件路径失败: ' + (error.message || '未知错误')));
								});
							} catch (error) {
								reject(new Error('APP环境文件读取异常: ' + (error.message || '未知错误')));
							}
							// #endif
						},
						fail: reject
					}, this);
				});
			},

			// 设置签字数据（用于编辑模式）
			setSignatureData(dataUrl) {
				if (!dataUrl || !this.ctx) return;

				// 如果有签字数据，设置hasSignature为true
				this.hasSignature = true;

				// 这里可以添加从dataUrl恢复签字的逻辑
				// 暂时简化处理
			}
		}
	}
</script>

<style scoped>
	.signature-container {
		background: #fff;
		border-radius: 8px;
		overflow: hidden;
		box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
		border: 3rpx solid #c8e6c9;
		height: 100%;
		display: flex;
		flex-direction: column;
		justify-content: space-between;
	}

	.signature-header {
		display: flex;
		justify-content: space-between;
		align-items: center;
		padding: 12px 16px;
		background: linear-gradient(135deg, #e8f5e9 0%, #b2dfdb 100%);
		border-bottom: 1px solid #c8e6c9;
	}

	.signature-title {
		font-size: 16px;
		font-weight: 500;
		color: #2e7d32;
	}

	.signature-actions {
		display: flex;
		gap: 8px;
	}

	.btn-clear,
	.btn-confirm {
		padding: 6px 12px;
		border: none;
		border-radius: 4px;
		font-size: 14px;
		cursor: pointer;
		transition: all 0.2s;
	}

	.btn-clear {
		background: #f9fff9;
		color: #6a9c6a;
		border: 1px solid #c8e6c9;
	}

	.btn-clear:hover {
		background: #e8f5e9;
	}

	.btn-confirm {
		background: linear-gradient(120deg, #43e97b 0%, #38f9d7 100%);
		color: #fff;
	}

	.btn-confirm:hover {
		background: linear-gradient(120deg, #38d96b 0%, #2ee5c7 100%);
	}

	.signature-pad {
		/* padding: 16px; */
		display: flex;
		justify-content: center;
		flex: 1;
		box-sizing: border-box;
		width: 100%;
		height: 100%;
	}

	.signature-canvas {
		/* border: 1px solid #c8e6c9; */
		border-radius: 4px;
		background: #fff;
		box-shadow: inset 0 1px 3px rgba(0, 0, 0, 0.1);
	}

	.signature-canvas.signature-disabled {
		pointer-events: none;
		opacity: 0.7;
	}

	.signature-tips {
		padding: 8px 16px;
		background: #f9fff9;
		text-align: center;
		border-top: 1px solid #c8e6c9;
	}

	.tips-text {
		font-size: 12px;
		color: #6a9c6a;
	}

	/* 品项信息显示样式 */
	.signature-px-info {
		padding: 40rpx 30rpx;
		background: linear-gradient(135deg, #f9fff9 0%, #e8f5e9 100%);
		height: 100%;
		display: flex;
		flex-direction: column;
		justify-content: center;
	}

	.px-info-title {
		font-size: 36rpx;
		color: #2e7d32;
		font-weight: bold;
		text-align: center;
		margin-bottom: 40rpx;
	}

	.px-info-list {
		/* flex: 1; */
		height: 50vh;
		overflow-y: scroll;
		margin-bottom: 30rpx;
	}

	.px-info-row {
		display: flex;
		justify-content: space-between;
		align-items: center;
		padding: 24rpx 20rpx;
		margin-bottom: 20rpx;
		background: #fff;
		border-radius: 12rpx;
		border: 2rpx solid #c8e6c9;
	}

	.px-name {
		font-size: 28rpx;
		color: #1b5e20;
		flex: 1;
		word-break: break-all;
	}

	.px-info-right {
		display: flex;
		flex-direction: column;
		align-items: flex-end;
		gap: 8rpx;
		flex-shrink: 0;
	}

	.px-type {
		font-size: 24rpx;
		color: #ff9800;
		font-weight: 500;
		padding: 4rpx 12rpx;
		background: #fff3e0;
		border-radius: 8rpx;
		border: 1rpx solid #ff9800;
	}

	.px-count {
		font-size: 26rpx;
		color: #6a9c6a;
	}

	.px-info-total {
		display: flex;
		justify-content: space-between;
		align-items: center;
		padding: 24rpx 20rpx;
		background: #fff;
		border-radius: 12rpx;
		border: 2rpx solid #c8e6c9;
		margin-bottom: 40rpx;
	}

	.total-label {
		font-size: 28rpx;
		color: #1b5e20;
		font-weight: normal;
	}

	.total-value {
		font-size: 28rpx;
		color: #f44336;
		font-weight: normal;
	}

	.px-info-action {
		width: 100%;
	}

	.btn-start-sign {
		width: 100%;
		padding:10rpx 24rpx;
		background: linear-gradient(120deg, #43e97b 0%, #38f9d7 100%);
		color: #fff;
		border: none;
		border-radius: 12rpx;
		font-size: 32rpx;
		font-weight: bold;
		cursor: pointer;
		transition: all 0.2s;
		box-shadow: 0 4rpx 16rpx rgba(67, 233, 123, 0.3);
	}

	.btn-start-sign:hover {
		box-shadow: 0 8rpx 32rpx rgba(67, 233, 123, 0.4);
		transform: translateY(-2rpx);
	}

	/* 确认后的提示信息样式 */
	.signature-confirm-tips {
		padding: 60rpx 40rpx;
		background: linear-gradient(135deg, #fff3e0 0%, #ffe0b2 100%);
		border: 3rpx solid #ff9800;
		border-radius: 20rpx;
		margin: 40rpx;
		text-align: center;
	}

	.confirm-tips-text {
		font-size: 32rpx;
		color: #e65100;
		line-height: 1.8;
		font-weight: 500;
		display: block;
	}
</style>