<template>
	<view class="container">
		<!-- 详情卡片 -->
		<view class="detail-card">
			<view class="card-header">报销申请详情</view>
			<view class="detail-content">
				<!-- 加载状态 -->
				<view v-if="loading" class="loading">正在加载详情...</view>
				
				<!-- 错误状态 -->
				<view v-else-if="error" class="error-state">
					<view>{{ error }}</view>
					<u-button class="retry-btn" @click="retryLoad" type="primary" size="small">重试</u-button>
				</view>
				
				<!-- 详情内容 -->
				<view v-else-if="detailData" class="info-sections">
					<!-- 基本信息 -->
					<view class="info-section">
						<view class="section-title">基本信息</view>
						<view class="info-grid">
							<view class="info-item">
								<text class="info-label">申请人</text>
								<text class="info-value">{{ detailData.applicationUserName || '无' }}</text>
							</view>
							<view class="info-item">
								<text class="info-label">申请门店</text>
								<text class="info-value">{{ getStoreName(detailData.applicationStoreId) || '无' }}</text>
							</view>
							<view class="info-item">
								<text class="info-label">申请时间</text>
								<text class="info-value">{{ formatTime(detailData.applicationTime) }}</text>
							</view>
							<view class="info-item">
								<text class="info-label">总金额</text>
								<text class="info-value amount">¥{{ detailData.amount || 0 }}</text>
							</view>
							<view class="info-item">
								<text class="info-label">审批状态</text>
								<view class="status-badge" :class="detailData.approveStatus=='已审批'?'approved':detailData.approveStatus=='待审批'?'pending':detailData.approveStatus=='未通过'?'rejected':'unapproved'">
									{{ detailData.approveStatus || '未审批' }}
								</view>
							</view>
						</view>
					</view>
					
					<!-- 购买物品清单 -->
					<view class="info-section" v-if="purchaseRecords && purchaseRecords.length > 0">
						<view class="section-title">购买物品清单</view>
						<view class="purchase-records-list">
							<view v-for="(item, index) in purchaseRecords" :key="item.id || index" class="purchase-record-item">
								<view class="record-header">
									<text class="record-category">{{ item.reimbursementCategoryName || '无' }}</text>
									<text class="record-amount">¥{{ item.amount || 0 }}</text>
								</view>
								<view class="record-details">
									<view class="record-detail-item">
										<text class="record-label">单价:</text>
										<text class="record-value">¥{{ item.unitPrice || 0 }}</text>
									</view>
									<view class="record-detail-item">
										<text class="record-label">数量:</text>
										<text class="record-value">{{ item.quantity || 0 }}</text>
									</view>
									<view class="record-detail-item">
										<text class="record-label">购买时间:</text>
										<text class="record-value">{{ formatTime(item.purchaseTime) }}</text>
									</view>
								</view>
								<view class="record-memo" v-if="item.memo">
									<text class="record-label">备注:</text>
									<text class="record-value">{{ item.memo }}</text>
								</view>
								<!-- 附件信息 -->
								<view class="record-attachment" v-if="item.attachment && item.attachment.length > 0">
									<text class="record-label">附件:</text>
									<view class="attachment-list">
										<view 
											v-for="(file, fileIndex) in item.attachment" 
											:key="fileIndex" 
											class="attachment-item"
											@click="previewFile(file, item.attachment)">
											<text class="file-icon">📎</text>
											<text class="file-name">{{ file.name || '文件' }}</text>
										</view>
									</view>
								</view>
							</view>
						</view>
					</view>
					
					<!-- 审批信息 -->
					<view class="info-section" v-if="detailData.approveStatus && detailData.approveStatus !== '未审批'">
						<view class="section-title">审批信息</view>
						<view class="info-grid">
							<view class="info-item" v-if="detailData.approveUser">
								<text class="info-label">审批人</text>
								<text class="info-value">{{ detailData.approveUserName || detailData.approveUser || '无' }}</text>
							</view>
							<view class="info-item" v-if="detailData.approveTime">
								<text class="info-label">审批时间</text>
								<text class="info-value">{{ formatTime(detailData.approveTime) }}</text>
							</view>
						</view>
					</view>
				</view>
			</view>
		</view>
	</view>
</template>

<script>
	import api from '@/apis/index.js'
	import purchaseApi from '@/apis/modules/purchase.js'
	import config from '@/common/config.js'

	export default {
		data() {
			return {
				loading: false,
				error: null,
				detailData: null,
				purchaseRecords: [],
				reimbursementId: null,
				storeOptions: [],
				baseUrl: config.getImgBaseUrl()
			}
		},

		onLoad(options) {
			if (options.id) {
				this.reimbursementId = options.id
				this.loadStoreOptions()
				this.loadDetail()
			} else {
				this.error = '缺少记录ID'
			}
		},

		methods: {
			// 加载门店列表
			async loadStoreOptions() {
				try {
					const res = await api.getStoreList({
						currentPage: 1,
						pageSize: 1000
					})
					if (res.code === 200 && res.data && res.data.list) {
						this.storeOptions = res.data.list
					} else {
						this.storeOptions = []
					}
				} catch (error) {
					console.error('加载门店列表失败:', error)
					this.storeOptions = []
				}
			},

			// 获取门店名称
			getStoreName(storeId) {
				if (!storeId) return '无'
				const store = this.storeOptions.find(item => item.id === storeId)
				return store ? store.dm : '无'
			},

			// 加载详情数据
			async loadDetail() {
				if (!this.reimbursementId) return

				try {
					this.loading = true
					this.error = null

					const res = await api.getReimbursementDetail(this.reimbursementId)

					if (res.code === 200 && res.data) {
						this.detailData = res.data
						
						// 加载关联的购买记录
						if (this.detailData.purchaseRecordsId) {
							await this.loadPurchaseRecords(this.detailData.purchaseRecordsId)
						}
					} else {
						this.error = res.message || '加载详情失败'
					}
				} catch (error) {
					console.error('加载详情失败:', error)
					this.error = '加载详情失败，请重试'
				} finally {
					this.loading = false
				}
			},

			// 加载购买记录
			async loadPurchaseRecords(purchaseRecordsId) {
				if (!purchaseRecordsId) {
					this.purchaseRecords = []
					return
				}

				// 处理逗号分隔的ID字符串
				const normalizedStr = purchaseRecordsId.toString().replace(/[\r\n]+/g, ',').replace(/\s+/g, '')
				const ids = normalizedStr.split(',').map(id => id.trim()).filter(id => id && id !== '')

				if (ids.length === 0) {
					this.purchaseRecords = []
					return
				}

				try {
					// 批量加载购买记录
					const promises = ids.map(id => {
						return purchaseApi.getPurchaseDetail(id)
							.then(res => res.code === 200 ? res.data : null)
							.catch(() => null)
					})

					const results = await Promise.all(promises)
					this.purchaseRecords = results.filter(item => item !== null)
				} catch (error) {
					console.error('加载购买记录失败:', error)
					this.purchaseRecords = []
				}
			},

			// 重试加载
			retryLoad() {
				this.loadDetail()
			},

			// 格式化时间
			formatTime(timestamp) {
				if (!timestamp) return '无'
				const date = new Date(timestamp)
				return date.toLocaleString('zh-CN', {
					year: 'numeric',
					month: '2-digit',
					day: '2-digit',
					hour: '2-digit',
					minute: '2-digit'
				})
			},

			// 获取状态样式类
			getStatusClass(status) {
				switch (status) {
					case '已审批':
						return 'approved'
					case '待审批':
						return 'pending'
					case '未通过':
						return 'rejected'
					case '未审批':
					default:
						return 'unapproved'
				}
			},
			// 预览文件
			previewFile(file, attachmentList) {
				if (!file || !file.url) {
					uni.showToast({
						title: '附件URL不存在',
						icon: 'none'
					})
					return
				}
				
				const fullUrl = file.url.startsWith('http') ? file.url : `${this.baseUrl}${file.url}`
				
				// 判断文件类型
				const fileExtension = this.getFileExtension(file.name || file.url)
				const imageExtensions = ['jpg', 'jpeg', 'png', 'gif', 'bmp', 'webp']
				
				if (imageExtensions.includes(fileExtension.toLowerCase())) {
					// 图片类型：预览
					// 构建所有图片URL列表
					const imageUrls = attachmentList
						.filter(item => {
							const ext = this.getFileExtension(item.name || item.url)
							return imageExtensions.includes(ext.toLowerCase())
						})
						.map(item => {
							const url = item.url.startsWith('http') ? item.url : `${this.baseUrl}${item.url}`
							return url
						})
					
					const currentIndex = imageUrls.findIndex(url => url === fullUrl)
					
					uni.previewImage({
						urls: imageUrls,
						current: currentIndex >= 0 ? currentIndex : 0
					})
				} else {
					// 其他类型：下载或打开
					uni.showToast({
						title: '非图片文件，请下载查看',
						icon: 'none'
					})
					// 可以在这里添加下载逻辑
					// uni.downloadFile({
					// 	url: fullUrl,
					// 	success: (res) => {
					// 		// 处理下载成功
					// 	}
					// })
				}
			},
			// 获取文件扩展名
			getFileExtension(fileName) {
				if (!fileName) return ''
				const lastDot = fileName.lastIndexOf('.')
				return lastDot > -1 ? fileName.substring(lastDot + 1) : ''
			}
		}
	}
</script>

<style lang="scss" scoped>
	.container {
		min-height: 100vh;
		background: linear-gradient(135deg, #e8f5e9 0%, #b2dfdb 100%);
		padding: 40rpx;
		box-sizing: border-box;
	}

	.detail-card {
		background: #fff;
		border-radius: 32rpx;
		box-shadow: 0 8rpx 32rpx rgba(76, 175, 80, 0.1);
		overflow: hidden;
	}

	.card-header {
		background: linear-gradient(120deg, #43e97b 0%, #38f9d7 100%);
		padding: 32rpx 40rpx;
		color: #fff;
		font-size: 36rpx;
		font-weight: 600;
		letter-spacing: 2rpx;
		text-align: center;
	}

	.detail-content {
		padding: 40rpx;
	}

	.loading {
		text-align: center;
		padding: 80rpx 40rpx;
		color: #6a9c6a;
		font-size: 28rpx;
	}

	.error-state {
		text-align: center;
		padding: 80rpx 40rpx;
		color: #f56c6c;
		font-size: 28rpx;
	}

	.retry-btn {
		margin-top: 32rpx;
	}

	.info-sections {
		display: flex;
		flex-direction: column;
		gap: 32rpx;
	}

	.info-section {
		background: #f9fff9;
		border-radius: 24rpx;
		padding: 32rpx;
		border: 2rpx solid #e8f5e9;
	}

	.section-title {
		font-size: 32rpx;
		font-weight: 600;
		color: #2e7d32;
		margin-bottom: 24rpx;
		padding-bottom: 16rpx;
		border-bottom: 2rpx solid #c8e6c9;
	}

	.info-grid {
		display: grid;
		grid-template-columns: 1fr 1fr;
		gap: 24rpx;
	}

	.info-item {
		display: flex;
		flex-direction: column;
		gap: 8rpx;
	}

	.info-label {
		font-size: 24rpx;
		color: #6a9c6a;
		font-weight: 500;
	}

	.info-value {
		font-size: 28rpx;
		color: #2e7d32;
		font-weight: 500;
		word-break: break-all;
	}

	.info-value.amount {
		color: #f57c00;
		font-weight: 600;
		font-size: 32rpx;
	}

	.status-badge {
		display: inline-block;
		padding: 8rpx 24rpx;
		border-radius: 40rpx;
		font-size: 24rpx;
		font-weight: 500;
		text-align: center;
		width: fit-content;
	}

	.status-badge.unapproved {
		background: #fff3e0;
		color: #ef6c00;
		border: 2rpx solid #ffe0b2;
	}

	.status-badge.pending {
		background: #e3f2fd;
		color: #1976d2;
		border: 2rpx solid #bbdefb;
	}

	.status-badge.approved {
		background: #e8f5e9;
		color: #2e7d32;
		border: 2rpx solid #c8e6c9;
	}

	.status-badge.rejected {
		background: #ffebee;
		color: #c62828;
		border: 2rpx solid #ffcdd2;
	}

	.purchase-records-list {
		display: flex;
		flex-direction: column;
		gap: 16rpx;
	}

	.purchase-record-item {
		background: #fff;
		border-radius: 16rpx;
		padding: 24rpx;
		border: 2rpx solid #e0e0e0;
	}

	.record-header {
		display: flex;
		justify-content: space-between;
		align-items: center;
		margin-bottom: 16rpx;
		padding-bottom: 16rpx;
		border-bottom: 2rpx solid #f0f0f0;
	}

	.record-category {
		font-size: 28rpx;
		color: #2e7d32;
		font-weight: 600;
	}

	.record-amount {
		font-size: 32rpx;
		color: #f57c00;
		font-weight: 600;
	}

	.record-details {
		display: flex;
		flex-wrap: wrap;
		gap: 24rpx;
		margin-bottom: 12rpx;
	}

	.record-detail-item {
		display: flex;
		align-items: center;
		gap: 8rpx;
	}

	.record-label {
		font-size: 24rpx;
		color: #6a9c6a;
	}

	.record-value {
		font-size: 26rpx;
		color: #2e7d32;
		font-weight: 500;
	}

	.record-memo {
		margin-top: 12rpx;
		padding-top: 12rpx;
		border-top: 1rpx solid #f0f0f0;
		display: flex;
		gap: 8rpx;
	}

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

	.record-attachment {
		margin-top: 12rpx;
		padding-top: 12rpx;
		border-top: 1rpx solid #f0f0f0;
		display: flex;
		flex-direction: column;
		gap: 8rpx;
	}

	.attachment-list {
		display: flex;
		flex-direction: column;
		gap: 8rpx;
		margin-top: 8rpx;
	}

	.attachment-item {
		display: flex;
		align-items: center;
		gap: 8rpx;
		padding: 8rpx 12rpx;
		background: #f5f5f5;
		border-radius: 8rpx;
		cursor: pointer;
	}

	.file-icon {
		font-size: 24rpx;
	}

	.file-name {
		font-size: 24rpx;
		color: #409EFF;
		flex: 1;
		overflow: hidden;
		text-overflow: ellipsis;
		white-space: nowrap;
	}
</style>

