<template>
    <div class="orders-lists">
        <el-card class="!border-none" shadow="never">
            <el-form :inline="true" class="mb-[-16px]">
                <el-form-item label="订单类型" class="w-[280px]">
                    <el-select class="w-[280px]" v-model="queryParams.type">
                        <el-option label="全部" value />
                        <el-option label="后台点单" value="0" />
                        <el-option label="扫码点单" value="1" />
                    </el-select>
                </el-form-item>
                <el-form-item label="订单状态" class="w-[280px]">
                    <el-select class="w-[280px]" v-model="queryParams.status">
                        <el-option label="全部" value />
                        <el-option label="待下单" value="0" />
                        <el-option label="待结帐" value="1" />
                        <el-option label="已完成" value="2" />
                        <el-option label="已退款" value="4" />
                    </el-select>
                </el-form-item>
                <el-form-item label="创建时间" class="w-[280px]">
                    <el-date-picker v-model="createTime" @change="setCreateTime" type="datetimerange"
                        range-separator="-" start-placeholder="开始时间" end-placeholder="结束时间" />
                </el-form-item>
                <el-form-item label="结账时间" class="w-[280px]">
                    <el-date-picker v-model="checkoutTime" @change="setCheckoutTime" type="datetimerange"
                        range-separator="-" start-placeholder="开始时间" end-placeholder="结束时间" />
                </el-form-item>
                <el-form-item class="w-[280px]">
                    <el-button type="primary" @click="resetPage">查询</el-button>
                    <el-button @click="resetParams">重置</el-button>
                </el-form-item>
            </el-form>
        </el-card>
        <el-card class="!border-none mt-4" shadow="never">
            <el-table v-loading="pager.loading" :data="pager.lists" row-key="id" :expand-row-keys="expandRowKeys" @expand-change="handleExpandChange">
                <el-table-column type="expand" >
                    <template #default="{ row }">
                        <div class="order-detail-wrapper" v-loading="!orderDetails[row.id]">
                            <template v-if="orderDetails[row.id]">
                                <div class="detail-header">
                                    <span>订单详情</span>
                                    <span class="time">下单时间：{{ timeFormat(orderDetails[row.id].createTime) }}</span>
                                </div>
                                <el-table :data="orderDetails[row.id].dishes" border class="detail-table">
                                    <el-table-column label="菜品图片" width="120" align="center">
                                        <template #default="{ row }">
                                            <el-image :src="row.image" :preview-src-list="[row.image]"
                                                class="dish-image" fit="cover" />
                                        </template>
                                    </el-table-column>
                                    <el-table-column prop="name" label="菜品名称">
                                        <template #default="{ row }">
                                            <div>
                                                {{ row.name }}
                                                <div v-if="row.specsList && row.specsList.length" class="mt-1">
                                                    <el-tag
                                                        v-for="spec in row.specsList"
                                                        :key="spec.id"
                                                        size="small"
                                                        class="mr-1 mb-1"
                                                    >
                                                        {{ spec.name }}: {{ spec.value }}
                                                    </el-tag>
                                                </div>
                                            </div>
                                        </template>
                                    </el-table-column>
                                    <el-table-column prop="amount" label="单价">
                                        <template #default="{ row }">
                                            ￥{{ row.amount }}
                                        </template>
                                    </el-table-column>
                                    <el-table-column prop="number" label="数量" width="120" align="center" />
                                    <el-table-column label="小计" width="120" align="right">
                                        <template #default="{ row }">
                                            ￥{{ row.amount * row.number}}
                                        </template>
                                    </el-table-column>
                                </el-table>
                                <div class="detail-footer">
                                    <div class="total-info">
                                        <span>共 {{ getTotalCount(orderDetails[row.id].dishes) }} 件商品</span>
                                        <span class="total-price">
                                            订单总价：<em>￥{{ orderDetails[row.id].amount}}</em>
                                        </span>
                                    </div>
                                </div>
                            </template>
                        </div>
                    </template>
                </el-table-column>
                <el-table-column type="index" min-width="80" />
                <el-table-column label="订单号" prop="number" show-overflow-tooltip></el-table-column>
                <el-table-column label="支付金额" min-width="160" prop="amount">
                    <template #default="{ row }">
                        <div>
                            <div :style="row.status > 1 && row.status != 6 ? 'text-decoration: line-through;': ''" v-if="row.status > 1 && row.status != 6">订单金额:￥{{row.amount}}</div>
                            <div style="color: #f01414;" v-if="row.status >= 2 && row.status != 6">
                              实付:￥{{row.payAmount || row.amount}}   {{row.status==4 ? '退款:￥' + row.refundAmount : ''}}
                            </div>
                            <div v-if="row.ticketNo" class="refund-info">
                                <div style="font-size: 12px;">抵扣券券号:{{ row.ticketNo }}</div>
                                <div style="font-size: 12px;">抵扣券金额:￥{{ row.ticketAmount }}</div>
                            </div>
                        </div>
                    </template>
                </el-table-column>
                <el-table-column label="桌号" prop="deskName"></el-table-column>
                <el-table-column label="备注" prop="remark"  min-width="150" show-tooltip-when-overflow>
                    <!-- <template #default="{ row }">
                        <div class="remark-text">
                            {{row.remark}}
                        </div>
                    </template> -->
                </el-table-column>
                <el-table-column label="类型" prop="type"
                    :formatter="(row: any) => (row.type == 0 ? '后台点单' : '扫码点单')"></el-table-column>
                <el-table-column label="状态" min-width="160" prop="status" >
                    <template #default="{ row }">
                        <div>
                            {{ row.status == 4 ? '退款成功' : row.status == 2 ? '已完成' : row.status == 0 ? '待下单'
                            : row.status == 1 ? '待支付' : row.status == 5 ? '退款中' : '已取消' }}
                            <div v-if="row.refundStatus=='SUCCESS'" class="refund-info">
                                <div>退款时间:{{ row.refundTime }}</div>
                                <div>退款金额:￥{{ row.refundAmount }}</div>
                            </div>
                        </div>
                    </template>
                </el-table-column>
                <el-table-column label="结账时间" prop="checkoutTime"></el-table-column>
                <el-table-column label="创建时间" prop="createTime"></el-table-column>
                <el-table-column label="操作" width="200" fixed="right">
                    <template #default="{ row }">
                        <el-button type="primary" link @click="showDetail(row)">查看已点菜品</el-button>
                        <el-button v-if="row.status=='2' && !row.refundAmount" type="danger" link @click="refund(row)">退款</el-button>
                    </template>
                </el-table-column>
            </el-table>
            <div class="flex justify-end mt-4">
                <pagination v-model="pager" @change="getLists" />
            </div>
        </el-card>
        <el-dialog
            v-model="refundDialogVisible"
            title="退款"
            width="400px"
            @close="refundDialogVisible = false">
            <div class="refund-dialog-content">
                <el-input
                    v-model="refundAmount"
                    placeholder="请输入退款金额"
                    type="number">
                    <template #prepend><icon :size="25" name="el-icon-money" /></template>
                    <template #append>元</template>
                </el-input>
            </div>
            <template #footer>
                <span class="dialog-footer">
                    <el-button @click="refundDialogVisible = false">取 消</el-button>
                    <el-button type="primary" :loading="refundLoading" @click="confirmRefund">确 定</el-button>
                </span>
            </template>
        </el-dialog>
    </div>
</template>

<script setup lang="ts">
    import { ordersList, getOrderDetail, refundReq } from '@/api/orders'
    import { usePaging } from '@/hooks/usePaging'
    import { timeFormat } from '@/utils/util'
    import feedback from '@/utils/feedback'
    // import Money from '@/utils/money'

    const createTime = ref()
    const checkoutTime = ref()
    const queryParams = reactive({
        type: '',
        status: '',
        checkoutTime: '',
        createTime: ''
    })
    const { pager, getLists, resetPage, resetParams } = usePaging({
        fetchFun: ordersList,
        params: queryParams
    })
    const setCreateTime = (v : any) => {
        queryParams.createTime =
            Math.round(v[0].getTime() / 1000).toString() +
            ',' +
            Math.round(v[1].getTime() / 1000).toString()
    }
    const setCheckoutTime = (v : any) => {
        queryParams.checkoutTime =
            Math.round(v[0].getTime() / 1000).toString() +
            ',' +
            Math.round(v[1].getTime() / 1000).toString()
    }
    // watch(queryParams, (newV, oldV) => {
    //     console.log(JSON.stringify(newV))
    // })

    const expandRowKeys = ref<string[]>([])
    const orderDetails = ref<Record<string, any>>({})
    const handleExpandChange = (row: any, expandedRows: any) => {
        // console.log('当前行展开状态改变：', row, expandedRows);
        if (!orderDetails.value[row.id]) {
            showDetail(row);
        }
    }
    // 添加这些变量到组件顶层
    const refundDialogVisible = ref(false)
    const refundAmount = ref(0)
    var refundOrder: {
        refundTime: string;
        refundAmount: number;
        payAmount: number;
        amount: number;
        status: number; id: any;
    };
    // 添加loading状态变量
    const refundLoading = ref(false)
    // 修改refund函数
    const refund = async (row: any) => {
        refundDialogVisible.value = true
        refundAmount.value = 0
        refundOrder = row;
    }

    const confirmRefund = async () => {
        try {
            if(!refundAmount.value || refundAmount.value<=0){
                return feedback.msgError('退款金额不合法')
            }
            if(refundAmount.value > (refundOrder.payAmount || refundOrder.amount)){
                return feedback.msgError('退款金额不能大于订单实付金额')
            }
            refundLoading.value = true
            const res = await refundReq({ orderId: refundOrder.id, payAmount: refundAmount.value })
            if (res) {
                feedback.msgSuccess('退款成功')
                refundOrder.status = 5;
                // refundOrder.refundAmount = refundAmount.value;
                // refundOrder.refundTime = "待处理";
                setTimeout(()=>{
                    getLists();
                },200)
            } else {
                feedback.msgError('退款失败')
            }
        } catch (error) {
            console.error('退款失败:', error)
        } finally {
            refundLoading.value = false
            refundDialogVisible.value = false
        }
    }

    // 展示订单详情
    const showDetail = async (row : any) => {
        try {
            // 如果已经加载过该订单详情，直接展开
            if (orderDetails.value[row.id]) {
                expandRowKeys.value = [row.id]
                return
            }

            // 调用获取订单详情接口
            const res = await getOrderDetail({id:row.id})
            console.warn("***getOrderDetail***",res)
            if (res) {
                // 定义正确的类型
                let orderDetail: Record<string, any> = {};
                orderDetail.id = res.orderItem.id;
                orderDetail.amount = res.orderItem.amount;//总价
                orderDetail.createTime = res.orderItem.createTime;
                orderDetail.dishes = res.orderDishList;
                // 保存订单详情
                orderDetails.value[row.id] = orderDetail
                // 展开当前行
                expandRowKeys.value = [row.id]
            } else {
                feedback.msgError('获取订单详情失败111')
            }
        } catch (error) {
            console.error('获取订单详情失败:', error)
            feedback.msgError('获取订单详情失败')
        }
    }

    // 计算商品总数
    const getTotalCount = (dishes : any[]) => {
        return dishes.reduce((total, dish) => total + dish.number, 0)
    }
    // 计算订单总价
    // const getTotalPrice = (dishes: any[]) => {
    //     return dishes.reduce((total, dish) => {
    //         return Money.add(total, Money.multiply(dish.price, dish.count))
    //     }, 0)
    // }

    getLists()
</script>

<style lang="scss" scoped>
    .order-detail-wrapper {
        padding: 20px;
        background: #f8f8f8;

        .detail-header {
            margin-bottom: 20px;
            display: flex;
            justify-content: space-between;
            align-items: center;

            span {
                font-size: 14px;
                color: #333;

                &.time {
                    color: #999;
                }
            }
        }

        .detail-table {
            margin-bottom: 20px;

            :deep(.dish-image) {
                width: 60px;
                height: 60px;
                border-radius: 4px;
            }
        }

        .detail-footer {
            display: flex;
            justify-content: flex-end;

            .total-info {
                text-align: right;

                span {
                    margin-left: 20px;
                    font-size: 14px;
                    color: #666;

                    &.total-price {
                        em {
                            font-style: normal;
                            font-size: 16px;
                            color: #f56c6c;
                            font-weight: bold;
                        }
                    }
                }
            }
        }
    }

    .refund-dialog-content {
        padding: 20px 0px;

        :deep(.el-input) {
            width: 100%;
        }
    }

    .dialog-footer {
        text-align: right;

        .el-button + .el-button {
            margin-left: 12px;
        }
    }

    .refund-info {
        font-size: 12px;
        color: #999;
        margin-top: 4px;
    }

    .remark-text {
        display: -webkit-box;
        -webkit-box-orient: vertical;
        -webkit-line-clamp: 2;
        overflow: hidden;
        text-overflow: ellipsis;
        word-break: break-all;
        line-height: 1.5;
        max-height: 3em; // 2行的高度
    }
</style>
