<template>
	<uni-navbar-lite :showRight="false" title="物料详情" @clickLeft="goBack"></uni-navbar-lite>
	<view class="page-container">
		<scroll-view class="detail-content" scroll-y="true">
			<!-- 基本信息 -->
			<view class="detail-section">
				<view class="section-title">基本信息</view>
				<view class="info-row">
					<text class="info-label">物料名称</text>
					<text class="info-value">{{ getDisplayText(itemDetail.itemName) }}</text>
				</view>
				<view class="info-row">
					<text class="info-label">物料编号</text>
					<text class="info-value">{{ getDisplayText(itemDetail.itemCode) }}</text>
				</view>
				<view class="info-row">
					<text class="info-label">规格型号</text>
					<text class="info-value">{{ getDisplayText(itemDetail.specification) }}</text>
				</view>
				<view class="info-row">
					<text class="info-label">单位</text>
					<text class="info-value">{{ getDisplayText(itemDetail.measureName) }}</text>
				</view>
				<view class="info-row">
					<text class="info-label">状态</text>
					<text class="info-value status-tag" :class="'status-' + itemDetail.auditStatus">{{ getStatusText(itemDetail.auditStatus) }}</text>
				</view>
			</view>
			
			<!-- 产品信息 -->
			<view class="detail-section">
				<view class="section-title">产品信息</view>
				<view class="info-row">
					<text class="info-label">产品链接</text>
					<text class="info-value link-value" @click="openProductUrl" v-if="hasProductUrl === true">{{ itemDetail.productUrl }}</text>
					<text class="info-value" v-else>-</text>
				</view>
			</view>
			
			<!-- 图片信息 -->
			<view class="detail-section" v-if="hasImages === true">
				<view class="section-title">物料图片</view>
				<view class="image-list">
					<view 
						class="image-item" 
						v-for="(img, index) in imageList" 
						:key="index"
						@click="previewImage(index)"
					>
						<image class="material-image" :src="img" mode="aspectFill"></image>
					</view>
				</view>
			</view>
		</scroll-view>
	</view>
</template>

<script setup lang="uts">
	import { ref, computed, onMounted } from 'vue'
	import { getItemDetail } from '../../api/item/index'
	import { getBaseUrl } from '../../utils/request'

	// 图片基础路径
	const getImageUrl = (filename: string): string => {
		if (filename == null || filename.length === 0) {
			return ''
		}
		// 如果已经是完整URL，直接返回
		if (filename.startsWith('http://') || filename.startsWith('https://')) {
			return filename
		}
		// 添加服务器地址和资源路径前缀
		const baseUrl = getBaseUrl()
		// baseUrl已经是 http://192.168.189.43:83，添加prod-api/resource/
		return baseUrl + filename
	}

	type ItemDetail = {
		itemId: string
		itemName: string
		itemCode: string
		specification: string
		measureName: string
		productUrl: string
		imageUrls: string
		auditStatus: number
	}

	const itemDetail = ref<ItemDetail>({
		itemId: '',
		itemName: '',
		itemCode: '',
		specification: '',
		measureName: '',
		productUrl: '',
		imageUrls: '',
		auditStatus: 0
	})

	const imageList = ref<string[]>([])

	const hasProductUrl = ref<boolean>(false)

	const hasImages = ref<boolean>(false)

	const getDisplayText = (value: string): string => {
		if (value == null || value.length === 0) {
			return '-'
		}
		return value
	}

	// 获取状态文本
	const getStatusText = (status: number): string => {
		if (status == 0) {
			return '待审核'
		} else if (status == 1) {
			return '已审核'
		} else if (status == 2) {
			return '已禁用'
		} else if (status == 3) {
			return '已拒绝'
		}
		return '未知'
	}

	// 打开产品链接
	const openProductUrl = (): void => {
		if (hasProductUrl.value === true) {
			const url = itemDetail.value.productUrl
			if (url.length > 0) {
				// 使用webview组件打开外部链接
				uni.navigateTo({
					url: '/pages/webview/webview?url=' + encodeURIComponent(url)
				})
			}
		}
	}

	// 预览图片
	const previewImage = (index: number): void => {
		uni.previewImage({
			urls: imageList.value,
			current: index
		})
	}

	// 返回上一页
	const goBack = (): void => {
		uni.navigateBack()
	}

	// 加载物料详情
	const loadItemDetail = (): void => {
		const pages = getCurrentPages()
		const currentPage = pages[pages.length - 1]
		const options = currentPage.options
		let itemId: string = ''
		if (options != null) {
			const id = options['id']
			if (id != null) {
				itemId = id.toString()
			}
		}
		
		console.log('itemId:', itemId)
		
		if (itemId.length === 0) {
			uni.showToast({ title: '参数错误: ' + itemId, icon: 'none' })
			return
		}

		getItemDetail(itemId).then((res: any) => {
			console.log('API response:', JSON.stringify(res))
			let ret: UTSJSONObject = res as UTSJSONObject
			let data: UTSJSONObject = ret['data'] as UTSJSONObject
			
			console.log('item data:', JSON.stringify(data))
			
			// 检查是否有数据
			if (data['itemId'] == null && data['itemName'] == null) {
				uni.showToast({ title: '未找到物料', icon: 'none' })
				return
			}
			const detail: ItemDetail = {
				itemId: data['itemId'] != null ? data['itemId'].toString() : '',
				itemName: data['itemName'] != null ? data['itemName'].toString() : '',
				itemCode: data['itemCode'] != null ? data['itemCode'].toString() : '',
				specification: data['specification'] != null ? data['specification'].toString() : '',
				measureName: data['measureName'] != null ? data['measureName'].toString() : '',
				productUrl: data['productUrl'] != null ? data['productUrl'].toString() : '',
				imageUrls: data['imageUrls'] != null ? data['imageUrls'].toString() : '',
				auditStatus: data['auditStatus'] != null ? parseInt(data['auditStatus'].toString()) : 0
			}
			itemDetail.value = detail

			// 判断是否有产品链接
			if (itemDetail.value.productUrl.length > 0) {
				hasProductUrl.value = true
			}

			// 处理图片
			const imageUrls = itemDetail.value.imageUrls
			console.log('raw imageUrls:', imageUrls)
			if (imageUrls.length > 0) {
				const urls = imageUrls.split(',')
				const validUrls: string[] = []
				for (let i = 0; i < urls.length; i++) {
					const url = urls[i].trim()
					if (url.length > 0) {
						// 添加服务器前缀
						const fullUrl = getImageUrl(url)
						validUrls.push(fullUrl)
					}
				}
				imageList.value = validUrls
				console.log('processed imageUrls:', JSON.stringify(validUrls))
				if (validUrls.length > 0) {
					hasImages.value = true
				}
			}
		}).catch((e) => {
			console.error('加载物料详情失败', e)
			uni.showToast({ title: '加载失败', icon: 'none' })
		})
	}

	onMounted(() => {
		loadItemDetail()
	})
</script>

<style lang="scss">
	.page-container {
		flex: 1;
		background-color: #f5f8fe;
		padding-top: env(safe-area-inset-top);
		padding: 20rpx 20rpx 20rpx 20rpx;
	}

	.detail-content {
		padding-bottom: 40rpx;
	}

	.detail-section {
		background-color: #ffffff;
		border-radius: 16rpx;
		padding: 30rpx;
		margin-bottom: 20rpx;
	}

	.section-title {
		font-size: 32rpx;
		font-weight: bold;
		color: #333333;
		margin-bottom: 20rpx;
		padding-bottom: 20rpx;
		border-bottom: 1rpx solid #f0f0f0;
	}

	.info-row {
		flex-direction: row;
		justify-content: space-between;
		align-items: center;
		padding: 20rpx 0;
		border-bottom: 1rpx solid #f5f5f5;
	}

	.info-row:last-child {
		border-bottom: none;
	}

	.info-label {
		font-size: 28rpx;
		color: #666666;
	}

	.info-value {
		font-size: 28rpx;
		color: #333333;
		font-weight: 500;
	}

	.link-value {
		color: #007aff;
		flex: 1;
		text-align: right;
		margin-left: 20rpx;
		overflow: hidden;
		text-overflow: ellipsis;
		white-space: nowrap;
	}

	.status-tag {
		padding: 6rpx 16rpx;
		border-radius: 8rpx;
		font-size: 24rpx;
	}

	.status-0 {
		background-color: #fff7e6;
		color: #fa8c16;
	}

	.status-1 {
		background-color: #e6f7ff;
		color: #1890ff;
	}

	.status-2 {
		background-color: #f5f5f5;
		color: #999999;
	}

	.status-3 {
		background-color: #f6ffed;
		color: #52c41a;
	}

	.image-list {
		flex-direction: row;
		flex-wrap: wrap;
		gap: 20rpx;
	}

	.image-item {
		width: 200rpx;
		height: 200rpx;
		border-radius: 12rpx;
		overflow: hidden;
	}

	.material-image {
		width: 100%;
		height: 100%;
	}
</style>
