<!-- 我的订单页面 -->

<template>
    <div class="box">
        <div class="box-contents">
            <h2>我的订单</h2>
            <!-- 订单状态筛选 -->
            <div class="filter-section">
                <el-radio-group v-model="filterStatus" @change="handleStatusChange">
                    <el-radio-button label="">全部</el-radio-button>
                    <el-radio-button label="0">待处理</el-radio-button>
                    <el-radio-button label="1">已发货</el-radio-button>
                    <el-radio-button label="2">已支付</el-radio-button>
                    <el-radio-button label="3">已取消</el-radio-button>
                </el-radio-group>
            </div>

            <!-- 表格数据 -->
            <div class="box-content">
                <el-table :data="g_dataList" border style="width: 100%" empty-text="暂无数据"
                    :cell-style="{ whiteSpace: 'nowrap' }">
                    <el-table-column prop="id" label="订单编号" min-width="180" />
                    <el-table-column prop="name" label="产品" min-width="180" />
                    <el-table-column prop="money" label="金额" min-width="120">
                        <template #default="scope">
                            ¥{{ scope.row.money?.toFixed(2) || '0.00' }}
                        </template>
                    </el-table-column>
                    <el-table-column prop="status" label="订单状态" min-width="100">
                        <template #default="scope">
                            <el-tag :type="getStatusType(scope.row.status)">
                                {{ getStatusText(scope.row.status) }}
                            </el-tag>
                        </template>
                    </el-table-column>
                    <el-table-column prop="refundStatus" label="退款状态" min-width="100">
                        <template #default="scope">
                            <el-tag :type="getRefundStatusType(scope.row.refundStatus)">
                                {{ getRefundStatusText(scope.row.refundStatus) }}
                            </el-tag>
                        </template>
                    </el-table-column>
                    <el-table-column prop="dataTime" label="购买时间" min-width="180" />

                    <!-- 操作 -->
                    <el-table-column label="操作" min-width="250" fixed="right">
                        <template #default="scope">
                            <el-button-group>
                                <el-button type="primary" size="small" @click="viewOrderDetailClick(scope.row)">
                                    查看详情
                                </el-button>
                                <el-button v-if="scope.row.status === '0'" type="success" size="small"
                                    @click="payOrderClick(scope.row)">
                                    立即支付
                                </el-button>
                                <el-button v-if="scope.row.status === '0'" type="danger" size="small"
                                    @click="cancelOrderClick(scope.row)">
                                    取消订单
                                </el-button>
                                <el-button v-if="scope.row.status === '1' && scope.row.refundStatus === '0'"
                                    type="warning" size="small" @click="refundClick(scope.row)">
                                    申请退款
                                </el-button>
                                <el-button v-if="scope.row.status === '2'" type="warning" size="small"
                                    @click="invoiceClick(scope.row)">
                                    开发票
                                </el-button>
                            </el-button-group>
                        </template>
                    </el-table-column>
                </el-table>
            </div>

            <div class="box-foot">
                <el-pagination v-model:current-page="g_PagingData.currentPage" v-model:page-size="g_PagingData.pageSize"
                    :page-sizes="[10, 20, 50, 100]" :small="g_PagingData.small" :disabled="g_PagingData.disabled"
                    :background="g_PagingData.background" layout="total, sizes, prev, pager, next, jumper"
                    :total="g_PagingData.total" @size-change="act_handleSizeChange"
                    @current-change="act_handleCurrentChange" />
            </div>
        </div>
    </div>

    <!-- 订单详情弹窗 -->
    <el-dialog v-model="dialogVisible" title="订单详情" width="60%" :close-on-click-modal="false">
        <div v-if="currentOrder" class="order-detail">
            <!-- 订单基本信息 -->
            <div class="detail-section">
                <h3>订单信息</h3>
                <el-descriptions :column="2" border>
                    <el-descriptions-item label="订单编号">{{ currentOrder.id }}</el-descriptions-item>
                    <el-descriptions-item label="下单时间">{{ currentOrder.dataTime }}</el-descriptions-item>
                    <el-descriptions-item label="订单状态">
                        <el-tag :type="getStatusType(currentOrder.status)">
                            {{ getStatusText(currentOrder.status) }}
                        </el-tag>
                    </el-descriptions-item>
                    <el-descriptions-item label="退款状态">
                        <el-tag :type="getRefundStatusType(currentOrder.refundStatus)">
                            {{ getRefundStatusText(currentOrder.refundStatus) }}
                        </el-tag>
                    </el-descriptions-item>
                    <el-descriptions-item label="退款时间">{{ currentOrder.refundDate || '-' }}</el-descriptions-item>
                </el-descriptions>
            </div>

            <!-- 订单明细 -->
            <div class="detail-section">
                <h3>订单明细</h3>
                <el-table :data="currentOrder.orderDetails" border style="width: 100%">
                    <el-table-column prop="templateId" label="模板ID" min-width="100" />
                    <el-table-column prop="quantity" label="数量" min-width="100" />
                    <el-table-column prop="price" label="单价" min-width="120">
                        <template #default="scope">
                            ¥{{ scope.row.price?.toFixed(2) || '0.00' }}
                        </template>
                    </el-table-column>
                    <el-table-column label="小计" min-width="120">
                        <template #default="scope">
                            ¥{{ (scope.row.price * scope.row.quantity)?.toFixed(2) || '0.00' }}
                        </template>
                    </el-table-column>
                    <el-table-column prop="createTime" label="创建时间" min-width="180" />
                </el-table>
            </div>

            <!-- 订单金额 -->
            <div class="detail-section">
                <h3>订单金额</h3>
                <div class="amount-info">
                    <div class="amount-item">
                        <span>商品总额：</span>
                        <span>¥{{ currentOrder.money?.toFixed(2) || '0.00' }}</span>
                    </div>
                    <div class="amount-item">
                        <span>实付金额：</span>
                        <span class="total-amount">¥{{ currentOrder.money?.toFixed(2) || '0.00' }}</span>
                    </div>
                </div>
            </div>
        </div>
    </el-dialog>
</template>

<script setup>
import { ref, reactive, onMounted } from 'vue'
import { useRouter } from 'vue-router'
import { ElMessage, ElMessageBox } from 'element-plus'
import { listUserOrder, cancelOrder, getOrderDetail } from '@/http/api/pages/Order/index'

const router = useRouter()
const filterStatus = ref('')

// 订单列表数据
const g_dataList = ref([])

// 配置分页
const g_PagingData = ref({
    currentPage: 1,
    pageSize: 10,
    total: 0,
    small: false,
    background: true,
    disabled: false,
});

// 弹窗控制
const dialogVisible = ref(false)
const currentOrder = ref(null)

// 获取订单状态文本
const getStatusText = (status) => {
    console.log(status)
    const statusMap = {
        0: '待处理',
        1: '已发货',
        2: '已支付',
        3: '已取消'
    }
    return statusMap[status] || '未知'
}

// 获取订单状态类型
const getStatusType = (status) => {
    const typeMap = {
        0: 'warning',
        1: 'primary',
        2: 'success',
        3: 'danger'
    }
    return typeMap[status] || 'info'
}

// 获取退款状态文本
const getRefundStatusText = (status) => {
    const statusMap = {
        0: '未申请',
        1: '已申请',
        2: '已处理'
    }
    return statusMap[status] || '未知'
}

// 获取退款状态类型
const getRefundStatusType = (status) => {
    const typeMap = {
        0: 'info',
        1: 'warning',
        2: 'success'
    }
    return typeMap[status] || 'info'
}

// 获取订单列表
const getOrderListData = async () => {
    try {
        const response = await listUserOrder()
        if (response.code === 200 && response.data) {
            // 处理订单数据
            g_dataList.value = response.data.map(order => ({
                id: order.id,
                name: order.orderDetailsList?.[0]?.templateId ? `模板${order.orderDetailsList[0].templateId}` : '未知商品',
                money: order.totalAmount,
                dataTime: order.orderDate,
                status: order.orderStatus,
                payStatus: order.orderStatus === 0 ? 0 : 1,
                refundStatus: order.refundStatus,
                orderDetails: order.orderDetailsList
            }))
            if (filterStatus.value !== "") {
                g_dataList.value = g_dataList.value.filter(item => item.status == filterStatus.value);
            }
            g_PagingData.value.total = g_dataList.value.length
        } else {
            ElMessage.error(response.msg || '获取订单列表失败')
        }
    } catch (error) {
        console.error('获取订单列表失败:', error)
        ElMessage.error('获取订单列表失败')
    }
}

// 查看订单详情
const viewOrderDetailClick = async (order) => {
    console.log(order)
    // TODO: 实现获取订单详情API
    try {
        const response = await getOrderDetail(order.id)
        if (response.code === 200 && response.data) {
            currentOrder.value = {
                ...order,
                orderDetails: response.data.orderDetailsList || []
            }
            dialogVisible.value = true
        } else {
            ElMessage.error(response.msg || '获取订单详情失败')
        }
    } catch (error) {
        console.error('获取订单详情失败:', error)
        ElMessage.error('获取订单详情失败')
    }
}

// 支付订单
const payOrderClick = (order) => {
    router.push({
        name: 'PayOrder',
        query: { orderId: order.id }
    })
}

// 取消订单
const cancelOrderClick = async (order) => {
    try {
        await ElMessageBox.confirm('确定要取消该订单吗？', '提示', {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'warning'
        })

        const response = await cancelOrder({ orderId: order.id })
        if (response.code === 200) {
            ElMessage.success('订单已取消')
            getOrderListData()
        } else {
            ElMessage.error(response.message || '取消订单失败')
        }
    } catch (error) {
        if (error !== 'cancel') {
            console.error('取消订单失败:', error)
            ElMessage.error('取消订单失败')
        }
    }
}

// 开发票
const invoiceClick = (order) => {
    // TODO: 实现开发票功能
    console.log('开发票:', order)
}

// 添加退款方法
const refundClick = (order) => {
    // TODO: 实现退款功能
    console.log('申请退款:', order)
}

// 改变每页条数
const act_handleSizeChange = (val) => {
    g_PagingData.value.pageSize = val
    getOrderListData()
}

// 改变页码
const act_handleCurrentChange = (val) => {
    g_PagingData.value.currentPage = val
    getOrderListData()
}

// 处理状态筛选变化
const handleStatusChange = () => {
    g_PagingData.value.currentPage = 1
    getOrderListData()
}

// 挂载完成
onMounted(() => {
    getOrderListData()
})
</script>

<style scoped>
.box {
    flex: 1;
    background-color: #fff;
    border-radius: 8px;
    box-shadow: 0 2px 12px rgba(0, 0, 0, 0.1);
    display: flex;
    padding: 24px;
    width: 100%;
    margin: 0;
}

.box-contents {
    flex: 1;
    display: flex;
    flex-direction: column;
    gap: 20px;
    width: 100%;
}

.box-contents h2 {
    margin: 0;
    font-size: 20px;
    color: #2c3e50;
    padding-bottom: 16px;
    border-bottom: 1px solid #eee;
}

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

.box-content {
    flex: 1;
    width: 100%;
    overflow: auto;
}

.box-foot {
    display: flex;
    justify-content: flex-end;
    padding-top: 20px;
    border-top: 1px solid #ebeef5;
}

:deep(.el-button-group) {
    display: flex;
    gap: 8px;
}

:deep(.el-table) {
    width: 100% !important;
}

:deep(.el-table__body) {
    width: 100% !important;
}

:deep(.el-table__row) {
    width: 100% !important;
}

:deep(.el-table__cell) {
    white-space: nowrap;
}

.order-detail {
    padding: 20px;
}

.detail-section {
    margin-bottom: 30px;
}

.detail-section h3 {
    margin-bottom: 15px;
    font-size: 16px;
    color: #303133;
}

.amount-info {
    padding: 20px;
    background-color: #f5f7fa;
    border-radius: 4px;
}

.amount-item {
    display: flex;
    justify-content: space-between;
    margin-bottom: 10px;
    font-size: 14px;
}

.amount-item:last-child {
    margin-bottom: 0;
    font-size: 16px;
    font-weight: bold;
}

.total-amount {
    color: #f56c6c;
    font-size: 18px;
}

:deep(.el-dialog__body) {
    padding: 20px;
}
</style>