<template>
	<el-dialog 
		title="报销申请详情" 
		:visible.sync="visible" 
		:close-on-click-modal="false"
		class="NCC-dialog NCC-dialog_center" 
		width="1200px"
		@close="handleClose"
		@update:visible="handleVisibleChange">
		<div class="detail-content" v-loading="loading">
			<!-- 基本信息卡片 -->
			<el-card class="info-card" shadow="hover">
				<div slot="header" class="card-header">
					<i class="el-icon-document"></i>
					<span class="card-title">基本信息</span>
				</div>
				<el-row :gutter="20">
					<el-col :span="8">
						<div class="info-item">
							<label class="info-label">申请编号：</label>
							<span class="info-value">{{ dataForm.id || '无' }}</span>
						</div>
					</el-col>
					<el-col :span="8">
						<div class="info-item">
							<label class="info-label">申请人：</label>
							<span class="info-value">{{ dataForm.applicationUserName || '无' }}</span>
						</div>
					</el-col>
					<el-col :span="8">
						<div class="info-item">
							<label class="info-label">门店：</label>
							<span class="info-value">{{ getStoreName(dataForm.applicationStoreId) || '无' }}</span>
						</div>
					</el-col>
					<el-col :span="8">
						<div class="info-item">
							<label class="info-label">申请时间：</label>
							<span class="info-value">{{ formatDate(dataForm.applicationTime) || '无' }}</span>
						</div>
					</el-col>
					<el-col :span="8">
						<div class="info-item">
							<label class="info-label">总金额：</label>
							<span class="info-value amount">{{ dataForm.amount || '无' }}</span>
						</div>
					</el-col>
					<el-col :span="8">
						<div class="info-item">
							<label class="info-label">审批状态：</label>
							<span class="info-value" :class="{'status-approved': dataForm.approveStatus === '已审批', 'status-pending': dataForm.approveStatus === '未审批'}">
								{{ dataForm.approveStatus || '无' }}
							</span>
						</div>
					</el-col>
				</el-row>
			</el-card>

			<!-- 购买物品清单卡片 -->
			<el-card class="info-card" shadow="hover" v-if="purchaseRecords && purchaseRecords.length > 0">
				<div slot="header" class="card-header">
					<i class="el-icon-shopping-cart-full"></i>
					<span class="card-title">购买物品清单</span>
				</div>
				<el-table 
					:data="purchaseRecords" 
					border
					size="small"
					style="width: 100%">
					<el-table-column type="index" label="序号" width="60" align="center" />
					<el-table-column prop="reimbursementCategoryName" label="分类名称" />
					<el-table-column prop="createUserStoreId" label="门店" align="left">
                        <template slot-scope="scope">
                            {{ getStoreName(scope.row.createUserStoreId) }}
                        </template>
                    </el-table-column>
					<el-table-column prop="unitPrice" label="单价" align="right" />
					<el-table-column prop="quantity" label="数量" align="right" />
					<el-table-column prop="amount" label="总金额" align="right" />
					<el-table-column prop="purchaseTime" label="购买时间" width="120">
						<template slot-scope="scope">
							{{ formatDate(scope.row.purchaseTime) || '无' }}
						</template>
					</el-table-column>
					<el-table-column prop="memo" label="备注说明" min-width="150" show-overflow-tooltip />
					<el-table-column prop="attachment" label="附件" width="180" align="left">
						<template slot-scope="scope">
							<div v-if="scope.row.attachment && scope.row.attachment.length > 0" class="attachment-list">
								<div 
									v-for="(file, index) in scope.row.attachment" 
									:key="index"
									class="attachment-item"
									@click="handleAttachmentClick(file, scope.row.attachment)">
									<i class="el-icon-paperclip"></i>
									<span class="attachment-name" :title="file.name || '文件'">{{ file.name || '文件' }}</span>
								</div>
							</div>
							<span v-else>无</span>
						</template>
					</el-table-column>
				</el-table>
			</el-card>

			<!-- 审批信息卡片 -->
			<el-card class="info-card" shadow="hover" v-if="dataForm.approveStatus === '已审批'">
				<div slot="header" class="card-header">
					<i class="el-icon-check"></i>
					<span class="card-title">审批信息</span>
				</div>
				<el-row :gutter="20">
					<el-col :span="8">
						<div class="info-item">
							<label class="info-label">审批人：</label>
							<span class="info-value">{{ getUserName(dataForm.approveUser) || '无' }}</span>
						</div>
					</el-col>
					<el-col :span="8">
						<div class="info-item">
							<label class="info-label">审批时间：</label>
							<span class="info-value">{{ formatDate(dataForm.approveTime) || '无' }}</span>
						</div>
					</el-col>
				</el-row>
			</el-card>
		</div>
		<span slot="footer" class="dialog-footer">
			<el-button type="warning" @click="handlePrint" v-if="dataForm.id">打 印</el-button>
			<el-button @click="visible = false">关 闭</el-button>
		</span>
		
		<!-- 图片预览对话框 -->
		<el-dialog 
			title="图片预览" 
			:visible.sync="imagePreviewVisible" 
			width="600px"
			append-to-body
			@close="resetImageRotation">
			<div class="image-preview-container">
				<div class="image-wrapper">
					<el-image 
						:src="previewImageUrl" 
						:style="{
							maxWidth: '100%',
							maxHeight: '400px',
							objectFit: 'contain',
							transform: `rotate(${imageRotation}deg)`,
							transition: 'transform 0.3s ease',
							display: 'block',
							margin: '0 auto'
						}">
					</el-image>
				</div>
				<div class="image-controls">
					<el-button 
						icon="el-icon-refresh-left" 
						@click="rotateImage(-90)"
						size="small">
						逆时针旋转
					</el-button>
					<el-button 
						icon="el-icon-refresh-right" 
						@click="rotateImage(90)"
						size="small"
						type="primary">
						顺时针旋转
					</el-button>
					<el-button 
						@click="resetImageRotation"
						size="small">
						重置
					</el-button>
				</div>
			</div>
		</el-dialog>
	</el-dialog>
</template>

<script>
import request from '@/utils/request'

export default {
	name: 'ReimbursementApplicationDetail',
	data() {
		return {
			visible: false,
			loading: false,
			dataForm: {},
			purchaseRecords: [],
			storeOptions: [],
			userMap: {},
			imagePreviewVisible: false, // 图片预览对话框显示状态
			previewImageUrl: '', // 预览的图片URL
			imageRotation: 0 // 图片旋转角度
		}
	},
	methods: {
		init(id) {
			this.visible = true
			this.loading = true
			this.dataForm = {}
			this.purchaseRecords = []
			this.userMap = {}
			
			// 加载门店列表
			this.loadStoreOptions()
			
			// 加载详情数据
			request({
				url: `/api/Extend/LqReimbursementApplication/${id}`,
				method: 'GET'
			}).then(res => {
				this.dataForm = res.data || {}
				// 如果有关联的购买记录，加载购买记录详情
				if (this.dataForm.purchaseRecordsId) {
					this.loadPurchaseRecords(this.dataForm.purchaseRecordsId)
				}
				// 加载用户信息
				this.loadUserInfo()
				this.loading = false
			}).catch(() => {
				this.loading = false
				this.$message.error('加载详情失败')
			})
		},
		// 加载门店列表
		loadStoreOptions() {
			request({
				url: '/api/Extend/LqMdxx',
				method: 'GET',
				data: {
					currentPage: 1,
					pageSize: 1000
				}
			}).then(res => {
				if (res.data && res.data.list) {
					this.storeOptions = res.data.list
				}
			}).catch(() => {
				this.storeOptions = []
			})
		},
		// 加载购买记录
		loadPurchaseRecords(purchaseRecordsId) {
			if (!purchaseRecordsId) {
				this.purchaseRecords = []
				return
			}
			// 处理逗号分隔的ID字符串
			const normalizedStr = purchaseRecordsId.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
			}
			
			// 批量加载购买记录
			Promise.all(ids.map(id => {
				return request({
					url: `/api/Extend/LqPurchaseRecords/${id}`,
					method: 'GET'
				}).then(res => res.data).catch(() => null)
			})).then(results => {
				this.purchaseRecords = results.filter(item => item !== null)
			})
		},
		// 加载用户信息
		loadUserInfo() {
			const userIds = []
			if (this.dataForm.approveUser) {
				userIds.push(this.dataForm.approveUser)
			}
			
			// 去重
			const uniqueUserIds = [...new Set(userIds)]
			
			// 批量加载用户信息
			Promise.all(uniqueUserIds.map(userId => {
				return request({
					url: `/api/permission/Users/${userId}`,
					method: 'GET'
				}).then(res => {
					if (res.data) {
						this.userMap[userId] = res.data.realName || res.data.account || userId
					}
				}).catch(() => {
					this.userMap[userId] = userId
				})
			}))
		},
		// 获取门店名称
		getStoreName(storeId) {
			if (!storeId) return ''
			const store = this.storeOptions.find(item => item.id === storeId)
			return store ? store.dm : ''
		},
		// 获取用户名称
		getUserName(userId) {
			if (!userId) return ''
			return this.userMap[userId] || userId
		},
		// 格式化日期
		formatDate(timestamp) {
			if (!timestamp) return ''
			const date = new Date(timestamp)
			const year = date.getFullYear()
			const month = String(date.getMonth() + 1).padStart(2, '0')
			const day = String(date.getDate()).padStart(2, '0')
			return `${year}-${month}-${day}`
		},
		// 关闭弹窗
		handleClose() {
			this.visible = false
			this.dataForm = {}
			this.purchaseRecords = []
			this.userMap = {}
			this.imagePreviewVisible = false
			this.previewImageUrl = ''
			this.imageRotation = 0
			this.$emit('close')
		},
		// 处理附件点击
		handleAttachmentClick(file, attachmentList) {
			if (!file || !file.url) {
				this.$message.warning('附件URL不存在')
				return
			}
			
			// 判断文件类型
			const fileExtension = this.getFileExtension(file.name || file.url)
			const imageExtensions = ['jpg', 'jpeg', 'png', 'gif', 'bmp', 'webp']
			
			// 构建完整的URL（如果url是相对路径，需要加上基础URL）
			let fullUrl = file.url
			if (file.url && !file.url.startsWith('http')) {
				// 如果url是相对路径，需要加上基础URL
				const baseUrl = (this.define && this.define.comUrl) || window.location.origin
				fullUrl = baseUrl + file.url
			}
			
			if (imageExtensions.includes(fileExtension.toLowerCase())) {
				// 图片类型：预览
				this.previewImageUrl = fullUrl
				this.imagePreviewVisible = true
			} else {
				// 其他类型：下载
				this.downloadFile(fullUrl, file.name || file.fileId)
			}
		},
		// 获取文件扩展名
		getFileExtension(fileName) {
			if (!fileName) return ''
			const lastDot = fileName.lastIndexOf('.')
			return lastDot > -1 ? fileName.substring(lastDot + 1) : ''
		},
		// 下载文件
		downloadFile(url, fileName) {
			const link = document.createElement('a')
			link.href = url
			link.download = fileName || 'download'
			link.target = '_blank'
			document.body.appendChild(link)
			link.click()
			document.body.removeChild(link)
		},
		// 旋转图片
		rotateImage(angle) {
			this.imageRotation = (this.imageRotation + angle) % 360
		},
		// 重置图片旋转
		resetImageRotation() {
			this.imageRotation = 0
		},
		// 处理 visible 变化
		handleVisibleChange(val) {
			this.visible = val
			if (!val) {
				this.handleClose()
			}
		},
		// 打印功能
		handlePrint() {
			if (!this.dataForm.id) {
				this.$message.warning('无法打印，数据未加载完成')
				return
			}
			
			// 构建打印内容
			let printContent = this.buildPrintContent()
			
			// 打开新窗口并打印
			let newWindow = window.open('_blank')
			if (!newWindow) {
				this.$message.error('无法打开打印窗口，请检查浏览器弹窗设置')
				return
			}
			
			newWindow.document.write(printContent)
			newWindow.document.close()
			
			// 等待内容加载完成后打印
			setTimeout(() => {
				newWindow.print()
			}, 300)
		},
		// 构建打印内容
		buildPrintContent() {
			const storeName = this.getStoreName(this.dataForm.applicationStoreId) || '无'
			const approveStatus = this.dataForm.approveStatus || '未审批'
			const approveTime = this.dataForm.approveTime ? this.formatDate(this.dataForm.approveTime) : '无'
			
			// 构建购买物品清单表格
			let purchaseTableRows = ''
			if (this.purchaseRecords && this.purchaseRecords.length > 0) {
				this.purchaseRecords.forEach((item, index) => {
					const storeName = this.getStoreName(item.createUserStoreId) || '无'
					purchaseTableRows += `
						<tr>
							<td style="text-align: center; width: 55px;">${index + 1}</td>
							<td>${item.reimbursementCategoryName || '无'}</td>
							<td>${storeName}</td>
							<td style="text-align: right;">${item.unitPrice || '0.00'}</td>
							<td style="text-align: center;">${item.quantity || '0'}</td>
							<td style="text-align: right;">${item.amount || '0.00'}</td>
							<td>${item.purchaseTime ? this.formatDate(item.purchaseTime) : '无'}</td>
							<td>${item.memo || '无'}</td>
						</tr>
					`
				})
			} else {
				purchaseTableRows = '<tr><td colspan="8" style="text-align: center;">暂无数据</td></tr>'
			}
			
			return `
				<!DOCTYPE html>
				<html>
				<head>
					<meta charset="UTF-8">
					<title>报销申请单</title>
					<style>
						* {
							margin: 0;
							padding: 0;
							box-sizing: border-box;
						}
						body {
							font-family: "Microsoft YaHei", Arial, sans-serif;
							font-size: 13px;
							padding: 15px;
							color: #333;
						}
						.print-header {
							text-align: center;
							margin-bottom: 15px;
							border-bottom: 2px solid #333;
							padding-bottom: 10px;
						}
						.print-header h1 {
							font-size: 22px;
							font-weight: bold;
							margin-bottom: 5px;
						}
						.print-info {
							margin-bottom: 12px;
						}
						.print-info table {
							width: 100%;
							border-collapse: collapse;
							margin-bottom: 12px;
						}
						.print-info table td {
							padding: 6px 10px;
							border: 1px solid #ddd;
						}
						.print-info table td:first-child {
							background-color: #f5f5f5;
							font-weight: bold;
							width: 120px;
							text-align: right;
						}
						.print-table {
							width: 100%;
							border-collapse: collapse;
							margin-bottom: 12px;
						}
						.print-table thead {
							display: table-header-group;
						}
						.print-table tbody {
							display: table-row-group;
						}
						.print-table th,
						.print-table td {
							border: 1px solid #ddd;
							padding: 5px 6px;
							text-align: left;
							font-size: 12px;
						}
						.print-table th {
							background-color: #f5f5f5;
							font-weight: bold;
							text-align: center;
						}
						.print-table tbody tr {
							page-break-inside: avoid;
						}
						.print-footer {
							margin-top: 15px;
							padding-top: 10px;
							border-top: 1px solid #ddd;
							text-align: right;
							font-size: 11px;
							color: #666;
						}
						@media print {
							body {
								padding: 8px;
							}
							.print-header {
								page-break-after: avoid;
								margin-bottom: 12px;
								padding-bottom: 8px;
							}
							.print-info {
								page-break-after: avoid;
								margin-bottom: 10px;
							}
							.print-table {
								page-break-inside: auto;
							}
							.print-table thead {
								display: table-header-group;
							}
							.print-table tbody tr {
								page-break-inside: avoid;
								page-break-after: auto;
							}
							.print-table tbody tr:last-child {
								page-break-after: auto;
							}
							.print-footer {
								page-break-before: avoid;
								margin-top: 10px;
								padding-top: 8px;
							}
							@page {
								margin: 1cm;
							}
						}
					</style>
				</head>
				<body>
					<div class="print-header">
						<h1>报销申请单</h1>
					</div>
					
					<div class="print-info">
						<table>
							<tr>
								<td>申请编号：</td>
								<td>${this.dataForm.id || '无'}</td>
								<td>申请人：</td>
								<td>${this.dataForm.applicationUserName || '无'}</td>
							</tr>
							<tr>
								<td>申请门店：</td>
								<td>${storeName}</td>
								<td>申请时间：</td>
								<td>${this.dataForm.applicationTime ? this.formatDate(this.dataForm.applicationTime) : '无'}</td>
							</tr>
							<tr>
								<td>总金额：</td>
								<td>¥${this.dataForm.amount || '0.00'}</td>
								<td>审批状态：</td>
								<td>${approveStatus}</td>
							</tr>
							<tr>
								<td>审批人：</td>
								<td>${this.getUserName(this.dataForm.approveUser) || '无'}</td>
								<td>审批时间：</td>
								<td>${approveTime}</td>
							</tr>
						</table>
					</div>
					
					<div class="print-info">
						<h3 style="margin-bottom: 10px;">购买物品清单</h3>
						<table class="print-table">
							<thead>
								<tr>
									<th style="width: 55px;">序号</th>
									<th>分类名称</th>
									<th>门店</th>
									<th style="width: 100px;">单价</th>
									<th style="width: 80px;">数量</th>
									<th style="width: 100px;">总金额</th>
									<th style="width: 120px;">购买时间</th>
									<th>备注说明</th>
								</tr>
							</thead>
							<tbody>
								${purchaseTableRows}
							</tbody>
						</table>
					</div>
					
					<div class="print-footer">
						<p>打印时间：${new Date().toLocaleString('zh-CN')}</p>
					</div>
				</body>
				</html>
			`
		}
	}
}
</script>

<style lang="scss" scoped>
/* 详情内容 */
.detail-content {
	//max-height: 70vh;
	overflow-y: auto;
	padding: 0 10px;
}

/* 信息卡片 */
.info-card {
	margin-bottom: 20px;
	border-radius: 8px;
	overflow: hidden;
}

.card-header {
	display: flex;
	align-items: center;
	gap: 8px;
	font-size: 16px;
	font-weight: 600;
	color: #303133;
}

.card-header i {
	font-size: 18px;
	color: #409EFF;
}

.card-title {
	font-size: 16px;
	font-weight: 600;
}

/* 信息项 */
.info-item {
	margin-bottom: 16px;
}

.info-label {
	display: inline-block;
	font-weight: 500;
	color: #606266;
	margin-right: 8px;
}

.info-value {
	color: #303133;
	font-size: 14px;
}

.info-value.amount {
	color: #E6A23C;
	font-weight: 600;
}

.status-approved {
	color: #67C23A;
	font-weight: 600;
}

.status-pending {
	color: #E6A23C;
	font-weight: 600;
}

/* 附件列表样式 */
.attachment-list {
	.attachment-item {
		display: flex;
		align-items: center;
		padding: 4px 0;
		cursor: pointer;
		color: #409EFF;
		transition: color 0.3s;
		
		&:hover {
			color: #66b1ff;
		}
		
		i {
			margin-right: 4px;
			font-size: 14px;
		}
		
		.attachment-name {
			font-size: 12px;
			max-width: 120px;
			overflow: hidden;
			text-overflow: ellipsis;
			white-space: nowrap;
		}
	}
}

/* 图片预览容器样式 */
.image-preview-container {
	.image-wrapper {
		min-height: 200px;
		max-height: 450px;
		overflow: auto;
		display: flex;
		align-items: center;
		justify-content: center;
		padding: 20px;
		background-color: #f5f5f5;
		border-radius: 4px;
		margin-bottom: 15px;
		
		::v-deep .el-image {
			display: block;
		}
	}
	
	.image-controls {
		text-align: center;
		padding-top: 10px;
	}
}
</style>

