<template>
	<view class="live-shop-panel">
		<!-- 购买提示 -->
		<view
			v-if="showPurchasePrompt && orderUser && orderUser.count && liveItem && liveItem.status == 2"
			class="purchase-prompt"
		>
			<image
				class="prompt-icon mr8"
				src="https://bjzmky-1323137866.cos.ap-chongqing.myqcloud.com/userapp/images/signal.png"
			/>
			<text>{{ orderUser.count || 0 }}人正在去购买</text>
		</view>

		<!-- 商品卡片 -->
		<view
			class="goods-card"
			v-if="isShowGoods"
			@click.stop="goShop(goodsCard.productId, goodsCard.goodsId)"
		>
			<view class="goods-card-header">
				<view></view>
				<image
					@click.stop="closeGoodsCard"
					class="close-icon"
					src="/static/images/close_w.png"
				/>
			</view>
			<image class="goods-image" :src="goodsCard.imgUrl" />
			<view class="goods-info">
				<view class="goods-title oneline-hide">{{ goodsCard.productName }}</view>
				<view class="goods-action">
					<view class="goods-price">
						<text class="price-symbol">
							￥<text class="price-integer">{{ goodsCard.price }}</text>
							<text class="price-decimal"></text>
						</text>
					</view>
					<image class="shop-icon" src="/static/images/shop.png"></image>
				</view>
			</view>
		</view>

		<!-- 商品弹窗 -->
		<u-popup :show="shopping" @close="closeShop" round="20rpx" bgColor="#f3f5f9" zIndex="10075">
			<view class="shopping-popup">
				<view class="shopping-header">
					<view class="search-input-container">
						<image
							class="search-icon"
							src="https://bjzmky-1323137866.cos.ap-chongqing.myqcloud.com/userapp/images/search.png"
							mode="widthFix"
						/>
						<input placeholder="请搜索商品" v-model="inputInfo" @input="handleSearchInput" />
					</view>
					<view class="x-f">
						<view class="shopping-action-button mr30" @click="onOpenOrders">
							<image
								class="action-button-icon"
								src="https://bjzmky-1323137866.cos.ap-chongqing.myqcloud.com/userapp/images/carts.png"
							/>
							<view class="action-button-label">订单</view>
						</view>
						<view class="shopping-action-button" @click="onOpenMore">
							<image
								class="action-button-icon"
								src="https://bjzmky-1323137866.cos.ap-chongqing.myqcloud.com/userapp/images/search2.png"
							/>
							<view class="action-button-label">更多</view>
						</view>
					</view>
				</view>

				<scroll-view enable-flex scroll-y class="products-list">
					<view v-for="(item, index) in products" :key="index" class="product-item">
						<view class="product-image-container">
							<image class="product-image" :src="item.imgUrl" mode="widthFix" />
							<view class="product-index-label">{{ index + 1 }}</view>
						</view>
						<view class="product-info">
							<view class="product-name">{{ item.productName }}</view>
							<view class="product-action-section">
								<text class="product-price">
									<text class="price-symbol">￥</text>
									<text class="price-integer">{{ Math.trunc(item.price) }}</text>
									.{{ getPureDecimal(item.price) ? getPureDecimal(item.price) : '00' }}
								</text>
								<view class="product-action-buttons">
									<view class="collect-button">
										<image
											v-if="item.isFavorite"
											@click="onGoodsCollect(item)"
											class="collect-icon"
											src="https://bjzmky-1323137866.cos.ap-chongqing.myqcloud.com/userapp/images/collect_select.png"
										/>
										<image
											v-else
											@click="onGoodsCollect(item)"
											class="collect-icon"
											src="https://bjzmky-1323137866.cos.ap-chongqing.myqcloud.com/userapp/images/collect.png"
										/>
									</view>
									<view
										v-if="item.status == 1"
										class="buy-button"
										@click="goShop(item.productId, item.goodsId)"
									>
										去购买
									</view>
									<view v-else-if="item.status == 0" class="buy-button disabled">已下架</view>
								</view>
							</view>
						</view>
					</view>
				</scroll-view>
			</view>
		</u-popup>
	</view>
</template>

<script>
import { fetchLiveStore, verifyPurchaseLimit } from '../services/liveShopService.js'

export default {
	name: 'LiveShopPanel',
	props: {
		liveId: {
			type: [String, Number],
			default: ''
		},
		storeId: {
			type: [String, Number],
			default: ''
		},
		liveItem: {
			type: Object,
			default: () => ({})
		},
		goodsCard: {
			type: Object,
			default: () => ({})
		},
		isShowGoods: {
			type: Boolean,
			default: false
		},
		orderUser: {
			type: Object,
			default: () => ({})
		},
		showPurchasePrompt: {
			type: Boolean,
			default: false
		}
	},
	data() {
		return {
			shopping: false,
			products: [],
			inputInfo: '',
			loadingProducts: false,
			searchTimer: null,
			goShoppingMap: {}
		}
	},
	beforeDestroy() {
		if (this.searchTimer) {
			clearTimeout(this.searchTimer)
			this.searchTimer = null
		}
	},
	methods: {
		async openCart() {
			if (!this.liveId || this.loadingProducts) return
			await this.fetchProducts(true)
		},
		handleSearchInput() {
			clearTimeout(this.searchTimer)
			this.searchTimer = setTimeout(() => {
				this.fetchProducts(true)
			}, 500)
		},
		async fetchProducts(showPopup = false) {
			if (!this.liveId) return
			this.loadingProducts = true
			if (this.inputInfo == null) this.inputInfo = ''
			uni.showLoading({
				title: '加载中'
			})
			try {
				const res = await fetchLiveStore(this.liveId, this.inputInfo)
				if (showPopup) {
					this.shopping = true
				}
				if (res.code === 200) {
					this.products = Array.isArray(res.data) ? res.data : []
				}
			} catch (error) {
				console.error('获取小黄车商品失败:', error)
			} finally {
				uni.hideLoading()
				this.loadingProducts = false
			}
		},
		async goShop(productId, goodsId) {
			if (!this.liveId) return

			const key = `${productId}_${goodsId}`
			if (this.goShoppingMap[key]) {
				return
			}

			this.$set(this.goShoppingMap, key, true)

			try {
				const res = await verifyPurchaseLimit(productId, 1)
				if (res.code !== 200) {
					uni.showToast({
						icon: 'none',
						title: res.msg || '该商品限购，目前剩余可购买数量不足'
					})
					return
				}
				this.$emit('buy', { productId, goodsId })
			} catch (error) {
				console.error('检查限购失败:', error)
				uni.showToast({
					icon: 'none',
					title: '检查限购失败，请稍后重试'
				})
			} finally {
				setTimeout(() => {
					this.$delete(this.goShoppingMap, key)
				}, 500)
			}
		},
		onGoodsCollect(item) {
			if (!item || !item.goodsId) {
				return
			}
			this.$emit('collect', item)
		},
		closeShop() {
			this.shopping = false
		},
		closeGoodsCard() {
			this.$emit('update:isShowGoods', false)
		},
		onOpenOrders() {
			this.$emit('open-orders')
		},
		onOpenMore() {
			this.shopping = false
			this.$emit('open-more')
		},
		getPureDecimal(num, precision = 6) {
			const decimalPart = Math.abs(num).toFixed(precision).split('.')[1]
			return decimalPart?.replace(/0+$/, '') || ''
		}
	}
}
</script>

<style scoped lang="scss">
.live-shop-panel {
	.purchase-prompt {
		position: absolute;
		bottom: 750rpx;
		left: 24rpx;
		padding: 6rpx 20rpx;
		background: rgba(230, 154, 34, 0.7);
		border-radius: 24rpx;
		z-index: 9;
		font-weight: 500;
		color: #ffffff;
		transition: opacity 0.3s ease;
		font-size: 30rpx;
		display: flex;
		align-items: center;

		.prompt-icon {
			width: 32rpx;
			height: 32rpx;
		}
	}

	.goods-card {
		position: fixed;
		bottom: 140rpx;
		right: 24rpx;
		z-index: 5;
		background-color: #fff;
		border-radius: 20rpx;
		overflow: hidden;
		width: 300rpx;
		padding: 4rpx;

		.goods-card-header {
			position: absolute;
			top: 4rpx;
			display: flex;
			justify-content: space-between;
			align-items: center;
			color: #fff;
			width: 100%;
			padding-right: 10rpx;
			box-sizing: border-box;

			.close-icon {
				width: 30rpx;
				height: 30rpx;
			}
		}

		.goods-image {
			width: 100%;
			height: 300rpx;
			border-radius: 20rpx 20rpx 0 0;
			overflow: hidden;
		}

		.goods-info {
			padding: 4rpx;

			.goods-title {
				font-weight: 600;
				font-size: 32rpx;
				color: rgba(0, 0, 0, 0.85);
				line-height: 44rpx;
				margin: 10rpx 0 12rpx;
			}

			.goods-action {
				color: #fff;
				text-align: center;
				font-weight: 500;
				font-size: 30rpx;
				position: relative;

				.goods-price {
					left: 10rpx;
					position: absolute;
					top: 40%;
					transform: translateY(-50%);
					font-size: 30rpx;
					z-index: 999;

					.price-symbol {
						font-weight: 600;
						font-size: 20rpx;
						color: #ffffff;
					}

					.price-integer {
						font-size: 36rpx;
						margin-right: 10rpx;
					}
				}

				.shop-icon {
					width: 204rpx;
					height: 52rpx;
				}
			}
		}
	}

	.shopping-popup {
		padding: 22rpx 16rpx;

		.shopping-header {
			display: flex;
			justify-content: space-between;
			align-items: center;
			padding: 0 16rpx 22rpx;

			.search-input-container {
				width: 414rpx;
				height: 76rpx;
				background: #ffffff;
				border-radius: 36rpx;
				margin-left: 20rpx;
				padding: 0 32rpx;
				box-sizing: border-box;
				font-size: 24rpx;
				margin-right: 24rpx;
				display: flex;
				align-items: center;
				color: #000;

				.search-icon {
					width: 24rpx;
					margin-right: 16rpx;
				}
			}

			.shopping-action-button {
				display: flex;
				flex-direction: column;
				align-items: center;
				font-size: 20rpx;
				color: #222222;

				.action-button-icon {
					width: 48rpx;
					height: 48rpx;
				}

				.action-button-label {
					text-align: center;
				}
			}
		}

		.products-list {
			height: 30vh;
			overflow: hidden;

			.product-item {
				display: flex;
				align-items: center;
				padding: 20rpx 16rpx;
				background: #ffffff;
				border-radius: 16rpx;
				margin-bottom: 16rpx;

				.product-image-container {
					width: 200rpx;
					height: 200rpx;
					border-radius: 16rpx;
					overflow: hidden;
					position: relative;
					margin-right: 24rpx;

					.product-image {
						width: 100%;
						height: 100%;
					}

					.product-index-label {
						position: absolute;
						top: 0;
						width: 64rpx;
						height: 40rpx;
						background: rgba(0, 0, 0, 0.06);
						border-radius: 16rpx 0 16rpx 0;
						text-align: center;
						font-weight: 500;
						font-size: 28rpx;
						color: rgba(0, 0, 0, 0.85);
					}
				}

				.product-info {
					flex: 1;

					.product-name {
						font-weight: 500;
						font-size: 30rpx;
						color: #000000;
						margin-bottom: 10rpx;
					}

					.product-action-section {
						display: flex;
						justify-content: space-between;
						align-items: center;

						.product-price {
							color: #ff5c03;
							font-size: 22rpx;
							font-weight: 500;

							.price-symbol {
								font-size: 20rpx;
								font-weight: 600;
							}

							.price-integer {
								font-size: 36rpx;
								font-weight: bold;
							}
						}

						.product-action-buttons {
							display: flex;
							align-items: center;
							text-align: center;
							line-height: 56rpx;

							.collect-button {
								width: 72rpx;
								height: 100%;
								background: #f5f7fa;
								border-radius: 8rpx 0 0 8rpx;

								.collect-icon {
									width: 36rpx;
									height: 36rpx;
									vertical-align: middle;
								}
							}

							.buy-button {
								width: 152rpx;
								background: linear-gradient(270deg, #ff5c03 0%, #ffac64 100%);
								border-radius: 0 8rpx 8rpx 0;
								font-weight: 500;
								font-size: 30rpx;
								color: #ffffff;

								&.disabled {
									background: #cccccc;
								}
							}
						}
					}
				}
			}
		}
	}
}
</style>
