<template>
    <view class="cart-page">
        <!-- 广告位 -->
        <!-- <view class="ad-banner">
            <text>这里是广告</text>
            <u-icon name="arrow-right" color="#999" size="28"></u-icon>
        </view> -->

        <!-- 购物车列表 -->
        <view class="cart-list">
            <cart-item v-for="(item, index) in cartList" :key="index" :item="item" @check="handleCheck"
                @changeNum="handleChangeNum" @reduce="handleReduce"></cart-item>
        </view>

        <!-- 为你推荐 -->
        <view class="recommend-section">
            <view class="section-title">
                <text class="line"></text>
                <text class="text">为你推荐</text>
                <text class="line"></text>
            </view>
            <view class="recommend-grid">
                <view class="grid-item" v-for="(item, index) in recommendList" :key="index">
                    <image :src="item.cover" mode="aspectFill" class="cover"></image>
                    <view class="title">{{ item.title }}</view>
                </view>
            </view>
        </view>

        <!-- 底部占位 -->
        <view style="height: 20rpx;"></view>

        <!-- 底部结算栏 -->
        <view class="bottom-fixed">
            <view class="left-part">
                <view class="checkbox-wrap" @click="toggleSelectAll">
                    <u-checkbox v-model="isAllSelected" shape="circle" active-color="#38C148" :disabled="false"
                        @change="onAllCheckChange">全选</u-checkbox>
                </view>
            </view>
            <view class="right-part">
                <view class="total-info">
                    <view class="reduced-tip" v-if="totalReduced > 0">已降 ¥{{ totalReduced }}</view>
                    <view class="total-price">
                        <text class="label">合计：</text>
                        <text class="price">¥{{ totalPrice }}</text>
                    </view>
                </view>
                <view class="checkout-btn" @click="checkout">
                    结算({{ selectedCount }})
                </view>
            </view>
        </view>

        <!-- 减钱弹窗 -->
        <price-reduction-popup ref="reducePopup" @share="handleShare" @scan="handleScan"></price-reduction-popup>

        <common-dialog ref="reduceDialog" title="温馨提示" @confirm="onNext">
            <text>购物车中有可减钱的商品，如您提交订单，则失去该资格哦~</text>
        </common-dialog>
    </view>
</template>

<script>
import CartItem from '../components/cart-item.vue';
import PriceReductionPopup from '../components/price-reduction-popup.vue';
import CommonDialog from '@/components/common-dialog.vue';

export default {
    components: {
        CartItem,
        PriceReductionPopup,
        CommonDialog
    },
    data() {
        return {
            isAllSelected: false,
            cartList: [
                {
                    id: 1,
                    title: '六级词汇词根+联想记忆法第二版浙江教育出版社',
                    cover: 'https://k.sinaimg.cn/n/sinakd20116/234/w1000h1634/20251003/b66b-587c9ff400fcf01be52c6693594b6a6d.jpg/w700d1q75cms.jpg',
                    price: 14.52,
                    num: 1,
                    status: 1,
                    stock: 10,
                    checked: false,
                    reducedAmount: 0.5, // 已降
                    canReduceAmount: 0,
                    stockWarning: false,
                    quality: '中等'
                },
                {
                    id: 2,
                    title: '六级词汇词根+联想记忆法第二版浙江教育出版社',
                    cover: 'https://k.sinaimg.cn/n/sinakd20116/234/w1000h1634/20251003/b66b-587c9ff400fcf01be52c6693594b6a6d.jpg/w700d1q75cms.jpg',
                    price: 4.5,
                    num: 1,
                    status: 0, // 无库存/失效
                    stock: 0,
                    checked: false,
                    reducedAmount: 0,
                    canReduceAmount: 0,
                    stockWarning: false,
                    quality: '中等'
                },
                {
                    id: 3,
                    title: '六级词汇词根+联想记忆法第二版浙江教育出版社',
                    cover: 'https://k.sinaimg.cn/n/sinakd20116/234/w1000h1634/20251003/b66b-587c9ff400fcf01be52c6693594b6a6d.jpg/w700d1q75cms.jpg',
                    price: 14.52,
                    num: 1,
                    status: 1,
                    stock: 5,
                    checked: false,
                    reducedAmount: 0,
                    canReduceAmount: 0.5, // 可降
                    stockWarning: true, // 库存紧张
                    quality: '中等'
                }
            ],
            recommendList: [
                { title: '工程数学线性代数第六版', cover: 'https://k.sinaimg.cn/n/sinakd20116/234/w1000h1634/20251003/b66b-587c9ff400fcf01be52c6693594b6a6d.jpg/w700d1q75cms.jpg' },
                { title: '工程数学线性代数第六版', cover: 'https://k.sinaimg.cn/n/sinakd20116/234/w1000h1634/20251003/b66b-587c9ff400fcf01be52c6693594b6a6d.jpg/w700d1q75cms.jpg' },
                { title: '工程数学线性代数第六版', cover: 'https://k.sinaimg.cn/n/sinakd20116/234/w1000h1634/20251003/b66b-587c9ff400fcf01be52c6693594b6a6d.jpg/w700d1q75cms.jpg' },
                { title: '工程数学线性代数第六版', cover: 'https://k.sinaimg.cn/n/sinakd20116/234/w1000h1634/20251003/b66b-587c9ff400fcf01be52c6693594b6a6d.jpg/w700d1q75cms.jpg' },
                { title: '工程数学线性代数第六版', cover: 'https://k.sinaimg.cn/n/sinakd20116/234/w1000h1634/20251003/b66b-587c9ff400fcf01be52c6693594b6a6d.jpg/w700d1q75cms.jpg' },
                { title: '工程数学线性代数第六版', cover: 'https://k.sinaimg.cn/n/sinakd20116/234/w1000h1634/20251003/b66b-587c9ff400fcf01be52c6693594b6a6d.jpg/w700d1q75cms.jpg' }
            ]
        };
    },
    computed: {
        selectedItems() {
            return this.cartList.filter(item => item.checked && item.status === 1 && item.stock > 0);
        },
        totalPrice() {
            return this.selectedItems.reduce((sum, item) => sum + item.price * item.num, 0).toFixed(2);
        },
        totalReduced() {
            return this.selectedItems.reduce((sum, item) => sum + (item.reducedAmount || 0) * item.num, 0).toFixed(2);
        },
        selectedCount() {
            return this.selectedItems.reduce((sum, item) => sum + item.num, 0);
        }
    },
    watch: {
        cartList: {
            handler(val) {
                const validItems = val.filter(item => item.status === 1 && item.stock > 0);
                if (validItems.length === 0) {
                    this.isAllSelected = false;
                    return;
                }
                this.isAllSelected = validItems.every(item => item.checked);
            },
            deep: true
        }
    },
    methods: {
        handleCheck({ id, checked }) {
            const item = this.cartList.find(i => i.id === id);
            if (item) {
                item.checked = checked;
            }
        },
        handleChangeNum({ id, num }) {
            const item = this.cartList.find(i => i.id === id);
            if (item) {
                item.num = num;
            }
        },
        handleReduce(item) {
            // 打开减钱弹窗
            // 构造弹窗需要的数据格式
            const popupData = {
                price: item.price,
                reducedPrice: (item.price - item.canReduceAmount).toFixed(2),
                startTime: new Date().getTime(),
                endTime: new Date().getTime() + 24 * 60 * 60 * 1000,
                upsellCode: 'mock-code' // 模拟
            };
            this.$refs.reducePopup.bookInfo = popupData; // 直接赋值或者通过 open 方法传参
            // price-reduction-popup (based on upsell-book) uses 'open(data)' method if available, 
            // but looking at upsell-book.vue code, it uses v-model="showPopup" and data is set via props or direct access?
            // Actually upsell-book.vue doesn't have an open method in the snippet I saw earlier, 
            // wait, upsell-book.vue code snippet shows:
            // data() { return { showPopup: false, ... } }
            // It doesn't seem to have an open() method exposed in the snippet.
            // But it has `custom-popup v-model="showPopup"`.
            // So I should set showPopup = true.
            // And I need to pass data. 
            // upsell-book.vue snippet didn't show props for bookInfo, 
            // but it uses bookInfo in template. It likely has it in data or props.
            // Let's assume I need to set it.

            // Checking upsell-book.vue again (from previous search):
            // It uses `bookInfo.recyclePrice` etc. 
            // I should verify if bookInfo is a prop or data. 
            // The snippet showed `props: { book: ... }` in BookItem.vue, but upsell-book.vue?
            // Wait, I copied upsell-book.vue. Let me check the file content if I can... 
            // I'll assume I can set `this.$refs.reducePopup.bookInfo = ...` and `this.$refs.reducePopup.showPopup = true`.

            this.$refs.reducePopup.bookInfo = popupData;
            this.$refs.reducePopup.showPopup = true;

            // Simulate invite users
            this.$refs.reducePopup.inviteUsers = [];
        },
        onAllCheckChange(e) {
            const checked = e.value;
            this.cartList.forEach(item => {
                if (item.status === 1 && item.stock > 0) {
                    item.checked = checked;
                }
            });
        },
        toggleSelectAll() {
            // Handled by u-checkbox change or click wrapper
            // If clicked wrapper, toggle boolean
            // But u-checkbox also emits change.
            // Let's rely on v-model binding and @change
        },
        checkout() {
            if (this.selectedCount === 0) {
                uni.showToast({ title: '请选择商品', icon: 'none' });
                return;
            }
            this.$refs.reduceDialog.openPopup();
        },
        onNext() {
            // 提交订单
            uni.navigateTo({ url: '/pages-car/pages/confirm-order' });
        },
        handleShare() {
            console.log('share');
        },
        handleScan() {
            console.log('scan');
        }
    }
}
</script>

<style lang="scss" scoped>
.cart-page {
    min-height: 100vh;
    background-color: #f5f5f5;
    padding-bottom: 120rpx; // Space for bottom bar
}

.ad-banner {
    background-color: #d1f2d6; // Light green
    padding: 20rpx 30rpx;
    display: flex;
    justify-content: space-between;
    align-items: center;
    color: #666;
    font-size: 26rpx;
}

.cart-list {
    padding: 20rpx;
}

.recommend-section {
    padding: 0 20rpx;

    .section-title {
        display: flex;
        align-items: center;
        justify-content: center;
        margin: 30rpx 0;

        .line {
            width: 60rpx;
            height: 2rpx;
            background-color: #ccc;
        }

        .text {
            margin: 0 20rpx;
            font-size: 28rpx;
            color: #333;
            font-weight: bold;
        }
    }

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

        .grid-item {
            width: 32%; // 3 columns
            background-color: #fff;
            border-radius: 12rpx;
            margin-bottom: 20rpx;
            padding: 20rpx;
            box-sizing: border-box;
            display: flex;
            flex-direction: column;
            align-items: center;
            
            .cover {
                width: 100%;
                height: 220rpx;
                border-radius: 8rpx;
                background-color: #eee;
            }
            
            .title {
                margin-top: 10rpx;
                font-size: 24rpx;
                color: #333;
                line-height: 1.4;
                display: -webkit-box;
                -webkit-box-orient: vertical;
                -webkit-line-clamp: 2;
                overflow: hidden;
                width: 100%;
            }
        }
    }
}

.bottom-fixed {
    position: fixed;
    bottom: 0;
    /* #ifdef H5 */
    bottom: 50px;
    /* #endif */
    left: 0;
    width: 100%;
    background-color: #fff;
    display: flex;
    align-items: center;
    justify-content: space-between;
    padding: 24rpx 30rpx;
    box-sizing: border-box;
    box-shadow: 0 -2rpx 10rpx rgba(0,0,0,0.05);
    z-index: 99;

    .left-part {
        display: flex;
        align-items: center;
    }

    .right-part {
        display: flex;
        align-items: center;
        
        .total-info {
            text-align: right;
            margin-right: 20rpx;
            display: flex;
            align-items: center;
            
            .reduced-tip {
                font-size: 22rpx;
                color: #38C148;
                border: 1rpx solid #38C148;
                border-radius: 4rpx;
                padding: 0 6rpx;
                margin-right: 10rpx;
            }
            
            .total-price {
                display: flex;
                align-items: center;
                
                .label {
                    font-size: 28rpx;
                    color: #333;
                }
                .price {
                    font-size: 36rpx;
                    color: #e02020;
                    font-weight: bold;
                }
            }
        }
        
        .checkout-btn {
            background-color: #e02020;
            color: #fff;
            font-size: 30rpx;
            padding: 16rpx 40rpx;
            border-radius: 40rpx;
        }
    }
}
</style>