<template>
    <view class="book-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="section-card">
            <view class="flex-a flex-j-b mb-20">
                <view class="flex-a">
                    <view :style="titleStyle" class="font-28">订单备注</view>
                </view>
                <view class="flex-a" style="flex: 1; justify-content: flex-end;">
                    <u-input v-model="submitData.remark" type="text" placeholder="选填，请先和商家协商一致" :custom-style="{textAlign: 'right'}" />
                </view>
            </view>
        </view>

        <!-- 书籍列表 -->
        <view class="book-list">
            <book-item v-for="book in books" :key="book.id" :book="book"></book-item>
        </view>

        <!-- 底部栏 -->
        <view class="bottom-bar">
            <view class="order-summary">
                <view class="total">
                    共<text class="price">{{ totalNum }}</text>件 
                    合计: <text class="price">¥{{ totalMoney }}</text>
                    <text v-if="totalDiscount > 0" style="font-size: 24rpx; color: #999; margin-left: 10rpx;">(已优惠 ¥{{ totalDiscount }})</text>
                </view>
                <u-button type="primary" @click="submitOrder" :custom-style="{ margin: 0 }">提交订单</u-button>
            </view>
        </view>

        <submit-confirm ref="submitConfirmDialog" @confirm="handleConfirmSubmit" title="确认提交订单" content="请确认收货地址和商品信息无误"></submit-confirm>
    </view>
</template>

<script>
import bookItem from "@/pages-home/components/BookItem.vue";
import SubmitConfirm from "@/pages-home/components/SubmitConfirm.vue";

export default {
    components: {
        bookItem,
        SubmitConfirm,
    },
    data() {
        return {
            titleStyle: {
                "font-family": "PingFang SC",
                "font-weight": 400,
                color: "#333333",
            },
            books: [],
            defaultAddr: {},
            cartIdList: [], // 接收参数
            
            submitData: {
                cartIdList: [],
                addressId: "",
                remark: "",
                userCouponIds: [],
            },
            
            totalNum: 0,
            totalMoney: 0,
            totalDiscount: 0,
        };
    },
    onLoad(options) {
        if (options.cartIds) {
            this.cartIdList = options.cartIds.split(',').map(Number);
            this.submitData.cartIdList = this.cartIdList;
            this.getPreSubmitOrder();
        } else {
            this.$u.toast('参数错误');
            setTimeout(() => uni.navigateBack(), 1500);
        }
    },
    methods: {
        // 添加或者选择地址
        handleAddress() {
            uni.navigateTo({
                url: `/pages-mine/pages/address/list?id=${this.defaultAddr.id}&isSelect=1`,
            });
        },
        
        submitOrder() {
            if (!this.submitData.addressId) {
                this.$u.toast("请选择收货地址");
                return;
            }
            // 显示确认弹窗
            this.$refs.submitConfirmDialog.openPopup();
        },

        // 确认提交订单
        handleConfirmSubmit() {
            uni.showLoading({ title: '提交中' });
            this.$u.api.submitShopOrderAjax(this.submitData).then((res) => {
                uni.hideLoading();
                if (res.code == 200) {
                    // 支付逻辑待定，暂时跳转成功页或提示
                    this.$u.toast('下单成功');
                    setTimeout(() => {
                        uni.redirectTo({
                            url: "/pages-home/pages/order-success",
                        });
                    }, 1000);
                    uni.removeStorageSync("selectAddr");
                } else {
                    this.$u.toast(res.msg || '下单失败');
                }
            }).catch(() => {
                uni.hideLoading();
            });
        },
        
        // 获取预提交订单信息
        getPreSubmitOrder() {
            uni.showLoading({ title: '加载中' });
            this.$u.api.preSubmitOrderAjax({ 
                cartIdList: this.cartIdList 
            }).then((res) => {
                uni.hideLoading();
                if (res.code === 200) {
                    const data = res.data;
                    
                    // 地址信息
                    if (data.defaultAddress) {
                        this.defaultAddr = data.defaultAddress;
                        this.submitData.addressId = this.defaultAddr.id;
                    }
                    
                    // 商品列表
                    this.books = data.orderDetailList || [];
                    
                    // 价格汇总
                    this.totalMoney = data.totalMoney;
                    this.totalDiscount = data.discountMoney || 0;
                    this.totalNum = data.totalQuantity;
                    
                } 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;
        }
    },
};
</script>

<style lang="scss">
.book-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: 10rpx;
    box-sizing: border-box;
}

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

.book-list {
    margin-bottom: 20rpx;
}

.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: #333;
            
            .price {
                color: #ff0000;
                font-size: 32rpx;
                font-weight: bold;
                margin: 0 8rpx;
            }
        }
    }
}
</style>
