<template>
    <view class="confirm-order">
        <!-- 收货地址部分 -->
        <view class="section-card">
            <view class="flex-a flex-j-b mb-20" @click="handleAddress" v-if="defaultAddr.id">
                <image src="/pages-mine/static/adderss.png" style="width: 40rpx; height: 40rpx"></image>
                <view class="flex-d flex-1 ml-24" style="margin-right: 90rpx">
                    <view class="flex-a flex-j-b mb-10">
                        <view :style="titleStyle">收货人：{{ defaultAddr.name }}</view>
                        <view :style="titleStyle">{{ defaultAddr.mobile }}</view>
                    </view>
                    <view :style="titleStyle">地址：{{ defaultAddr.fullAddress }}</view>
                </view>
                <u-icon name="arrow-right" :size="28" color="#666" top="4"></u-icon>
            </view>

            <view class="flex-a flex-j-b" @click="handleAddress" v-else>
                <view class="flex-a">
                    <u-icon name="plus-circle-fill" :size="48" color="#38C148" top="2"></u-icon>
                    <view :style="titleStyle" class="ml-10 font-30">添加收货地址</view>
                    <text class="u-required">*</text>
                </view>

                <view class="flex-a">
                    <view :style="titleStyle" class="ml-10">请添加</view>
                    <u-icon name="arrow-right" :size="28" color="#666" top="4"></u-icon>
                </view>
            </view>
        </view>

        <!-- 商品列表 -->
        <view class="book-list">
            <buy-book-item v-for="(book, index) in books" :key="index" :book="book"></buy-book-item>
        </view>

        <!-- 订单信息 -->
        <view class="section-card mt-20" style="padding: 0; overflow: hidden;">
            <u-cell-group :border="false">
                <u-cell-item title="配送服务"
                    :value="!preOrder.expressMoney ? '快递 免邮' : '快递费 ' + preOrder.expressMoney + '元'" :arrow="false"
                    :title-style="{ color: '#333' }" :value-style="{ color: '#333' }"></u-cell-item>
                <u-cell-item title="红包" :value="redPacketText" @click="showRedPacket = true"
                    :title-style="{ color: '#333' }"></u-cell-item>
                <u-cell-item title="订单备注" :arrow="false" :title-style="{ color: '#333' }">
                    <u-input slot="right-icon" v-model="submitData.remark" type="text" placeholder="无备注"
                        input-align="right" :custom-style="{ color: '#999', minHeight: '28px' }" />
                </u-cell-item>
                <u-cell-item title="如遇缺货" :value="selectedStockOption.text || '其他商品继续发货'"
                    @click="showStockShortage = true" :border-bottom="false"
                    :title-style="{ color: '#ff4500', fontWeight: 'bold' }"></u-cell-item>
            </u-cell-group>
        </view>

        <!-- 底部栏 -->
        <view class="bottom-bar">
            <view class="order-summary">
                <view class="total">
                    共<text class="num">{{ preOrder.totalQuantity }}</text>本
                    <text class="reduce-text" v-if="totalDiscountAmount > 0" @click="openDiscountDetail">已降¥{{
                        totalDiscountAmount }}</text>
                    合计: <text class="price">¥{{ finalTotalMoney }}</text>
                </view>
                <u-button type="primary" shape="circle" @click="submitOrder">提交订单</u-button>
            </view>
        </view>

        <submit-confirm ref="submitConfirmDialog" @confirm="handleConfirmSubmit"></submit-confirm>
        <red-packet-popup v-model="showRedPacket" :list="preOrder.couponList"
            @confirm="onRedPacketConfirm"></red-packet-popup>
        <stock-shortage-popup v-model="showStockShortage" @confirm="onStockShortageConfirm"></stock-shortage-popup>

        <!-- 优惠明细弹窗 -->
        <u-popup v-model="showDiscountDetail" mode="bottom" border-radius="24">
            <view class="discount-popup">
                <view class="popup-header">
                    <text>优惠明细</text>
                    <u-icon name="close" size="28" color="#999" class="close-icon"
                        @click="showDiscountDetail = false"></u-icon>
                </view>
                <view class="discount-list">
                    <view class="discount-item" v-for="(item, index) in discountDetails" :key="index">
                        <text class="label">{{ item.label }}</text>
                        <text class="amount">-¥{{ item.amount }}</text>
                    </view>
                </view>
                <view class="popup-footer">
                    <u-button type="primary" shape="circle" @click="showDiscountDetail = false">确认</u-button>
                </view>
            </view>
        </u-popup>
    </view>
</template>

<script>
    import SubmitConfirm from "@/pages-car/components/submit-confirm.vue";
    import BuyBookItem from "@/pages-car/components/buy-book-item.vue";
    import RedPacketPopup from "@/pages-car/components/red-packet-popup.vue";
    import StockShortagePopup from "@/pages-car/components/stock-shortage-popup.vue";

    export default {
        components: {
            SubmitConfirm,
            BuyBookItem,
            RedPacketPopup,
            StockShortagePopup
        },
        data() {
            return {
                titleStyle: {
                    "font-family": "PingFang SC",
                    "font-weight": 400,
                    color: "#333333",
                },
                books: [],
                defaultAddr: {},
                submitData: {
                    cartIdList: [],
                    addressId: "",
                    remark: "",
                    outOfStock: "2", // 默认为2
                    userCouponIds: []
                },
                totalNum: 0,
                totalPrice: 0,
                totalReduced: 0,
                btnStyle: {
                    width: '240rpx',
                    height: '80rpx',
                    lineHeight: '80rpx',
                    background: 'linear-gradient(90deg, #ff8c00, #ff4500)',
                    color: '#fff',
                    fontSize: '30rpx',
                    margin: '0'
                },
                showRedPacket: false,
                showStockShortage: false,
                showDiscountDetail: false,
                selectedPacket: null,
                selectedStockOption: { text: '其他商品继续发货（缺货商品退款）', value: 2 },
                preOrder: {},// 预订单信息
            };
        },
        computed: {
            redPacketText() {
                if (!this.preOrder.couponList || this.preOrder.couponList.length === 0) {
                    return '暂无红包';
                }
                return this.selectedPacket ? this.selectedPacket.couponName : '请选择';
            },
            finalTotalMoney() {
                let total = parseFloat(this.preOrder.totalMoney || 0);
                if (this.selectedPacket && this.selectedPacket.faceMoney) {
                    total -= parseFloat(this.selectedPacket.faceMoney);
                }
                return total < 0 ? '0.00' : total.toFixed(2);
            },
            totalDiscountAmount() {
                let total = 0;
                // 1. 活动优惠
                if (this.preOrder.discountMoney) {
                    total += parseFloat(this.preOrder.discountMoney);
                }
                // 2. 红包
                if (this.selectedPacket && this.selectedPacket.faceMoney) {
                    total += parseFloat(this.selectedPacket.faceMoney);
                }
                // 3. 分享降价
                if (this.preOrder.totalReduceMoney) {
                    total += parseFloat(this.preOrder.totalReduceMoney);
                }
                return total.toFixed(2);
            },
            discountDetails() {
                const list = [];
                // 1. 惊喜红包 (红包)
                if (this.selectedPacket && this.selectedPacket.faceMoney > 0) {
                    list.push({
                        label: this.selectedPacket.couponName,
                        amount: parseFloat(this.selectedPacket.faceMoney).toFixed(2)
                    });
                }
                // 2. 分享降价
                if (this.preOrder.totalReduceMoney > 0) {
                    list.push({
                        label: '分享降价',
                        amount: parseFloat(this.preOrder.totalReduceMoney).toFixed(2)
                    });
                }
                // 3. 活动优惠 (每满减等)
                if (this.preOrder.discountMoney > 0) {
                    list.push({
                        label: this.preOrder.discountDesc || '活动优惠',
                        amount: parseFloat(this.preOrder.discountMoney).toFixed(2)
                    });
                }
                return list;
            }
        },
        onLoad(options) {
            // 从本地存储获取提交订单数据
            const preSubmitOrderData = uni.getStorageSync('preSubmitOrderData');
            if (preSubmitOrderData) {
                this.preOrder = preSubmitOrderData;
                this.books = preSubmitOrderData.orderDetailList || [];
                this.defaultAddr = preSubmitOrderData.defaultAddress || {};

                //拼接提交数据
                this.submitData.cartIdList = preSubmitOrderData.cartIdList || [];
                this.submitData.addressId = this.defaultAddr.id || "";
            } else {
                this.$u.toast('参数错误');
                setTimeout(() => uni.navigateBack(), 1500);
            }
        },
        methods: {
            //添加或者选择地址
            handleAddress() {
                uni.navigateTo({
                    url: `/pages-mine/pages/address/list?id=${this.defaultAddr.id}&isSelect=1`,
                });
            },

            onRedPacketConfirm(packet) {
                this.selectedPacket = packet;
                if (packet && packet.userCouponId) {
                    this.submitData.userCouponIds = [packet.userCouponId];
                } else {
                    this.submitData.userCouponIds = [];
                }
            },

            onStockShortageConfirm(option) {
                this.selectedStockOption = option;
                this.submitData.outOfStock = option.value;
            },

            submitOrder() {
                if (!this.submitData.addressId) {
                    this.$u.toast("请选择收货地址");
                    return;
                }
                // 显示确认弹窗
                this.$refs.submitConfirmDialog.openPopup();
            },

            openDiscountDetail() {
                this.showDiscountDetail = true;
            },

            // 确认提交订单
            handleConfirmSubmit() {
                uni.showLoading({ title: '提交中' });
                this.$u.api.submitShopOrderAjax(this.submitData).then((res) => {
                    uni.hideLoading();
                    if (res.code == 200) {
                        uni.showToast({
                            title: '下单成功',
                            icon: "success",
                        });
                        uni.removeStorageSync("selectAddr");
                        //存储订单信息
                        uni.setStorageSync("orderBuyInfo", res.data);

                        //跳转到 收银台页面
                        uni.navigateTo({
                            url: `/pages-car/pages/cashier-desk?id=${res.data.orderId}`
                        })
                    } else {
                        this.$u.toast(res.msg || '下单失败');
                    }
                }).catch(() => {
                    uni.hideLoading();
                });
            },
        },

        onShow() {
            let selectAddr = uni.getStorageSync("selectAddr");
            if (selectAddr) {
                this.defaultAddr = selectAddr;
                this.submitData.addressId = selectAddr.id;
                uni.removeStorageSync("selectAddr"); // Clear after use
            }
        },
    };
</script>

<style lang="scss">
    .confirm-order {
        min-height: 100vh;
        background: #f5f5f5;
        padding: 20rpx 30rpx;
        padding-bottom: calc(env(safe-area-inset-bottom) + 120rpx);
    }

    .section-card {
        background: #fff;
        margin-bottom: 20rpx;
        padding: 30rpx;
        border-radius: 16rpx;
        box-sizing: border-box;
    }

    .u-required {
        color: #ff0000;
        margin-left: 8rpx;
    }

    .book-list {
        background: #fff;
        border-radius: 16rpx;
        margin-bottom: 20rpx;
    }

    .info-row {
        display: flex;
        justify-content: space-between;
        align-items: center;
        padding: 20rpx 0;
        font-size: 28rpx;
        color: #333;

        .label {
            &.red-label {
                color: #ff4500;
                font-weight: bold;
            }
        }

        .value {
            &.text-gray {
                color: #999;
            }
        }

        .mr-10 {
            margin-right: 10rpx;
        }
    }

    .bottom-bar {
        position: fixed;
        bottom: 0;
        left: 0;
        right: 0;
        background: #fff;
        padding: 20rpx 30rpx;
        padding-bottom: env(safe-area-inset-bottom);
        box-shadow: 0 -2rpx 10rpx rgba(0, 0, 0, 0.05);
        z-index: 9;

        .order-summary {
            display: flex;
            justify-content: space-between;
            align-items: center;

            .total {
                font-size: 28rpx;
                color: #666;

                .num {
                    color: #333;
                    font-weight: bold;
                    margin: 0 4rpx;
                }

                .reduce-text {
                    color: #38C148;
                    margin-left: 10rpx;
                    margin-right: 10rpx;
                    background-color: #e6f9e9;
                    padding: 4rpx 10rpx;
                    border-radius: 4rpx;
                    font-size: 24rpx;
                }

                .price {
                    font-size: 36rpx;
                    color: #ff4500;
                    font-weight: bold;
                    margin-left: 10rpx;
                }
            }
        }
    }

    .mt-20 {
        margin-top: 20rpx;
    }

    .ml-10 {
        margin-left: 10rpx;
    }

    .discount-popup {
        padding: 30rpx;
        background-color: #fff;

        .popup-header {
            display: flex;
            justify-content: center;
            align-items: center;
            position: relative;
            padding-bottom: 30rpx;
            border-bottom: 1rpx solid #eee;
            font-size: 32rpx;
            font-weight: bold;
            color: #333;

            .close-icon {
                position: absolute;
                right: 0;
                top: 0;
            }
        }

        .discount-list {
            padding: 30rpx 0;

            .discount-item {
                display: flex;
                justify-content: space-between;
                align-items: center;
                padding: 20rpx 0;
                font-size: 28rpx;

                .label {
                    color: #333;
                }

                .amount {
                    color: #ff4500;
                    font-weight: bold;
                }
            }
        }

        .popup-footer {
            margin-top: 20rpx;
            padding-bottom: env(safe-area-inset-bottom);
        }
    }
</style>
