<template>
	<scroll-view class="tag-scroll-container" scroll-x="true">
		<view class="record-card2 flex-row">
			<view class="tag-circle" v-for="(item, index) in initRecords" :key="index" @click="tabsClick(item.senum)"
				:class="{'checked-tag' : item.senum == current}">
				<text class="circle" :class="{
								'bg-green': item.status == 3,
								'bg-yellow': item.status == 2,
								'bg-red': item.status == 4,
								'bg-black': item.status == 1
							  }">{{item.senum}}</text>
			</view>
		</view>
	</scroll-view>

	<!-- #ifdef APP -->
	<scroll-view style="flex:1">
	<!-- #endif -->
		<view class="record-card" v-for="(item, index) in records" :key="index"
			v-show="current == item.senum as number">
			<view class="header-row">
				<text class="label">序号：</text>
				<text class="value">{{ item.senum }}</text>
				<text class="status"
					:class="{'status-cancelled': item.status === 5, 'bg-red': item.status == 4}">{{ recordStatusDict[item.status.toString()] }}</text>
			</view>

			<view class="info-row">
				<text class="label">产品码：</text>
				<text class="value">{{ item.productno }}</text>
			</view>

			<view class="info-row">
				<text class="label">拍照点：</text>
				<text class="value">{{ item.photoitem }}</text>
			</view>

			<view class="info-row">
				<text class="label">拍照位置：</text>
				<text class="value">{{ item.part }}</text>
			</view>

			<view class="info-row">
				<text class="label">描述：</text>
				<text class="value">{{ item.descb }}</text>
			</view>

			<view class="info-row">
				<text class="label">位置编号：</text>
				<text class="value">{{ item.partno }}</text>
			</view>

			<view class="info-row">
				<text class="label">数量：</text>
				<text class="" :class="{'bg-yellow bg-text': item.num > 1}">{{ item.num }}</text>
			</view>

			<button class="cancel-btn" v-if="item.status == 1 || item.status == 2" @click="cancel(item.sxid, item.senum, maxcount)">
				拍照
			</button>

			<view class="tag-banner" style="">
				<view class="tag-banner" v-for="(tag,index) in item.imgname" :key="index" v-if="item.imgname.length>0">
					<text class="img-banner" v-if="item.imgname[index]!=''&& closeTags[index]"
						@click="closeTag(index)">{{tag}}</text>
				</view>

			</view>
			<view class="my-page">
				<swiper class="swiper-box my-swiper" :current="0" :indicator-dots="true" v-if="item.urlpdt.length>0" :key="'photo-'+item.sxid">
					<swiper-item v-for="(url, index) in item.urlpdt" :key="index" @tap="preview(uni.env.USER_DATA_PATH+url)">
						<view class="swiper-item ">
							<image class="my-image" :src="uni.env.USER_DATA_PATH+url" mode="aspectFill" />
						</view>
						<view v-if="item.imgname.length>0">
							<text class="demo-view-label">{{ item.imgname?.[index] ?? ''}}</text>
						</view>
					</swiper-item>
				</swiper>

				<swiper class="swiper-box my-swiper mg-top" :current="0" :indicator-dots="true"
					v-if="item.urlspl.length>0" :key="'example-'+item.sxid">
					<swiper-item v-for="(url, index) in item.urlspl" :key="index" @tap="preview(url)" >
						<view class="swiper-item ">
							<image class="my-image" :src="url" mode="aspectFill" />
						</view>
					</swiper-item>
				</swiper>

				<view v-if="item.urlspl">
					<text class="demo-view-label">样张</text>
				</view>
			</view>

		</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
	} from 'vue'
	import { getList, Record, recordStatusDict, updateData } from '@/api/work';

	// 存储页面参数
	let part = "";
	let pid = "";
	let senum = "";

	//自定义返回行为，覆盖系统默认返回按钮
	const backPressOptions = reactive({
		from: 'backbutton'
	} as OnBackPressOptions)

	onBackPress((options : OnBackPressOptions) : boolean | null => {
		console.log('onBackPress', options)
		uni.navigateTo({
			url: `/pages/work/record/InfoDetail?id=${pid}`,
			// 修改动画方向为从左到右退回
			animationType: 'slide-in-left', // 使用从左到右滑出的动画效果
			animationDuration: 300 // 动画持续时间，单位ms
		})
		// 返回true表示拦截默认返回行为
		return true
	})

	//检查项目最大数量
	var maxcount = 5
	var current = ref(1)
	var records = ref<Record[]>([]);
	const closeTags = ref<boolean[]>([]);
	var initRecords = [] as Record[]
	let canEdit = ref<boolean>(true)

	// 定义数据刷新函数
	const refreshRecords = (index : number) => {
		// 清空现有数据
		initRecords = [];
		closeTags.value = [];

		// #ifdef APP-ANDROID
		getList('app_media_record', 'part', part, 'pid', pid, null).then((res : UTSJSONObject) => {
			let dataList = res?.['data'] as UTSJSONObject[] ?? Array<UTSJSONObject>()
			if (dataList != null && dataList.length > 0) {
				let index = 1
				dataList.forEach(item => {
					if (item != null) {
						const imgnameStr = item?.['imgname'] as string ?? ''
						const urlpdtStr = item?.['urlpdt'] as string ?? ''
						const urlsplStr = item?.['urlspl'] as string ?? ''
						const uploadFlag = parseInt(item?.['uploadFlag'] as string ?? '0')
						if(uploadFlag == 1) {
							canEdit.value = false;
						}
						const imgnameArr = imgnameStr.indexOf(",") > -1 ? imgnameStr.split(",") : (imgnameStr != '' ? [imgnameStr] : [])
						const urlpdtArr = urlpdtStr.indexOf(",") > -1 ? urlpdtStr.split(",") : (urlpdtStr != '' ? [urlpdtStr] : [])
						const urlsplArr = urlsplStr.indexOf(",") > -1 ? urlsplStr.split(",") : (urlsplStr != '' ? [urlsplStr] : [])
						item['imgname'] = imgnameArr
						item['urlpdt'] = urlpdtArr
						item['urlspl'] = urlsplArr
						item['senum'] = index
						let record = JSON.parse<Record>(item.toJSONString());
						if (record != null) {
							for (let i : Int = 0; i < record.num; i++) {
								closeTags.value.push(true)
							}
							initRecords.push(record)
						}
						index++
					}
				});
				maxcount = index-1;
			}
			if (initRecords.length > 0) {
				if (index > 0) {
					current.value = index
				} else {
					current.value = initRecords[0].senum
				}
				records.value = initRecords.filter(item => item['senum'] == current.value)
			}
		});
		// #endif
	}



	onLoad((options) => {
		part = options?.part ?? ""
		const num = options?.num ?? "1"
		pid = options?.pid ?? "1"
		senum = options?.senum ?? "1"
		maxcount = parseInt(num)

		// 加载初始数据
		refreshRecords(parseInt(senum));
	});


	const tabsClick = (obj : number) => {
		current.value = obj
		records.value = initRecords.filter(item => item['senum'] == current.value)
	}
	const closeTag = (index : number) => {
		let record = records.value[0]
		if(!canEdit.value){
			uni.showToast({
			  title: "已上传的图片无法删除",
			  icon: 'error', 
			});
			return;
		}

		uni.showModal({
			title: '系统提示',
			content: '确认是否删除图片',
			cancelText: '取消',
			confirmText: '确定',
			success: function (res) {
				if (res.confirm) {
					closeTags.value[index] = false
					let imgname = record.imgname.filter((img, i) => i != index)
					let urlpdt = record.urlpdt.filter((url, i) => i != index)
					let updatedData = ''
					if (imgname.length != urlpdt.length) {
						uni.showToast({
							title: '图片数据不正确',
							icon: 'error',
							duration: 2000
						});
						return;
					}
					console.log(urlpdt)
					if (imgname.length == 0 && urlpdt.length == 0) {
						updatedData = "imgname='',urlpdt=''"
					} else if (imgname.length == 1 && urlpdt.length == 1) {
						updatedData = "imgname='" + imgname[0] + "',urlpdt='" + urlpdt[0] + "'"
					} else {
						updatedData = "imgname='" + imgname.join(",") + "',urlpdt='" + urlpdt.join(",") + "'"
					}

					if (imgname.length == 0) {
						updatedData += ',status=1  '
					} else if (imgname.length < record.num) {
						updatedData += ',status=2 '
					} else if (imgname.length + 1 == record.num){
						updatedData += ',status=3 '
					}

					updateData('app_media_record', updatedData, 'sxid', record.sxid.toString()).then((res : UTSJSONObject) => {
						let dataRes = res?.['data'] as boolean ?? false
						if (dataRes) {
							uni.showToast({
								title: "删除成功！",
							});
							// 刷新页面数据
							refreshRecords(record.senum);
						}
					});
				}
			}
		})
	}

	const preview = (imageUrl : string) => {
		uni.previewImage({
			urls: [imageUrl], // 需要预览的图片链接列表
			current: 0, // 当前显示图片的索引
			indicator: 'number', // 图片指示器样式
			loop: false // 是否可循环预览
		});
	}

	const cancel = (id : number, num : number, maxcount : number) => {
		uni.navigateTo({
			url: `/pages/work/record/Camera?id=${id}&senum=${num}&maxcount=${maxcount}`
		})
	}
	defineExpose({
		backPressOptions
	})
</script>

<style scoped>
	.container {
		padding: 24rpx;
		background-color: #f0f4f8;
		flex: 1;
		display: flex;
		flex-direction: column;
		font-family: "PingFang SC", "Helvetica Neue", Helvetica, Arial, sans-serif;
		/* #ifndef APP-ANDROID */
		min-height: 100vh;
		/* #endif */
	}

	.banner {
		background: linear-gradient(135deg, #6dd5ed, #2193b0);
		border-radius: 24rpx;
		padding: 40rpx 30rpx;
		margin-bottom: 40rpx;
		box-shadow: 0 8rpx 16rpx rgba(33, 147, 176, 0.3);
	}

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

	/* 卡片整体 */
	.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: 15rpx;
		margin-top: 10rpx;
	}

	/* 卡片整体 */
	.record-card2 {
		background: #ffffff;
		border-radius: 20rpx;
		padding: 24rpx 32rpx;
		display: flex;
		flex-direction: column;
		margin-bottom: 20rpx;
		margin-top: 20rpx;
	}

	/* 头部：科室 和 状态 */
	.header-row {
		display: flex;
		flex-direction: row;
		justify-content: space-between;
		align-items: center;
	}

	.department {
		font-size: 32rpx;
		font-weight: 700;
		color: #004a99;
	}

	.status {
		font-size: 28rpx;
		color: #1890ff;
		padding: 6rpx 18rpx;
		border-radius: 16rpx;
		background-color: #e6f7ff;
	}

	.status-cancelled {
		color: #ff4d4f;
		background-color: #fff1f0;
	}

	/* 信息行 */
	.info-row {
		display: flex;
		flex-direction: row;
		/* #ifdef H5 */
		font-size: 28rpx;
		color: #33475b;
		/* #endif */
		align-items: center;
	}

	.label {
		color: #102a43;
		min-width: 100rpx;
		width: 180rpx;
		line-height: 1.5;
	}

	.value {
	flex: 1;
	word-break: break-all;
	word-wrap: break-word;
	}	

	.fee {
		color: #fa541c;
		font-weight: 700;
	}

	/* 取消按钮 */
	.cancel-btn {
		align-self: flex-end;
		background-color: #ff4d4f;
		color: #fff;
		border: none;
		border-radius: 32rpx;
		padding: 5rpx 30rpx;
		font-size: 28rpx;
		font-weight: 700;
	}

	.cancel-btn:hover {
		background-color: #d9363e;
	}

	.cancel-btn:active {
		background-color: #a93232;
	}

	.swiper {
		height: 300rpx;
		margin: 20rpx 0;
	}

	.swiper-box {
		height: 500rpx;
	}

	.swiper-item {
		/* #ifndef APP-NVUE */
		display: flex;
		/* #endif */
		flex-direction: column;
		justify-content: center;
		align-items: center;
		color: #fff;
		height: 500rpx;
		line-height: 300rpx;
	}

	.my-page {
		display: flex;
		flex-direction: column;
		box-sizing: border-box;
		background-color: #fff;
		/* #ifndef APP-ANDROID */
		min-height: 100%;
		/* #endif */
		height: 100%;
	}

	.flex-row {
		flex-direction: row;
		flex-wrap: nowrap;
		width: auto;
		/* #ifdef H5 */
		min-width: 100%;
		/* #endif */
		/* 确保容器宽度至少为屏幕宽度 */
	}

	.demo-view-label {
		text-align: center;
		color: #102a43;
		line-height: 1.5;
		margin-top: 5rpx;
	}

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

	.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-green {
		background-color: seagreen;
	}

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

	.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;
	}

	/* 安卓兼容的滚动容器样式 */
	.tag-scroll-container {
		width: 100%;
		overflow-x: auto;
		overflow-y: hidden;
		-webkit-overflow-scrolling: touch;
		box-sizing: border-box;
		padding: 10rpx 15rpx;
		white-space: nowrap;
		display: flex;
		flex-direction: row;
	}


	.tag-scroll-container::-webkit-scrollbar-thumb {
		background-color: rgba(0, 0, 0, 0.2) !important;
		border-radius: 3rpx !important;
	}

	.img-banner {
		height: 50rpx;
		width: 100%;
		background-color: #004a99;
		text-align: center;
		color: #fff;
		line-height: 50rpx;
		border-radius: 10rpx;
		margin-left: 2rpx;
		font-size: 12px;
		padding: 0 10rpx;
	}

	.tag-banner {
		flex-direction: column;
		flex-wrap: wrap;
		margin: 4px 0;
		font-size: 12px;
	}

	.mg-top {
		margin-top: 20rpx;
	}
	
	.bg-text {
		width: 120rpx;
		min-width: 120rpx;
		border-radius: 10rpx;
		text-align: center;
	}
</style>