<template>
	<view class="index-bg">
		<view class="index-content">
			<view class="btn-group">
				<button class="main-btn" @click="scanInventory">扫码盘点</button>
				<button class="main-btn outline" @click="scanView">扫码查看</button>
			</view>
			<view class="task-section">
				<view class="task-title">盘点任务列表</view>
				<view class="task-list">
					<view class="task-item" v-for="(item, idx) in taskList" :key="idx" @click="goTaskDetail(item)">
						<view class="task-info">
							<text class="task-name">{{item.title}}</text>
							<text class="task-time">{{item.time}}</text>
						</view>
						<text class="task-status" :class="item.status">{{item.statusText}}</text>
					</view>
				</view>
			</view>
			<!-- H5扫码弹窗 -->
			<div v-if="showH5Scan" class="h5-scan-modal">
				<div id="reader" style="width:300px;height:300px;margin:0 auto;"></div>
				<button @click="closeH5Scan">关闭</button>
			</div>
		</view>
	</view>
</template>

<script>
	// #ifdef H5
	import { Html5Qrcode, Html5QrcodeSupportedFormats } from 'html5-qrcode';
	// #endif

	export default {
		data() {
			return {
				currentDate: '',
				taskList: [
					{
						title: '仓库A盘点',
						time: '2024-06-01 10:00',
						status: 'pending',
						statusText: '待完成'
					},
					{
						title: '仓库B盘点',
						time: '2024-05-28 14:30',
						status: 'completed',
						statusText: '已完成'
					},
					{
						title: '仓库C盘点',
						time: '2024-05-25 09:15',
						status: 'in-progress',
						statusText: '进行中'
					}
				],
				showH5Scan: false,
				html5QrCode: null,
				scanType: '' // 'inventory' or 'view'
			}
		},
		onLoad() {
			this.updateDate()
		},
		methods: {
			updateDate() {
				const now = new Date()
				const year = now.getFullYear()
				const month = String(now.getMonth() + 1).padStart(2, '0')
				const day = String(now.getDate()).padStart(2, '0')
				this.currentDate = `${year}-${month}-${day}`
			},
			handleScan(type) {
				this.scanType = type;
				// #ifdef H5
				// 先请求摄像头权限
				navigator.mediaDevices.getUserMedia({ 
					video: { 
						facingMode: "environment",
						width: { ideal: 1280 },
						height: { ideal: 720 }
					} 
				})
					.then(() => {
						this.showH5Scan = true;
						this.$nextTick(() => {
							if (!window.Html5Qrcode) {
								window.Html5Qrcode = Html5Qrcode;
							}
							const config = {
								fps: 10,
								qrbox: { width: 250, height: 250 },
								aspectRatio: 1.0,
								formatsToSupport: [ Html5QrcodeSupportedFormats.QR_CODE ]
							};
							
							this.html5QrCode = new window.Html5Qrcode("reader");
							this.html5QrCode.start(
								{ facingMode: "environment" },
								config,
								qrCodeMessage => {
									this.closeH5Scan();
									let url = qrCodeMessage;
									let id = '';
									const match = url.match(/[?&]id=([^&]+)/);
									if (match) {
										id = match[1];
									}
									if (!id) {
										uni.showToast({ title: '二维码无效', icon: 'none' });
										return;
									}
									if (this.scanType === 'inventory') {
										uni.navigateTo({ url: `/pages/inventory/inventory?code=${encodeURIComponent(id)}` });
									} else {
										uni.navigateTo({ url: `/pages/inventory/inventory?code=${encodeURIComponent(id)}&view=1` });
									}
								},
								errorMessage => {
									console.log('扫码错误:', errorMessage);
								}
							).catch(err => {
								console.error('启动扫码失败:', err);
								uni.showToast({ 
									title: '启动扫码失败，请检查摄像头权限', 
									icon: 'none',
									duration: 2000
								});
								this.closeH5Scan();
							});
						});
					})
					.catch(err => {
						console.error('摄像头权限错误:', err);
						uni.showModal({
							title: '提示',
							content: '请允许访问摄像头以使用扫码功能',
							confirmText: '确定',
							showCancel: false,
							success: () => {
								// 引导用户去设置页面开启权限
								if (uni.getSystemInfoSync().platform === 'android') {
									uni.showToast({
										title: '请在系统设置中开启摄像头权限',
										icon: 'none',
										duration: 2000
									});
								}
							}
						});
					});
				// #endif
				// #ifndef H5
				uni.scanCode({
					success: (res) => {
						let url = res.result;
						let id = '';
						const match = url.match(/[?&]id=([^&]+)/);
						if (match) {
							id = match[1];
						}
						if (!id) {
							uni.showToast({ title: '二维码无效', icon: 'none' });
							return;
						}
						if (type === 'inventory') {
							uni.navigateTo({ url: `/pages/inventory/inventory?code=${encodeURIComponent(id)}` });
						} else {
							uni.navigateTo({ url: `/pages/inventory/inventory?code=${encodeURIComponent(id)}&view=1` });
						}
					},
					fail: () => {
						uni.showToast({ title: '扫码失败', icon: 'none' });
					}
				});
				// #endif
			},
			scanInventory() {
				this.handleScan('inventory');
			},
			scanView() {
				this.handleScan('view');
			},
			closeH5Scan() {
				this.showH5Scan = false;
				if (this.html5QrCode) {
					this.html5QrCode.stop().then(() => {
						this.html5QrCode.clear();
					});
				}
			},
			goTaskDetail(item) {
				uni.navigateTo({
					url: `/pages/task-detail/task-detail?title=${encodeURIComponent(item.title)}&time=${encodeURIComponent(item.time)}&status=${item.status}&statusText=${encodeURIComponent(item.statusText)}`
				});
			}
		}
	}
</script>

<style>
	.index-bg {
		min-height: 100vh;
		background: linear-gradient(180deg, #eaf1fb 0%, #f7fafd 100%);
		display: flex;
		flex-direction: column;
		align-items: center;
		justify-content: center;
	}

	.index-content {
		width: 100%;
		max-width: 600px;
		flex: 1;
		display: flex;
		flex-direction: column;
		align-items: center;
		justify-content: center;
		padding: 4vw 0 6vw 0;
		box-sizing: border-box;
	}

	.btn-group {
		width: 90%;
		max-width: 500px;
		display: flex;
		flex-direction: column;
		margin: 0 auto 48rpx auto;
	}

	.main-btn {
		height: 110rpx;
		font-size: 38rpx;
		font-weight: 800;
		border-radius: 28rpx;
		background: linear-gradient(90deg, #409eff 0%, #3b7cff 100%);
		color: #fff;
		box-shadow: 0 8px 24px rgba(64,158,255,0.15);
		letter-spacing: 10rpx;
		margin: 0;
		border: none;
		outline: none;
		width: 100%;
		display: flex;
		align-items: center;
		justify-content: center;
		transition: background 0.2s, box-shadow 0.2s;
		margin-bottom: 36rpx;
	}

	.main-btn:last-child {
		margin-bottom: 0;
	}

	.main-btn:active {
		background: linear-gradient(90deg, #337ecc 0%, #2a5db0 100%);
		box-shadow: 0 4px 12px rgba(64,158,255,0.10);
	}

	.main-btn.outline {
		background: #fff;
		color: #409eff;
		border: 3px solid #409eff;
		box-shadow: none;
	}

	.main-btn.outline:active {
		background: #f0f7ff;
	}

	.task-section {
		width: 92%;
		max-width: 520px;
		margin: 0 auto;
		background: #fff;
		border-radius: 22rpx;
		box-shadow: 0 4px 18px rgba(64,158,255,0.07);
		padding: 28rpx 20rpx 18rpx 20rpx;
	}

	.task-title {
		font-size: 28rpx;
		color: #222;
		font-weight: 700;
		margin-bottom: 18rpx;
	}

	.task-list {
		display: flex;
		flex-direction: column;
		gap: 14rpx;
	}

	.task-item {
		display: flex;
		justify-content: space-between;
		align-items: center;
		padding: 14rpx 0;
		border-bottom: 1px solid #f0f0f0;
	}

	.task-item:last-child {
		border-bottom: none;
	}

	.task-info {
		display: flex;
		flex-direction: column;
	}

	.task-name {
		font-size: 24rpx;
		color: #333;
		font-weight: 600;
	}

	.task-time {
		font-size: 20rpx;
		color: #999;
		margin-top: 2rpx;
	}

	.task-status {
		font-size: 20rpx;
		padding: 4rpx 14rpx;
		border-radius: 16rpx;
	}

	.task-status.pending {
		background-color: #fff3e0;
		color: #ff9800;
	}

	.task-status.completed {
		background-color: #e8f5e9;
		color: #4caf50;
	}

	.task-status.in-progress {
		background-color: #e8f5e9;
		color: #4caf50;
	}

	.h5-scan-modal {
		position: fixed;
		left: 0; top: 0; right: 0; bottom: 0;
		background: rgba(0,0,0,0.6);
		z-index: 9999;
		display: flex;
		flex-direction: column;
		align-items: center;
		justify-content: center;
	}

	.h5-scan-modal #reader {
		width: 300px !important;
		height: 300px !important;
		margin: 0 auto;
		background: #fff;
		border-radius: 8px;
		overflow: hidden;
	}

	.h5-scan-modal #reader video {
		width: 100% !important;
		height: 100% !important;
		object-fit: cover;
	}

	.h5-scan-modal #reader__scan_region {
		width: 100% !important;
		height: 100% !important;
	}

	.h5-scan-modal #reader__scan_region video {
		width: 100% !important;
		height: 100% !important;
	}

	.h5-scan-modal button {
		margin-top: 20px;
		padding: 8px 20px;
		background: #409eff;
		color: #fff;
		border: none;
		border-radius: 4px;
		cursor: pointer;
	}

	.h5-scan-modal button:hover {
		background: #66b1ff;
	}
</style>
