<template>
  <view class="content">
    <!-- logo 和标题 -->
    <image class="logo" src="/static/logo.jpg"></image>
    <view class="text-area">
      <text class="title">{{ title }}</text>
    </view>

    <!-- 扫码按钮 -->
    <button class="scan-btn" @click="startScan">点击扫码</button>

    <!-- 扫码结果组件：仅传递必要props -->
    <scan-result-card 
      v-if="scanResult"
      :scan-result="scanResult" 
      :code-status="codeStatus"
      :current-time="currentTime"
    />
		
    <!-- 备注和确认按钮：仅状态非2（已出库）时显示 -->
    <textarea 
      v-if="scanResult && codeStatus !== CODE_STATUS.OUT_STOCK" 
      v-model="remark" 
      placeholder="请填写备注"
    ></textarea>

    <button 
      class="confirm-btn" 
      @click="confirm"
      v-if="scanResult && codeStatus !== CODE_STATUS.OUT_STOCK"
    >
      确认信息并录入系统
    </button>
  </view>
</template>

<script>
	// 引入组件和API
	import {
		formatCurrentTime
	} from '@/utils/wms';
	import {
		CODE_STATUS,
		IO_TYPE
	} from '@/constants/wms';
	import {
		SCAN_OPERATION_STRATEGIES
	} from '@/strategies/wmsScan';
	import {
		addStockIoDetail
	} from '@/api/wms/stockIoDetail.js';
	import {
		getGenerateRecord,
		updateGenerateRecord
	} from '@/api/wms/code.js';

	export default {
		data() {
			return {
				title: '科伦普扫码器',
				scanResult: null, // 扫码结果（传递给组件）
				currentTime: '', // 扫码时间（传递给组件）
				recordId: undefined,
				codeStatus: undefined,
				remark: '',
				CODE_STATUS,
			};
		},
		onLoad() {
			this.currentTime = formatCurrentTime(); // 用工具函数
		},
		methods: {
			// 更新当前时间（格式化后传递给组件）
			updateCurrentTime() {
				const date = new Date();
				const year = date.getFullYear();
				const month = (date.getMonth() + 1).toString().padStart(2, '0');
				const day = date.getDate().toString().padStart(2, '0');
				const hour = date.getHours().toString().padStart(2, '0');
				const minute = date.getMinutes().toString().padStart(2, '0');
				this.currentTime = `${year}-${month}-${day} ${hour}:${minute}`;
			},

			// 开始扫码：仅保留调用API和赋值逻辑，无业务分支
			async startScan() {
				uni.scanCode({
					success: async (res) => {
						const codeId = res.result;
						this.recordId = codeId;
						uni.showLoading({
							title: '正在获取二维码信息'
						});

						try {
							const {
								data
							} = await getGenerateRecord(codeId);
							this.scanResult = JSON.parse(data.content);
							this.codeStatus = data.status; // 直接用枚举对应的数值
							this.currentTime = formatCurrentTime(); // 工具函数
						} catch (error) {
							console.error('获取扫码信息失败：', error);
							uni.showToast({
								title: '获取信息失败',
								icon: 'none',
								duration: 2000
							});
						} finally {
							uni.hideLoading();
						}
					},
					fail: (err) => {
						/* 原有逻辑不变 */ }
				});
			},

			// 确认录入：用策略模式替代if-else
			async confirm() {
				if (!this.scanResult || this.codeStatus === undefined) return;

				// 1. 生成策略key（状态-IO类型）
				const strategyKey = `${this.codeStatus}-${this.scanResult.ioType}`;
				// 2. 匹配对应的策略（无策略则提示异常）
				const strategy = SCAN_OPERATION_STRATEGIES[strategyKey];
				if (!strategy) {
					uni.showToast({
						title: '未知业务场景，无法处理',
						icon: 'none'
					});
					return;
				}

				try {
					// 3. 执行策略：组装参数并调用入库API
					const addParams = strategy.getAddParams(this.scanResult, this.remark);
					await addStockIoDetail(addParams);

					// 4. 执行策略：更新二维码状态
					const targetStatus = strategy.getUpdateStatus();
					await updateGenerateRecord({
						recordId: this.recordId,
						status: targetStatus
					});

					// 成功提示 + 清空数据
					uni.showToast({
						title: '确认成功，信息已录入系统',
						icon: 'none',
						duration: 2000
					});
					setTimeout(() => {
						this.scanResult = null;
						this.recordId = undefined;
						this.codeStatus = undefined;
						this.remark = '';
					}, 2000); // 原0秒无意义，改为与提示同步

				} catch (error) {
					console.error('确认失败：', error);
					uni.showToast({
						title: '确认失败，请重试',
						icon: 'none'
					});
				}
			}
		}
	};
</script>

<style>
	/* 父页面样式：保留原有样式，新增确认按钮样式 */
	.content {
		display: flex;
		flex-direction: column;
		align-items: center;
		justify-content: flex-start;
		padding: 20rpx;
		min-height: 100vh;
		background-color: #f5f5f5;
	}

	.logo {
		height: 200rpx;
		margin-top: 100rpx;
		margin-bottom: 50rpx;
	}

	.text-area {
		display: flex;
		justify-content: center;
		margin-bottom: 80rpx;
	}

	.title {
		font-size: 36rpx;
		color: #333;
		font-weight: 500;
	}

	/* 扫码按钮样式 */
	.scan-btn {
		width: 600rpx;
		height: 100rpx;
		line-height: 100rpx;
		font-size: 36rpx;
		background-color: #007aff;
		color: white;
		border-radius: 50rpx;
		margin-bottom: 60rpx;
		box-shadow: 0 4rpx 10rpx rgba(0, 122, 255, 0.3);
	}

	/* 确认按钮样式（父页面新增，与组件间距协调） */
	.confirm-btn {
		width: 680rpx;
		/* 与组件宽度一致，视觉对齐 */
		height: 90rpx;
		line-height: 90rpx;
		font-size: 32rpx;
		background-color: #00b42a;
		color: white;
		border-radius: 10rpx;
		margin-top: 30rpx;
		/* 与组件保持间距 */
		box-shadow: 0 2rpx 8rpx rgba(0, 180, 42, 0.2);
	}
</style>