<template>
    <view class="container">
        <!-- 统计banner：圆角浮动卡，左右30rpx边距 -->
        <view class="stats-banner">
            <view class="banner-item">
                <text class="banner-num">{{ stats.total }}</text>
                <text class="banner-label">累计接单</text>
            </view>
            <view class="banner-item">
                <text class="banner-num">{{ stats.reject }}</text>
                <text class="banner-label">累计拒单</text>
            </view>
            <view class="banner-item">
                <text class="banner-num">{{ stats.reward }}</text>
                <text class="banner-label">奖励单量</text>
            </view>
            <view class="banner-item">
                <text class="banner-num">{{ stats.punish }}</text>
                <text class="banner-label">惩罚单量</text>
            </view>
        </view>

        <!-- 标签页（全宽，无圆角，紧贴屏幕宽度） -->
        <view class="tab-bar">
            <view
                class="tab-item"
                v-for="(tab, idx) in tabs"
                :key="idx"
                :class="{ active: activeTab === idx }"
                @click="switchTab(idx)"
            >
                <text>{{ tab }}</text>
                <view class="tab-line" v-if="activeTab === idx"></view>
            </view>
        </view>

        <!-- 订单列表：每张卡片用margin左右各30rpx，与banner宽度对齐 -->
        <scroll-view scroll-y class="order-scroll" @scrolltolower="onReachBottom">
            <view style="height: 16rpx;"></view>

            <view
                class="order-card"
                v-for="(order, idx) in filteredOrders"
                :key="idx"
            >
                <!-- 卡片头部：类型图标 + 类型名 | 状态 + 时间 -->
                <view class="card-header">
                    <view class="type-badge">
                        <image class="type-icon" :src="order.typeIcon"></image>
                        <text class="type-text">{{ order.typeName }}</text>
                    </view>
                    <text class="status-text" :style="{ color: order.statusColor }">
                        {{ order.statusLabel }}
                    </text>
                </view>

                <!-- 服务时间 -->
                <text class="service-time">服务时间：{{ order.serviceTime }}</text>

                <!-- 宠物信息卡（灰底）+ 右侧价格 -->
                <view class="pet-card">
                    <image class="pet-avatar" :src="order.petAvatar" mode="aspectFill"></image>
                    <view class="pet-info">
                        <text class="pet-name">{{ order.petName }}</text>
                        <text class="pet-breed">品种: {{ order.petBreed }}</text>
                    </view>
                    <text class="pet-price">¥{{ order.fulfillmentCommission }}</text>
                </view>

                <!-- 路线信息 -->
                <view class="route-info">
                    <!-- 接送：取 → 送 -->
                    <template v-if="order.orderType === 1">
                        <view class="route-item">
                            <view class="icon-circle pickup">取</view>
                            <view class="route-connector"></view>
                            <view class="address-box">
                                <text class="addr-title">{{ order.startName }}</text>
                                <text class="addr-desc">{{ order.startAddr }}</text>
                            </view>
                        </view>
                        <view class="route-item">
                            <view class="icon-circle deliver">送</view>
                            <view class="address-box">
                                <text class="addr-title">{{ order.endName }}</text>
                                <text class="addr-desc">{{ order.endAddr }}</text>
                            </view>
                        </view>
                    </template>
                    <!-- 喂遛/洗护：服 -->
                    <template v-else>
                        <view class="route-item">
                            <view class="icon-circle service">服</view>
                            <view class="address-box">
                                <text class="addr-title">{{ order.endName }}</text>
                                <text class="addr-desc">{{ order.endAddr }}</text>
                            </view>
                        </view>
                        <view class="service-note-row" v-if="order.serviceNote">
                            <text class="service-note-text">服务内容：{{ order.serviceNote }}</text>
                        </view>
                    </template>
                </view>
            </view>

            <!-- 空状态 -->
            <view class="empty-state" v-if="filteredOrders.length === 0 && !loading">
                <text class="empty-text">暂无相关订单</text>
            </view>
            
            <view class="loading-more" v-if="loading">
                <text>加载中...</text>
            </view>

            <view style="height: 40rpx;"></view>
        </scroll-view>
    </view>
</template>

<script>
import { getOrderStats } from '@/api/order/subOrderLog';
import { getStatisticOrders } from '@/api/order/subOrder';
import { listAllService } from '@/api/service/list';


export default {
    data() {
        return {
            tabs: ['全部', '已完成', '已拒绝'],
            activeTab: 0,
            stats: {
                total: 0,
                reject: 0,
                reward: 0,
                punish: 0
            },
            orders: [],
            serviceList: [],
            pageNum: 1,
            pageSize: 10,
            total: 0,
            loading: false
        };
    },
    computed: {
        filteredOrders() {
            return this.orders;
        }
    },
    async onLoad() {
        await this.loadServiceList();
        this.fetchStats();
        this.fetchOrders(true);
    },
    methods: {
        async loadServiceList() {
            try {
                const res = await listAllService();
                this.serviceList = res.data || [];
            } catch (err) {
                console.error('获取服务类型失败:', err);
                uni.showToast({ title: err.message || err.msg || '请求失败', icon: 'none' });
            }
        },
        async fetchStats() {
            try {
                const res = await getOrderStats();
                if (res.code === 200 && res.data) {
                    this.stats = {
                        ...this.stats,
                        ...res.data
                    };
                }
            } catch (err) {
                console.error('获取统计值失败:', err);
            }
        },
        async fetchOrders(reset = false) {
            if (reset) {
                this.pageNum = 1;
                this.orders = [];
            }
            if (this.loading) return;
            if (!reset && this.orders.length >= this.total && this.total !== 0) return;

            this.loading = true;
            try {
                const statusMap = { 0: undefined, 1: 4, 2: 5 };
                const params = {
                    status: statusMap[this.activeTab],
                    pageNum: this.pageNum,
                    pageSize: this.pageSize
                };
                const res = await getStatisticOrders(params);
                if (res.code === 200) {
                    this.total = res.total || 0;
                    const rows = res.rows || [];
                    const mapped = rows.map(item => this.transformOrder(item));
                    this.orders = this.orders.concat(mapped);
                    this.pageNum++;
                }
            } catch (err) {
                console.error('获取订单列表失败:', err);
                uni.showToast({ title: err.message || err.msg || '请求失败', icon: 'none' });
            } finally {
                this.loading = false;
            }
        },
        transformOrder(order) {
            const service = this.serviceList.find(s => s.id === order.service);
            const mode = service?.mode || 0;
            const isRoundTrip = mode === 1;
            
            // 状态枚举映射
            const statusMap = {
                0: { label: '待派单', color: '#f56c6c' },
                1: { label: '待接单', color: '#e6a23c' },
                2: { label: '待服务', color: '#49a3ff' },
                3: { label: '服务中', color: '#49a3ff' },
                4: { label: '已完成', color: '#67c23a' },
                5: { label: '已取消', color: '#909399' }
            };
            const statusInfo = statusMap[order.status] || { label: '未知', color: '#999' };

            return {
                id: order.id,
                orderType: isRoundTrip ? 1 : 2,
                typeName: service?.name || '未知',
                typeIcon: service?.iconUrl || '',
                statusLabel: statusInfo.label,
                statusColor: statusInfo.color,
                finishTime: order.serviceTime || '',
                serviceTime: order.serviceTime || '',
                petName: order.petName || '未知',
                petBreed: order.breed || '未知',
                petAvatar: order.petAvatarUrl || '/static/dog.png',
                fulfillmentCommission: (order.fulfillmentCommission / 100).toFixed(2),
                startName: order.fromAddress || '',
                startAddr: order.fromAddress || '',
                endName: (order.customerName || '') + ' ' + (order.customerPhone || ''),
                endAddr: order.toAddress || '',
                serviceNote: order.remark || ''
            };
        },
        switchTab(idx) {
            this.activeTab = idx;
            this.fetchOrders(true);
        },
        onReachBottom() {
            this.fetchOrders();
        },
        navBack() {
            uni.navigateBack();
        }
    }
};
</script>

<style>
page { background-color: #F7F8FA; }
.container { min-height: 100vh; background-color: #F7F8FA; padding: 20rpx 0 0; display: flex; flex-direction: column; }

/* ===== 统计banner：圆角浮动卡，左右30rpx边距 ===== */
.stats-banner {
    background: linear-gradient(135deg, #FF9800 0%, #FF5722 100%);
    padding: 28rpx 16rpx;
    display: flex;
    justify-content: space-around;
    margin: 0 30rpx 20rpx;
    border-radius: 20rpx;
    box-shadow: 0 6rpx 20rpx rgba(255, 87, 34, 0.25);
    flex-shrink: 0;
}

.banner-item { display: flex; flex-direction: column; align-items: center; }
.banner-num { font-size: 34rpx; font-weight: bold; color: #fff; margin-bottom: 4rpx; }
.banner-unit { font-size: 22rpx; font-weight: normal; }
.banner-label { font-size: 20rpx; color: rgba(255,255,255,0.85); }

/* ===== 标签页：全宽平铺，无圆角，无side margin ===== */
.tab-bar {
    background-color: #fff;
    display: flex;
    padding: 0 30rpx;
    border-bottom: 1rpx solid #f0f0f0;
    margin-bottom: 0;
    flex-shrink: 0;
}

.tab-item {
    padding: 20rpx 24rpx;
    font-size: 28rpx;
    color: #999;
    position: relative;
    display: flex;
    flex-direction: column;
    align-items: center;
}

.tab-item.active { color: #FF9800; font-weight: bold; }

.tab-line {
    position: absolute;
    bottom: 0;
    left: 50%;
    transform: translateX(-50%);
    width: 36rpx;
    height: 4rpx;
    background-color: #FF9800;
    border-radius: 2rpx;
}

/* ===== 订单列表：scroll-view 全宽，每张card用margin左右30rpx ===== */
.order-scroll { flex: 1; height: 0; width: 100%; }

.order-card {
    background-color: #fff;
    border-radius: 16rpx;
    padding: 24rpx;
    margin: 0 30rpx 16rpx;
    box-sizing: border-box;
}

/* 卡片头部 */
.card-header {
    display: flex;
    align-items: center;
    justify-content: space-between;
    margin-bottom: 10rpx;
}

.type-badge { display: flex; align-items: center; }

.type-icon {
    width: 44rpx;
    height: 44rpx;
    margin-right: 12rpx;
}

.type-text { font-size: 30rpx; font-weight: bold; color: #333; }

.status-text { font-size: 24rpx; }
.status-text.green { color: #4CAF50; }
.status-text.red { color: #F44336; }

/* 服务时间 */
.service-time {
    font-size: 24rpx;
    color: #999;
    margin-bottom: 16rpx;
    display: block;
}

/* 宠物信息卡（灰底背景，右侧显示价格） */
.pet-card {
    background-color: #F7F8FA;
    border-radius: 10rpx;
    padding: 16rpx 20rpx;
    display: flex;
    align-items: center;
    margin-bottom: 16rpx;
}

.pet-avatar { width: 70rpx; height: 70rpx; border-radius: 50%; margin-right: 16rpx; flex-shrink: 0; }

.pet-info { flex: 1; display: flex; flex-direction: column; }
.pet-name { font-size: 28rpx; font-weight: bold; color: #333; margin-bottom: 4rpx; }
.pet-breed { font-size: 24rpx; color: #999; }

/* 价格在宠物卡右侧 */
.pet-price { font-size: 34rpx; font-weight: bold; color: #FF5722; flex-shrink: 0; }

/* 路线信息 */
.route-info { display: flex; flex-direction: column; }

.route-item {
    display: flex;
    align-items: flex-start;
    position: relative;
    padding-bottom: 8rpx;
}

.icon-circle {
    width: 44rpx;
    height: 44rpx;
    border-radius: 50%;
    display: flex;
    align-items: center;
    justify-content: center;
    font-size: 22rpx;
    font-weight: bold;
    color: #fff;
    flex-shrink: 0;
    margin-right: 16rpx;
    margin-top: 2rpx;
}

.icon-circle.pickup { background: linear-gradient(135deg, #FF9800, #FF6D00); }
.icon-circle.deliver { background: linear-gradient(135deg, #4CAF50, #2E7D32); }
.icon-circle.service { background: linear-gradient(135deg, #4CAF50, #1B5E20); }

/* 取→送之间的虚线连接 */
.route-connector {
    position: absolute;
    left: 21rpx;
    top: 46rpx;
    width: 2rpx;
    height: 30rpx;
    background-color: #e0e0e0;
}

.address-box { flex: 1; padding-bottom: 14rpx; }
.addr-title { font-size: 26rpx; color: #333; display: block; margin-bottom: 4rpx; }
.addr-desc { font-size: 24rpx; color: #999; display: block; }

/* 服务内容说明（喂遛/洗护） */
.service-note-row { padding: 4rpx 0 0 60rpx; }
.service-note-text { font-size: 24rpx; color: #999; }

/* 空状态 */
.empty-state { text-align: center; padding: 80rpx 0; }
.empty-text { font-size: 28rpx; color: #ccc; }

.loading-more { text-align: center; padding: 20rpx; font-size: 24rpx; color: #999; }
</style>
