<template>
	<div class="NCC-common-layout">
		<div class="NCC-common-layout-center">
			<!-- 查询条件 -->
			<el-row class="NCC-common-search-box" :gutter="16">
				<el-form @submit.native.prevent>
					<el-col :span="6">
						<el-form-item label="仓库">
							<el-select v-model="query.Warehouse" placeholder="请选择仓库（不选则统计全部）" clearable filterable :style="{ width: '100%' }">
								<el-option v-for="warehouse in warehouseOptions" :key="warehouse" :label="warehouse" :value="warehouse" />
							</el-select>
						</el-form-item>
					</el-col>
					<el-col :span="6">
						<el-form-item label="门店">
							<el-select v-model="query.StoreId" placeholder="请选择门店（不选则统计全部）" clearable filterable :style="{ width: '100%' }">
								<el-option v-for="store in storeOptions" :key="store.id" :label="store.dm" :value="store.id" />
							</el-select>
						</el-form-item>
					</el-col>
					<el-col :span="6">
						<el-form-item>
							<el-button type="primary" icon="el-icon-search" @click="search()">查询</el-button>
							<el-button icon="el-icon-refresh-right" @click="reset()">重置</el-button>
						</el-form-item>
					</el-col>
				</el-form>
			</el-row>

			<!-- 统计结果 -->
			<div class="NCC-common-layout-main NCC-flex-main">
				<div class="NCC-common-head">
					<div class="head-actions">
						<el-button type="primary" icon="el-icon-printer" @click="printAll()" :disabled="!list.length">打印全部仓库</el-button>
					</div>
					<div class="NCC-common-head-right">
						<el-tooltip effect="dark" content="刷新" placement="top">
							<el-link icon="icon-ym icon-ym-Refresh NCC-common-head-icon" :underline="false" @click="initData()" />
						</el-tooltip>
						<screenfull isContainer />
					</div>
				</div>

				<!-- 统计卡片 -->
				<el-row :gutter="16" style="margin-bottom: 20px;">
					<el-col :span="8">
						<el-card class="statistics-card" shadow="never">
							<div class="card-content">
								<div class="card-icon">
									<i class="el-icon-office-building"></i>
								</div>
								<div class="card-info">
									<div class="card-label">待领取仓库数</div>
									<div class="card-value">{{ warehouseCount }}</div>
								</div>
							</div>
						</el-card>
					</el-col>
					<el-col :span="8">
						<el-card class="statistics-card" shadow="never">
							<div class="card-content">
								<div class="card-icon">
									<i class="el-icon-s-shop"></i>
								</div>
								<div class="card-info">
									<div class="card-label">待领取门店数</div>
									<div class="card-value">{{ storeCount }}</div>
								</div>
							</div>
						</el-card>
					</el-col>
					<el-col :span="8">
						<el-card class="statistics-card" shadow="never">
							<div class="card-content">
								<div class="card-icon">
									<i class="el-icon-coin"></i>
								</div>
								<div class="card-info">
									<div class="card-label">待领取总金额</div>
									<div class="card-value">¥{{ formatMoney(totalAmount) }}</div>
								</div>
							</div>
						</el-card>
					</el-col>
				</el-row>

				<!-- 仓库待领取列表 -->
				<div class="warehouse-list" ref="warehouseList" v-loading="loading">
					<div v-if="!list.length" class="empty-text">
						<i class="el-icon-warning-outline empty-icon"></i> 暂无待领取数据
					</div>
					<el-card v-for="(warehouse, wIndex) in list" :key="warehouse.Warehouse || wIndex" class="warehouse-card" shadow="hover" :ref="'warehouseCard-' + wIndex">
						<div class="warehouse-header">
							<div class="warehouse-title">
								<i class="el-icon-office-building warehouse-icon"></i>
								<span class="text-nowrap">{{ warehouse.Warehouse || '未知仓库' }}</span>
								<span class="badge">门店 {{ warehouseStoreCount(warehouse) }}</span>
								<span class="badge amount">金额 ¥{{ formatMoney(warehouseAmount(warehouse)) }}</span>
							</div>
							<div class="warehouse-actions">
								<el-button type="primary" icon="el-icon-printer" size="mini" @click="printWarehouse(wIndex)">打印该仓库</el-button>
							</div>
						</div>

						<div v-for="(store, sIndex) in warehouse.Stores || []" :key="store.BatchId || sIndex" class="store-block">
							<div class="store-header">
								<div class="store-info">
									<i class="el-icon-s-shop store-icon"></i>
									<span>{{ store.StoreName || '无' }}</span>
								</div>
								<div class="store-meta">
									<div class="meta-item">
										<i class="el-icon-collection"></i>
										<span>批次号：{{ store.BatchId || '无' }}</span>
									</div>
									<div class="meta-item">
										<i class="el-icon-user"></i>
										<span>申请人：{{ store.ApplicationUserName || '无' }}</span>
									</div>
									<div class="meta-item">
										<i class="el-icon-time"></i>
										<span>申请时间：{{ formatDateTime(store.ApplicationTime) }}</span>
									</div>
									<div class="meta-item highlight">
										<i class="el-icon-coin"></i>
										<span>合计：¥{{ formatMoney(store.TotalAmount) }}</span>
									</div>
								</div>
							</div>

							<NCC-table :data="store.Products || []" :header-cell-style="{ background: '#f5f7fa', color: '#606266' }">
								<el-table-column label="序号" type="index" width="60" align="center" />
								<el-table-column label="产品名称" prop="ProductName" align="center">
									<template slot-scope="scope">
										<div class="product-info">
											<i class="el-icon-box product-icon"></i>
											<span>{{ scope.row.ProductName || '无' }}</span>
										</div>
									</template>
								</el-table-column>
								<el-table-column label="数量" prop="Quantity" align="center">
									<template slot-scope="scope">
										<span>{{ scope.row.Quantity || 0 }}</span>
									</template>
								</el-table-column>
								<el-table-column label="单价" prop="UnitPrice" align="center">
									<template slot-scope="scope">
										<span>¥{{ formatMoney(scope.row.UnitPrice) }}</span>
									</template>
								</el-table-column>
								<el-table-column label="金额" prop="Amount" align="center">
									<template slot-scope="scope">
										<span class="amount-text">¥{{ formatMoney(scope.row.Amount) }}</span>
									</template>
								</el-table-column>
							</NCC-table>
						</div>
					</el-card>
				</div>
			</div>
		</div>
	</div>
</template>

<script>
import request from '@/utils/request'
import printStyle from '../extend/printData/printStyle'
import { getWarehousePendingDelivery } from '@/api/extend/lqInventory'

export default {
	data() {
		return {
			loading: false,
			list: [],
			query: {
				Warehouse: undefined,
				StoreId: undefined
			},
			storeOptions: [],
			warehouseOptions: []
		}
	},
	computed: {
		warehouseCount() {
			return this.list.length
		},
		storeCount() {
			return this.list.reduce((sum, item) => sum + (item.Stores ? item.Stores.length : 0), 0)
		},
		totalAmount() {
			return this.list.reduce((sum, warehouse) => {
				const warehouseSum = (warehouse.Stores || []).reduce((s, store) => s + Number(store.TotalAmount || 0), 0)
				return sum + warehouseSum
			}, 0)
		}
	},
	created() {
		this.initStoreOptions()
		this.initWarehouseOptions()
		this.initData()
	},
	methods: {
		initData() {
			this.loading = true
			getWarehousePendingDelivery({ ...this.query }).then(res => {
				this.loading = false
				if (res.code === 200 && res.data && res.data.success) {
					this.list = res.data.data || []
					return
				}
				this.list = []
				if (res.data && res.data.message) {
					this.$message({
						type: 'info',
						message: res.data.message
					})
				}
			}).catch(() => {
				this.loading = false
				this.list = []
			})
		},
		initStoreOptions() {
			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 = []
			})
		},
		initWarehouseOptions() {
			request({
				url: '/api/Extend/LqProduct/GetList',
				method: 'GET',
				data: {
					currentPage: 1,
					pageSize: 10000
				}
			}).then(res => {
				if (res.code === 200 && res.data && res.data.list) {
					const warehouses = res.data.list
						.map(item => item.warehouse)
						.filter(warehouse => warehouse && warehouse.trim() !== '')
					this.warehouseOptions = [...new Set(warehouses)].sort()
				}
			}).catch(() => {
				this.warehouseOptions = []
			})
		},
		search() {
			this.initData()
		},
		reset() {
			this.query = {
				Warehouse: undefined,
				StoreId: undefined
			}
			this.initData()
		},
		formatMoney(amount) {
			if (!amount && amount !== 0) return '0.00'
			return Number(amount).toFixed(2)
		},
		formatDateTime(value) {
			if (!value) return '无'
			const date = new Date(value)
			if (isNaN(date.getTime())) return '无'
			const y = date.getFullYear()
			const m = String(date.getMonth() + 1).padStart(2, '0')
			const d = String(date.getDate()).padStart(2, '0')
			const h = String(date.getHours()).padStart(2, '0')
			const mi = String(date.getMinutes()).padStart(2, '0')
			const s = String(date.getSeconds()).padStart(2, '0')
			return `${y}-${m}-${d} ${h}:${mi}:${s}`
		},
		warehouseStoreCount(warehouse) {
			return warehouse && warehouse.Stores ? warehouse.Stores.length : 0
		},
		warehouseAmount(warehouse) {
			if (!warehouse || !warehouse.Stores) return 0
			return warehouse.Stores.reduce((sum, store) => sum + Number(store.TotalAmount || 0), 0)
		},
		printWarehouse(index) {
			const warehouse = this.list[index]
			if (!warehouse) {
				this.$message.warning('未找到可打印的仓库数据')
				return
			}
			this.printData([warehouse])
		},
		printAll() {
			if (!this.list.length) {
				this.$message.warning('暂无可打印数据')
				return
			}
			this.printData(this.list)
		},
		printData(warehouses) {
			const css = `
				<style>
					body { margin: 0; padding: 16px; color: #303133; font-size: 12px; font-family: "Microsoft YaHei", Arial, sans-serif; }
					.print-title { text-align: center; font-size: 18px; font-weight: 600; margin-bottom: 12px; }
					.section { margin-bottom: 18px; page-break-after: avoid; }
					.section:last-child { margin-bottom: 0; page-break-after: auto; }
					.warehouse-head { display: flex; justify-content: space-between; align-items: center; margin-bottom: 8px; }
					.warehouse-name { font-size: 15px; font-weight: 600; color: #303133; }
					.badge { background: #ecf5ff; color: #409EFF; padding: 2px 8px; border-radius: 8px; font-size: 12px; margin-left: 8px; }
					.badge-amount { background: #f0f9eb; color: #67C23A; }
					.store-block { border: 1px solid #ebeef5; border-radius: 6px; padding: 10px; margin-bottom: 10px; page-break-inside: avoid; }
					.store-header { display: flex; flex-wrap: wrap; gap: 10px; margin-bottom: 6px; font-size: 12px; color: #606266; }
					.meta { display: flex; gap: 4px; }
					table { width: 100%; border-collapse: collapse; margin-top: 6px; }
					th, td { border: 1px solid #ebeef5; padding: 6px 8px; font-size: 12px; }
					th { background: #f5f5f5; font-weight: 600; text-align: center; }
					td.number { text-align: center; }
					.amount-text { color: #67C23A; font-weight: 600; }
					@media print {
						body { padding: 12px; }
						.section { page-break-after: always; }
						.section:last-child { page-break-after: auto; }
					}
				</style>
			`

			const htmlBlocks = warehouses.map((wh, idx) => {
				const storeBlocks = (wh.Stores || []).map(store => {
					const rows = (store.Products || []).map((p, i) => `
						<tr>
							<td class="number">${i + 1}</td>
							<td>${p.ProductName || '无'}</td>
							<td class="number">${p.Quantity || 0}</td>
							<td class="number">¥${this.formatMoney(p.UnitPrice)}</td>
							<td class="number amount-text">¥${this.formatMoney(p.Amount)}</td>
						</tr>
					`).join('') || '<tr><td colspan="5" class="number">暂无产品</td></tr>'

					return `
						<div class="store-block">
							<div class="store-header">
								<div class="meta"><strong>门店：</strong><span>${store.StoreName || '无'}</span></div>
								<div class="meta"><strong>批次号：</strong><span>${store.BatchId || '无'}</span></div>
								<div class="meta"><strong>申请人：</strong><span>${store.ApplicationUserName || '无'}</span></div>
								<div class="meta"><strong>申请时间：</strong><span>${this.formatDateTime(store.ApplicationTime)}</span></div>
								<div class="meta"><strong>合计：</strong><span class="amount-text">¥${this.formatMoney(store.TotalAmount)}</span></div>
							</div>
							<table>
								<thead>
									<tr>
										<th style="width: 60px;">序号</th>
										<th>产品名称</th>
										<th style="width: 90px;">数量</th>
										<th style="width: 100px;">单价</th>
										<th style="width: 110px;">金额</th>
									</tr>
								</thead>
								<tbody>
									${rows}
								</tbody>
							</table>
						</div>
					`
				}).join('')

				return `
					<div class="section">
						<div class="warehouse-head">
							<div class="warehouse-name">
								${wh.Warehouse || '未知仓库'}
								<span class="badge">门店 ${this.warehouseStoreCount(wh)}</span>
								<span class="badge badge-amount">金额 ¥${this.formatMoney(this.warehouseAmount(wh))}</span>
							</div>
							<div class="meta"><strong>序号：</strong><span>${idx + 1}</span></div>
						</div>
						${storeBlocks || '<div class="store-block">暂无门店数据</div>'}
					</div>
				`
			}).join('')

			const html = `${printStyle}${css}<div class="print-title">仓库待领取清单</div>${htmlBlocks}`
			const newWindow = window.open('_blank')
			if (!newWindow) {
				this.$message.warning('请允许浏览器弹出窗口以打印')
				return
			}
			newWindow.document.write(html)
			newWindow.document.close()
			setTimeout(() => newWindow.print(), 200)
		}
	}
}
</script>

<style lang="scss" scoped>
.head-actions {
	display: flex;
	align-items: center;
	gap: 8px;
}

.statistics-card {
	height: 100px;
	border-radius: 12px;

	.card-content {
		display: flex;
		align-items: center;
		height: 100%;
		padding: 12px;

		.card-icon {
			font-size: 40px;
			color: #409EFF;
			margin-right: 20px;
		}

		.card-info {
			flex: 1;

			.card-label {
				font-size: 14px;
				color: #909399;
				margin-bottom: 8px;
			}

			.card-value {
				font-size: 24px;
				font-weight: 600;
				color: #303133;
			}
		}
	}
}

.warehouse-list {
	// display: flex;
	// flex-direction: column;
	gap: 16px;
	max-height: calc(100vh - 260px);
	overflow-y: scroll;
	// padding-right: 8px;
}

.warehouse-card {
	border-radius: 12px;
}

.warehouse-header {
	display: flex;
	align-items: center;
	justify-content: space-between;
	margin-bottom: 12px;
}

.warehouse-title {
	display: flex;
	align-items: center;
	gap: 10px;
	font-weight: 600;
	font-size: 16px;
}

.warehouse-icon {
	color: #409EFF;
	font-size: 18px;
}

.badge {
	background: #ecf5ff;
	color: #409EFF;
	padding: 2px 8px;
	border-radius: 8px;
	font-size: 12px;
}

.badge.amount {
	background: #f0f9eb;
	color: #67C23A;
}

.warehouse-actions {
	display: flex;
	align-items: center;
	gap: 8px;
}

.store-block {
	border: 1px dashed #ebeef5;
	border-radius: 8px;
	padding: 12px;
	margin-bottom: 12px;

	&:last-child {
		margin-bottom: 0;
	}
}

.store-header {
	display: flex;
	align-items: center;
	justify-content: space-between;
	margin-bottom: 10px;
}

.store-info {
	display: flex;
	align-items: center;
	gap: 6px;
	font-weight: 600;
}

.store-icon {
	color: #409EFF;
	font-size: 16px;
}

.store-meta {
	display: flex;
	align-items: center;
	gap: 12px;
	flex-wrap: wrap;
	color: #606266;
}

.meta-item {
	display: flex;
	align-items: center;
	gap: 4px;
}

.meta-item.highlight {
	color: #67C23A;
	font-weight: 600;
}

.product-info {
	display: flex;
	align-items: center;
	justify-content: center;
	gap: 6px;
}

.product-icon {
	color: #409EFF;
}

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

.empty-text {
	display: flex;
	align-items: center;
	gap: 6px;
	color: #909399;
	justify-content: center;
	padding: 20px 0;
}

.empty-icon {
	font-size: 16px;
}

@media print {
	.warehouse-list {
		max-height: unset;
		overflow: visible;
		padding-right: 0;
	}
}

.text-nowrap {
	white-space: nowrap;
	overflow: hidden;
	text-overflow: ellipsis;
	max-width: 280px;
}

::v-deep .el-table__row:hover {
	background-color: #f5f7fa;
}

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

