<template>
    <view class="cart-page">
        <!-- 购物车列表 -->
        <view class="cart-list">
            <u-swipe-action :show="item.show" :index="index" v-for="(item, index) in cartList" :key="item.id"
                @click="clickAction" @open="openAction" :options="actionOptions">
                <cart-item :item="item" @check="handleCheck" @changeNum="handleChangeNum" @reduce="handleReduce"
                    @selectCondition="onSelectCondition"></cart-item>
            </u-swipe-action>
        </view>

        <!-- 品相切换弹窗 -->
        <condition-popup ref="conditionPopup" @select="handleConditionUpdate"></condition-popup>

        <!-- 空状态 -->
        <view class="empty-cart" v-if="cartList.length === 0 && !loading" style="margin:15% 0">
            <u-empty text="购物车空空如也" mode="car"></u-empty>
        </view>

        <!-- 为你推荐 -->
        <view class="recommend-section" v-if="recommendList.length > 0">
            <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: 120rpx;"></view>

        <!-- 悬浮清空按钮 -->
        <view class="floating-clear-btn" v-if="cartList.length > 0" @click="handleClearCart">
            <u-icon name="trash" size="36" color="#fa3534"></u-icon>
        </view>

        <!-- 底部结算栏 -->
        <view class="bottom-fixed" v-if="cartList.length > 0">
            <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="total-price">
                        <text class="label">合计：</text>
                        <text class="price">¥{{ totalPrice }}</text>
                    </view>
                    <view class="reduced-tip" v-if="totalReduced > 0">已降 ¥{{ totalReduced }}</view>
                </view>
                <view class="checkout-btn" @click="checkout">
                    结算({{ selectedCount }})
                </view>
            </view>
        </view>

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

        <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/price-reduction-popup.vue';
    import ReduceQrcode from '@/components/reduce-qrcode/reduce-qrcode.vue';
    import CommonDialog from '@/components/common-dialog.vue';
    import ConditionPopup from '../components/condition-popup.vue';

    export default {
        components: {
            CartItem,
            PriceReductionPopup,
            ReduceQrcode,
            CommonDialog,
            ConditionPopup
        },
        data() {
            return {
                loading: true,
                currentItem: null,
                isAllSelected: false,
                cartList: [],
                actionOptions: [
                    {
                        text: '删除',
                        style: {
                            backgroundColor: '#fa3534'
                        }
                    }
                ],
                recommendList: []
            };
        },
        onShow() {
            this.loadData();
            this.$updateCartBadge();
        },
        mounted() {
            this.loadData();
        },
        // 分享配置
        onShareAppMessage(res) {
            console.log(res, '分享');
            if (res.from === "button") {
                let reduceCode = uni.getStorageSync("reduceCodeShare");
                // 调用分享接口
                this.$u.api.goToReduceShareAjax({ reduceCode: reduceCode });
                return {
                    title: "快来帮我减钱买书吧！",
                    path: "/pages/home/index?reduceCode=" + reduceCode,
                    imageUrl: "https://shuhi.oss-cn-qingdao.aliyuncs.com/mini/share.jpg",
                    desc: "书嗨，专注于书籍交易的平台，提供新书和二手书的买卖服务",
                };
            } else {
                return {
                    title: "书嗨",
                    page: "/pages/home/index",
                };
            }
        },
        // 分享到朋友圈
        onShareTimeline(res) {
            if (res.from === "button") {
                let reduceCode = uni.getStorageSync("reduceCodeShare");
                // 调用分享接口
                this.$u.api.goToReduceShareAjax({ reduceCode: reduceCode });
                return {
                    title: "快来帮我减钱买书吧！",
                    path: "/pages/home/index?reduceCode=" + reduceCode,
                    imageUrl: "https://shuhi.oss-cn-qingdao.aliyuncs.com/mini/share.jpg",
                    desc: "书嗨，专注于书籍交易的平台，提供新书和二手书的买卖服务",
                };
            } else {
                return {
                    title: "书嗨",
                    page: "/pages/home/index",
                };
            }
        },
        computed: {
            selectedItems() {
                return this.cartList.filter(item => item.checked && item.stockStatus !== 3 && item.availableStock > 0);
            },
            totalPrice() {
                const sumPrice = this.selectedItems.reduce((sum, item) => sum + item.price * item.quantity, 0);
                const sumReduce = this.selectedItems.reduce((sum, item) => sum + (item.currReduceMoney || 0), 0);
                const result = sumPrice - sumReduce;
                return result > 0 ? result.toFixed(2) : "0.00";
            },
            totalReduced() {
                return this.selectedItems.reduce((sum, item) => sum + (item.currReduceMoney || 0), 0).toFixed(2);
            },
            selectedCount() {
                return this.selectedItems.reduce((sum, item) => sum + item.quantity, 0);
            }
        },
        watch: {
            cartList: {
                handler(val) {
                    const validItems = val.filter(item => item.stockStatus !== 3 && item.availableStock > 0);
                    if (validItems.length === 0) {
                        this.isAllSelected = false;
                        return;
                    }
                    this.isAllSelected = validItems.every(item => item.checked);
                },
                deep: true
            }
        },
        methods: {
            clickAction(index, index1) {
                if (this.actionOptions[index1].text == '删除') {
                    const item = this.cartList[index];
                    this.handleDelete(item);
                }
            },
            openAction(index) {
                this.cartList[index].show = true;
                this.cartList.map((val, idx) => {
                    if (index != idx) this.cartList[idx].show = false;
                })
            },
            loadData() {
                this.loading = true;
                // 获取购物车列表
                this.$u.api.getShopCartListAjax({}).then(res => {
                    this.loading = false;

                    // 获取本地缓存的选中状态，和当前列表的选中状态合并
                    let storageCheckedIds = uni.getStorageSync('cartCheckedIds') || [];
                    const currentCheckedIds = this.cartList.filter(i => i.checked).map(i => i.id);

                    // 合并并去重
                    let checkedIds = [...new Set([...storageCheckedIds, ...currentCheckedIds])];

                    // 本地添加选中状态属性
                    const list = res.rows || [];
                    this.cartList = list.map(item => {
                        return {
                            ...item,
                            checked: checkedIds.includes(item.id),
                            show: false
                        };
                    });

                    // 更新缓存中存在的且当前在购物车里的项
                    const finalCheckedIds = this.cartList.filter(i => i.checked).map(i => i.id);
                    uni.setStorageSync('cartCheckedIds', finalCheckedIds);

                }).catch(() => {
                    this.loading = false;
                });

                // 获取推荐列表
                this.$u.api.getSearchRecommendAjax().then(res => {
                    if (res.code == 200) {
                        this.recommendList = res.data || [];
                    }
                });
            },
            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) {
                    // 乐观更新还是等待服务器？
                    // 通常是服务器优先。
                    this.$u.api.updateCartNumAjax({
                        id: id,
                        quantity: num
                    }).then(() => {
                        item.quantity = num;
                        // 通过 computed 重新计算总额
                        this.$updateCartBadge();
                    }).catch(() => {
                    });
                }
            },
            handleReduce(item) {
                console.log('handleReduce item:', item);
                this.$nextTick(() => {
                    if (this.$refs.reducePopup) {
                        this.$refs.reducePopup.open({
                            isbn: item.isbn,
                            conditionType: item.conditionType,
                            orderId: item.id
                        });
                    } else {
                        console.error('reducePopup ref not found');
                    }
                });
            },
            onAllCheckChange(e) {
                const checked = e.value;
                this.cartList.forEach(item => {
                    if (item.stockStatus !== 3 && item.availableStock > 0) {
                        item.checked = checked;
                    }
                });
            },
            toggleSelectAll() {
                // 由 u-checkbox 处理
            },
            handleClearCart() {
                uni.showModal({
                    title: '提示',
                    content: '确定要清空购物车吗？',
                    success: (res) => {
                        if (res.confirm) {
                            this.$u.api.clearCartAjax().then(() => {
                                this.$u.toast('清空成功');
                                this.cartList = [];
                                this.$updateCartBadge();
                            });
                        }
                    }
                });
            },
            checkout() {
                if (this.selectedCount === 0) {
                    uni.showToast({ title: '请选择商品', icon: 'none' });
                    return;
                }
                // 如果需要，检查减价商品逻辑
                // 如果有选中的商品可以减价，显示对话框？
                const hasReduceItem = this.selectedItems.some(item => (item.reduceNum < item.maxReduceNum) && (item.reduceMoney > 0));
                if (hasReduceItem) {
                    this.$refs.reduceDialog.openPopup();
                } else {
                    this.onNext();
                }
            },
            onNext() {
                // 提交订单 - 传递选中的 ID
                if (this.selectedItems.length === 0) {
                    this.$u.toast('请选择商品');
                    return;
                }

                const ids = this.selectedItems.map(item => item.id);

                // 调用预提交接口检查
                uni.showLoading({ title: '处理中' });
                this.$u.api.preSubmitOrderAjax({ cartIdList: ids }).then(res => {
                    uni.hideLoading();
                    if (res.code === 200) {
                        if (res.data.code === 2) {
                            return this.$u.toast('库存不足');
                        } else if (res.data.code === 3) {
                            return this.$u.toast('图书已下架');
                        }

                        uni.navigateTo({
                            url: `/pages-car/pages/confirm-order`
                        });

                        //存储提交的数据
                        res.data.cartIdList = ids;
                        uni.setStorageSync('preSubmitOrderData', res.data);
                    } else {
                        // 失败，显示错误信息
                        this.$u.toast(res.msg || '无法提交订单');
                    }
                }).catch(() => {
                    uni.hideLoading();
                });
            },
            handleShare() {
                console.log('share');
            },
            handleScan(bookInfo) {
                this.$refs.reduceQrcode.open(bookInfo);
            },
            handleDelete(item) {
                uni.showModal({
                    title: '提示',
                    content: '确定要删除该商品吗？',
                    success: (res) => {
                        if (res.confirm) {
                            this.$u.api.deleteCartItemAjax(item.id).then(() => {
                                this.$u.toast('删除成功');
                                // 从本地列表中移除
                                const index = this.cartList.findIndex(i => i.id === item.id);
                                if (index > -1) {
                                    this.cartList.splice(index, 1);
                                }
                                this.$updateCartBadge();
                            });
                        } else {
                            item.show = false;
                        }
                    }
                });
            },
            onSelectCondition(item) {
                this.currentItem = item;
                // 获取商品详情中的 SKU 列表
                // 注意：这里使用 isbn，假设 item 中包含 isbn
                if (!item.isbn) {
                    this.$u.toast('无法获取商品信息');
                    return;
                }

                uni.showLoading({ title: '加载中' });
                this.$u.http.get('/token/shop/bookDetail', { isbn: item.isbn }).then(res => {
                    uni.hideLoading();
                    if (res.code === 200 && res.data && res.data.skuList) {
                        this.$refs.conditionPopup.open(res.data.skuList, item.conditionType);
                    } else {
                        this.$u.toast('获取品相信息失败');
                    }
                }).catch(() => {
                    uni.hideLoading();
                    this.$u.toast('网络请求失败');
                });
            },
            handleConditionUpdate(sku) {
                if (!this.currentItem) return;

                uni.showLoading({
                    title: '更新中'
                });
                this.$u.api.updateCartConditionAjax({
                    id: this.currentItem.id,
                    conditionType: sku.conditionType
                }).then(() => {
                    uni.hideLoading();
                    this.$u.toast('更新成功');

                    this.loadData();
                }).catch(() => {
                    uni.hideLoading();
                });
            }
        }
    }
</script>

<style lang="scss" scoped>
    .cart-page {
        min-height: 100vh;
        background-color: #f5f5f5;
        padding-bottom: 120rpx; // 底部栏的留白
    }

    .ad-banner {
        background-color: #d1f2d6; // 浅绿色
        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 列
                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%;
                }
            }
        }
    }

    .floating-clear-btn {
        position: fixed;
        right: 30rpx;
        bottom: 160rpx; /* 留出底部结算栏的空间 */
        /* #ifdef H5 */
        bottom: calc(160rpx + 50px);
        /* #endif */
        width: 80rpx;
        height: 80rpx;
        background-color: #fff;
        border: 2rpx solid #f56c6c;
        border-radius: 50%;
        display: flex;
        justify-content: center;
        align-items: center;
        z-index: 98;
        box-shadow: 0 4rpx 10rpx rgba(250, 53, 52, 0.2);
        
        &:active {
            background-color: #fef0f0;
        }
    }

    .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;

                .total-price {
                    display: flex;
                    align-items: center;

                    .label {
                        font-size: 28rpx;
                        color: #333;
                    }

                    .price {
                        font-size: 36rpx;
                        color: #e02020;
                        font-weight: bold;
                    }
                }
                
                .reduced-tip {
                    font-size: 22rpx;
                    color: #38C148;
                    border: 1rpx solid #38C148;
                    border-radius: 4rpx;
                    padding: 0 10rpx;
                    margin-left: 10rpx;
                }
            }

            .checkout-btn {
                background-color: #e02020;
                color: #fff;
                font-size: 30rpx;
                padding: 16rpx 40rpx;
                border-radius: 40rpx;
            }
        }
    }
</style>