<template>
    <BasicModal type="bottom" v-model:open="getOpen" :isMack="true">
        <view class="cart-modal">
            <!-- 顶部标题栏 -->
            <view class="cart-modal__header">
                <text class="header-title">已选菜品</text>
                <view class="header-clear" @click="handleClear" v-if="cartList.length > 0">
                    <text class="clear-text">清空</text>
                </view>
            </view>

            <!-- 购物车列表 -->
            <scroll-view class="cart-modal__list" scroll-y>
                <view v-for="(item, index) in cartList" :key="item.cuisineId || item.id || index" class="cart-item">
                    <!-- 菜品图片：接口返回 cuisineImage（可能逗号分隔多图，取首图） -->
                    <image :src="getItemImageSrc(item)" mode="aspectFill" class="cart-item__image"></image>

                    <!-- 菜品信息：接口返回 cuisineName / unitPrice / subtotalAmount / remark -->
                    <view class="cart-item__info">
                        <view class="cart-item__name">{{ item.cuisineName || item.name }}</view>
                        <view class="cart-item__remark" v-if="item.remark">{{ item.remark }}</view>
                        <view class="cart-item__tags" v-if="item.tags && item.tags.length > 0">
                            <view v-for="(tag, tagIndex) in item.tags" :key="tagIndex" class="cart-item__tag"
                                :class="tag.type">
                                {{ tag.text }}
                            </view>
                        </view>
                        <view class="cart-item__price">
                            <text class="price-symbol">¥</text>
                            <text class="price-number">{{ formatPrice(getItemLinePrice(item)) }}</text>
                        </view>
                    </view>

                    <!-- 数量选择器（餐具 cuisineId 为 -1 时不可修改） -->
                    <view class="cart-item__actions">
                        <view class="action-btn minus" :class="{ disabled: item.quantity === 0 || isTablewareItem(item) }"
                            @click="handleDecrease(item)" hover-class="hover-active">
                            <image :src="getFileUrl('img/icon/reduce1.png')" mode="aspectFit" class="action-icon"
                                v-show="item.quantity == 0"></image>
                            <image :src="getFileUrl('img/icon/reduce2.png')" mode="aspectFit" class="action-icon"
                                v-show="item.quantity != 0"></image>
                        </view>
                        <view class="quantity">{{ item.quantity || 0 }}</view>
                        <view class="action-btn plus" :class="{ disabled: isTablewareItem(item) }" @click="handleIncrease(item)" hover-class="hover-active">
                            <image :src="getFileUrl('img/icon/add2.png')" mode="widthFix" class="action-icon"
                                v-show="item.quantity < 99"></image>
                            <image :src="getFileUrl('img/icon/add1.png')" mode="widthFix" class="action-icon"
                                v-show="item.quantity >= 99"></image>
                        </view>
                    </view>
                </view>

            </scroll-view>

        </view>
    </BasicModal>
</template>

<script setup>
import { computed } from 'vue';
import BasicModal from '@/components/Modal/BasicModal.vue';
import { getFileUrl } from '@/utils/file.js';

const props = defineProps({
    open: {
        type: Boolean,
        default: false
    },
    cartList: {
        type: Array,
        default: () => []
    }
});

const emit = defineEmits(['update:open', 'increase', 'decrease', 'clear', 'order-click', 'close']);

const getOpen = computed({
    get: () => props.open,
    set: (val) => emit('update:open', val)
});

// 计算总数量
const totalQuantity = computed(() => {
    return props.cartList.reduce((sum, item) => {
        return sum + (item.quantity || 0);
    }, 0);
});

// 计算总价格：接口项用 subtotalAmount，否则 数量×单价
const totalPrice = computed(() => {
    return props.cartList.reduce((sum, item) => sum + getItemLinePrice(item), 0);
});

// 格式化价格（保留两位小数，避免 NaN）
const formatPrice = (price) => {
    const num = Number(price);
    return Number.isNaN(num) ? '0.00' : num.toFixed(2);
};

// 菜品图片地址：接口返回 cuisineImage（可能逗号分隔，取首图），兼容 image/imageUrl/pic/cover
const getItemImageSrc = (item) => {
    const raw = item?.cuisineImage ?? item?.image ?? item?.images ?? item?.imageUrl ?? item?.pic ?? item?.cover ?? '';
    const url = typeof raw === 'string' ? raw.split(',')[0].trim() : raw;
    return url ? getFileUrl(url) : '';
};

// 单品单价：接口返回 unitPrice，兼容 price/salePrice 等
const getItemPrice = (item) => {
    const p = item?.unitPrice ?? item?.price ?? item?.salePrice ?? item?.currentPrice ?? item?.totalPrice ?? 0;
    return Number(p) || 0;
};

// 行小计：接口返回 subtotalAmount，否则 数量×单价
const getItemLinePrice = (item) => {
    if (item?.subtotalAmount != null) return Number(item.subtotalAmount);
    const qty = Number(item?.quantity) || 0;
    const unitPrice = getItemPrice(item);
    return qty * unitPrice;
};

// 餐具（cuisineId 或 id 为 -1）不可修改数量
const isTablewareItem = (item) => {
    if (!item) return false;
    const id = item.cuisineId ?? item.id;
    return Number(id) === -1;
};

// 处理关闭
const handleClose = () => {
    getOpen.value = false;
    emit('close');
};

// 增加数量
const handleIncrease = (item) => {
    if (isTablewareItem(item)) {
        uni.showToast({ title: '不允许更改餐具数量', icon: 'none' });
        return;
    }
    if (item.quantity >= 99) return;
    emit('increase', item);
};

// 减少数量
const handleDecrease = (item) => {
    if (isTablewareItem(item)) {
        uni.showToast({ title: '不允许更改餐具数量', icon: 'none' });
        return;
    }
    if (item && item.quantity > 0) {
        emit('decrease', item);
    }
};

// 清空购物车
const handleClear = () => {
    uni.showModal({
        title: '提示',
        content: '确定要清空购物车吗？',
        success: (res) => {
            if (res.confirm) {
                emit('clear');
            }
        }
    });
};

</script>

<style scoped lang="scss">
.cart-modal {
    width: 100%;
    background: #FFFFFF;
    border-radius: 24rpx 24rpx 0 0;
    padding: 0;
    box-sizing: border-box;
    max-height: 80vh;
    display: flex;
    flex-direction: column;
    overflow: hidden;

    &__header {
        position: relative;
        display: flex;
        align-items: center;
        justify-content: space-between;
        height: 88rpx;
        padding: 0 30rpx;
        background: #FFFFFF;

        .header-title {
            font-weight: bold;
            font-size: 34rpx;
            color: #151515;
        }

        .header-clear {
            display: flex;
            align-items: center;
            gap: 8rpx;
            color: #AAAAAA;
            font-size: 28rpx;
            padding: 8rpx 16rpx;
            border-radius: 8rpx;
            transition: all 0.3s;

            &:active {
                background-color: #F5F5F5;
            }

            .clear-text {
                font-size: 28rpx;
                color: #AAAAAA;
            }
        }
    }

    &__list {
        flex: 1;
        padding: 24rpx 30rpx;
        padding-bottom: calc(140rpx + env(safe-area-inset-bottom));
        box-sizing: border-box;
        overflow-y: auto;
        min-height: 0;
    }
}

.cart-item {
    display: flex;
    align-items: center;
    padding: 20rpx 0;
    border-bottom: 1rpx solid #F0F0F0;

    &:last-child {
        border-bottom: none;
    }

    &__image {
        width: 140rpx;
        height: 140rpx;
        border-radius: 8rpx;
        flex-shrink: 0;
        background-color: #f5f5f5;
    }

    &__info {
        flex: 1;
        margin-left: 20rpx;
        display: flex;
        flex-direction: column;
        justify-content: space-between;
        min-height: 140rpx;
    }

    &__name {
        font-size: 28rpx;
        font-weight: 500;
        color: #151515;
        margin-bottom: 8rpx;
    }

    &__remark {
        font-size: 24rpx;
        color: #999;
        margin-bottom: 8rpx;
    }

    &__tags {
        display: flex;
        gap: 10rpx;
        margin-bottom: 12rpx;
    }

    &__tag {
        padding: 4rpx 12rpx;
        border-radius: 4rpx;
        font-size: 20rpx;

        &.signature {
            background: linear-gradient(90deg, #FCB13F 0%, #FC793D 100%);
            color: #fff;
        }

        &.spicy {
            background: #2E2E2E;
            color: #fff;
        }
    }

    &__price {
        display: flex;
        align-items: baseline;
        color: #151515;
        font-weight: 500;

        .price-symbol {
            font-size: 24rpx;
            margin-right: 2rpx;
        }

        .price-number {
            font-size: 32rpx;
        }
    }

    &__actions {
        display: flex;
        align-items: center;
        justify-content: space-between;
        width: 180rpx;
        height: 58rpx;
        background: #F8F8F8;
        border-radius: 56rpx;
        box-sizing: border-box;
        padding: 0 3rpx;
        margin-left: 20rpx;
    }
}

.action-btn {
    width: 52rpx;
    height: 52rpx;
    border-radius: 50%;
    display: flex;
    align-items: center;
    justify-content: center;
    transition: all 0.3s;
    background-color: #fff;

    .action-icon {
        width: 24rpx;
        height: 24rpx;
    }

    &.disabled {
        opacity: 0.5;
    }
}

.quantity {
    font-size: 28rpx;
    color: #151515;
    min-width: 40rpx;
    text-align: center;
    font-weight: bold;
}

.cart-modal__footer {
    display: flex;
    align-items: center;
    justify-content: space-between;
    padding: 20rpx 30rpx;
    padding-bottom: calc(20rpx + env(safe-area-inset-bottom));
    background: #2E2E2E;
    border-top: 1rpx solid #3E3E3E;

    .footer-coupon-btn {
        display: flex;
        flex-direction: column;
        align-items: center;
        justify-content: center;
        width: 140rpx;
        height: 100rpx;
        background: rgba(255, 255, 255, 0.1);
        border-radius: 8rpx;
        gap: 6rpx;

        .footer-coupon-icon {
            width: 30rpx;
            height: 21rpx;
        }

        .footer-coupon-text {
            font-size: 24rpx;
            color: #FFFFFF;
        }
    }

    .footer-cart-info {
        flex: 1;
        display: flex;
        align-items: center;
        justify-content: space-between;
        margin-left: 20rpx;
    }

    .footer-cart-content {
        display: flex;
        align-items: center;
        position: relative;

        .footer-cart-icon {
            width: 76rpx;
            height: 76rpx;
        }

        .footer-cart-number {
            display: inline-block;
            padding: 2rpx 10rpx;
            background-color: #FF4545;
            position: absolute;
            left: 60rpx;
            top: -10rpx;
            border-radius: 40rpx;
            color: #fff;
            font-size: 24rpx;
        }

        .footer-cart-price {
            display: flex;
            align-items: baseline;
            color: #FFFFFF;
            font-weight: bold;
            margin-left: 20rpx;

            .price-symbol {
                font-size: 24rpx;
                margin-right: 2rpx;
            }

            .price-number {
                font-size: 38rpx;
            }
        }
    }

    .footer-order-btn {
        width: 200rpx;
        height: 100rpx;
        display: flex;
        align-items: center;
        justify-content: center;
        background: #FF6B35;
        border-radius: 50rpx;
        font-weight: bold;
        font-size: 31rpx;
        color: #FFFFFF;
        margin-left: 20rpx;
    }
}
</style>
