<template>
	<view class="goods-stock-page">
		<erp-nav-bar title="库存信息" />

		<!-- 客户分类标签 -->
		<scroll-view scroll-x class="client-tabs" :show-scrollbar="false" :scroll-with-animation="true"
			:scroll-into-view="'ctab-' + currentTab">
			<view class="client-tabs-box">
				<view v-for="(tab, index) in clientTabs" :key="index" :id="'ctab-' + index" class="client-tab-item"
					:class="{ active: currentTab === index }" @click="switchTab(index)">
					<text class="client-tab-txt">{{ tab.label }}</text>
				</view>
			</view>
		</scroll-view>

		<!-- 库存列表滚动区 -->
		<scroll-view scroll-y class="stock-scroll-view" :style="{ height: scrollHeight }" @scrolltolower="onReachEnd"
			:refresher-enabled="true" :refresher-triggered="refresherTriggered" @refresherrefresh="onPullDownRefresh"
			:show-scrollbar="false">

			<view class="stock-list-inner">
				<view class="stock-card" v-for="(item, index) in displayList" :key="index">
					<view class="stock-card-head">
						<!-- 全部：客户名称为主标题；锁定客户：型号为主标题 -->
						<view class="stock-model-info" v-if="currentTab === 0">
							<text class="stock-model">{{ item.clientName || '-' }}</text>
							<text class="stock-client" v-if="item.saleCode">{{ item.saleCode }}</text>
						</view>
						<view class="stock-model-info" v-else>
							<text class="stock-model">{{ item.saleCode }}</text>
							<text class="stock-client">{{ item.clientName || '-' }}</text>
						</view>
					</view>
					<view class="stock-card-body">
						<view class="stock-info-row">
							<text class="stock-label">支数</text>
							<text class="stock-value highlight">{{ item.sumQty != null ? item.sumQty : '-' }} 支</text>
						</view>
						<view class="stock-info-row">
							<text class="stock-label">重量</text>
							<text class="stock-value">{{ item.sumWt != null ? Number(item.sumWt).toFixed(2) + ' kg' :
								'-' }}</text>
						</view>
					</view>
				</view>

				<!-- 加载提示 -->
				<view class="list-status-info" v-if="displayList.length > 0">
					<view class="loading-wrap" v-if="loading">
						<view class="load-dot"></view><text>加载中...</text>
					</view>
					<view class="nomore-wrap" v-if="noMore">
						<text class="nomore-line"></text>
						<text class="nomore-text">已加载全部数据</text>
						<text class="nomore-line"></text>
					</view>
				</view>

				<!-- 缺省态 -->
				<view class="empty-state" v-if="displayList.length === 0 && !loading">
					<image src="https://img.icons8.com/clouds/200/open-box.png" mode="aspectFit"></image>
					<text>暂无库存记录</text>
				</view>

				<view class="safe-bottom"></view>
			</view>
		</scroll-view>
	</view>
</template>

<script>
import ErpNavBar from '@/components/erp-nav-bar.vue';
import { getGoodsStockSummaryPage } from '@/api/erp/goodsStock.js';
import { getMyInfo } from '@/api/system/employee.js';
import { getClientByIds } from '@/api/erp/client.js';

export default {
	components: { ErpNavBar },
	data() {
		return {
			statusBarHeight: 20,
			navBarHeight: 44,
			currentTab: 0,
			loading: false,
			noMore: false,
			refresherTriggered: false,
			pageNum: 1,
			pageSize: 10,
			clientTabs: [{ label: '全部', clientId: '' }],
			displayList: []
		}
	},
	computed: {
		scrollHeight() {
			return `calc(100vh - ${this.statusBarHeight + this.navBarHeight + 40}px)`;
		}
	},
	onLoad() {
		const winInfo = uni.getWindowInfo ? uni.getWindowInfo() : uni.getSystemInfoSync();
		this.statusBarHeight = winInfo.statusBarHeight;
		this.loadClientTabs();
	},
	methods: {
		async loadClientTabs() {
			try {
				const res = await getMyInfo();
				const employee = res.data;
				if (employee && employee.authClientFRowIDs) {
					const ids = employee.authClientFRowIDs.split(',').map(s => s.trim()).filter(Boolean);
					if (ids.length > 0) {
						const clientRes = await getClientByIds(ids.join(','));
						const clients = clientRes.data || [];
						const tabs = [{ label: '全部', clientId: '' }];
						clients.forEach(c => {
							tabs.push({ label: c.name || c.num || '-', clientId: c.frowId || c.rowId || '' });
						});
						this.clientTabs = tabs;
					}
				}
			} catch (e) {
				console.error('加载授权客户失败', e);
			}
			this.refresh();
		},
		switchTab(i) {
			this.currentTab = i;
			this.refresh();
		},
		refresh() {
			this.displayList = [];
			this.noMore = false;
			this.pageNum = 1;
			this.loadData();
		},
		onPullDownRefresh() {
			this.refresherTriggered = true;
			this.refresh();
			setTimeout(() => { this.refresherTriggered = false; }, 500);
		},
		onReachEnd() {
			if (!this.loading && !this.noMore) this.loadData();
		},
		async loadData() {
			if (this.loading || this.noMore) return;
			this.loading = true;
			try {
				const currentClient = this.clientTabs[this.currentTab];
				const params = {
					pageNum: this.pageNum,
					pageSize: this.pageSize
				};
				if (currentClient && currentClient.clientId) {
					params.clientId = currentClient.clientId;
				}
				const res = await getGoodsStockSummaryPage(params);
				const rows = res.rows || [];

				this.displayList = [...this.displayList, ...rows];
				this.pageNum++;
				this.noMore = rows.length === 0 || this.displayList.length >= (res.total || 0);
			} catch (e) {
				console.error('加载库存列表失败', e);
				uni.showToast({ title: e || '加载失败', icon: 'none' });
			} finally {
				this.loading = false;
			}
		}
	}
}
</script>

<style scoped>
.goods-stock-page {
	width: 100vw;
	height: 100vh;
	background: #f7f8fa;
	display: flex;
	flex-direction: column;
	overflow: hidden;
}

/* ========== 客户标签栏 ========== */
.client-tabs {
	flex-shrink: 0;
	background: #fff;
	border-bottom: 1rpx solid #f0f0f0;
	white-space: nowrap;
}

.client-tabs-box {
	display: flex;
	padding: 0 20rpx;
	height: 80rpx;
	align-items: center;
	gap: 10rpx;
}

.client-tab-item {
	display: flex;
	align-items: center;
	justify-content: center;
	padding: 0 28rpx;
	height: 56rpx;
	border-radius: 28rpx;
	background: #f5f6f7;
	flex-shrink: 0;
	transition: all 0.2s;
}

.client-tab-item.active {
	background: #C1001C;
}

.client-tab-txt {
	font-size: 26rpx;
	color: #666;
}

.client-tab-item.active .client-tab-txt {
	color: #fff;
	font-weight: 600;
}

/* ========== 滚动列表区 ========== */
.stock-scroll-view {
	width: 100%;
	flex: 1;
}

.stock-list-inner {
	padding: 20rpx 30rpx;
}

/* ========== 库存卡片 ========== */
.stock-card {
	background: #fff;
	border-radius: 20rpx;
	padding: 30rpx;
	margin-bottom: 20rpx;
	box-shadow: 0 4rpx 16rpx rgba(0, 0, 0, 0.03);
}

.stock-card-head {
	display: flex;
	justify-content: space-between;
	align-items: flex-start;
	margin-bottom: 24rpx;
	padding-bottom: 20rpx;
	border-bottom: 1rpx solid #f5f5f5;
}

.stock-model-info {
	display: flex;
	flex-direction: column;
	gap: 6rpx;
}

.stock-model {
	font-size: 30rpx;
	font-weight: bold;
	color: #1a1a1a;
}

.stock-client {
	font-size: 24rpx;
	color: #999;
}

.stock-card-body {
	display: flex;
	flex-direction: column;
	gap: 16rpx;
}

.stock-info-row {
	display: flex;
	justify-content: space-between;
	align-items: center;
}

.stock-label {
	font-size: 26rpx;
	color: #999;
}

.stock-value {
	font-size: 26rpx;
	color: #333;
	font-weight: 500;
}

.stock-value.highlight {
	color: #C1001C;
	font-weight: bold;
	font-size: 30rpx;
}

/* ========== 加载状态 ========== */
.list-status-info {
	padding: 30rpx 0;
}

.loading-wrap {
	display: flex;
	align-items: center;
	justify-content: center;
	gap: 16rpx;
	font-size: 26rpx;
	color: #aaa;
}

.load-dot {
	width: 12rpx;
	height: 12rpx;
	border-radius: 50%;
	background: #ccc;
	animation: dot-blink 1s infinite;
}

@keyframes dot-blink {

	0%,
	100% {
		opacity: 0.3;
	}

	50% {
		opacity: 1;
	}
}

.nomore-wrap {
	display: flex;
	align-items: center;
	justify-content: center;
	gap: 16rpx;
}

.nomore-line {
	width: 60rpx;
	height: 1rpx;
	background: #e0e0e0;
}

.nomore-text {
	font-size: 24rpx;
	color: #ccc;
}

/* ========== 空状态 ========== */
.empty-state {
	display: flex;
	flex-direction: column;
	align-items: center;
	justify-content: center;
	padding: 120rpx 0;
}

.empty-state image {
	width: 160rpx;
	height: 160rpx;
	margin-bottom: 30rpx;
	opacity: 0.5;
}

.empty-state text {
	font-size: 28rpx;
	color: #bbb;
}

.safe-bottom {
	height: 60rpx;
}
</style>
