<template>
	<view class="record-card flex-row">
		<view class="tag-circle" v-for="(item, index) in initRecords" :key="index" @click="tabsClick(parseInt(item.no))"
			:class="{'checked-tag' : parseInt(item.no) == current}">
			<text class="circle" :class="{
							'bg-green': item.result == '合格',
							'bg-red': item.result == '不合格',
							'bg-black': item.result != '不合格' && item.result != '合格'
						  }">{{item.no}}</text>
		</view>
	</view>
	<!-- #ifdef APP -->
	<scroll-view style="flex:1">
	<!-- #endif -->

		<view v-if="reportList.length" class="card-list">
			<!-- 注意：v-for 遍历 reportList 时，item 是响应式的，但内部字段需通过计算属性转换 -->
			<view class="card" v-for="item in reportList" :key="item.no" v-show="current == parseInt(item.no)">
				<!-- 序号：绑定计算属性 parsedMinNum（对应 item.minNum） -->
				<view class="info-row">
					<text class="label">序号</text>
					<view class="value">
						{{getParsedValue(item.no)}}
					</view>
				</view>
				<view class="info-row">
					<text class="label">产品码</text>
					<view class="value">
						{{item.prodno}}
					</view>
				</view>
				<view class="info-row">
					<text class="label">检测项目</text>
					<view class="value">
						{{item.invname}}
					</view>
				</view>
				<view class="info-row">
					<text class="label">性质</text>
					<view class="value">
						<text :class="{
							'bg-yellow bg-text': item.nature == '定量',
						  }">
							{{item.nature}}
						</text>
					</view>
				</view>
				<!-- 上限要求：绑定计算属性 parsedMinNum -->
				<view class="info-row">
					<text class="label">上限要求</text>
					<view class="value">
						{{item.maxNum}}
					</view>
				</view>
				<!-- 下限要求：绑定计算属性 parsedMaxNum（对应 item.maxNum） -->
				<view class="info-row">
					<text class="label">下限要求</text>
					<view class="value">
						{{item.minNum}}
					</view>
				</view>
				<view class="divider"></view>
				<!-- 实测值小：绑定计算属性 parsedMeasuredValue（对应 item.measuredvalue） -->
				<view class="info-row">
					<text class="label">实测值小</text>
					<view class="value">
						<input type="digit" class="surround uni-input number-input" v-model="item.measuredvalue" @confirm="minNumberChange"></input>
					</view>
				</view>
				<!-- 实测值大：绑定计算属性 parsedMeasuredMaxValue（对应 item.measuredvaluemax） -->
				<view class="info-row">
					<text class="label">实测值大</text>
					<view class="value">
						<input type="digit" class="surround uni-input number-input" v-model="item.measuredvaluemax" @confirm="maxNumberChange"></input>
					</view>
				</view>
				<view class="info-row">
					<text class="label">结论</text>
					<view class="value">
						<radio-group class="radio-group-horizontal" @change="resultChange">
							<radio class="radio-group-horizontal-rg" value="合格" :checked="item.result == '合格'" :disabled="item.nature == '定量'">合格</radio>
							<radio class="radio-group-horizontal-rg" value="不合格" :checked="item.result == '不合格'" :disabled="item.nature == '定量'">不合格</radio>
						</radio-group>	
					</view>
				</view>
				<view class="info-row">
					<text class="label">备注</text>
					<view class="value">
						<input v-model="item.memo" class="surround uni-input" @confirm="remarksChange"></input>
					</view>
				</view>
			</view>
		</view>

		<!-- 空状态 -->
		<view v-else class="empty-card">
			<image src="/static/image/empty.png" class="empty-img" />
			<text class="empty-text">暂无检查检验记录</text>
		</view>

		<view class="info-row btn-panel">
			<button class="btn btn-first" @click="tabsClick(current-1)" v-if="current > 1">
				前一项
			</button>
			<button class="btn btn-second" @click="tabsClick(current+1)" v-if="current < maxcount">
				下一项
			</button>
		</view>
	<!-- #ifdef APP -->
	</scroll-view>
	<!-- #endif -->
</template>

<script setup>
	import { ref, computed } from 'vue' // 1. 引入 computed（计算属性核心）
	import { getJoinList, QcRecord, recordStatusDict, updateData } from '@/api/work';
	import { getCurrentUserSync } from '@/utils/auth';

	// 存储页面参数
	let pdid = "";
	let senum = "";
	// 检查项目最大数量（改为 ref 响应式，避免值变化不更新）
	const maxcount = ref(5)
	const current = ref(1)
	const reportList = ref<QcRecord[]>([])
	const initRecords = ref<QcRecord[]>([])

	// 下拉框选项数组 - 定性分析选项
	const array = ref(['合格', '不合格']);
	
	//自定义返回行为，覆盖系统默认返回按钮
	const backPressOptions = reactive({
		from: 'backbutton'
	} as OnBackPressOptions)
	
	onBackPress((options : OnBackPressOptions) : boolean | null => {
		uni.navigateTo({
			url: `/pages/work/download/DownloadDetail?id=${pdid}`,
			// 修改动画方向为从左到右退回
			animationType: 'slide-in-left', // 使用从左到右滑出的动画效果
			animationDuration: 300 // 动画持续时间，单位ms
		})
		// 返回true表示拦截默认返回行为
		return true
	})
	
	const getParsedValue = computed(() => {
		return (value : string | number) => {
			if (typeof value === 'number') {
				return value;
			}
			if (typeof value === 'string') {
				const num = parseFloat(value);
				return isNaN(num) ? 0 : num;
			}
			return 0;
		}
	});

	// 4. 切换标签时更新 reportList（使用响应式的 initRecords）
	const tabsClick = (obj : number) => {
		current.value = obj;
		const filtered = initRecords.value.filter(item =>
			getParsedValue.value(item.no) === current.value
		);
		reportList.value = filtered;
	}

	const refreshRecords = (index : number) => {
		// 清空现有数据（响应式数组需操作 .value）
		initRecords.value = [];
		// #ifdef APP-ANDROID
		getJoinList(
			'app_task_record as r',
			'app_task_record_item as i',
			'r.*,i.*',
			'r.sxid=i.psxid',
			'pdid',
			pdid,
			null
		).then((res : UTSJSONObject) => {
			const dataList = res?.['data'] as UTSJSONObject[] ?? []
			if (dataList.length > 0) {
				dataList.forEach(item => {
					if (item != null) {
						const record = JSON.parse<QcRecord>(item.toJSONString());
						if (record != null) {
							initRecords.value.push(record)
							// 计算 maxcount 时使用数值转换，避免字符串干扰
							const noValue = getParsedValue.value(record.no)
							if (noValue > maxcount.value) {
								maxcount.value = noValue;
							}
						}
					}
				});
			}
			// 对initRecords按照no字段进行升序排序
			if (initRecords.value.length > 0) {
				initRecords.value.sort((a, b) => {
					const noA = getParsedValue.value(a.no);
					const noB = getParsedValue.value(b.no);
					return noA - noB;
				});
				current.value = index > 0 ? index : getParsedValue.value(initRecords.value[0].no);
				const filtered = initRecords.value.filter(item =>
					getParsedValue.value(item.no) === current.value
				);
				reportList.value = filtered;
			}
		});
		// #endif
	}
	
	
	const resultChange = (event : UniRadioGroupChangeEvent) => {
		// 获取当前选中的报告项
		const currentItem = reportList.value.find(item => parseInt(item.no) === current.value);
		if (currentItem != null) {
			// 如果是定量性质，则不允许修改
			if (currentItem.memo == '定量') {
				uni.showToast({
					title: "定量项目不可修改结论",
					icon: 'error',
					duration: 2000
				});
				return;
			}
			// 更新结果值
			currentItem.result = event.detail.value;
			//更新数据库
			let updatedData = "result='" + currentItem.result + "', recorder='" + getCurrentUserSync() + "' "
			console.log(updatedData)
			updateData('app_task_record_item', updatedData, 'sxid', currentItem.sxid.toString()).then((res : UTSJSONObject) => {
				let data = res?.['data'] as boolean ?? false
				if (data != null && data== true) {
					uni.showToast({
						title: "保存成功！",
					});
				}
			});
		}
	}
	
	const minNumberChange = (event : UniInputConfirmEvent) => {
		// 获取当前选中的报告项
		const currentItem = reportList.value.find(item => parseInt(item.no) === current.value);
		if (currentItem != null) {
			// 更新结果值
			currentItem.measuredvalue = event.detail.value;
			let updatedData = "measuredvalue='" + currentItem.measuredvalue + "', recorder='" + getCurrentUserSync() + "' "
			if (currentItem.nature == '定量') {
			// 初始化结果为合格（上下限都为空时保持为合格）
			currentItem.result = '合格';
			// 解析实测值
			const measuredMin = parseFloat(currentItem.measuredvalue ?? '0');
			const measuredMax = parseFloat(currentItem.measuredvaluemax ?? '0');
			
			// 检查下限值（如果有设置）
			if (currentItem.minNum !== '' && currentItem.minNum !== null) {
				const lowerLimit = parseFloat(currentItem.minNum);
				// 下限非空时，实测最大最小值都需>=下限值，否则为不合格
				if (measuredMin < lowerLimit || measuredMax < lowerLimit) {
					currentItem.result = '不合格';
				}
			}
			
			// 检查上限值（如果有设置且当前仍为合格）
			if (currentItem.result === '合格' && currentItem.maxNum !== '' && currentItem.maxNum !== null) {
				const upperLimit = parseFloat(currentItem.maxNum);
				// 上限非空时，实测最大最小值都需<=上限值，否则为不合格
				if (measuredMin > upperLimit || measuredMax > upperLimit) {
					currentItem.result = '不合格';
				}
			}
			
			updatedData += " , result = '" + currentItem.result + "' "
		}
			
			//更新数据库
			updateData('app_task_record_item', updatedData, 'sxid', currentItem.sxid.toString()).then((res : UTSJSONObject) => {
				let data = res?.['data'] as boolean ?? false
				if (data != null && data== true) {
					uni.showToast({
						title: "保存成功！",
					});
				}
			});
		}
	}
	
	const maxNumberChange = (event : UniInputConfirmEvent) => {
		// 获取当前选中的报告项
		const currentItem = reportList.value.find(item => parseInt(item.no) === current.value);
		if (currentItem != null) {
			// 更新结果值
			currentItem.measuredvaluemax = event.detail.value;
			//更新数据库
			let updatedData = "measuredvaluemax='" + currentItem.measuredvaluemax + "', recorder='" + getCurrentUserSync() + "' "
			if (currentItem.nature == '定量') {
				// 初始化结果为合格
				currentItem.result = '合格';
				
				// 解析实测值
				const measuredMin = parseFloat(currentItem.measuredvalue ?? '0');
				const measuredMax = parseFloat(currentItem.measuredvaluemax ?? '0');
				
				// 检查下限值
				if (currentItem.minNum != null && currentItem.minNum != '') {
					const minLimit = parseFloat(currentItem.minNum);
					// 实测最大值和最小值都需要大于等于下限值
					if (measuredMin < minLimit || measuredMax < minLimit) {
						currentItem.result = '不合格';
					}
				}
				
				// 检查上限值
				if (currentItem.result === '合格' && currentItem.maxNum != null && currentItem.maxNum != '') {
					const maxLimit = parseFloat(currentItem.maxNum);
					// 实测最大值和最小值都需要小于等于上限值
					if (measuredMin > maxLimit || measuredMax > maxLimit) {
						currentItem.result = '不合格';
					}
				}
				
				// 如果上下限都为空，结果保持为合格
				updatedData += " ,result = '" + currentItem.result + "', recorder='" + getCurrentUserSync() + "' "
			}
			updateData('app_task_record_item', updatedData, 'sxid', currentItem.sxid.toString()).then((res : UTSJSONObject) => {
				let data = res?.['data'] as boolean ?? false
				if (data != null && data== true) {
					uni.showToast({
						title: "保存成功！",
					});
				}
			});
		}
	}
	
	const remarksChange = (event : UniInputConfirmEvent) => {
		// 获取当前选中的报告项
		const currentItem = reportList.value.find(item => parseInt(item.no) === current.value);
		if (currentItem != null) {
			// 更新结果值
			currentItem.memo = event.detail.value;
			//更新数据库
			let updatedData = "memo='" + currentItem.memo + "', recorder='" + getCurrentUserSync() + "' "
			updateData('app_task_record_item', updatedData, 'sxid', currentItem.sxid.toString()).then((res : UTSJSONObject) => {
				let data = res?.['data'] as boolean ?? false
				if (data != null && data== true) {
					uni.showToast({
						title: "保存成功！",
					});
				}
			});
		}
	}
	
	onLoad((options) => {
		pdid = options?.pdid ?? "1"
		senum = options?.senum ?? "1"
		// 加载初始数据（转换 senum 为数值，避免字符串类型问题）
		refreshRecords(getParsedValue.value(senum))
	});
	
	defineExpose({
		backPressOptions
	})
</script>

<style scoped>
	/* 样式部分保持不变，仅修复标签颜色冲突（tag=3时优先黄色） */
	.container {
		padding: 20px;
		background-color: #f5f7fa;
		flex: 1;
		box-sizing: border-box;
	}

	.banner {
		background: linear-gradient(135deg, #6dd5ed, #2193b0);
		border-radius: 12px;
		padding: 20px 15px;
		margin-bottom: 20px;
		box-shadow: 0 4px 8px rgba(33, 147, 176, 0.3);
	}

	.banner-title {
		color: white;
		font-size: 18px;
		font-weight: bold;
		text-align: center;
	}

	.box {
		width: 20px;
		background-color: #909193;
		border-radius: 7.5px;
	}

	.card-list {
		display: flex;
		flex-direction: column;
	}

	.card-list>.card {
		margin-bottom: 15px;
	}

	/* #ifndef APP-ANDROID */
	.card-list>.card:last-child {
		margin-bottom: 0;
	}

	/* #endif */

	.card {
		background-color: white;
		border-radius: 10px;
		padding: 15px;
		box-shadow: 0 3px 10px rgba(0, 0, 0, 0.05);
		display: flex;
		flex-direction: column;
	}

	.card-header {
		display: flex;
		align-items: center;
		margin-bottom: 20rpx;
	}

	.card-icon {
		width: 64rpx;
		height: 64rpx;
		margin-right: 20rpx;
		border-radius: 12rpx;
		background-color: #eef5ff;
		padding: 10rpx;
	}

	.info-row {
		display: flex;
		flex-direction: row;
		font-size: 14px;
		color: #33475b;
		align-items: center;
		padding: 10px;
	}

	.label {
		font-weight: bold;
		color: #102a43;
		min-width: 75px;
	}

	.value {
		flex: 1;
		white-space: nowrap;
		overflow: hidden;
		text-overflow: ellipsis;
	}

	.divider {
		height: 1px;
		background-color: #eee;
		margin: 10px 0;
	}

	.card-info {
		font-size: 28rpx;
		color: #666;
		line-height: 1.6;
		display: flex;
		flex-direction: column;
	}

	.card-info>.card-info-item {
		margin-bottom: 10rpx;
	}

	/* #ifndef APP-ANDROID */
	.card-info>.card-info-item:last-child {
		margin-bottom: 0;
	}

	/* #endif */
	.btn-group {
		display: flex;
		justify-content: flex-end;
		margin-top: 20rpx;
	}

	.main-btn {
		font-size: 28rpx;
		color: white;
		border: none;
		border-radius: 100rpx;
		background: linear-gradient(to right, #36d1dc, #5b86e5);
		box-shadow: 0 6rpx 16rpx rgba(91, 134, 229, 0.3);
		/* #ifndef APP-ANDROID */
		transition: all 0.2s ease-in-out;
		/* #endif */
	}

	/* #ifndef APP-ANDROID */
	.main-btn:active {
		opacity: 0.9;
		transform: scale(0.98);
	}

	/* #endif */

	.empty-card {
		background-color: white;
		border-radius: 20rpx;
		padding: 60rpx 30rpx;
		box-shadow: 0 6rpx 16rpx rgba(0, 0, 0, 0.05);
		text-align: center;
		margin-top: 100rpx;
	}

	.empty-img {
		width: 180rpx;
		height: 180rpx;
		margin-bottom: 30rpx;
		opacity: 0.8;
	}

	.empty-text {
		font-size: 30rpx;
		color: #999;
	}

	.surround {
		border: 2rpx solid #eee;
		border-radius: 10rpx;
		min-height: 60rpx;
		background-color: #f5f6f7;
	}

	.selectable {
		/* 确保在安卓设备上文字可以正常显示为可点击状态 */
		user-select: text;
		-webkit-user-select: text;
		cursor: pointer;
		/* #ifdef APP-ANDROID */
		/* 安卓设备特别处理，增强可点击性 */
		background-color: #f8f8f8;
		/* #endif */
	}

	.record-card {
		background: #ffffff;
		border-radius: 20rpx;
		padding: 24rpx 32rpx;
		box-shadow: 0 8rpx 15rpx rgba(0, 43, 92, 0.1);
		display: flex;
		flex-direction: column;
		margin-bottom: 20rpx;
		margin-top: 20rpx;
	}
	
	/* 横向排列radio的样式 */
	.radio-group-horizontal {
		display: flex;
		flex-direction: row;
		align-items: center;
	}
	
	.radio-group-horizontal-rg{
		margin-right: 30rpx;
	}

	.flex-row {
		flex-direction: row;
	}

	.tag-circle {
		width: 60rpx;
		height: 60rpx;
		margin: 0 10rpx;
		display: flex;
		justify-content: center;
		align-items: center;
	}

	.circle {
		height: 50rpx;
		width: 50rpx;
		background-color: #004a99;
		text-align: center;
		color: #fff;
		line-height: 50rpx;
		border-radius: 50rpx;
	}

	.checked-tag {
		height: 60rpx;
		width: 60rpx;
		line-height: 60rpx;
		border: 2rpx solid #ffffff;
		box-shadow: 0 0 0 2rpx #007aff;
		position: relative;
		z-index: 10;
	}
	
	.bg-text {
		width: 120rpx;
		min-width: 100rpx;
		border-radius: 10rpx;
		text-align: center;
	}

	.bg-green {
		background-color: seagreen;
	}

	.bg-yellow {
		background-color: yellow;
		color: #333;
		/* 黄色标签加深色文字，避免看不清 */
	}

	.bg-black {
		background-color: #102a43;
	}

	.bg-red {
		background-color: red;
	}

	.btn-panel {
		position: relative;
		width: 100%;
		height: 90rpx;
		overflow: visible;
	}

	.btn {
		position: absolute;
		height: 70rpx;
		line-height: 70rpx;
		padding: 0 20rpx;
		top: 50%;
		transform: translateY(-50%);
		background-color: #00aaff;
		color: #fff;
		border: 0 none;
		border-radius: 25rpx;
	}

	.btn-first {
		left: 15rpx;
	}

	.btn-second {
		right: 15rpx;
	}
	
	.number-input {
		width: 50%;
	}
	
</style>