<template>
	<view class="goods-detail">
		<!-- 产品图片列表 -->
		<view class="product-images" v-if="productImages.length > 0">
			<image v-for="(imageUrl, index) in productImages" :key="index" :src="$baseUrl + imageUrl"
				class="product-image" mode="widthFix" :lazy-load="true" @error="onImageError" @load="onImageLoad" />
		</view>

		<!-- 商品信息区域 -->
		<view class="product-info" v-if="currentProduct">
			<view class="product-name">{{ currentProduct.name }}</view>
			<view class="product-stock">库存 {{ currentProduct.stock || 0 }}件</view>
			<view class="product-price">{{ currentProduct.price || '0' }}积分</view>
			<view class="exchange-hint">点击选择规格</view>
		</view>

		<!-- 兑换按钮 -->
		<view class="exchange-section" v-if="currentProduct">
			<view class="exchange-btn" @tap="handleExchange">
				<text class="exchange-btn-text">{{ getExchangeButtonText() }}</text>
			</view>
		</view>

		<!-- 固定底部按钮区域 -->
		<view class="fixed-bottom">
			<view class="button-group">
				<image class="rights-btn" :src="$baseUrl + rightsBtn" @click="handleGoToRights">
				</image>
				<button class="share-btn" :src="$baseUrl + shareBtn" style="background: none; border: none; padding: 0;"
					open-type="share">
					<image class="share-btn-img" :src="$baseUrl + shareBtn" />
				</button>
			</view>
		</view>

		<!-- 规格选择弹窗 -->
		<view v-if="showSpecModal" class="spec-modal-overlay" @tap="hideSpecModal">
			<view class="spec-modal-content" @tap.stop>
				<!-- 关闭按钮 -->
				<view class="close-btn" @tap="hideSpecModal">
					<text class="close-icon">×</text>
				</view>

				<!-- 商品信息 -->
				<view class="spec-product-info">
					<view class="product-thumbnail">
						<image :src="$baseUrl + (currentProduct?.thumbnail || productImages[0])" class="thumbnail-img" />
					</view>
					<view class="product-details">
						<view class="product-name">{{ currentProduct?.name || '商品名称' }}</view>
						<view class="product-stock">库存 {{ currentProduct?.stock || 0 }}件</view>
					</view>
				</view>

				<!-- 净含量选择 -->
				<view class="spec-section">
					<view class="spec-label">净含量</view>
					<view class="spec-options">
						<view v-for="(spec, index) in netContentOptions" :key="index" 
							class="spec-option" 
							:class="{ 'selected': selectedNetContent === spec }"
							@tap="selectNetContent(spec)">
							{{ spec }}
						</view>
					</view>
				</view>

				<!-- 数量选择 -->
				<view class="spec-section">
					<view class="spec-label">选择数量 (限购{{ currentProduct?.limit || 1 }}件)</view>
					<view class="quantity-selector">
						<view class="quantity-btn" @tap="decreaseQuantity" :class="{ 'disabled': quantity <= 1 }">-</view>
						<view class="quantity-display">{{ quantity }}</view>
						<view class="quantity-btn" @tap="increaseQuantity" :class="{ 'disabled': quantity >= (currentProduct?.limit || 1) }">+</view>
					</view>
				</view>

				<!-- 确认按钮 -->
				<view class="confirm-spec-btn" @tap="confirmSpec">确认</view>
			</view>
		</view>
	</view>
</template>

<script setup>
import { ref, onMounted, computed, getCurrentInstance } from 'vue'
import { getProductById, getProductImagesById, getShareImageById, getShareTextById, shareBtn, rightsBtn } from '@/utils/constant.js'
import { useUserStore } from '@/stores/user'
import { jump, JumpType } from '@/utils'

// 响应式数据
const productId = ref('')
const currentProduct = ref(null)
const isLoading = ref(true)

// 用户状态
const userStore = ref(null)
const isLoggedIn = ref(false)

// 规格选择相关数据
const showSpecModal = ref(false)
const selectedNetContent = ref('')
const quantity = ref(1)
const netContentOptions = ref(['100g', '200g', '500g'])

// 计算属性
const productImages = computed(() => {
	return currentProduct.value ? currentProduct.value.productImages : []
})

// 页面加载时获取商品ID和产品信息
onMounted(async () => {
	// 初始化用户状态
	await initUserStatus()
	
	// 获取页面参数
	const pages = getCurrentPages()
	const currentPage = pages[pages.length - 1]
	const options = currentPage.options || {}

	// 获取goodId参数
	productId.value = options.goodId || ''

	console.log('接收到的产品ID:', productId.value)

	if (productId.value) {
		loadProductInfo()
	}
})

// 加载产品信息
const loadProductInfo = () => {
	const product = getProductById(productId.value)
	if (product) {
		currentProduct.value = product
		console.log('产品信息加载成功:', product)
	} else {
		console.warn('未找到对应的产品信息:', productId.value)
	}
}

// 初始化用户状态
const initUserStatus = async () => {
	// 获取用户store实例
	userStore.value = useUserStore()
	
	// 加载会员信息
	await userStore.value.loadMemberInfo()
	
	// 检查用户状态
	checkLoginStatus()
}

// 检查登录状态
const checkLoginStatus = () => {
	if (!userStore.value) {
		isLoggedIn.value = false
		return
	}
	
	// 检查用户信息是否存在且有效
	const userInfo = userStore.value.userInfo
	const memberId = userInfo?.memberId
	
	// 如果memberId为"not_login"或不存在，则未登录
	if (!memberId || memberId === "not_login") {
		isLoggedIn.value = false
	} else {
		isLoggedIn.value = true
	}
	
	console.log('登录状态检查:', {
		userInfo,
		memberId,
		isLoggedIn: isLoggedIn.value
	})
}

// 获取兑换按钮文本
const getExchangeButtonText = () => {
	return isLoggedIn.value ? '马上兑换' : '马上兑换'
}

// 处理兑换按钮点击
const handleExchange = () => {
	if (!isLoggedIn.value) {
		// 未登录，跳转到登录注册页面
		jump({
			type: JumpType.INNER,
			url: "/pages/activity/register",
		})
		return
	}
	
	// 已登录，显示规格选择弹窗
	openSpecModal()
}

// 图片加载成功
const onImageLoad = (e) => {
	console.log('图片加载成功:', e.target.src)
}

// 图片加载失败
const onImageError = (e) => {
	console.error('图片加载失败:', e.target.src)
}

// 跳转权益页面
const handleGoToRights = () => {
	uni.navigateTo({
		url: `/pages/rightsDetail/rightsDetail?rightsId=rights1`
	})
}

// 显示规格选择弹窗
const openSpecModal = () => {
	showSpecModal.value = true
	// 默认选择第一个净含量选项
	if (netContentOptions.value.length > 0) {
		selectedNetContent.value = netContentOptions.value[0]
	}
}

// 隐藏规格选择弹窗
const hideSpecModal = () => {
	showSpecModal.value = false
}

// 选择净含量
const selectNetContent = (spec) => {
	selectedNetContent.value = spec
}

// 增加数量
const increaseQuantity = () => {
	const maxLimit = currentProduct.value?.limit || 1
	if (quantity.value < maxLimit) {
		quantity.value++
	}
}

// 减少数量
const decreaseQuantity = () => {
	if (quantity.value > 1) {
		quantity.value--
	}
}

// 确认规格选择
const confirmSpec = () => {
	if (!selectedNetContent.value) {
		uni.showToast({
			title: '请选择净含量',
			icon: 'none'
		})
		return
	}
	
	// 这里可以处理兑换逻辑
	console.log('选择的规格:', {
		netContent: selectedNetContent.value,
		quantity: quantity.value,
		productId: productId.value
	})
	
	uni.showToast({
		title: '规格选择成功',
		icon: 'success'
	})
	
	hideSpecModal()
}
</script>

<script>
// 微信小程序分享配置 - 使用 Options API
export default {
	// 自定义分享内容
	onShareAppMessage() {
		const pages = getCurrentPages()
		const currentPage = pages[pages.length - 1]
		const options = currentPage.options || {}
		const productId = options.goodId || ''

		// 获取产品信息
		const product = getProductById(productId)

		const { proxy } = getCurrentInstance();
		const $baseUrl = proxy.$baseUrl;
		console.log('product', product)


		return {
			title: product.shareText || product.name,
			path: `/pages/goodsDetail/goodsDetail?goodId=${productId}`,
			imageUrl: product.shareImage ? `${$baseUrl + product.shareImage}` : undefined
		}
	},

}
</script>

<style lang="scss" scoped>
.goods-detail {
	min-height: 100vh;
}

.product-images {
	width: 100%;
}

.product-image {
	width: 100%;
	display: block;
}

.fixed-bottom {
	position: fixed;
	bottom: 75rpx;
	left: 0;
	right: 0;
	padding: 20rpx 30rpx;
	z-index: 999;
}

.button-group {
	display: flex;
	gap: 20rpx;
}

.share-btn {
	width: 350rpx;
	height: 75rpx;
	display: flex;
	align-items: center;
	justify-content: center;
	background: transparent;
	border: none;
	padding: 0;


}

.share-btn::after {
	border: none !important;
}

.share-btn-img {
	width: 100%;
	height: 100%;
}

.rights-btn {
	width: 350rpx;
	height: 75rpx;
	display: flex;
	align-items: center;
	justify-content: center;
}

.fixed-bottom {
	padding-bottom: calc(20rpx + var(--window-bottom));
}

.fixed-bottom {
	padding-bottom: 20rpx;
}

/* 商品信息样式 */
.product-info {
	padding: 30rpx;
	background-color: #ffffff;
	margin: 20rpx;
	border-radius: 20rpx;
}

.product-name {
	font-size: 36rpx;
	font-weight: bold;
	color: #333333;
	margin-bottom: 20rpx;
}

.product-stock {
	font-size: 28rpx;
	color: #666666;
	margin-bottom: 10rpx;
}

.product-price {
	font-size: 32rpx;
	color: #D3A458;
	font-weight: bold;
}

.exchange-hint {
	font-size: 24rpx;
	color: #999999;
	margin-top: 10rpx;
	text-align: center;
}

/* 兑换按钮样式 */
.exchange-section {
	padding: 0 30rpx;
	margin-bottom: 20rpx;
}

.exchange-btn {
	width: 100%;
	height: 88rpx;
	background-color: #D3A458;
	border-radius: 44rpx;
	display: flex;
	align-items: center;
	justify-content: center;
}

.exchange-btn-text {
	font-size: 32rpx;
	color: #ffffff;
	font-weight: 500;
}

/* 规格选择弹窗样式 */
.spec-modal-overlay {
	position: fixed;
	top: 0;
	left: 0;
	right: 0;
	bottom: 0;
	background-color: rgba(0, 0, 0, 0.5);
	z-index: 200;
	display: flex;
	justify-content: center;
	align-items: flex-end;
}

.spec-modal-content {
	background-color: #ffffff;
	width: 100%;
	border-top-left-radius: 20rpx;
	border-top-right-radius: 20rpx;
	height: 80vh;
	display: flex;
	flex-direction: column;
	animation: slideUp 0.3s ease-out;
	position: relative;
}

@keyframes slideUp {
	from {
		transform: translateY(100%);
	}
	to {
		transform: translateY(0);
	}
}

.close-btn {
	position: absolute;
	top: 20rpx;
	right: 20rpx;
	width: 60rpx;
	height: 60rpx;
	display: flex;
	align-items: center;
	justify-content: center;
	z-index: 10;
}

.close-icon {
	font-size: 40rpx;
	color: #999999;
}

.spec-product-info {
	display: flex;
	padding: 30rpx;
	border-bottom: 1rpx solid #f0f0f0;
	margin-top: 40rpx;
}

.product-thumbnail {
	width: 120rpx;
	height: 120rpx;
	margin-right: 20rpx;
}

.thumbnail-img {
	width: 100%;
	height: 100%;
	border-radius: 10rpx;
}

.product-details {
	flex: 1;
	display: flex;
	flex-direction: column;
	justify-content: center;
}

.spec-section {
	padding: 30rpx;
	border-bottom: 1rpx solid #f0f0f0;
}

.spec-label {
	font-size: 30rpx;
	color: #333333;
	margin-bottom: 20rpx;
}

.spec-options {
	display: flex;
	gap: 20rpx;
	flex-wrap: wrap;
}

.spec-option {
	padding: 15rpx 30rpx;
	border: 1rpx solid #e0e0e0;
	border-radius: 10rpx;
	font-size: 28rpx;
	color: #666666;
	background-color: #ffffff;
}

.spec-option.selected {
	border-color: #D3A458;
	color: #D3A458;
	background-color: #FFF9F0;
}

.quantity-selector {
	display: flex;
	align-items: center;
	gap: 20rpx;
}

.quantity-btn {
	width: 60rpx;
	height: 60rpx;
	border: 1rpx solid #A8A8A8;
	border-radius: 10rpx;
	display: flex;
	align-items: center;
	justify-content: center;
	font-size: 32rpx;
	color: #A8A8A8;
	background-color: #ffffff;
}

.quantity-btn.disabled {
	opacity: 0.5;
}

.quantity-display {
	width: 100rpx;
	height: 60rpx;
	border: 1rpx solid #e0e0e0;
	border-radius: 10rpx;
	display: flex;
	align-items: center;
	justify-content: center;
	font-size: 30rpx;
	color: #333333;
	background-color: #ffffff;
}

.confirm-spec-btn {
	width: 680rpx;
	height: 100rpx;
	background-color: #D3A458;
	color: #ffffff;
	text-align: center;
	font-size: 32rpx;
	border-radius: 50rpx;
	display: flex;
	align-items: center;
	justify-content: center;
	position: absolute;
	bottom: 40rpx;
	left: 50%;
	transform: translateX(-50%);
	font-weight: 500;
}
</style>
