<template>
	<el-dialog title="批次详情" :close-on-click-modal="false" :visible.sync="visible"
		class="NCC-dialog NCC-dialog_center" lock-scroll width="1000px">
		<div v-loading="loading">
			<!-- 批次基本信息 -->
			<el-card class="box-card" shadow="never">
				<div slot="header" class="card-header">
					<span>批次基本信息</span>
				</div>
				<el-row :gutter="20">
					<el-col :span="8">
						<div class="info-item">
							<span class="label">批次ID：</span>
							<span class="value">{{ batchInfo.BatchId || '无' }}</span>
						</div>
					</el-col>
					<el-col :span="8">
						<div class="info-item">
							<span class="label">创建时间：</span>
							<span class="value">{{ formatDateTime(batchInfo.CreateTime) }}</span>
						</div>
					</el-col>
					<el-col :span="8">
						<div class="info-item">
							<span class="label">创建人：</span>
							<span class="value">{{ batchInfo.CreateUserName || '无' }}</span>
						</div>
					</el-col>
					<el-col :span="8">
						<div class="info-item">
							<span class="label">总记录数：</span>
							<span class="value">{{ batchInfo.TotalCount || 0 }}</span>
						</div>
					</el-col>
					<el-col :span="8">
						<div class="info-item">
							<span class="label">有效记录数：</span>
							<span class="value">{{ batchInfo.EffectiveCount || 0 }}</span>
						</div>
					</el-col>
					<el-col :span="8">
						<div class="info-item">
							<span class="label">无效记录数：</span>
							<span class="value">{{ batchInfo.IneffectiveCount || 0 }}</span>
						</div>
					</el-col>
					<el-col :span="8">
						<div class="info-item">
							<span class="label">总使用数量：</span>
							<span class="value">{{ batchInfo.TotalUsageQuantity || 0 }}</span>
						</div>
					</el-col>
					<!-- <el-col :span="8">
						<div class="info-item">
							<span class="label">总使用金额：</span>
							<span class="value">¥{{ formatMoney(batchInfo.TotalUsageAmount) }}</span>
						</div>
					</el-col> -->
				</el-row>
			</el-card>

			<!-- 申请记录信息 -->
			<el-card v-if="batchInfo.ApplicationInfo" class="box-card" shadow="never" style="margin-top: 20px;">
				<div slot="header" class="card-header">
					<span>申请记录信息</span>
				</div>
				<el-row :gutter="20">
					<el-col :span="8">
						<div class="info-item">
							<span class="label">申请编号：</span>
							<span class="value">{{ batchInfo.ApplicationInfo.Id || '无' }}</span>
						</div>
					</el-col>
					<el-col :span="8">
						<div class="info-item">
							<span class="label">申请人：</span>
							<span class="value">{{ batchInfo.ApplicationInfo.ApplicationUserName || '无' }}</span>
						</div>
					</el-col>
					<el-col :span="8">
						<div class="info-item">
							<span class="label">申请门店：</span>
							<span class="value">{{ batchInfo.ApplicationInfo.ApplicationStoreName || '无' }}</span>
						</div>
					</el-col>
					<el-col :span="8">
						<div class="info-item">
							<span class="label">申请时间：</span>
							<span class="value">{{ formatDateTime(batchInfo.ApplicationInfo.ApplicationTime) }}</span>
						</div>
					</el-col>
					<el-col :span="8">
						<div class="info-item">
							<span class="label">审批状态：</span>
							<el-tag :type="getStatusType(batchInfo.ApplicationInfo.ApprovalStatus)" size="small">
								{{ batchInfo.ApplicationInfo.ApprovalStatus || '无' }}
							</el-tag>
						</div>
					</el-col>
					<el-col :span="8">
						<div class="info-item">
							<span class="label">是否已领取：</span>
							<el-tag :type="batchInfo.ApplicationInfo.IsReceived === 1 ? 'success' : 'info'" size="small">
								{{ batchInfo.ApplicationInfo.IsReceived === 1 ? '已领取' : '未领取' }}
							</el-tag>
						</div>
					</el-col>
					<el-col :span="8" v-if="batchInfo.ApplicationInfo.ReceiveTime">
						<div class="info-item">
							<span class="label">领取时间：</span>
							<span class="value">{{ formatDateTime(batchInfo.ApplicationInfo.ReceiveTime) }}</span>
						</div>
					</el-col>
					<el-col :span="8" v-if="batchInfo.ApplicationInfo.ReceiveUser">
						<div class="info-item">
							<span class="label">领取人：</span>
							<span class="value">{{ batchInfo.ApplicationInfo.ReceiveUserName || '无' }}</span>
						</div>
					</el-col>
					<el-col :span="24" v-if="batchInfo.ApplicationInfo.Remarks">
						<div class="info-item">
							<span class="label">备注：</span>
							<span class="value">{{ batchInfo.ApplicationInfo.Remarks || '无' }}</span>
						</div>
					</el-col>
				</el-row>
			</el-card>

			<!-- 使用记录列表 -->
			<el-card class="box-card" shadow="never" style="margin-top: 20px;">
				<div slot="header" class="card-header">
					<span>使用记录列表</span>
				</div>
				<!-- 添加仓库筛选 -->
				<div class="filter-container" style="margin-bottom: 15px;">
					<el-select v-model="filterStore" placeholder="请选择仓库" clearable style="width: 200px;" @change="handleFilterStoreChange">
						<el-option 
							v-for="store in storeList" 
							:key="store" 
							:label="store" 
							:value="store">
						</el-option>
					</el-select>

					<el-button type="text" icon="el-icon-printer" @click="handlePrint()" class="print-btn" style="margin-left: 10px;">
						打印
					</el-button>
				</div>
				
				<NCC-table :data="filteredUsageRecords"
					:header-cell-style="{ background: '#f5f7fa', color: '#606266' }">
					<el-table-column label="产品名称" align="center" prop="productName" />
					<el-table-column label="单价" align="center" >
						<template slot-scope="scope">
							<span>¥{{ formatMoney(scope.row.unitPrice) }}</span>
						</template>
					</el-table-column>
					<el-table-column label="门店" align="center" prop="storeName"/>
					<el-table-column label="仓库" align="center" prop="productWarehouse"/>
					<el-table-column label="使用时间" align="center" prop="usageTime" width="150">
						<template slot-scope="scope">
							<span>{{ formatDateTime(scope.row.usageTime) }}</span>
						</template>
					</el-table-column>
					<el-table-column label="使用数量" align="center" prop="usageQuantity"  />
					<el-table-column label="合计金额" align="center" prop="totalAmount" >
						<template slot-scope="scope">
							<span class="amount-text">¥{{ formatMoney(scope.row.totalAmount) }}</span>
						</template>
					</el-table-column>
					<el-table-column label="是否有效" align="center">
						<template slot-scope="scope">
							<el-tag :type="scope.row.isEffective === 1 ? 'success' : 'info'" size="small">
								{{ scope.row.isEffective === 1 ? '有效' : '无效' }}
							</el-tag>
						</template>
					</el-table-column>
				</NCC-table>
			</el-card>
		</div>
	</el-dialog>
</template>

<script>
import { getBatchInfo } from '@/api/extend/lqInventory'

export default {
		data() {
		return {
			storeList:[],
			filterStore:'',
			visible: false,
			loading: false,
			batchInfo: {
				BatchId: '',
				CreateTime: null,
				CreateUser: '',
				CreateUserName: '',
				TotalCount: 0,
				EffectiveCount: 0,
				IneffectiveCount: 0,
				TotalUsageQuantity: 0,
				TotalUsageAmount: 0,
				UsageRecords: [],
				ApplicationInfo: null
			}
		}
	},
	computed: {
		// 筛选后的使用记录
		filteredUsageRecords() {
			if (!this.filterStore) {
				return this.batchInfo.UsageRecords || []
			}
			return (this.batchInfo.UsageRecords || []).filter(record => 
				record.productWarehouse === this.filterStore
			)
		}
	},
	methods: {
		handleFilterStoreChange(e){
			console.log(e)
			// this.filterStore = e
		},
		init(batchId) {
			this.visible = true
			this.loading = true
			this.filterStore = '' // 重置筛选
			this.batchInfo = {
				BatchId: '',
				CreateTime: null,
				CreateUser: '',
				CreateUserName: '',
				TotalCount: 0,
				EffectiveCount: 0,
				IneffectiveCount: 0,
				TotalUsageQuantity: 0,
				TotalUsageAmount: 0,
				UsageRecords: [],
				ApplicationInfo: null
			}
			getBatchInfo(batchId).then(res => {
				this.loading = false
				if (res.code == 200 && res.data) {
					this.batchInfo = res.data
					// 生成仓库列表
					this.generateStoreList()
				} else {
					this.$message({
						type: 'error',
						message: res.msg || '查询失败'
					})
				}
			}).catch(() => {
				this.loading = false
			})
		},
		// 生成仓库列表（去重）
		generateStoreList() {
			const records = this.batchInfo.UsageRecords || []
			const storeSet = new Set()
			
			records.forEach(record => {
				if (record.productWarehouse) {
					storeSet.add(record.productWarehouse)
				}
			})
			
			this.storeList = Array.from(storeSet)
		},
		// 重置筛选
		resetFilter() {
			this.filterStore = ''
		},
		getStatusType(status) {
			const statusMap = {
				'待审批': 'info',
				'审批中': 'warning',
				'已通过': 'success',
				'未通过': 'danger',
				'已退回': 'info'
			}
			return statusMap[status] || 'info'
		},
		formatDateTime(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')
			const hours = String(date.getHours()).padStart(2, '0')
			const minutes = String(date.getMinutes()).padStart(2, '0')
			const seconds = String(date.getSeconds()).padStart(2, '0')
			return `${year}-${month}-${day} ${hours}:${minutes}:${seconds}`
		},
		formatMoney(amount) {
			if (!amount && amount !== 0) return '0.00'
			return Number(amount).toFixed(2)
		},
		// 打印功能
		handlePrint() {
			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() {
			let batchData = this.batchInfo
			console.log(batchData)
			// 格式化时间
			const formatDateTime = (timestamp) => {
				if (!timestamp) return '无'
				try {
					const date = new Date(timestamp)
					if (isNaN(date.getTime())) return '无'
					const year = date.getFullYear()
					const month = String(date.getMonth() + 1).padStart(2, '0')
					const day = String(date.getDate()).padStart(2, '0')
					const hours = String(date.getHours()).padStart(2, '0')
					const minutes = String(date.getMinutes()).padStart(2, '0')
					const seconds = String(date.getSeconds()).padStart(2, '0')
					return `${year}-${month}-${day} ${hours}:${minutes}:${seconds}`
				} catch (e) {
					return '无'
				}
			}
			
			const formatDate = (timestamp) => {
				if (!timestamp) return '无'
				try {
					const date = new Date(timestamp)
					if (isNaN(date.getTime())) return '无'
					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}`
				} catch (e) {
					return '无'
				}
			}
			
			const formatMoney = (amount) => {
				if (!amount && amount !== 0) return '0.00'
				return Number(amount).toFixed(2)
			}
			
			// 过滤出有效记录（isEffective === 1）
			let effectiveRecords = batchData.UsageRecords ? batchData.UsageRecords.filter(item => item.isEffective === 1) : []
			// 过滤仓库
			if(this.filterStore){
				let oneeffectiveRecords = effectiveRecords
				effectiveRecords = oneeffectiveRecords.filter(item => item.productWarehouse == this.filterStore)

			}
			console.log(effectiveRecords)
			// 获取门店名称
		
			console.log(batchData.ApplicationInfo.ApplicationStoreName)
			const storeName = effectiveRecords.length > 0 ? (effectiveRecords[0].storeName || '无') : '无'
			let usageTableRows = ''
			if (effectiveRecords.length > 0) {
				effectiveRecords.forEach((item, index) => {
					usageTableRows += `
						<tr>
							<td style="text-align: center;">${index + 1}</td>
							<td>${item.productName || '无'}</td>
							<td style="text-align: center;">${item.usageQuantity || 0}</td>
						</tr>
					`
				})
			} else {
				usageTableRows = '<tr><td colspan="3" 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: 200px;
							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;
							}
						}
					</style>
				</head>
				<body>
					<div class="print-header">
						<h1>产品使用批次详情</h1>
					</div>
					
					<div class="print-info">
						<table>
							<tr>
								<td>门店名称：</td>
								<td>${storeName}</td>
							</tr>
						</table>
					</div>
					
					<div class="print-info">
						<h3 style="margin-bottom: 8px; font-size: 14px;">使用记录明细</h3>
						<table class="print-table">
							<thead>
								<tr>
									<th style="width: 50px;">序号</th>
									<th>产品名称</th>
									<th style="width: 100px;">数量</th>
								</tr>
							</thead>
							<tbody>
								${usageTableRows}
							</tbody>
						</table>
					</div>
					
					<div class="print-footer">
						<p>打印时间：${formatDateTime(new Date().getTime())}</p>
					</div>
				</body>
				</html>
			`
		}
	}
}
</script>

<style lang="scss" scoped>
.box-card {
	margin-bottom: 0;
}

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

.info-item {
	display: flex;
	align-items: center;
	margin-bottom: 12px;

	.label {
		color: #606266;
		font-weight: 500;
		min-width: 100px;
	}

	.value {
		color: #303133;
	}
}

.amount-text {
	color: #67C23A;
	font-weight: 600;
}

::v-deep .el-table__header-wrapper {
	.el-table__header {
		th {
			background-color: #f5f7fa;
			color: #606266;
			font-weight: 600;
		}
	}
}
</style>

