<template>
    <view class="order-detail-page">
        <!-- 顶部状态栏 -->
        <view class="status-header">
            <view class="status-text">{{ statusText }}</view>
            <view class="status-desc" v-if="orderInfo.status == '2'">
                订单编号：{{ orderInfo.orderId }}
                <image src="/pages-mine/static/copy.png" class="copy-icon" @click="copyOrderNo" mode="aspectFit">
                </image>
            </view>
            <view class="status-desc" v-else-if="orderInfo.status == '3'">
                订单编号：{{ orderInfo.orderId }}
                <image src="/pages-mine/static/copy.png" class="copy-icon" @click="copyOrderNo" mode="aspectFit">
                </image>
            </view>
            <view class="status-desc-block" v-else-if="orderInfo.status == '8'">
                <view class="status-tip">还剩9天22时18分自动确认收货</view>
                <view class="status-desc-row">
                    订单编号：{{ orderInfo.orderId }}
                    <image src="/pages-mine/static/copy.png" class="copy-icon" @click="copyOrderNo" mode="aspectFit">
                    </image>
                </view>
            </view>
            <view class="status-desc" v-else>
                订单编号：{{ orderInfo.orderId }}
                <image src="/pages-mine/static/copy.png" class="copy-icon" @click="copyOrderNo" mode="aspectFit">
                </image>
            </view>
        </view>

        <!-- 地址信息 -->
        <view class="info-card address-card" @click="handleAddressClick">
            <view class="icon-box">
                <image src="/pages-mine/static/adderss.png" style="width: 40rpx; height: 40rpx"></image>
            </view>
            <view class="address-content">
                <view class="user-info">
                    <text class="name">{{ orderInfo.receiverName }}</text>
                    <text class="mobile">{{ orderInfo.receiverMobile }}</text>
                </view>
                <view class="address-detail">{{ orderInfo.receiverAddress }}</view>
            </view>
            <u-icon v-if="orderInfo.showModifyAddress == 1" name="arrow-right" color="#999" size="28"></u-icon>
        </view>

        <!-- 物流信息 -->
        <view class="info-card express-card"
            v-if="['3', '4', '8', '12', '10'].includes(String(orderInfo.status)) && orderInfo.waybillCode"
            @click.stop="viewLogistics">
            <view class="icon-box">
                <u-icon name="car" color="#38C148" size="48"></u-icon>
            </view>
            <view class="express-content">
                <view class="express-name">{{ orderInfo.expressName || '快递' }}({{ orderInfo.waybillCode }})</view>
                <view class="express-trace">{{ latestTrace ? (latestTrace.context || latestTrace.status) : '点击查看物流详情' }}
                </view>
            </view>
            <u-icon name="arrow-right" color="#999" size="28"></u-icon>
        </view>

        <!-- 商品列表 -->
        <view class="info-card goods-card">
            <view class="goods-item" v-for="(goods, index) in orderInfo.detailVoList" :key="index">
                <image :src="goods.cover" mode="aspectFill" class="goods-cover"></image>
                <view class="goods-info">
                    <view class="goods-title">{{ goods.bookName }}</view>
                    <view class="goods-quality" v-if="goods.conditionType || goods.bookConditionType">品相：{{
                        (goods.conditionType || goods.bookConditionType) | conditionText }}</view>
                    <view class="price-box">
                        <text class="price">¥{{ goods.price }}</text>
                        <text class="num">x{{ goods.num }}</text>
                    </view>
                </view>
                <!-- 商品级按钮 -->
                <view class="goods-action">
                    <u-button v-if="goods.refundOrderId" size="mini" shape="circle" plain
                        @click="goToRefundDetail(goods.refundOrderId)"
                        custom-style="margin-left: 20rpx; height: 50rpx; line-height: 50rpx; color: #333; border-color: #ccc;">查看详情</u-button>
                    <u-button v-show="!goods.refundOrderId && orderInfo.status > 1" size="mini" shape="circle" plain
                        @click="applyRefund(goods)"
                        custom-style="margin-left: 20rpx; height: 50rpx; line-height: 50rpx; color: #333; border-color: #ccc;">申请售后</u-button>
                </view>
            </view>

            <!-- 价格明细 -->
            <view class="price-detail">
                <view class="row">
                    <text>邮费</text>
                    <text>¥ {{ orderInfo.expressMoney || '0.00' }}</text>
                </view>
                <view class="row">
                    <text>商品金额</text>
                    <text class="goods-total">¥{{ (orderInfo.totalMoney - (orderInfo.expressMoney || 0)).toFixed(2)
                        }}</text>
                </view>
                <view class="row">
                    <text>优惠金额</text>
                    <text class="discount">-¥{{ orderInfo.discountMoney || '0.00' }}</text>
                </view>
                <view class="divider"></view>
                <view class="real-pay-row">
                    <text>实付款 ({{ orderInfo.payType == 1 ? '余额支付' : '微信支付' }})</text>
                    <text class="real-price">¥ {{ orderInfo.payMoney }}</text>
                </view>
            </view>
        </view>

        <!-- 订单时间及其他信息 -->
        <view class="info-card time-card">
            <view class="row" v-if="orderInfo.outOfStock">
                <text class="label">如遇缺货</text>
                <text class="value" style="color: #ff4500; font-weight: 500;">{{ outOfStockText }}</text>
            </view>
            <view class="row">
                <text class="label">下单时间</text>
                <text class="value">{{ orderInfo.createTime }}</text>
            </view>
            <view class="row" v-if="orderInfo.payTime">
                <text class="label">付款时间</text>
                <text class="value">{{ orderInfo.payTime }}</text>
            </view>
            <view class="row" v-if="orderInfo.deliveryTime">
                <text class="label">发货时间</text>
                <text class="value">{{ orderInfo.deliveryTime }}</text>
            </view>
            <view class="row" v-if="orderInfo.finishTime">
                <text class="label">完成时间</text>
                <text class="value">{{ orderInfo.finishTime }}</text>
            </view>
        </view>

        <!-- 底部操作栏 -->
        <order-bottom-bar :orderInfo="orderInfo" @action="handleAction"></order-bottom-bar>

        <!-- 取消订单弹窗 -->
        <cancel-order-popup ref="cancelDialog" @success="loadOrderDetail(orderInfo.orderId)"></cancel-order-popup>

        <!-- 催发货弹窗 -->
        <urge-delivery-dialog ref="urgeDialog" @success="loadOrderDetail(orderInfo.orderId)"></urge-delivery-dialog>

        <!-- 极速退款弹窗 -->
        <fast-refund-dialog ref="refundDialog" @refresh="loadOrderDetail(orderInfo.orderId)"></fast-refund-dialog>

        <!-- 占位符，防止底部按钮遮挡内容 -->
        <view style="height: 120rpx;"></view>
    </view>
</template>

<script>
import OrderBottomBar from '../components/order-bottom-bar.vue';
import CancelOrderPopup from '../components/cancel-order-popup.vue';
import UrgeDeliveryDialog from '../components/urge-delivery-dialog.vue';
import FastRefundDialog from '../components/fast-refund-dialog.vue';

export default {
    components: {
        OrderBottomBar,
        CancelOrderPopup,
        UrgeDeliveryDialog,
        FastRefundDialog
    },
    data() {
        return {
            orderId: '',
            orderInfo: {
                status: '2',
                orderId: '',
                detailVoList: [],
                receiverName: '',
                receiverMobile: '',
                receiverAddress: '',
                expressMoney: 0,
                totalMoney: 0,
                discountMoney: 0,
                payMoney: 0,
                createTime: ''
            },
            latestTrace: null,
            isModifyingAddress: false,
        };
    },
    computed: {
        statusText() {
            //订单状态:1-待付款 2-待发货 3-待收货 4-已完成 5-已取消 6-退款中 7-已退款
            const map = {
                '1': '等待买家付款',
                '2': '等待卖家发货',
                '3': '已发货',
                '4': '交易完成',
                '5': '已取消',
                '6': '退款中',
                '7': '交易关闭'
            };
            return map[String(this.orderInfo.status)] || '未知状态';
        },
        outOfStockText() {
            const map = {
                '1': '缺货时电话与我沟通',
                '2': '其他商品继续发货（缺货商品退款）',
                '3': '有缺货直接取消订单'
            };
            return map[String(this.orderInfo.outOfStock)] || '其他商品继续发货（缺货商品退款）';
        }
    },
    onLoad(options) {
        if (options.orderId) {
            this.orderId = options.orderId;
        }
        // 监听地址选择
        uni.$on('selectAddr', this.onAddressSelected);
    },
    onShow() {
        if (this.orderId) {
            this.loadOrderDetail(this.orderId);
        }
    },
    onUnload() {
        uni.$off('selectAddr', this.onAddressSelected);
    },
    methods: {
        onAddressSelected(addr) {
            if (this.isModifyingAddress && addr && addr.id) {
                this.$u.api.modifyOrderAddressAjax({
                    orderId: this.orderInfo.orderId,
                    addressId: addr.id
                }).then(res => {
                    uni.hideLoading();
                    if (res.code == 200) {
                        uni.showToast({ title: '修改成功', icon: 'success' });
                        setTimeout(() => {
                            this.loadOrderDetail(this.orderInfo.orderId);
                        }, 1000);
                    }
                }).finally(() => {
                    this.isModifyingAddress = false;
                });
            }
        },
        loadOrderDetail(orderId) {
            uni.$u.http.get('/token/shop/order/getOrderDetail', {
                orderId: orderId
            }).then((res) => {
                if (res.code == 200) {
                    this.orderInfo = res.data;
                    if (['3', '4', '8', '12', '10'].includes(String(this.orderInfo.status)) && this.orderInfo.waybillCode) {
                        this.getLogisticsData();
                    }
                }
            });
        },
        getLogisticsData() {
            this.$u.api.getOrderTrackingAjax({ orderId: this.orderInfo.orderId }).then(res => {
                if (res.code == 200 && res.data && res.data.length > 0) {
                    // 取第一个包裹的最新一条轨迹
                    const package1 = res.data[0];
                    if (package1.trackingVoList && package1.trackingVoList.length > 0) {
                        this.latestTrace = package1.trackingVoList[0];
                    }
                }
            });
        },
        copyOrderNo() {
            uni.setClipboardData({
                data: String(this.orderInfo.orderId),
                success: () => {
                    uni.showToast({ title: '复制成功', icon: 'none' });
                }
            });
        },
        viewLogistics() {
            uni.navigateTo({
                url: `/pages-car/pages/logistics-detail?orderId=${this.orderInfo.orderId}`
            });
        },
        goToRefundDetail(refundOrderId) {
            uni.navigateTo({
                url: `/pages-car/pages/refund-detail?refundOrderId=${refundOrderId}`
            });
        },
        applyRefund(goods) {
            if (this.orderInfo.status == '2') {
                // 待发货状态，使用极速退款弹窗
                this.$refs.refundDialog.open(this.orderInfo);
                return;
            }
            // 跳转到申请售后页面，并传递 orderId 和对应的 detailOrderId
            uni.navigateTo({
                url: `/pages-car/pages/apply-refund?orderId=${this.orderInfo.orderId}&detailOrderId=${goods.detailOrderId}`
            });
        },
        handleAddressClick() {
            if (this.orderInfo.showModifyAddress == 1) {
                this.handleAction('address');
            }
        },
        handleAction(type) {
            if (type === 'complaint') {
                uni.setStorageSync('tempComplaintOrder', this.orderInfo);
                uni.navigateTo({
                    url: `/pages-car/pages/complaint?orderId=${this.orderInfo.orderId}`
                });
                return;
            }
            if (type === 'cancel') {
                this.$refs.cancelDialog.open(this.orderInfo.orderId);
                return;
            }
            if (type === 'remind') {
                this.$refs.urgeDialog.open(this.orderInfo);
                return;
            }
            if (type === 'overtime') {
                // 超时发货补偿
                uni.showModal({
                    title: '提示',
                    content: '确认申请超时发货补偿？',
                    success: (res) => {
                        if (res.confirm) {
                            this.$u.api.sendTimeoutCompensationAjax(this.orderInfo.orderId).then(res => {
                                if (res.code == 200) {
                                    uni.showToast({
                                        title: '申请成功',
                                        icon: 'success'
                                    });
                                    // 刷新订单详情
                                    this.loadOrderDetail(this.orderInfo.orderId);
                                }
                            });
                        }
                    }
                });
                return;
            }
            if (type === 'priceMatch') {
                // 降价补差
                uni.showModal({
                    title: '提示',
                    content: '确认申请降价补差？',
                    success: (res) => {
                        if (res.confirm) {
                            this.$u.api.priceReductionCompensationAjax(this.orderInfo.orderId).then(res => {
                                if (res.code == 200) {
                                    uni.showToast({
                                        title: '申请成功',
                                        icon: 'success'
                                    });
                                    // 刷新订单详情
                                    this.loadOrderDetail(this.orderInfo.orderId);
                                }
                            });
                        }
                    }
                });
                return;
            }
            if (type === 'address') {
                this.isModifyingAddress = true;
                // 兼容可能的字段差异
                const addressId = this.orderInfo.addressId || this.orderInfo.receiverAddressId || '';
                uni.navigateTo({
                    url: `/pages-mine/pages/address/list?isSelect=1&id=${addressId}`
                });
                return;
            }
            if (type === 'logistics') {
                this.viewLogistics();
                return;
            }
            if (type === 'confirm') {
                uni.showModal({
                    title: '提示',
                    content: '是否确认收货？',
                    success: (res) => {
                        if (res.confirm) {
                            uni.showLoading({ title: '处理中' });
                            this.$u.api.confirmReceiveAjax({ orderId: this.orderInfo.orderId }).then(res => {
                                uni.hideLoading();
                                if (res.code == 200) {
                                    uni.showToast({ title: '收货成功', icon: 'success' });
                                    this.loadOrderDetail(this.orderInfo.orderId);
                                }
                            });
                        }
                    }
                });
                return;
            }
            if (type === 'addToCart') {
                uni.showLoading({ title: '加载中' });
                this.$u.api.orderAddToCartAjax({
                    orderId: this.orderInfo.orderId
                }).then(res => {
                    uni.hideLoading();
                    if (res.code == 200) {
                        uni.showToast({
                            title: '已加入购物车',
                            icon: 'success',
                            duration: 3000
                        });
                        this.$updateCartBadge();
                    }
                });
                return;
            }
            if (type === 'pay') {
                uni.navigateTo({
                    url: `/pages-car/pages/cashier-desk?id=${this.orderInfo.orderId}`
                });
                return;
            }
        }
    }
};
</script>

<style lang="scss" scoped>
.order-detail-page {
    min-height: 100vh;
    background-color: #F5F5F5;
    padding-bottom: 20rpx;

    .status-header {
        background-color: #EBF8EE;
        padding: 40rpx 30rpx 60rpx;
        color: #333;

        .status-text {
            font-size: 36rpx;
            font-weight: bold;
            margin-bottom: 10rpx;
        }

        .status-desc {
            font-size: 26rpx;
            color: #666;
            display: flex;
            align-items: center;

            .copy-icon {
                width: 32rpx;
                height: 32rpx;
                margin-left: 10rpx;
            }
        }

        .status-desc-block {
            .status-tip {
                font-size: 26rpx;
                color: #e02020;
                margin-bottom: 10rpx;
            }

            .status-desc-row {
                font-size: 26rpx;
                color: #666;
                display: flex;
                align-items: center;

                .copy-icon {
                    width: 32rpx;
                    height: 32rpx;
                    margin-left: 10rpx;
                }
            }
        }
    }

    .info-card {
        background-color: #fff;
        margin: 20rpx;
        border-radius: 16rpx;
        padding: 30rpx;
        display: flex;

        &.address-card {
            align-items: center;

            .icon-box {
                margin-right: 20rpx;
            }

            .address-content {
                flex: 1;
                margin-right: 20rpx;

                .user-info {
                    font-size: 30rpx;
                    font-weight: 500;
                    margin-bottom: 10rpx;

                    .mobile {
                        margin-left: 20rpx;
                    }
                }

                .address-detail {
                    font-size: 26rpx;
                    color: #666;
                    line-height: 1.4;
                }
            }
        }

        &.express-card {
            align-items: center;

            .icon-box {
                margin-right: 20rpx;
            }

            .express-content {
                flex: 1;
                margin-right: 20rpx;

                .express-name {
                    color: #38C148;
                    font-size: 28rpx;
                    margin-bottom: 10rpx;
                    font-weight: 500;
                }

                .express-trace {
                    color: #333;
                    font-size: 26rpx;
                    line-height: 1.4;
                    display: -webkit-box;
                    -webkit-box-orient: vertical;
                    -webkit-line-clamp: 2;
                    overflow: hidden;
                }
            }
        }

        &.goods-card {
            display: block;

            .goods-item {
                display: flex;
                margin-bottom: 30rpx;

                .goods-cover {
                    width: 120rpx;
                    height: 120rpx;
                    border-radius: 8rpx;
                    margin-right: 20rpx;
                    background-color: #eee;
                }

                .goods-info {
                    flex: 1;

                    .goods-title {
                        font-size: 28rpx;
                        color: #333;
                        margin-bottom: 10rpx;
                    }

                    .goods-quality {
                        font-size: 24rpx;
                        color: #999;
                    }

                    .price-box {
                        margin-top: 10rpx;
                        display: flex;
                        justify-content: space-between;

                        .price {
                            font-weight: 500;
                        }

                        .num {
                            color: #999;
                        }
                    }
                }

                .goods-action {
                    display: flex;
                    align-items: center;
                }
            }

            .price-detail {
                margin-top: 30rpx;

                .row {
                    display: flex;
                    justify-content: space-between;
                    font-size: 26rpx;
                    color: #666;
                    margin-bottom: 20rpx;

                    .goods-total {
                        color: #38C148;
                    }

                    .discount {
                        color: #38C148;
                    }
                }

                .divider {
                    height: 1rpx;
                    background-color: #eee;
                    margin: 20rpx 0;
                }

                .real-pay-row {
                    display: flex;
                    justify-content: space-between;
                    align-items: center;
                    font-size: 28rpx;
                    color: #333;
                    font-weight: bold;
                    margin-top: 10rpx;

                    .real-price {
                        color: #38C148;
                        font-size: 32rpx;
                    }
                }
            }
        }

        &.time-card {
            display: block;

            .row {
                display: flex;
                justify-content: space-between;
                font-size: 24rpx;
                color: #999;
                margin-bottom: 10rpx;

                &:last-child {
                    margin-bottom: 0;
                }
            }
        }
    }
}
</style>
