<template>
    <view class="order-list">
        <!-- 订单按月分组显示 -->
        <view class="month-group" v-for="monthGroup in orderData" :key="monthGroup.month">
            <view class="month-header">
                <text class="month-title">{{ monthGroup.pay_time }}</text>
                <text class="month-expense">支出¥{{ monthGroup.amount }}元</text>
            </view>

            <!-- 订单列表 -->
            <view v-if="orderData.length > 0">
                <view class="order-item" v-for="order in monthGroup.orders" :key="order.id"
                    @tap="viewOrderDetail(order)">
                    <view class="order-left">
                        <view class="order-type">
                            <view class="order-type1">
                                <image class="order-icon"
                                    src="https://static.hshuishang.com/park/park_p.png"
                                    mode="aspectFit"></image>
                                <text class="order-type-text">停车</text>
                            </view>
                            <text class="order-status">{{ order.status == 1 ? '待支付' : '已支付' }}</text>
                        </view>

                        <view class="order-park-info">
                            <text class="order-park-name">{{ order.record_info.parking_info.parking_name }}</text>
                            <text class="order-amount">¥{{ order.amount.toFixed(2) }}</text>
                        </view>

                        <view class="order-car-info">
                            <text class="order-car-number">{{ order.record_info.car_number }}</text>
                            <text class="order-car-type">{{ order.record_info.car_billing_type == 1 ? '月租车' :
                                (order.record_info.car_billing_type == 2) ? '临时车' : '贵宾车' }}</text>
                        </view>

                        <text class="order-time">{{ order.pay_time }}</text>
                    </view>
                    <view class="delete-button" @tap.stop="deleteOrder(order)">
                        <u-icon name="trash" size="45rpx"></u-icon>
                    </view>
                </view>
            </view>
        </view>

        <!-- 空状态显示 -->
        <view class="empty-state" v-if="orderData.length === 0">
            <image class="empty-icon" src="https://static.hshuishang.com/park/empty_order.png"
                mode="aspectFit"></image>
            <text class="empty-text">暂无停车订单</text>
        </view>
    </view>
</template>

<script>
import {
    isPhone,
    picUrl,
    request,
    upload,
    NavgateTo
} from '../../../utils';
import { apiArr } from '@/api/park.js'

export default {
    data() {
        return {
            orderData: [],
            page_num: 1,
            page_size: 20,
        }
    },
    methods: {
        // 查看订单详情
        viewOrderDetail(order) {
            const orderStr = JSON.stringify(order);
            // 编码特殊字符（如&、?等）
            const encodedOrder = encodeURIComponent(orderStr);
            NavgateTo(`../orderDetail/index?order=${encodedOrder}`);
        },

        // 删除订单方法
        deleteOrder(order) {
            const that = this;
            uni.showModal({
                title: '确认删除订单',
                content: '你确定删除订单吗？删除之后你将无法再找回该订单',
                success: function (res) {
                    if (res.confirm) {
                        const params = {
                            order_id: order.id
                        }
                        request(apiArr.tempParkingOrderDelete, "POST", params).then((res) => {
                            uni.showToast({
                                title: '删除成功',
                                icon: 'success',
                                duration: 2000
                            });
                            that.getOrderData();
                        })
                    }
                }
            });
        },

        // 按月份对订单进行分组的方法
        groupOrdersByMonth(orderList) {
            const monthMap = new Map();

            orderList.forEach(order => {
                let payTime;
                try {
                    payTime = new Date(order.pay_time);
                } catch (error) {
                    payTime = new Date(order.pay_time.replace(/T/, ' ').replace(/\+.*$/, ''));
                }

                // 获取年月作为分组键
                const year = payTime.getFullYear();
                const month = payTime.getMonth() + 1;
                const monthKey = `${year}-${month.toString().padStart(2, '0')}`;

                // 如果该月份还没有分组，创建一个新分组
                if (!monthMap.has(monthKey)) {
                    monthMap.set(monthKey, {
                        month: monthKey,
                        pay_time: `${year}年${month}月`,
                        amount: 0,
                        orders: []
                    });
                }

                // 将当前订单添加到对应月份的分组中
                const monthGroup = monthMap.get(monthKey);
                monthGroup.orders.push(order);
                monthGroup.amount += parseFloat(order.amount || 0);
            });

            // 将Map转换为数组，并按月份降序排序
            const groupedArray = Array.from(monthMap.values());
            groupedArray.sort((a, b) => b.month.localeCompare(a.month));

            // 格式化总金额，保留两位小数
            groupedArray.forEach(group => {
                group.amount = group.amount.toFixed(2);
            });

            return groupedArray;
        },

        // 获取订单数据
        getOrderData() {
            const params = {
                page_num: this.page_num,
                page_size: this.page_size,
                user_id: uni.getStorageSync('userId')
            }
            request(apiArr.tempParkingOrderList, "POST", params).then((res) => {
                this.orderData = this.groupOrdersByMonth(res.order_list);
            })
        }
    },
    onLoad() {
        // 页面加载时获取订单数据
        this.getOrderData();
    },

    // 页面滑动到底部时触发
    onReachBottom() {
        this.page_size += 10;
        this.getOrderData();
    }
}
</script>

<style>
@import url('./index.css');
</style>