<template>
	<view class="order-container">
		<erp-nav-bar title="ERP 下单" :show-back="false" />
		<!-- 0. 全屏加载过渡 -->
		<view class="loading-state-full" v-if="isLoading">
			<view class="loading-anim-box">
				<view class="dot-spinner">
					<view class="dot"></view>
					<view class="dot"></view>
					<view class="dot"></view>
				</view>
				<text class="loading-text">正在同步 ERP 数据...</text>
			</view>
		</view>

		<!-- 1. 未登录状态 -->
		<view class="auth-waiting-full" v-else-if="!isLoggedIn">
			<view class="auth-card">
				<image class="auth-icon" src="https://img.icons8.com/color/192/hourglass-sand-top.png" mode="aspectFit">
				</image>
				<text class="auth-title">未登录</text>
				<text class="auth-desc">您还未登录账号，请先登录以后在进行下单操作</text>
				<button class="contact-btn" @click="goToLogin">前往登录</button>
			</view>
		</view>

		<!-- 2. 已登录但未分配授权客户 -->
		<view class="auth-waiting-full" v-else-if="!myInfo.authClientFRowID">
			<view class="auth-card">
				<image class="auth-icon" src="https://img.icons8.com/color/192/hourglass-sand-top.png" mode="aspectFit">
				</image>
				<text class="auth-title">待管理员授权</text>
				<text class="auth-desc">您的账户尚未获得下单权限，请联系管理员核准授权后即可进行下单操作。</text>
				<button class="contact-btn" @click="contactAdmin">联系管理员</button>
			</view>
		</view>

		<!-- 3. 已登录且已分配授权客户：显示下单页面 -->
		<template v-else>
			<scroll-view scroll-y class="order-scroll-list" :show-scrollbar="false" :enhanced="true">
				<view class="list-wrapper">
					<!-- 列表头部：仅在有数据时显示 -->
					<view class="list-header" v-if="selectedModels.length > 0">
						<text class="header-text">已选型号列表：</text>
					</view>

					<!-- 1. 列表渲染 (精品化设计) -->
					<view class="model-item-card" v-for="(item, index) in selectedModels" :key="index"
						v-if="selectedModels.length > 0" @click="editItem(index, item)">
						<view class="remove-icon" @click.stop="removeItem(index)">
							<text class="x-icon">×</text>
						</view>
						<view class="card-line">
							<view class="model-info">
								<text class="model-value">{{ item.modelNum }}</text>
							</view>
							<view class="count-tag">
								支数<text class="count-num">{{ item.count }}</text>
							</view>
						</view>
						<view class="card-line secondary">
							<text class="surface-label">表面名称：</text>
							<text class="surface-text">{{ item.surfaceName }}</text>
						</view>
					</view>

					<!-- 2. 全屏缺省状态：美化后的引导页 -->
					<view class="empty-state-full" v-else>
						<view class="empty-visual">
							<image class="empty-img" src="https://img.icons8.com/clouds/200/shopping-cart.png"
								mode="aspectFit"></image>
							<view class="empty-bg-glow"></view>
						</view>
						<text class="empty-title">暂无已选型号</text>
						<button class="empty-action-btn" @click="goToAddModel">选型下单</button>
					</view>

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

			<!-- 悬浮添加按钮 (仅在有数据时显示) -->
			<view class="floating-add-btn" @click="goToAddModel" v-if="selectedModels.length > 0">
				<view class="plus-icon"></view>
			</view>

			<!-- 底部支付/下单汇总栏 (仅在有数据时显示) -->
			<view class="footer-summary-bar" v-if="selectedModels.length > 0">
				<view class="summary-info">
					<text class="count-label">共计：</text>
					<text class="num-highlight">{{ selectedModels.length }}</text>
					<text class="unit">条</text>
					<view class="split-line"></view>
					<text class="num-highlight green">{{ totalCount }}</text>
					<text class="unit">支</text>
				</view>
				<button class="submit-order-btn" :disabled="selectedModels.length === 0"
					@click="submitFinalOrder">立即下单</button>
			</view>
		</template>

		<!-- 底部菜单栏 -->
		<erp-tab-bar active="order"></erp-tab-bar>
	</view>
</template>

<script>
import ErpTabBar from '@/components/erp-tab-bar.vue';
import ErpNavBar from '@/components/erp-nav-bar.vue';
import { getMyInfo } from '@/api/system/customer.js';
import { listOrderDetail } from '@/api/erp/orderDetail.js';
import { addOrder } from '@/api/erp/order.js';
export default {
	components: { ErpNavBar, ErpTabBar },
	data() {
		return {
			isLoggedIn: false,
			isLoading: true, // 初始为加载中
			myInfo: {},
			selectedModels: []
		}
	},
	computed: {
		totalCount() {
			return this.selectedModels.reduce((sum, item) => sum + parseInt(item.count || 0), 0);
		}
	},
	onLoad() {
		// 监听添加型号的事件 - 重新从后端加载
		uni.$on('add_order_item', (data) => {
			this.loadOrderItems(false); // 添加时静默加载，不显示全屏动画
		});
		// 监听修改型号的事件 - 重新从后端加载
		uni.$on('update_order_item', (res) => {
			this.loadOrderItems(false);
		});
	},
	onShow() {
		this.checkLoginStatus();
	},
	onUnload() {
		uni.$off('add_order_item');
		uni.$off('update_order_item');
	},
	methods: {
		/**
		 * 加载已选型号列表（OrderID 为空的草稿）
		 * @Author: Antigravity
		 */
		async loadOrderItems(showFullLoading = true) {
			if (showFullLoading) this.isLoading = true;
			try {
				const res = await listOrderDetail({ orderId: '' });
				this.selectedModels = res.data || [];
			} catch (e) {
				console.error('加载型号列表失败', e);
			} finally {
				this.isLoading = false;
			}
		},
		async checkLoginStatus() {
			const token = uni.getStorageSync('token');
			if (!token) {
				this.isLoggedIn = false;
				this.myInfo = {};
				return;
			}
			try {
				const res = await getMyInfo();
				this.isLoggedIn = true;
				this.myInfo = res.data || {};
				// 登录成功后加载列表
				this.loadOrderItems();
			} catch (e) {
				uni.removeStorageSync('token');
				uni.removeStorageSync('isLogin');
				this.isLoggedIn = false;
				this.myInfo = {};
				this.isLoading = false;
			}
		},
		goToLogin() {
			uni.reLaunch({ url: '/pages/login/index' });
		},
		contactAdmin() { uni.showModal({ title: '联系管理员', content: '管理员电话：138-0000-0000', showCancel: false, confirmColor: '#C1001C' }); },
		goToAddModel() {
			uni.navigateTo({
				url: '/pages/order/add-model/index'
			});
		},
		editItem(index, item) {
			uni.navigateTo({
				url: `/pages/order/edit-model/index?index=${index}&data=${encodeURIComponent(JSON.stringify(item))}`
			});
		},
		removeItem(index) {
			const self = this;
			uni.showModal({
				title: '提示',
				content: '确定移除该型号吗？',
				success: (res) => {
					if (res.confirm) {
						self.selectedModels.splice(index, 1);
					}
				}
			});
		},
		async submitFinalOrder() {
			if (this.selectedModels.length === 0) return;

			uni.showLoading({ title: '正在提交订单', mask: true });
			try {
				const detailIds = this.selectedModels.map(item => item.rowId);
				const res = await addOrder({ detailIds });
				uni.hideLoading();
				const orderId = res.data;
				uni.showToast({ title: '下单成功', icon: 'success' });
				setTimeout(() => {
					uni.navigateTo({
						url: '/pages/order/success/index?orderId=' + orderId
					});
				}, 1500);
			} catch (e) {
				uni.hideLoading();
				// request.js 会统一处理并提示异常信息
			}
		}
	}
}
</script>

<style scoped>
/deep/ ::-webkit-scrollbar {
	display: none !important;
	width: 0 !important;
	height: 0 !important;
}

.order-container {
	width: 100%;
	height: 100vh;
	background: #f8fafc;
	display: flex;
	flex-direction: column;
	overflow: hidden;
}

/* 授权等待样式保持一致 */
.auth-waiting-full {
	flex: 1;
	display: flex;
	flex-direction: column;
	align-items: center;
	justify-content: flex-start;
	padding: 200rpx 40rpx 40rpx;
	background: linear-gradient(180deg, rgba(0, 122, 255, 0.08) 0%, rgba(247, 248, 250, 1) 100%);
}

.auth-card {
	display: flex;
	flex-direction: column;
	align-items: center;
	text-align: center;
}

.auth-icon {
	width: 200rpx;
	height: 200rpx;
	margin-bottom: 50rpx;
}

.auth-title {
	font-size: 44rpx;
	font-weight: bold;
	color: #1a1a1a;
	margin-bottom: 24rpx;
}

.auth-desc {
	font-size: 28rpx;
	color: #666;
	line-height: 1.8;
	margin-bottom: 80rpx;
	padding: 0 20rpx;
}

.contact-btn {
	width: 360rpx;
	height: 96rpx;
	background: linear-gradient(135deg, #C1001C 0%, #FF4D4F 100%);
	color: #fff;
	border-radius: 48rpx;
	display: flex;
	align-items: center;
	justify-content: center;
	font-size: 32rpx;
	font-weight: bold;
	border: none;
	box-shadow: 0 12rpx 30rpx rgba(193, 0, 28, 0.2);
}

.authorized-btn {
	width: 360rpx;
	height: 96rpx;
	background: #fff;
	color: #C1001C;
	border-radius: 48rpx;
	display: flex;
	align-items: center;
	justify-content: center;
	font-size: 32rpx;
	font-weight: bold;
	border: 2rpx solid #C1001C;
	margin-top: 30rpx;
}

/* 已授权列表页样式 */
.order-container {
	width: 100%;
	height: 100vh;
	background: #f7f8fa;
	display: flex;
	flex-direction: column;
	overflow: hidden;
}

.order-scroll-list {
	flex: 1;
	height: 0;
}

.list-wrapper {
	padding: 30rpx;
	/* 确保最后一条数据不被底部双层固定栏遮挡：汇总栏130 + 菜单栏110 + 安全区 + 缓冲余量 */
	padding-bottom: calc(280rpx + env(safe-area-inset-bottom));
}

.list-header {
	padding: 10rpx 0 20rpx;
}

.header-text {
	font-size: 34rpx;
	font-weight: bold;
	color: #1a1a1a;
	position: relative;
	padding-left: 24rpx;
}

.header-text::before {
	content: '';
	position: absolute;
	left: 0;
	top: 10%;
	height: 80%;
	width: 8rpx;
	background: #C1001C;
	border-radius: 4rpx;
}

/* 型号卡片：大幅升级美化 */
.model-item-card {
	background: #fff;
	border-radius: 24rpx;
	padding: 36rpx;
	margin-bottom: 30rpx;
	position: relative;
	box-shadow: 0 8rpx 30rpx rgba(0, 0, 0, 0.04);
	border: 1rpx solid rgba(0, 0, 0, 0.02);
}

.remove-icon {
	position: absolute;
	right: 0;
	top: 0;
	width: 50rpx;
	height: 50rpx;
	background: rgba(255, 77, 79, 0.1);
	border-radius: 0 24rpx 0 24rpx;
	display: flex;
	align-items: center;
	justify-content: center;
	z-index: 5;
}

.x-icon {
	font-size: 32rpx;
	color: #ff4d4f;
	font-weight: bold;
}

.card-line {
	display: flex;
	align-items: center;
	margin-bottom: 20rpx;
}

.card-line.secondary {
	margin-bottom: 0;
	padding-top: 20rpx;
	border-top: 1rpx dashed #f0f0f0;
}

.model-value {
	font-size: 34rpx;
	font-weight: bold;
	color: #333;
	flex: 1;
}

.count-tag {
	background: #FFF1F2;
	color: #C1001C;
	padding: 4rpx 16rpx;
	border-radius: 8rpx;
	font-size: 24rpx;
	font-weight: bold;
}

.count-num {
	font-size: 30rpx;
	margin-left: 8rpx;
}

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

.surface-text {
	font-size: 28rpx;
	color: #666;
}

/* 悬浮添加按钮：位置上移避免拥挤 */
.floating-add-btn {
	position: fixed;
	right: 40rpx;
	bottom: calc(260rpx + env(safe-area-inset-bottom) + 40rpx);
	width: 110rpx;
	height: 110rpx;
	background: #C1001C;
	border-radius: 50%;
	display: flex;
	align-items: center;
	justify-content: center;
	box-shadow: 0 12rpx 40rpx rgba(193, 0, 28, 0.4);
	z-index: 100;
	transition: transform 0.2s;
}

.floating-add-btn:active {
	transform: scale(0.9);
}

.plus-icon {
	width: 40rpx;
	height: 4rpx;
	background: #fff;
	border-radius: 2rpx;
	position: relative;
}

.plus-icon::after {
	content: '';
	position: absolute;
	top: 0;
	left: 0;
	width: 100%;
	height: 100%;
	background: #fff;
	transform: rotate(90deg);
	border-radius: 2rpx;
}

/* 底部汇总栏：微调间距与样式 */
.footer-summary-bar {
	position: fixed;
	bottom: calc(110rpx + env(safe-area-inset-bottom));
	left: 0;
	width: 100%;
	height: 130rpx;
	background: #fff;
	border-top: 1rpx solid #f0f0f0;
	display: flex;
	align-items: center;
	justify-content: space-between;
	padding: 0 40rpx;
	box-sizing: border-box;
	z-index: 99;
	box-shadow: 0 -10rpx 40rpx rgba(0, 0, 0, 0.05);
}

.summary-info {
	display: flex;
	align-items: center;
}

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

.num-highlight {
	font-size: 36rpx;
	font-weight: bold;
	color: #1a1a1a;
	margin: 0 4rpx;
}

.num-highlight.green {
	color: #C1001C;
}

.unit {
	font-size: 24rpx;
	color: #999;
	margin-left: 2rpx;
}

.split-line {
	width: 1rpx;
	height: 30rpx;
	background: #eee;
	margin: 0 20rpx;
}

.submit-order-btn {
	width: 220rpx;
	height: 80rpx;
	background: #e0e0e0;
	color: #666;
	font-size: 28rpx;
	border-radius: 40rpx;
	display: flex;
	align-items: center;
	justify-content: center;
	border: none;
	margin: 0;
	transition: all 0.3s;
}

.submit-order-btn:not([disabled]) {
	background: #C1001C;
	color: #fff;
	font-weight: bold;
}

/* 全屏缺省页样式 */
.empty-state-full {
	display: flex;
	flex-direction: column;
	align-items: center;
	justify-content: center;
	padding-top: 120rpx;
}

.empty-visual {
	position: relative;
	margin-bottom: 40rpx;
	width: 400rpx;
	height: 400rpx;
	display: flex;
	align-items: center;
	justify-content: center;
}

.empty-img {
	width: 320rpx;
	height: 320rpx;
	z-index: 2;
}

.empty-bg-glow {
	position: absolute;
	width: 240rpx;
	height: 240rpx;
	background: radial-gradient(circle, rgba(193, 0, 28, 0.15) 0%, rgba(248, 250, 252, 0) 70%);
	z-index: 1;
	border-radius: 50%;
}

.empty-title {
	font-size: 36rpx;
	font-weight: bold;
	color: #1a1a1a;
	margin-bottom: 80rpx;
}

.empty-desc {
	font-size: 26rpx;
	color: #999;
	margin-bottom: 60rpx;
	text-align: center;
	padding: 0 80rpx;
	line-height: 1.6;
}

.empty-action-btn {
	width: 320rpx;
	height: 90rpx;
	background: #C1001C;
	color: #fff;
	border-radius: 45rpx;
	font-size: 30rpx;
	font-weight: bold;
	display: flex;
	align-items: center;
	justify-content: center;
	box-shadow: 0 10rpx 30rpx rgba(193, 0, 28, 0.2);
	border: none;
}

.empty-action-btn:active {
	opacity: 0.8;
	transform: scale(0.96);
}

.bottom-safe-space {
	height: 100rpx;
}

/* 加载动画样式 */
.loading-state-full {
	flex: 1;
	display: flex;
	align-items: center;
	justify-content: center;
	padding-bottom: 200rpx;
}

.loading-anim-box {
	display: flex;
	flex-direction: column;
	align-items: center;
}

.dot-spinner {
	display: flex;
	justify-content: center;
	align-items: center;
	margin-bottom: 30rpx;
}

.dot {
	width: 16rpx;
	height: 16rpx;
	background-color: #C1001C;
	border-radius: 50%;
	margin: 0 8rpx;
	animation: dot-pulse 1.4s infinite ease-in-out both;
}

.dot:nth-child(1) {
	animation-delay: -0.32s;
}

.dot:nth-child(2) {
	animation-delay: -0.16s;
}

@keyframes dot-pulse {

	0%,
	80%,
	100% {
		transform: scale(0);
		opacity: 0.3;
	}

	40% {
		transform: scale(1);
		opacity: 1;
	}
}

.loading-text {
	font-size: 26rpx;
	color: #999;
	letter-spacing: 2rpx;
}
</style>
