<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="快递 免邮" :arrow="false" :title-style="{ color: '#333' }"
                    :value-style="{ color: '#333' }"></u-cell-item>
                <u-cell-item title="红包" :value="selectedPacket ? selectedPacket.name : ''" @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">{{ totalNum }}</text>本
                    <text class="reduce-text" v-if="totalReduced > 0">已降¥{{ totalReduced }}</text>
                    合计: <text class="price">¥{{ totalPrice }}</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" @confirm="onRedPacketConfirm"></red-packet-popup>
        <stock-shortage-popup v-model="showStockShortage" @confirm="onStockShortageConfirm"></stock-shortage-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: {
                addressId: "",
                remark: "",
            },
            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,
            selectedPacket: null,
            selectedStockOption: { text: '其他商品继续发货（缺货商品退款）', value: 2 }
        };
    },
    methods: {
        //添加或者选择地址
        handleAddress() {
            uni.navigateTo({
                url: `/pages-mine/pages/address/list?id=${this.defaultAddr.id}&isSelect=1`,
            });
        },

        onRedPacketConfirm(packet) {
            this.selectedPacket = packet;
            // Recalculate price if needed
        },

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

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

        // 确认提交订单
        handleConfirmSubmit() {
            // 处理订单提交
            uni.showToast({
                title: '订单提交成功',
                icon: "success",
            });
            setTimeout(() => {
                uni.redirectTo({
                    url: "/pages-car/pages/my-order"
                });
            }, 1500);

            // uni.$u.http.post("/token/order/submitBuyOrder", this.submitData).then((res) => {
            //     if (res.code == 200) {
            //         uni.navigateTo({
            //             url: "/pages-car/pages/pay-success",
            //         });
            //     } else {
            //         uni.showToast({
            //             title: res.msg,
            //             icon: "none",
            //         });
            //     }
            // });
        },
        //获取默认地址
        getDefaultAddress() {
            // Mock default address
            this.defaultAddr = {
                id: '1',
                name: '张三',
                mobile: '18888888888',
                fullAddress: '北京市朝阳区xx街道xx小区1号楼101'
            };
            this.submitData.addressId = this.defaultAddr.id;

            // uni.$u.http.get("/token/user/address/getDefault").then((res) => {
            //     if (res.code == 200) {
            //         this.defaultAddr = res.data;
            //         this.submitData.addressId = this.defaultAddr.id;
            //     }
            // });
        },
        // 获取结算商品信息
        getCheckoutInfo() {
            // Mock books data
            this.books = [
                {
                    title: '商品名称商品名称商品',
                    cover: 'https://k.sinaimg.cn/n/sinakd20116/234/w1000h1634/20251003/b66b-587c9ff400fcf01be52c6693594b6a6d.jpg/w700d1q75cms.jpg',
                    quality: '中等',
                    price: '0.01',
                    originalPrice: '0.01',
                    priceReduced: '0.5',
                    num: 1
                },
                {
                    title: '商品名称商品名称商品',
                    cover: 'https://k.sinaimg.cn/n/sinakd20116/234/w1000h1634/20251003/b66b-587c9ff400fcf01be52c6693594b6a6d.jpg/w700d1q75cms.jpg',
                    quality: '中等',
                    canReduce: '0.5',
                    price: '0.01',
                    originalPrice: '0.01',
                    num: 1
                }
            ];
            this.totalNum = 2;
            this.totalPrice = '0.01';
            this.totalReduced = '1.01';
        }
    },
    mounted() {
        this.getDefaultAddress();
        this.getCheckoutInfo();
    },

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

    .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;
}
</style>
