<template>
	<view class="cart-container">

		<!-- 购物车标题栏 -->
		<view class="cart-header">
			<text class="cart-title">我的购物车</text>
			<text v-if='!isDele' @click="isDele=true" class="cart-manage">管理</text>
			<text v-if='isDele' @click="isDele=false" class="cart-manage">退出管理</text>
		</view>


		<!-- 购物车商品列表 -->
		<scroll-view scroll-y class="cart-items" :show-scrollbar="false">
			<view class="cart-item" v-for="(item, index) in cartData" :key="item.cgId">
				<view class="" @click.stop="selectItem(index)"
					:style="{ 'background-color': selectedIds.includes(item.cgId) ? '#2979ff' : '', 'border': selectedIds.includes(item.cgId) ? '' : '1rpx solid #e2e2e2' }"
					style="display: flex; align-items: center; justify-content: center; width: 34rpx; height: 34rpx; border-radius: 4rpx;">
					<up-icon name="checkbox-mark" color="#fff" size="14"></up-icon>
				</view>
				<image :src="Service.GetMateUrlByImg(item.goodsImg)" mode="scaleToFill" class="item-image">
				</image>
				<view class="item-info" style="position: relative;">
					<view class="" style="display: flex; justify-content: space-between;">
						<text class="item-title" style="flex: 1;">{{ item.goodsName }}</text>
						<image v-if="isDele" @click.stop="deleteItem(item)"
							:src="Service.GetpayImg('/static/icon/shop/dele.png')"
							style="width: 32rpx; height: 32rpx;"  />
					</view>
					<view class="">
						<text v-for="(ruleIndex, ruleItem) in item.rule.split('-')" :key="ruleItem"
							class="item-spec">{{ ruleIndex }}</text>
					</view>
					<view class="item-actions">
						<text class="item-price">¥{{ item.price.toFixed(2) }}</text>
						<view class="stepper">
							<view class="stepper-btn" :class="{ disabled: item.count <= 1 }"
								@click.stop="decreaseCount(item)">
								-
							</view>
							<view class="stepper-input">{{ item.count }}</view>
							<view class="stepper-btn" @click.stop="increaseCount(item)">
								+
							</view>
						</view>
					</view>
				</view>
			</view>

			<!-- 空购物车提示 -->
			<view v-if="cartData.length === 0" class="empty-cart">
				<image :src="Service.GetpayImg('/static/dele/empty-cart.png')" mode="aspectFit" class="empty-image">
				</image>
				<text class="empty-text">购物车空空如也</text>
			</view>

			<!-- 底部空间，确保内容不被底部结算栏遮挡 -->
			<view class="bottom-space"></view>
		</scroll-view>

		<!-- 底部结算栏 -->
		<view class="checkout-bar">
			<view v-if="!isDele" class="select-all" @click="toggleSelectAll">
				<view class=""
					:style="{ 'background-color': isAllSelected ? '#2979ff' : '', 'border': isAllSelected ? '' : '1rpx solid #e2e2e2' }"
					style="display: flex; align-items: center; justify-content: center; width: 34rpx; height: 34rpx; border-radius: 4rpx;">
					<up-icon name="checkbox-mark" color="#fff" size="14"></up-icon>
				</view>
				<text class="select-all-text">全选</text>
			</view>
			<view v-if="!isDele" class="total-info">
				<view class="total-price">
					<text class="total-text">合计：</text>
					<text class="price-text">¥{{ totalPrice.toFixed(2) }}</text>
				</view>
				<text class="total-count">共{{ totalCount }}件</text>
			</view>
			<view v-if="!isDele" class="checkout-btn" @click="handleCheckout">
				<text class="checkout-text">结算({{ selectedCount }})</text>
			</view>

			<view v-if="isDele" style="width: 100%;" class="delete-btn" @click="deleteSelectedItems">
				<view class=""
					style=" padding: 20rpx 30rpx; border-radius: 10rpx; font-size: 22rpx; background-color: red;  color: #fff; display: flex; align-items: center; justify-content: center; ">
					删除选中({{ selectedCount }})
				</view>
			</view>
		</view>


	</view>
</template>

<script setup lang="ts">
	import { ref, computed } from 'vue';
	import { Service } from '@/Service/Service';
	import { onLoad, onShow } from '@dcloudio/uni-app';
	import { CarService } from '@/Service/api/CarService';
	import { OrderService } from '@/Service/api/OrderService';

	let isDele = ref(false)

	let status = ref('nomore')
	let page = ref(1)

	let selectedIds = ref<string[]>([])

	// 购物车数据结构
	const cartData = ref<Array<any>>([])



	// 计算属性：选中商品列表
	const selectedItems = computed(() => {
		return cartData.value.filter(item => selectedIds.value.includes(item.cgId))
	})

	// 计算属性：选中商品总数
	const selectedCount = computed(() => {
		return selectedItems.value.length
	})

	// 计算属性：选中商品总数量
	const totalCount = computed(() => {
		return selectedItems.value.reduce((sum, item) => sum + item.count, 0)
	})

	// 计算属性：选中商品总价
	const totalPrice = computed(() => {
		return selectedItems.value.reduce((sum, item) => sum + item.count * item.price, 0)
	})

	// 计算属性：是否全选
	const isAllSelected = computed(() => {
		return cartData.value.length > 0 && selectedIds.value.length === cartData.value.length
	})

	onLoad(() => {

	})

	onShow(() => {
		selectedIds.value = []
		getData()
	})

	// 获取商品
	const getData = () => {
		cartData.value = []
		status.value = 'loadmore'
		page.value = 1
		getList()
	}

	const getList = () => {
		if (status.value == 'loading' || status.value == 'nomore') {
			return
		}
		status.value = 'loading'
		CarService.GetUserCarList(page.value).then(res => {
			if (res.code == 0) {
				cartData.value = [...cartData.value, ...res.data.list]
				status.value = res.data.list.length == 10 ? 'loadmore' : 'nomore'
				page.value++
			} else {
				Service.Msg(res.msg)
			}
		})
	}

	// 选择/取消选择单个商品
	const selectItem = (index: number) => {
		const cgId = cartData.value[index].cgId
		const idx = selectedIds.value.indexOf(cgId)
		if (idx > -1) {
			selectedIds.value.splice(idx, 1)
		} else {
			selectedIds.value.push(cgId)
		}
	}

	// 全选/取消全选
	const toggleSelectAll = () => {
		if (isAllSelected.value) {
			selectedIds.value = []
		} else {
			selectedIds.value = cartData.value.map(item => item.cgId)
		}
	}

	// 增加商品数量
	const increaseCount = (shop : any) => {
		shop.count++
		updateItemCount(shop.cgId, shop.count)
	}

	// 减少商品数量
	const decreaseCount = (shop : any) => {
		if (shop.count <= 1) {
			return
		}
		shop.count--
		updateItemCount(shop.cgId, shop.count)
	}

	// 更新商品数量
	const updateItemCount = (cgId : string, count : number) => {
		CarService.UpdateCarCount(cgId, count).then(res => {
			if (res.code == 0) {

			} else {
				Service.Msg(res.msg)
			}
		})
	}

	// 删除单个商品
	const deleteItem = (goods : any) => {
		uni.showModal({
			title: '提示',
			content: '确定要删除该商品吗？',
			success: (res) => {
				if (res.confirm) {
					CarService.DelUserCar(goods.goodsId, 1).then(res => {
						if (res.code == 0) {
							Service.Msg(res.data)
							getData()
							selectedIds.value = []
							isDele.value = false
						} else {
							Service.Msg(res.msg)
						}
					})
				}
			}
		})
	}

	// 删除选中商品
	const deleteSelectedItems = () => {
		if (selectedIds.value.length === 0) {
			Service.Msg('请选择要删除的商品')
			return
		}

		uni.showModal({
			title: '提示',
			content: `确定要删除选中的${selectedIds.value.length}件商品吗？`,
			success: (res) => {
				if (res.confirm) {
					const goodsIds = selectedItems.value.map(item => item.goodsId).join(',')
					CarService.DelUserCar(goodsIds, 2).then(res => {
						if (res.code == 0) {
							Service.Msg(res.data)
							selectedIds.value = []
							getData()
							isDele.value = false
						} else {
							Service.Msg(res.msg)
						}
					})
				} else {
					isDele.value = false
				}
			}
		})
	}

	// 结算按钮点击处理
	const handleCheckout = () => {
		if (selectedCount.value === 0) {
			Service.Msg('请选择要结算的商品')
			return
		}
		const data = selectedItems.value.map(item => ({
			goodsId: item.goodsId,
			goodsImg: item.goodsImg,
			goodsName: item.goodsName,
			rule: item.rule,
			count: item.count,
			price: item.price
		}))

		OrderService.AddUserOrder(JSON.stringify(data), 0).then(res => {
			if (res.code == 0) {
				Service.GoPage('/pages/webView/orderDetail?orderId=' + res.data.orderId)
			} else {
				Service.Msg(res.msg)
			}
		})
	}
</script>

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

	/* 购物车标题栏 */
	.cart-header {
		display: flex;
		justify-content: space-between;
		align-items: center;
		padding: 24rpx 32rpx;
		background-color: #ffffff;
		font-size: 32rpx;
		font-weight: bold;
		color: #333333;
	}

	.cart-title {
		font-size: 36rpx;
	}

	.cart-manage {
		font-size: 28rpx;
		color: #666666;
		font-weight: normal;
	}

	/* 购物车商品列表 */
	.cart-items {
		flex: 1;
		margin-top: 20rpx;
	}

	/* 商品项 */
	.cart-item {
		display: flex;
		align-items: center;
		padding: 24rpx 32rpx;
		margin: 0 20rpx 10rpx;
		background-color: #ffffff;
		border-radius: 20rpx;
	}

	.item-image {
		width: 160rpx;
		height: 160rpx;
		margin-left: 16rpx;
		border-radius: 8rpx;
		overflow: hidden;
	}

	.item-info {
		flex: 1;
		margin-left: 24rpx;
	}

	.item-title {
		font-size: 28rpx;
		color: #333333;
		line-height: 1.4;
		display: -webkit-box;
		-webkit-box-orient: vertical;
		-webkit-line-clamp: 2;
		overflow: hidden;
	}

	.item-spec {
		font-size: 24rpx;
		color: #999999;
		margin-right: 10rpx;
		margin-top: 8rpx;
	}

	.item-actions {
		display: flex;
		justify-content: space-between;
		align-items: center;
		margin-top: 16rpx;
	}

	.item-price {
		font-size: 32rpx;
		color: #ff6600;
		font-weight: bold;
	}

	/* 手写步进器样式 */
	.stepper {
		display: flex;
		align-items: center;
		border: 1rpx solid #e0e0e0;
		border-radius: 8rpx;
		overflow: hidden;
	}

	.stepper-btn {
		width: 56rpx;
		height: 52rpx;
		display: flex;
		align-items: center;
		justify-content: center;
		font-size: 36rpx;
		color: #333;
		background-color: #f8f8f8;
		transition: background-color 0.2s;
	}

	.stepper-btn:active {
		background-color: #e8e8e8;
	}

	.stepper-btn.disabled {
		color: #ccc;
		background-color: #f5f5f5;
	}

	.stepper-input {
		width: 80rpx;
		height: 56rpx;
		display: flex;
		align-items: center;
		justify-content: center;
		font-size: 28rpx;
		color: #333;
		background-color: #fff;
		border-left: 1rpx solid #e0e0e0;
		border-right: 1rpx solid #e0e0e0;
	}

	/* 空购物车 */
	.empty-cart {
		display: flex;
		flex-direction: column;
		align-items: center;
		justify-content: center;
		padding: 100rpx 0;
	}

	.empty-image {
		width: 300rpx;
		height: 300rpx;
		margin-bottom: 30rpx;
	}

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

	/* 底部空间 */
	.bottom-space {
		height: 220rpx;
	}

	/* 底部结算栏 */
	.checkout-bar {
		position: fixed;
		bottom: 0rpx;
		left: 0;
		right: 0;
		height: 100rpx;
		display: flex;
		justify-content: space-between;
		align-items: center;
		background-color: #ffffff;
		border-top: 1rpx solid #f0f0f0;
		padding: 0 32rpx;
	}

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

	.select-all-text {
		font-size: 28rpx;
		color: #333333;
		margin-left: 16rpx;
	}

	.total-info {
		flex: 1;
		margin-left: 32rpx;
	}

	.total-price {
		display: flex;
		align-items: baseline;
	}

	.total-text {
		font-size: 28rpx;
		color: #333333;
	}

	.price-text {
		font-size: 36rpx;
		color: #ff6600;
		font-weight: bold;
	}

	.total-count {
		font-size: 24rpx;
		color: #999999;
	}

	.checkout-btn {
		width: 200rpx;
		height: 72rpx;
		background-color: #ff6600;
		border-radius: 36rpx;
		display: flex;
		align-items: center;
		justify-content: center;
	}

	.checkout-text {
		font-size: 28rpx;
		color: #ffffff;
		font-weight: bold;
	}

	.delete-btn {
		cursor: pointer;
	}
</style>