<!-- 购物车页面 -->
<template>
	<view class="cart-page">
		<!-- 顶部栏 -->
		<view class="cart-header">
			<view class="header-title">
				<text class="title-text">购物车</text>
			</view>
			<view v-if="selectedCount > 0" class="edit-btn" @click="toggleEditMode">
				<text class="edit-text">{{ isEditMode ? '完成' : '编辑' }}</text>
			</view>
		</view>

		<!-- 购物车为空 -->
		<view v-if="cartItems.length === 0" class="empty-cart">
			<text class="empty-icon">🛒</text>
			<text class="empty-text">购物车还是空的</text>
			<text class="empty-subtext">快去挑选心仪的商品吧</text>
			<button class="go-shopping-btn" @click="goShopping">去逛逛</button>
		</view>

		<!-- 购物车列表 -->
		<scroll-view v-else direction="vertical" class="cart-content">
			<!-- 商品列表 -->
			<view v-for="(item, index) in cartItems" :key="item.id" class="cart-item">
				<view class="item-selector" @click="toggleSelectItem(item)">
					<view :class="['select-icon', { selected: item.selected }]">
						<text v-if="item.selected" class="icon-text">✓</text>
					</view>
				</view>

				<image class="item-image" :src="item.product_image || '/static/default-product.png'" />

				<view class="item-info">
					<text class="item-name">{{ item.product_name }}</text>
					<text v-if="item.sku_specifications" class="item-spec">{{ getSpecText(item.sku_specifications) }}</text>
					<view class="item-price-row">
						<text class="item-price">¥{{ item.price }}</text>
						<view class="quantity-control">
							<view class="quantity-btn minus" @click="decreaseQuantity(item)">-</view>
							<text class="quantity-text">{{ item.quantity }}</text>
							<view class="quantity-btn plus" @click="increaseQuantity(item)">+</view>
						</view>
					</view>
				</view>

				<view v-if="isEditMode" class="delete-btn" @click="removeItem(item, index)">
					<text class="delete-text">删除</text>
				</view>
			</view>

			<!-- 推荐商品 -->
			<view v-if="recommendProducts.length > 0" class="recommend-section">
				<view class="section-header">
					<text class="section-title">猜你喜欢</text>
				</view>
				<view class="recommend-grid">
					<view v-for="product in recommendProducts" :key="product.id" class="recommend-item" @click="viewProduct(product)">
						<image class="recommend-image" :src="getProductFirstImage(product)" />
						<text class="recommend-name">{{ product.name }}</text>
						<text class="recommend-price">¥{{ product.price }}</text>
					</view>
				</view>
			</view>
		</scroll-view>

		<!-- 底部结算栏 -->
		<view v-if="cartItems.length > 0" class="bottom-bar">
			<view class="select-all" @click="toggleSelectAll">
				<view :class="['all-select-icon', { selected: isAllSelected }]">
					<text v-if="isAllSelected" class="icon-text">✓</text>
				</view>
				<text class="select-all-text">全选</text>
			</view>

			<view v-if="!isEditMode" class="settlement-info">
				<view class="total-price">
					<text class="total-label">合计：</text>
					<text class="total-value">¥{{ totalPrice.toFixed(2) }}</text>
				</view>
				<text class="total-desc">已选{{ selectedCount }}件</text>
			</view>

			<view v-if="isEditMode" class="edit-actions">
				<view class="delete-all-btn" @click="removeSelected">
					<text class="delete-all-text">删除({{ selectedCount }})</text>
				</view>
			</view>

			<view v-else class="settle-btn" :class="{ disabled: selectedCount === 0 }" @click="goToCheckout">
				<text class="settle-text">去结算</text>
			</view>
		</view>
	</view>
</template>

<script setup lang="uts">
import { ref, computed, onMounted } from 'vue'
import type { ProductType } from '@/types/mall-types.uts'
import supa from '@/components/supadb/aksupainstance.uts'

type CartItemType = {
	id: string
	user_id: string
	product_id: string
	sku_id: string
	product_name: string
	product_image: string
	sku_specifications: any
	price: number
	quantity: number
	selected: boolean
}

const cartItems = ref<Array<CartItemType>>([])
const recommendProducts = ref<Array<ProductType>>([])
const isEditMode = ref<boolean>(false)
const isLoading = ref<boolean>(false)

// 计算属性
const selectedCount = computed(() => {
	return cartItems.value.filter(item => item.selected).length
})

const totalPrice = computed(() => {
	return cartItems.value
		.filter(item => item.selected)
		.reduce((total, item) => total + (item.price * item.quantity), 0)
})

const isAllSelected = computed(() => {
	return cartItems.value.length > 0 && cartItems.value.every(item => item.selected)
})

// 生命周期
onMounted(() => {
	loadCartItems()
	loadRecommendProducts()
})

// 加载购物车商品
const loadCartItems = async () => {
	const userId = getCurrentUserId()
	if (!userId) {
		uni.showToast({
			title: '请先登录',
			icon: 'none'
		})
		uni.navigateTo({
			url: '/pages/user/login'
		})
		return
	}

	try {
		const { data, error } = await supa
			.from('shopping_cart')
			.select(`
				id,
				user_id,
				product_id,
				sku_id,
				quantity,
				products (
					name,
					price,
					images
				),
				product_skus (
					specifications,
					price as sku_price
				)
			`)
			.eq('user_id', userId)

		if (error !== null) {
			console.error('加载购物车失败:', error)
			return
		}

		const items: CartItemType[] = []
		const cartData = data ?? []
		
		for (let i = 0; i < cartData.length; i++) {
			const item = cartData[i]
			const product = item.products as any
			const sku = item.product_skus as any
			
			items.push({
				id: item.id,
				user_id: item.user_id,
				product_id: item.product_id,
				sku_id: item.sku_id,
				product_name: product?.name || '未知商品',
				product_image: product?.images?.[0] || '/static/default-product.png',
				sku_specifications: sku?.specifications,
				price: sku?.sku_price || product?.price || 0,
				quantity: item.quantity,
				selected: false
			})
		}
		
		cartItems.value = items
	} catch (err) {
		console.error('加载购物车异常:', err)
	}
}

// 加载推荐商品
const loadRecommendProducts = async () => {
	try {
		const { data, error } = await supa
			.from('products')
			.select('*')
			.eq('status', 1)
			.order('sales', { ascending: false })
			.limit(6)

		if (error !== null) {
			console.error('加载推荐商品失败:', error)
			return
		}

		recommendProducts.value = data ?? []
	} catch (err) {
		console.error('加载推荐商品异常:', err)
	}
}

// 获取当前用户ID
const getCurrentUserId = (): string | null => {
	// 这里应该从全局状态或storage中获取
	const userStore = uni.getStorageSync('userInfo')
	return userStore?.id || null
}

// 获取商品第一张图片
const getProductFirstImage = (product: ProductType): string => {
	return product.images?.[0] || '/static/default-product.png'
}

// 获取规格文本
const getSpecText = (specs: any): string => {
	if (!specs) return ''
	if (typeof specs === 'object') {
		return Object.keys(specs)
			.map(key => `${key}: ${specs[key]}`)
			.join('; ')
	}
	return String(specs)
}

// 切换编辑模式
const toggleEditMode = () => {
	isEditMode.value = !isEditMode.value
}

// 切换商品选择
const toggleSelectItem = (item: CartItemType) => {
	item.selected = !item.selected
	cartItems.value = [...cartItems.value]
}

// 全选/取消全选
const toggleSelectAll = () => {
	const newSelectedState = !isAllSelected.value
	cartItems.value.forEach(item => {
		item.selected = newSelectedState
	})
	cartItems.value = [...cartItems.value]
}

// 增加数量
const increaseQuantity = async (item: CartItemType) => {
	if (isLoading.value) return
	
	isLoading.value = true
	try {
		const newQuantity = item.quantity + 1
		
		const { error } = await supa
			.from('shopping_cart')
			.update({ quantity: newQuantity })
			.eq('id', item.id)

		if (error !== null) {
			console.error('更新数量失败:', error)
			uni.showToast({
				title: '更新失败',
				icon: 'none'
			})
			return
		}

		item.quantity = newQuantity
		cartItems.value = [...cartItems.value]
	} catch (err) {
		console.error('更新数量异常:', err)
	} finally {
		isLoading.value = false
	}
}

// 减少数量
const decreaseQuantity = async (item: CartItemType) => {
	if (item.quantity <= 1) {
		removeItem(item, cartItems.value.indexOf(item))
		return
	}

	if (isLoading.value) return
	
	isLoading.value = true
	try {
		const newQuantity = item.quantity - 1
		
		const { error } = await supa
			.from('shopping_cart')
			.update({ quantity: newQuantity })
			.eq('id', item.id)

		if (error !== null) {
			console.error('更新数量失败:', error)
			uni.showToast({
				title: '更新失败',
				icon: 'none'
			})
			return
		}

		item.quantity = newQuantity
		cartItems.value = [...cartItems.value]
	} catch (err) {
		console.error('更新数量异常:', err)
	} finally {
		isLoading.value = false
	}
}

// 移除单个商品
const removeItem = async (item: CartItemType, index: number) => {
	uni.showModal({
		title: '确认删除',
		content: '确定要删除这个商品吗？',
		success: async (res) => {
			if (res.confirm) {
				try {
					const { error } = await supa
						.from('shopping_cart')
						.delete()
						.eq('id', item.id)

					if (error !== null) {
						console.error('删除商品失败:', error)
						uni.showToast({
							title: '删除失败',
							icon: 'none'
						})
						return
					}

					cartItems.value.splice(index, 1)
					cartItems.value = [...cartItems.value]
					
					uni.showToast({
						title: '删除成功',
						icon: 'success'
					})
				} catch (err) {
					console.error('删除商品异常:', err)
				}
			}
		}
	})
}

// 移除选中商品
const removeSelected = () => {
	const selectedItems = cartItems.value.filter(item => item.selected)
	if (selectedItems.length === 0) {
		uni.showToast({
			title: '请选择要删除的商品',
			icon: 'none'
		})
		return
	}

	uni.showModal({
		title: '批量删除',
		content: `确定要删除选中的${selectedItems.length}件商品吗？`,
		success: async (res) => {
			if (res.confirm) {
				const deletePromises = selectedItems.map(item =>
					supa
						.from('shopping_cart')
						.delete()
						.eq('id', item.id)
				)

				try {
					await Promise.all(deletePromises)
					cartItems.value = cartItems.value.filter(item => !item.selected)
					
					uni.showToast({
						title: '删除成功',
						icon: 'success'
					})
				} catch (err) {
					console.error('批量删除异常:', err)
					uni.showToast({
						title: '删除失败',
						icon: 'none'
					})
				}
			}
		}
	})
}

// 查看商品详情
const viewProduct = (product: ProductType) => {
	uni.navigateTo({
		url: `/pages/mall/consumer/product-detail?id=${product.id}`
	})
}

// 去逛逛
const goShopping = () => {
	uni.switchTab({
		url: '/pages/mall/consumer/index'
	})
}

// 去结算
const goToCheckout = () => {
	if (selectedCount.value === 0) {
		uni.showToast({
			title: '请选择要结算的商品',
			icon: 'none'
		})
		return
	}

	const selectedItems = cartItems.value.filter(item => item.selected)
	const productIds = selectedItems.map(item => ({
		product_id: item.product_id,
		sku_id: item.sku_id,
		quantity: item.quantity
	}))

	uni.navigateTo({
		url: '/pages/mall/consumer/checkout',
		success: (res) => {
			res.eventChannel.emit('acceptData', {
				selectedItems: productIds,
				totalAmount: totalPrice.value
			})
		}
	})
}
</script>

<style scoped>
.cart-page {
	display: flex;
	flex-direction: column;
	height: 100vh;
	background-color: #f5f5f5;
}

.cart-header {
	background-color: #ffffff;
	padding: 15px;
	border-bottom: 1px solid #e5e5e5;
	display: flex;
	justify-content: space-between;
	align-items: center;
}

.header-title {
	flex: 1;
}

.title-text {
	font-size: 18px;
	font-weight: bold;
	color: #333333;
}

.edit-btn {
	padding: 5px 10px;
}

.edit-text {
	color: #007aff;
	font-size: 14px;
}

.empty-cart {
	flex: 1;
	display: flex;
	flex-direction: column;
	align-items: center;
	justify-content: center;
	padding: 50px 20px;
}

.empty-icon {
	font-size: 80px;
	margin-bottom: 20px;
}

.empty-text {
	font-size: 16px;
	color: #666666;
	margin-bottom: 10px;
}

.empty-subtext {
	font-size: 14px;
	color: #999999;
	margin-bottom: 30px;
}

.go-shopping-btn {
	background-color: #007aff;
	color: #ffffff;
	padding: 10px 40px;
	border-radius: 25px;
	font-size: 14px;
	border: none;
}

.cart-content {
	flex: 1;
}

.cart-item {
	background-color: #ffffff;
	margin-bottom: 10px;
	padding: 15px;
	display: flex;
	align-items: center;
	position: relative;
}

.item-selector {
	margin-right: 10px;
}

.select-icon {
	width: 20px;
	height: 20px;
	border: 1px solid #cccccc;
	border-radius: 10px;
	display: flex;
	align-items: center;
	justify-content: center;
}

.select-icon.selected {
	background-color: #007aff;
	border-color: #007aff;
}

.icon-text {
	color: #ffffff;
	font-size: 12px;
}

.item-image {
	width: 80px;
	height: 80px;
	border-radius: 5px;
	margin-right: 10px;
}

.item-info {
	flex: 1;
	min-height: 80px;
	display: flex;
	flex-direction: column;
	justify-content: space-between;
}

.item-name {
	font-size: 14px;
	color: #333333;
	line-height: 1.4;
	margin-bottom: 5px;
}

.item-spec {
	font-size: 12px;
	color: #999999;
	margin-bottom: 10px;
}

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

.item-price {
	font-size: 16px;
	color: #ff4757;
	font-weight: bold;
}

.quantity-control {
	display: flex;
	align-items: center;
	border: 1px solid #e5e5e5;
	border-radius: 15px;
	overflow: hidden;
}

.quantity-btn {
	width: 30px;
	height: 30px;
	display: flex;
	align-items: center;
	justify-content: center;
	font-size: 16px;
	color: #666666;
	background-color: #f8f8f8;
}

.quantity-btn.minus {
	border-right: 1px solid #e5e5e5;
}

.quantity-btn.plus {
	border-left: 1px solid #e5e5e5;
}

.quantity-text {
	width: 40px;
	text-align: center;
	font-size: 14px;
	color: #333333;
}

.delete-btn {
	position: absolute;
	right: 15px;
	bottom: 15px;
	padding: 5px 10px;
	background-color: #ff4757;
	border-radius: 12px;
}

.delete-text {
	color: #ffffff;
	font-size: 12px;
}

.recommend-section {
	background-color: #ffffff;
	margin-top: 10px;
	padding: 15px;
}

.section-header {
	margin-bottom: 15px;
}

.section-title {
	font-size: 16px;
	font-weight: bold;
	color: #333333;
}

.recommend-grid {
	display: flex;
	flex-wrap: wrap;
	justify-content: space-between;
}

.recommend-item {
	width: 48%;
	margin-bottom: 15px;
}

.recommend-image {
	width: 100%;
	height: 120px;
	border-radius: 5px;
	margin-bottom: 8px;
}

.recommend-name {
	font-size: 13px;
	color: #333333;
	line-height: 1.4;
	margin-bottom: 5px;
	display: -webkit-box;
	-webkit-box-orient: vertical;
	-webkit-line-clamp: 2;
	overflow: hidden;
}

.recommend-price {
	font-size: 14px;
	color: #ff4757;
	font-weight: bold;
}

.bottom-bar {
	background-color: #ffffff;
	border-top: 1px solid #e5e5e5;
	padding: 15px;
	display: flex;
	align-items: center;
	justify-content: space-between;
}

.select-all {
	display: flex;
	align-items: center;
}

.all-select-icon {
	width: 20px;
	height: 20px;
	border: 1px solid #cccccc;
	border-radius: 10px;
	margin-right: 8px;
	display: flex;
	align-items: center;
	justify-content: center;
}

.all-select-icon.selected {
	background-color: #007aff;
	border-color: #007aff;
}

.select-all-text {
	font-size: 14px;
	color: #333333;
}

.settlement-info {
	flex: 1;
	margin-left: 20px;
	display: flex;
	flex-direction: column;
	align-items: flex-end;
}

.total-price {
	display: flex;
	align-items: baseline;
	margin-bottom: 5px;
}

.total-label {
	font-size: 14px;
	color: #333333;
}

.total-value {
	font-size: 18px;
	color: #ff4757;
	font-weight: bold;
}

.total-desc {
	font-size: 12px;
	color: #999999;
}

.edit-actions {
	flex: 1;
	margin-left: 20px;
	display: flex;
	justify-content: flex-end;
}

.delete-all-btn {
	background-color: #ff4757;
	padding: 8px 20px;
	border-radius: 15px;
}

.delete-all-text {
	color: #ffffff;
	font-size: 14px;
}

.settle-btn {
	background-color: #007aff;
	padding: 10px 30px;
	border-radius: 20px;
	margin-left: 20px;
}

.settle-btn.disabled {
	background-color: #cccccc;
	opacity: 0.6;
}

.settle-text {
	color: #ffffff;
	font-size: 14px;
	font-weight: bold;
}
</style>