<template>
	<view class="cart-shop">
		<view class="cart-shop__head">
			<view
				class="cart-shop__check"
				:class="{ 'cart-shop__check--disabled': !hasPurchasable }"
				@click.stop="onShopCheck"
			>
				<view class="check-icon" :class="{ 'check-icon--on': shopAllChecked && hasPurchasable }">
					<u-icon v-if="shopAllChecked && hasPurchasable" name="checkbox-mark" color="#fff" size="14" />
				</view>
			</view>
			<view class="cart-shop__name-wrap" @click="emit('shop-click', group)">
				<u-icon name="shop" color="#2e7d32" size="18" />
				<text class="cart-shop__name">{{ group.shopName }}</text>
				<text v-if="group.isClosed" class="cart-shop__tag">休息中</text>
				<u-icon name="arrow-right" color="#ccc" size="14" />
			</view>
		</view>
		<cart-item-row
			v-for="item in group.items"
			:key="item.cartItemId"
			:item="item"
			@check-change="(row, checked) => emit('check-change', row, checked)"
			@quantity-change="(row, qty) => emit('quantity-change', row, qty)"
			@delete="(row) => emit('delete', row)"
			@goods-click="(row) => emit('goods-click', row)"
		/>
	</view>
</template>

<script setup>
import { computed } from 'vue'
import CartItemRow from '@/components/cart/CartItemRow.vue'

const props = defineProps({
	group: {
		type: Object,
		required: true
	}
})

const emit = defineEmits(['shop-check', 'shop-click', 'check-change', 'quantity-change', 'delete', 'goods-click'])

const purchasableItems = computed(() =>
	(props.group.items || []).filter((item) => item.purchasable)
)

const hasPurchasable = computed(() => purchasableItems.value.length > 0)

const shopAllChecked = computed(() => {
	if (!hasPurchasable.value) return false
	return purchasableItems.value.every((item) => item.checked)
})

function onShopCheck() {
	if (!hasPurchasable.value) return
	emit('shop-check', props.group, !shopAllChecked.value)
}
</script>

<style lang="scss" scoped>
.cart-shop {
	margin-bottom: 20rpx;
	background: #fff;
	border-radius: 12rpx;
	overflow: hidden;
	padding: 0 20rpx 8rpx;
}
.cart-shop__head {
	display: flex;
	align-items: center;
	padding: 20rpx 0 8rpx;
	border-bottom: 1rpx solid #f0f0f0;
}
.cart-shop__check {
	margin-right: 8rpx;
}
.cart-shop__check--disabled {
	opacity: 0.4;
}
.check-icon {
	width: 36rpx;
	height: 36rpx;
	border: 2rpx solid #ccc;
	border-radius: 50%;
	display: flex;
	align-items: center;
	justify-content: center;
	background: #fff;
}
.check-icon--on {
	background: #2e7d32;
	border-color: #2e7d32;
}
.cart-shop__name-wrap {
	flex: 1;
	display: flex;
	align-items: center;
	gap: 8rpx;
	min-width: 0;
}
.cart-shop__name {
	flex: 1;
	font-size: 28rpx;
	color: #333;
	font-weight: 500;
	overflow: hidden;
	text-overflow: ellipsis;
	white-space: nowrap;
}
.cart-shop__tag {
	font-size: 22rpx;
	color: #e65100;
	background: #fff3e0;
	padding: 4rpx 10rpx;
	border-radius: 6rpx;
	flex-shrink: 0;
}
</style>
