<template>
	<view v-if="visible" class="popup-overlay" :class="{ 'popup-overlay-enter': showAnimation }">
		<view class="popup-fixed" :class="{ 'popup-scale-enter': showAnimation }">
			<view class="popup-container-bg">
				<image src="/static/printbg.png" class="popup-bg-image" mode="aspectFill"></image>
				<view class="popup-container">
					<!-- 加载状态 -->
					<view class="loading-container" v-if="isLoading">
						<image class="loading-gif" src="/static/Loading.gif" mode="aspectFit"></image>
						<text class="loading-text">加载中...</text>
					</view>
					<!-- 无数据状态 -->
					<view class="empty-container" v-else-if="!isLoading && items.length == 0">
						<image class="empty-image" src="/static/error_black.png" mode="aspectFit"></image>
						<text class="empty-text">暂无排队数据</text>
					</view>
					<!-- 数据内容 -->
					<scroll-view class="list-scroll" v-else direction="vertical" @scrolltolower="handleScrollToLower"
						lower-threshold="50">
						<view v-for="(item,idx) in items" :key="item.id" class="queue-row"
							@click="handleItemClick(item)">
							<view class="thumb-wrap"
								:class="{ 'thumb-active': (idx as Int) == 0 && item.status.value == 'printing' }">
								<image class="thumb-image" :src="sanitize(item.works_image)" mode="aspectFill"></image>
								<image v-if="item.goods_front_image" class="front-image-overlay"
									:src="sanitize(item.goods_front_image)" mode="aspectFill"></image>
							</view>
							<view class="row-right">
								<view class="info-column">
									<text class="goods-name">{{ item.goods_name }}</text>
									<text class="queue-text" :class="{ 'queue-text-printing': item.status.value == 'printing' }">{{ item.status.label }}</text>
								</view>
							</view>
						</view>
						<!-- 加载更多状态 -->
						<view class="loadmore-container" v-if="isLoadingMore">
							<image class="loadmore-gif" src="/static/Loading.gif" mode="aspectFit"></image>
							<text class="loadmore-text">加载中...</text>
						</view>
						<!-- 没有更多数据 -->
						<view class="nomore-container" v-if="!hasMore && items.length > 0">
							<text class="nomore-text">没有更多数据了</text>
						</view>
					</scroll-view>
				</view>
			</view>
			<view class="close-button" @click="handleClose">
				<image src="/static/icon_close.png" class="close-icon"></image>
			</view>
		</view>
	</view>
</template>

<script setup lang="uts">
	import { queueList, type ResponseData } from '../../utils/reques.uts'

	// 队列项与状态的严格类型
	type QueueStatus = {
		label : string
		value : string
		css_class : string | null
		list_class : string | null
	}

	type QueueItem = {
		id : number
		order_id : number
		works_id : number
		works_image : string
		status : QueueStatus
		goods_name : string
		goods_front_image : string
		goods_design_color : string
	}

	interface PopupPrintListProps {
		visible : boolean
		closeOnOverlay : boolean
	}

	interface Emits {
		(e : 'close') : void
	}

	const props = withDefaults(defineProps<PopupPrintListProps>(), {
		visible: false,
		closeOnOverlay: false
	})

	const emit = defineEmits<Emits>()

	const showAnimation = ref(false)
	const items = ref<Array<QueueItem>>([])
	const isLoading = ref<boolean>(false)
	const reqToken = ref<number>(0)
	const page = ref<number>(1)
	const limit = ref<number>(10)
	const hasMore = ref<boolean>(true)
	const isLoadingMore = ref<boolean>(false)

	// 安全清理包裹的引号或反引号
	const sanitize = (s : string) : string => {
		let t : string = s.trim()
		if (t.length == 0) return t
		const startCode = t.charCodeAt(0)
		if (startCode != null) {
			const sc = startCode as number
			if (sc == 96 || sc == 34 || sc == 39) {
				t = t.substring(1)
			}
		}
		if (t.length > 0) {
			const endCode = t.charCodeAt(t.length - 1)
			if (endCode != null) {
				const ec = endCode as number
				if (ec == 96 || ec == 34 || ec == 39) {
					t = t.substring(0, t.length - 1)
				}
			}
		}
		return t.trim()
	}

	const fetchQueue = async (isLoadMore : boolean) : Promise<void> => {
		if (isLoadMore) {
			if (!hasMore.value || isLoadingMore.value) {
				return
			}
			isLoadingMore.value = true
		} else {
			isLoading.value = true
		}

		const current : number = reqToken.value + 1
		reqToken.value = current
		const params = {
			page: page.value,
			limit: limit.value
		} as UTSJSONObject

		try {
			const res = await queueList(params) as ResponseData
			if (current != reqToken.value) {
				return
			}
			if (res.code == 0) {
				const arr = (res.data as Array<any>) ?? []
				const out : Array<QueueItem> = []
				for (let i = 0; i < arr.length; i++) {
					const it = arr[i] as UTSJSONObject
					const stObj = it.getAny('status') as UTSJSONObject | null
					const st : QueueStatus = {
						label: stObj != null ? (stObj.getString('label') ?? '') : '',
						value: stObj != null ? (stObj.getString('value') ?? '') : '',
						css_class: stObj != null ? (stObj.getString('css_class') ?? null) : null,
						list_class: stObj != null ? (stObj.getString('list_class') ?? null) : null
					}
					const worksObj = it.getAny('works') as UTSJSONObject | null
					const goodsObj = worksObj != null ? (worksObj.getAny('goods') as UTSJSONObject | null) : null
					const qItem : QueueItem = {
						id: it.getNumber('id') ?? 0,
						order_id: it.getNumber('id') ?? 0,
						works_id: it.getNumber('works_id') ?? 0,
						works_image: sanitize(it.getString('works_image') ?? ''),
						status: st,
						goods_name: goodsObj != null ? (goodsObj.getString('name') ?? '') : '',
						goods_front_image: goodsObj != null ? sanitize(goodsObj.getString('front_image') ?? '') : '',
						goods_design_color: goodsObj != null ? (goodsObj.getString('design_color') ?? '') : ''
					}
					out.push(qItem)
				}

				if (isLoadMore) {
					items.value = items.value.concat(out)
				} else {
					items.value = out
				}

				// 判断是否还有更多数据
				if (arr.length < limit.value) {
					hasMore.value = false
				} else {
					hasMore.value = true
				}
			}
		} catch (e) {
			if (current == reqToken.value) {
				uni.showToast({ title: '获取队列失败', icon: 'none' })
			}
		} finally {
			if (current == reqToken.value) {
				isLoading.value = false
				isLoadingMore.value = false
			}
		}
	}

	const resetState = () : void => {
		showAnimation.value = false
		items.value = []
		isLoading.value = false
		isLoadingMore.value = false
		reqToken.value = reqToken.value + 1
		page.value = 1
		hasMore.value = true
	}

	watch(() : boolean => props.visible, (nv : boolean) : void => {
		if (nv) {
			isLoading.value = true
			nextTick(() => { showAnimation.value = true })
			fetchQueue(false)
		} else {
			resetState()
		}
	})

	const handleOverlayClick = () : void => {
		if (props.closeOnOverlay === true) {
			emit('close')
		}
	}

	const handleContentClick = () : void => {
		// 阻止冒泡
	}

	const handleClose = () : void => {
		resetState()
		emit('close')
	}

	const handleItemClick = (item : QueueItem) : void => {
		// 构造要传递的数据对象
		const workData = {
			works_id: item.works_id,
			image: item.works_image,
			order_id: item.order_id,
			status: item.status.value,
			status_label: item.status.label,
			goods: {
				name: item.goods_name,
				front_image: item.goods_front_image,
				design_color: item.goods_design_color
			}
		}
		// 将数据转换为 JSON 字符串并编码
		const workStr = encodeURIComponent(JSON.stringify(workData))
		// 跳转到 printlist 页面
		uni.navigateTo({
			url: `/pages/printlist/index?work=${workStr}`
		})
		// 关闭弹窗
		emit('close')
	}

	const handleScrollToLower = () : void => {
		if (hasMore.value && !isLoadingMore.value) {
			page.value = page.value + 1
			fetchQueue(true)
		}
	}

	onUnmounted(() => {
		resetState()
	})
</script>

<style>
	/* 遮罩与弹窗过渡 */
	.popup-overlay {
		position: fixed;
		top: 0;
		left: 0;
		width: 100%;
		height: 100%;
		background-color: rgba(0, 0, 0, 0);
		z-index: 9999;
		display: flex;
		justify-content: center;
		align-items: center;
		transition: background-color 0.3s ease;
	}

	.popup-overlay-enter {
		background-color: rgba(0, 0, 0, 0.5);
	}

	.popup-fixed {
		margin-top: 50rpx;
		display: flex;
		justify-content: center;
		align-items: center;
		flex-direction: column;
		transform: scale(0.7);
		transition: transform 0.3s cubic-bezier(0.25, 0.8, 0.25, 1);
	}

	.popup-scale-enter {
		transform: scale(1);
	}

	.popup-container {
		width: 90%;
		height: 537.92rpx;
		position: relative;
		z-index: 2;
		display: flex;
		flex-direction: column;
	}

	.popup-container-bg {
		display: flex;
		justify-content: center;
		position: relative;
		width: 497.22rpx;
		height: 633.33rpx;
		align-items: center;
	}

	.popup-bg-image {
		position: absolute;
		top: 0;
		left: 0;
		width: 100%;
		height: 100%;
	}

	.list-scroll {
		flex: 1;
		width: 100%;
	}

	/* 加载状态样式 */
	.loading-container {
		width: 100%;
		height: 100%;
		display: flex;
		flex-direction: column;
		align-items: center;
		justify-content: center;
	}

	.loading-gif {
		width: 120rpx;
		height: 120rpx;
		margin-bottom: 15rpx;
	}

	.loading-text {
		font-size: 28rpx;
		color: #999999;
	}

	/* 无数据状态样式 */
	.empty-container {
		width: 100%;
		height: 100%;
		display: flex;
		flex-direction: column;
		align-items: center;
		justify-content: center;
	}

	.empty-image {
		width: 120rpx;
		height: 120rpx;
		margin-bottom: 15rpx;
	}

	.empty-text {
		font-size: 28rpx;
		color: #999999;
	}

	.queue-row {
		display: flex;
		flex-direction: row;
		align-items: center;
		justify-content: space-between;
		background-color: #FDE8F3;
		border-radius: 18rpx;
		padding: 20rpx;
		margin-bottom: 20rpx;
	}

	.thumb-wrap {
		width: 120rpx;
		height: 120rpx;
		border-radius: 12rpx;
		border: 2rpx dashed rgba(0, 0, 0, 0);
		display: flex;
		justify-content: center;
		align-items: center;
		background-color: #FFFFFF;
		position: relative;
	}

	.thumb-active {
		border-color: #FF86C3;
	}

	.thumb-image {
		width: 110rpx;
		height: 110rpx;
		border-radius: 8rpx;
	}

	.front-image-overlay {
		position: absolute;
		width: 110rpx;
		height: 110rpx;
		border-radius: 8rpx;
		top: 50%;
		left: 50%;
		transform: translate(-50%, -50%);
	}

	.row-right {
		flex: 1;
		display: flex;
		flex-direction: row;
		justify-content: flex-end;
		align-items: center;
		margin-left: 20rpx;
	}

	.info-column {
		display: flex;
		flex-direction: column;
		align-items: flex-end;
	}

	.goods-name {
		font-size: 28rpx;
		color: #333333;
	}

	.printing-btn {
		width: 160rpx;
		height: 64rpx;
		background: linear-gradient(to bottom, #FD3C9F, #FCA7D3);
		border-radius: 32rpx;
		font-weight: bold;
		font-size: 26rpx;
		color: #FFFFFF;
		line-height: 64rpx;
		border: none;
	}

	.queue-text {
		font-size: 26rpx;
		color: #FD3C9F;
		margin-top: 8rpx;
	}

	.queue-text-printing {
		color: #00C853;
	}

	/* 关闭按钮 */
	.close-button {
		margin-top: 21rpx;
		width: 48rpx;
		height: 48rpx;
		box-shadow: 0 2rpx 8rpx rgba(0, 0, 0, 0.3);
		border-radius: 25rpx;
		display: flex;
		justify-content: center;
		align-items: center;
	}

	/* 关闭图标 */
	.close-icon {
		width: 48rpx;
		height: 48rpx;
	}

	/* 加载更多状态样式 */
	.loadmore-container {
		width: 100%;
		padding: 20rpx 0;
		display: flex;
		flex-direction: row;
		align-items: center;
		justify-content: center;
	}

	.loadmore-gif {
		width: 40rpx;
		height: 40rpx;
		margin-right: 10rpx;
	}

	.loadmore-text {
		font-size: 24rpx;
		color: #999999;
	}

	/* 没有更多数据样式 */
	.nomore-container {
		width: 100%;
		padding: 20rpx 0;
		display: flex;
		align-items: center;
		justify-content: center;
	}

	.nomore-text {
		font-size: 24rpx;
		color: #CCCCCC;
	}
</style>