<template>
    <div class="app-container">
        <div class="background-color-fff padding-20 border-radius-8px">
            <!-- 订单基本信息 -->
            <div class="order-section">
                <h3 class="section-title">订单信息</h3>
                <el-descriptions :column="4" border>
                    <el-descriptions-item label="订单编号">{{ form.orderNo }}</el-descriptions-item>
                    <el-descriptions-item label="订单类型">
                        <el-tag :type="getOrderTypeTag(form.orderType)">
                            {{ getOrderTypeText(form.orderType) }}
                        </el-tag>
                    </el-descriptions-item>
                    <el-descriptions-item label="订单状态">
                        <el-tag :type="getOrderStatusTag(form.orderStatus)">
                            {{ getOrderStatusText(form.orderStatus) }}
                        </el-tag>
                    </el-descriptions-item>
                    <el-descriptions-item label="支付状态">
                        <el-tag :type="getPayStatusTag(form.payStatus)">
                            {{ getPayStatusText(form.payStatus) }}
                        </el-tag>
                    </el-descriptions-item>
                    <el-descriptions-item label="订单总额">
                        ¥{{ formatAmount(form.totalAmount) }}
                    </el-descriptions-item>
                    <el-descriptions-item label="支付金额">
                        ¥{{ formatAmount(form.payAmount) }}
                    </el-descriptions-item>
                    <el-descriptions-item label="佣金金额">
                        ¥{{ formatAmount(form.commissionAmount) }}
                    </el-descriptions-item>
                    <el-descriptions-item label="佣金状态">
                        <el-tag :type="form.commissionStatus === 1 ? 'success' : 'info'">
                            {{ getCommissionStatusText(form.commissionStatus) }}
                        </el-tag>
                    </el-descriptions-item>
                    <el-descriptions-item label="下单时间">
                        {{ parseTime(form.createTime, '{y}-{m}-{d} {h}:{i}:{s}') }}
                    </el-descriptions-item>
                    <el-descriptions-item label="支付时间">
                        {{ parseTime(form.payTime, '{y}-{m}-{d} {h}:{i}:{s}') }}
                    </el-descriptions-item>
                    <el-descriptions-item label="取消时间">
                        {{ parseTime(form.cancelTime, '{y}-{m}-{d} {h}:{i}:{s}') || '-' }}
                    </el-descriptions-item>
                    <el-descriptions-item label="完成时间">
                        {{ parseTime(form.finishTime, '{y}-{m}-{d} {h}:{i}:{s}') || '-' }}
                    </el-descriptions-item>
                </el-descriptions>
            </div>

            <!-- 用户信息 -->
            <div class="order-section margin-top-20">
                <h3 class="section-title">用户信息</h3>
                <el-descriptions :column="3" border>
                    <el-descriptions-item label="用户ID">
                        {{ form.userId || '-' }}
                    </el-descriptions-item>
                    <el-descriptions-item label="用户姓名">
                        {{ form.userName || '-' }}
                    </el-descriptions-item>
                    <el-descriptions-item label="手机号码">
                        {{ form.userPhone || '-' }}
                    </el-descriptions-item>
                    <el-descriptions-item label="拼单ID">
                        {{ form.groupId || '-' }}
                    </el-descriptions-item>
                    <el-descriptions-item label="是否发起人">
                        <el-tag :type="form.isInitiator === 1 ? 'success' : 'info'">
                            {{ form.isInitiator === 1 ? '是' : '否' }}
                        </el-tag>
                    </el-descriptions-item>
                </el-descriptions>
            </div>

            <!-- 商品信息 -->
            <div class="order-section margin-top-20">
                <h3 class="section-title">商品信息</h3>
                <el-descriptions :column="2" border>
                    <el-descriptions-item label="商品ID">
                        {{ form.productId || '-' }}
                    </el-descriptions-item>
                    <el-descriptions-item label="SKU ID">
                        {{ form.skuId || '-' }}
                    </el-descriptions-item>
                    <el-descriptions-item label="购买数量">
                        {{ form.quantity || 0 }}
                    </el-descriptions-item>
                    <el-descriptions-item label="单价">
                        ¥{{ formatAmount(form.unitPrice) }}
                    </el-descriptions-item>
                </el-descriptions>

                <!-- 商品详情卡片 -->
                <div v-if="productInfo" class="product-card margin-top-20">
                    <div class="product-header">
                        <h4>商品详情</h4>
                    </div>
                    <div class="product-content">
                        <div class="product-image">
                            <img
                                v-if="productInfo.mainImage"
                                :src="productInfo.mainImage"
                                alt="商品图片"
                            />
                            <el-empty v-else description="暂无图片" :image-size="60" />
                        </div>
                        <div class="product-details">
                            <h4>{{ productInfo.productName }}</h4>
                            <p class="product-spec" v-if="skuInfo.specText">
                                规格：{{ skuInfo.specText }}
                            </p>
                            <p class="product-price">价格：¥{{ formatAmount(skuInfo.price) }}</p>
                            <p class="product-stock">库存：{{ skuInfo.stockQuantity || 0 }}</p>
                        </div>
                    </div>
                </div>
            </div>

            <!-- 拼单信息（如果是拼单订单） -->
            <div v-if="form.orderType === 2" class="order-section margin-top-20">
                <h3 class="section-title">拼单信息</h3>
                <el-table
                    v-loading="loading"
                    :data="groupOrderList"
                    @selection-change="handleSelectionChange"
                >
                    <el-table-column label="拼单ID" align="center" prop="id" />
                    <el-table-column label="拼单编号" align="center" prop="groupCode" />
                    <el-table-column label="拼单活动ID" align="center" prop="activityId" />
                    <el-table-column label="SKU ID" align="center" prop="skuId" />
                    <el-table-column label="拼单价" align="center" prop="groupPrice" />
                    <el-table-column label="拼单总金额" align="center" prop="totalAmount" />
                    <el-table-column label="成团人数" align="center" prop="totalPeople" />
                    <el-table-column label="当前人数" align="center" prop="currentPeople" />
                    <el-table-column label="状态" align="center" prop="status">
                        <template #default="{ row }">
                            <el-tag>
                                {{
                                    row.status == 0
                                        ? '拼单中'
                                        : row.status == 1
                                        ? '拼团成功'
                                        : row.status == 2
                                        ? '拼团失败'
                                        : '已取消'
                                }}
                            </el-tag>
                        </template>
                    </el-table-column>
                    <el-table-column label="发起人用户ID" align="center" prop="initiatorId" />
                    <el-table-column label="佣金比例(%)" align="center" prop="commissionRate" />
                    <el-table-column label="佣金金额" align="center" prop="commissionAmount" />
                    <el-table-column
                        label="拼单开始时间"
                        align="center"
                        prop="startTime"
                        width="180"
                    >
                        <template #default="scope">
                            <span>
                                {{ parseTime(scope.row.startTime, '{y}-{m}-{d} {h}:{i}:{s}') }}
                            </span>
                        </template>
                    </el-table-column>
                    <el-table-column label="拼单截止时间" align="center" prop="endTime" width="180">
                        <template #default="scope">
                            <span>
                                {{ parseTime(scope.row.endTime, '{y}-{m}-{d} {h}:{i}:{s}') }}
                            </span>
                        </template>
                    </el-table-column>
                    <el-table-column
                        label="拼单完成时间"
                        align="center"
                        prop="finishTime"
                        width="180"
                    >
                        <template #default="scope">
                            <span>{{ parseTime(scope.row.finishTime, '{y}-{m}-{d}') }}</span>
                        </template>
                    </el-table-column>
                    <!-- <el-table-column
                        label="操作"
                        align="center"
                        class-name="small-padding fixed-width"
                        fixed="right"
                    >
                        <template #default="scope">
                            <el-button
                                link
                                type="primary"
                                icon="Edit"
                                @click="handleUpdate(scope.row)"
                                v-hasPermi="['service:groupOrder:edit']"
                            >
                                修改
                            </el-button>
                            <el-button
                                link
                                type="primary"
                                icon="Delete"
                                @click="handleDelete(scope.row)"
                                v-hasPermi="['service:groupOrder:remove']"
                            >
                                删除
                            </el-button>
                        </template>
                    </el-table-column> -->
                </el-table>
            </div>
            <!-- 操作按钮区域 -->
            <div class="action-buttons margin-top-20">
                <el-button v-if="form.payStatus === 5" type="primary" @click="handleUpdate">
                    发货
                </el-button>
                <el-button v-if="form.payStatus === 4" type="primary" @click="handleRefund">
                    退款
                </el-button>
                <el-button type="info" @click="handleBack">返回</el-button>
            </div>
        </div>
    </div>
</template>

<script setup name="OrderDetail">
import { getCurrentInstance, ref, reactive, onMounted } from 'vue';
import { useRoute, useRouter } from 'vue-router';
import { getOrder, updateOrder } from '@/api/service/order';
import { getProduct } from '@/api/service/product';
import { getProductSku } from '@/api/service/productSku';
import {
    listGroupOrder,
    getGroupOrder,
    delGroupOrder,
    addGroupOrder,
    updateGroupOrder,
    refundGroupOrder,
} from '@/api/service/groupOrder';

const { proxy } = getCurrentInstance();
const route = useRoute();
const router = useRouter();

// 表单数据
const form = ref({});
const groupOrderList = ref([]);
// 商品信息
const productInfo = ref(null);
// SKU信息
const skuInfo = ref({});

// 加载状态
const loading = ref(false);

// 获取订单详情
const getOrderDetail = async () => {
    try {
        loading.value = true;
        const orderId = route.query.orderId || route.params.orderId;
        if (!orderId) {
            proxy.$modal.msgError('订单ID不存在');
            return;
        }

        const response = await getOrder(orderId);
        form.value = response.data;

        // 获取商品信息
        if (form.value.productId) {
            await loadProductInfo(form.value.productId);
        }

        // 获取SKU信息
        if (form.value.skuId) {
            await loadSkuInfo(form.value.skuId);
        }

        // 获取拼单信息
        getList(form.value.groupId);
    } catch (error) {
        console.error('获取订单详情失败:', error);
        proxy.$modal.msgError('获取订单详情失败');
    } finally {
        loading.value = false;
    }
};

/** 点击退款 */
function handleRefund() {
    refundGroupOrder(form.value.groupId).then(res => {
        proxy.$modal.msgSuccess('操作成功');
        getOrderDetail();
    });
}

/** 点击发货 */
function handleUpdate() {
    form.value.orderStatus = 6;
    updateOrder(form.value).then(response => {
        proxy.$modal.msgSuccess('操作成功');
        getOrderDetail();
    });
}

/** 查询拼单主列表 */
function getList(groupId) {
    listGroupOrder({ pageNum: 1, pageSize: 10, id: groupId }).then(response => {
        groupOrderList.value = response.rows;
    });
}

// 加载商品信息
const loadProductInfo = async productId => {
    try {
        const response = await getProduct(productId);
        productInfo.value = response.data;
    } catch (error) {
        console.error('获取商品信息失败:', error);
    }
};

// 加载SKU信息
const loadSkuInfo = async skuId => {
    try {
        const response = await getProductSku(skuId);
        skuInfo.value = response.data;
    } catch (error) {
        console.error('获取SKU信息失败:', error);
    }
};

// 获取订单类型文本
const getOrderTypeText = type => {
    const typeMap = {
        1: '普通订单',
        2: '拼单订单',
    };
    return typeMap[type] || '未知';
};

// 获取订单类型标签
const getOrderTypeTag = type => {
    const typeMap = {
        1: '',
        2: 'warning',
    };
    return typeMap[type] || '';
};

// 获取订单状态文本
const getOrderStatusText = status => {
    const statusMap = {
        0: '待支付',
        1: '已支付',
        2: '已取消',
        3: '已完成',
        4: '等待拼团',
        5: '待发货',
        6: '已发货',
        7: '待收货',
        8: '已收货',
        9: '已退款',
    };
    return statusMap[status] || '未知';
};

// 获取订单状态标签
const getOrderStatusTag = status => {
    const statusMap = {
        0: 'warning',
        1: 'success',
        2: 'danger',
        3: 'info',
    };
    return statusMap[status] || '';
};

// 获取支付状态文本
const getPayStatusText = status => {
    const statusMap = {
        0: '未支付',
        1: '已支付',
        2: '已退款',
    };
    return statusMap[status] || '未知';
};

// 获取支付状态标签
const getPayStatusTag = status => {
    const statusMap = {
        0: 'warning',
        1: 'success',
        2: 'danger',
    };
    return statusMap[status] || '';
};

// 获取佣金状态文本
const getCommissionStatusText = status => {
    const statusMap = {
        0: '未发放',
        1: '已发放',
    };
    return statusMap[status] || '未知';
};

// 格式化金额
const formatAmount = amount => {
    if (!amount) return '0.00';
    return parseFloat(amount).toFixed(2);
};

// 返回
const handleBack = () => {
    // router.back();
    proxy.$tab.closePage();
};

// 初始化加载
onMounted(() => {
    getOrderDetail();
});
</script>

<style scoped>
.order-section {
    background: #fff;
    border-radius: 8px;
    padding: 20px;
    border: 1px solid #ebeef5;
}

.section-title {
    font-size: 16px;
    font-weight: 600;
    margin-bottom: 20px;
    color: #303133;
    padding-bottom: 10px;
    border-bottom: 1px solid #ebeef5;
}

.margin-top-20 {
    margin-top: 20px;
}

.margin-bottom-20 {
    margin-bottom: 20px;
}

.operation-buttons {
    display: flex;
    justify-content: flex-end;
    gap: 10px;
    padding: 20px;
    background: #fff;
    border-radius: 8px;
    border: 1px solid #ebeef5;
}

.action-buttons {
    display: flex;
    gap: 10px;
    justify-content: center;
    padding-top: 20px;
    border-top: 1px solid #ebeef5;
}

/* 商品卡片样式 */
.product-card {
    background: #f8f9fa;
    border-radius: 8px;
    padding: 20px;
    border: 1px solid #ebeef5;
}

.product-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-bottom: 20px;
    padding-bottom: 10px;
    border-bottom: 1px solid #ebeef5;
}

.product-header h4 {
    margin: 0;
    font-size: 16px;
    font-weight: 600;
    color: #303133;
}

.product-content {
    display: flex;
    gap: 20px;
    align-items: flex-start;
}

.product-image {
    width: 120px;
    height: 120px;
    flex-shrink: 0;
    border-radius: 6px;
    overflow: hidden;
    background: #f5f7fa;
    display: flex;
    align-items: center;
    justify-content: center;
    border: 1px solid #ebeef5;
}

.product-image img {
    width: 100%;
    height: 100%;
    object-fit: cover;
}

.product-details {
    flex: 1;
}

.product-details h4 {
    margin: 0 0 10px 0;
    font-size: 16px;
    font-weight: 600;
    color: #303133;
}

.product-spec {
    margin: 8px 0;
    color: #606266;
    font-size: 14px;
}

.product-price {
    margin: 8px 0;
    color: #f56c6c;
    font-size: 16px;
    font-weight: 600;
}

.product-stock {
    margin: 8px 0 0 0;
    color: #909399;
    font-size: 14px;
}

/* 时间线样式 */
.el-timeline {
    padding-left: 20px;
}

.el-timeline-item {
    padding-bottom: 20px;
}

.el-timeline-item:last-child {
    padding-bottom: 0;
}

/* 响应式调整 */
@media (max-width: 768px) {
    .product-content {
        flex-direction: column;
    }

    .product-image {
        width: 100%;
        height: auto;
        max-height: 200px;
    }
}
</style>
