<template>
    <view class="container">
        <!-- 顶部橙色统计卡 -->
        <view class="top-banner">
            <!-- 月份切换：箭头在背景框内紧跟文字 -->
            <view class="month-btn" @click="openMonthPicker">
                <text class="month-text">{{ selectedYear }}年{{ selectedMonth }}月 ▾</text>
            </view>
            <view class="stats-grid">
                <view class="stats-cell">
                    <text class="stats-label">奖励订单</text>
                    <text class="stats-num">{{ stats.rewardCount }}<text class="stats-unit">单</text></text>
                    <view class="stats-divider"></view>
                    <text class="stats-sub">月度统计</text>
                </view>
                <view class="stats-cell">
                    <text class="stats-label">惩罚订单</text>
                    <text class="stats-num">{{ stats.punishCount }}<text class="stats-unit">单</text></text>
                    <view class="stats-divider"></view>
                    <text class="stats-sub">月度统计</text>
                </view>
                <view class="stats-cell">
                    <text class="stats-label">奖励金额</text>
                    <text class="stats-num reward-num">{{ (stats.rewardBalance / 100).toFixed(2) }}</text>
                    <view class="stats-divider"></view>
                    <text class="stats-sub">月度统计</text>
                </view>
                <view class="stats-cell">
                    <text class="stats-label">惩罚金额</text>
                    <text class="stats-num penalty-num">{{ (stats.punishBalance / 100).toFixed(2) }}</text>
                    <view class="stats-divider"></view>
                    <text class="stats-sub">月度统计</text>
                </view>
            </view>
        </view>

        <!-- 标签 + 查看全部 -->
        <view class="list-header">
            <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>
            <view class="view-all-btn" @click="goToAll">
                <text class="view-all-text">查看全部 ›</text>
            </view>
        </view>

        <!-- 列表 -->
        <view class="record-list">
            <view class="record-item" v-for="(item, idx) in filteredList" :key="idx">
                <!-- 左侧图标 -->
                <view class="ri-icon" :class="item.amount > 0 ? 'ri-reward' : 'ri-penalty'">
                    <text class="ri-icon-text">¥</text>
                </view>
                <!-- 内容 -->
                <view class="ri-content">
                    <view class="ri-title-row">
                        <text class="ri-date">{{ item.date }}</text>
                        <text class="ri-title">{{ item.title }}</text>
                    </view>
                    <text class="ri-desc">{{ item.desc }}</text>
                </view>
                <!-- 右侧金额 + 状态 -->
                <view class="ri-right">
                    <text class="ri-amount" :class="item.amount > 0 ? 'positive' : 'negative'">
                        {{ item.amount > 0 ? '+' : '' }}{{ item.amount.toFixed(2) }}
                    </text>
                    <text class="ri-status" :class="item.statusClass">{{ item.status }}</text>
                </view>
            </view>

            <!-- 底部提示 -->
            <text class="more-hint">更多记录请点击上方的查看全部</text>
        </view>

        <!-- 月份选择器 -->
        <view class="picker-mask" v-if="showMonthPicker" @click="closeMonthPicker">
            <view class="picker-sheet" @click.stop>
                <!-- 顶部操作 -->
                <view class="picker-header">
                    <text class="picker-cancel" @click="closeMonthPicker">取消</text>
                    <text class="picker-title">选择时间</text>
                    <text class="picker-confirm" @click="confirmMonthPicker">确定</text>
                </view>
                <!-- 年月两列 -->
                <view class="picker-body">
                    <!-- 年 -->
                    <scroll-view scroll-y class="picker-column" :scroll-top="yearScrollTop" @scroll="onYearScroll">
                        <view style="height: 80rpx;"></view>
                        <view
                            class="picker-col-item"
                            v-for="year in years"
                            :key="year"
                            :class="{ 'picker-selected': pickerYear === year }"
                            @click="pickerYear = year"
                        >{{ year }}年</view>
                        <view style="height: 80rpx;"></view>
                    </scroll-view>
                    <!-- 选中高亮条 -->
                    <view class="picker-highlight"></view>
                    <!-- 月 -->
                    <scroll-view scroll-y class="picker-column" :scroll-top="monthScrollTop" @scroll="onMonthScroll">
                        <view style="height: 80rpx;"></view>
                        <view
                            class="picker-col-item"
                            v-for="month in months"
                            :key="month"
                            :class="{ 'picker-selected': pickerMonth === month }"
                            @click="pickerMonth = month"
                        >{{ month }}月</view>
                        <view style="height: 80rpx;"></view>
                    </scroll-view>
                </view>
            </view>
        </view>
    </view>
</template>

<script>
import { countOnAppReward, listOnAppReward } from '@/api/fulfiller/log/index.js';
import fulfillerEnum from '@/enums/fulfiller.json';

const bizTypeMap = fulfillerEnum.FlfRewardBizType;

export default {
    data() {
        const now = new Date();
        return {
            tabs: ['全部', '奖励', '惩罚'],
            activeTab: 0,
            selectedYear: now.getFullYear(),
            selectedMonth: now.getFullYear() === 2026 && now.getMonth() < 2 ? 3 : now.getMonth() + 1, // 默认当前月，处理一下测试数据时间
            // 统计数据
            stats: {
                rewardCount: 0,
                punishCount: 0,
                rewardBalance: 0,
                punishBalance: 0
            },
            // 月份选择器状态
            showMonthPicker: false,
            pickerYear: 2026,
            pickerMonth: 3,
            years: [2024, 2025, 2026],
            months: [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12],
            yearScrollTop: 0,
            monthScrollTop: 0,
            // 奖惩记录列表
            records: []
        };
    },
    computed: {
        filteredList() {
            if (this.activeTab === 0) return this.records;
            const targetType = this.activeTab === 1 ? 'reward' : 'penalty';
            return this.records.filter(r => r.type === targetType);
        }
    },
    onShow() {
        // 设置默认选中的年月
        const now = new Date();
        if (this.selectedYear === 2026 && this.selectedMonth === 2) {
             // 保持默认或根据实际需求
        }
        this.fetchData();
    },
    methods: {
        async fetchData() {
            const params = {
                year: this.selectedYear,
                month: this.selectedMonth
            };
            this.fetchStats(params);
            this.fetchList(params);
        },
        async fetchStats(params) {
            try {
                const res = await countOnAppReward(params);
                if (res.code === 200) {
                    this.stats = res.data || {
                        rewardCount: 0,
                        punishCount: 0,
                        rewardBalance: 0,
                        punishBalance: 0
                    };
                }
            } catch (err) {
                console.error('获取奖惩统计失败:', err);
            }
        },
        async fetchList(params) {
            try {
                const res = await listOnAppReward(params);
                if (res.code === 200) {
                    const list = res.data || [];
                    this.records = list.map(item => {
                        const isAdd = item.type === 'add';
                        const amountVal = Math.abs(item.amount) / 100;
                        
                        // 格式化日期 MM-DD
                        let dateStr = '';
                        if (item.createTime) {
                            const datePart = item.createTime.split(' ')[0];
                            const parts = datePart.split('-');
                            if (parts.length >= 3) {
                                dateStr = `${parts[1]}-${parts[2]}`;
                            }
                        }

                        return {
                            ...item,
                            date: dateStr,
                            title: bizTypeMap[item.bizType] || item.bizType || '其他',
                            desc: item.reason || '',
                            amount: isAdd ? amountVal : -amountVal,
                            type: isAdd ? 'reward' : 'penalty',
                            status: isAdd ? '已入账' : '已扣款', // 简化处理状态
                            statusClass: isAdd ? 'credited' : 'deducted'
                        };
                    });
                }
            } catch (err) {
                console.error('获取奖惩列表失败:', err);
            }
        },
        switchTab(idx) { this.activeTab = idx; },
        openMonthPicker() {
            this.pickerYear = this.selectedYear;
            this.pickerMonth = this.selectedMonth;
            this.showMonthPicker = true;
        },
        closeMonthPicker() { this.showMonthPicker = false; },
        confirmMonthPicker() {
            this.selectedYear = this.pickerYear;
            this.selectedMonth = this.pickerMonth;
            this.closeMonthPicker();
            this.fetchData();
        },
        goToAll() {
            uni.navigateTo({ url: '/pages/mine/rewards-all' });
        }
    }
};
</script>

<style>
page { background-color: #F7F8FA; }
.container { min-height: 100vh; background-color: #F7F8FA; }

/* 顶部橙色banner */
.top-banner {
    background: linear-gradient(135deg, #FF9800 0%, #FF5722 100%);
    padding: 20rpx 30rpx 36rpx;
    border-radius: 20rpx;
    margin: 20rpx 30rpx 0;
    box-shadow: 0 6rpx 20rpx rgba(255, 87, 34, 0.25);
}

.month-btn {
    display: flex;
    align-items: center;
    justify-content: flex-end;
    margin-bottom: 20rpx;
}

/* 年月文字和箭头在同一个圆角背景框内 */
.month-text {
    font-size: 24rpx;
    color: rgba(255,255,255,0.95);
    background-color: rgba(255,255,255,0.2);
    padding: 6rpx 14rpx;
    border-radius: 14rpx;
}

.stats-grid {
    display: flex;
    flex-wrap: wrap;
    gap: 16rpx;
}

.stats-cell {
    width: calc(50% - 8rpx);
    background-color: rgba(255,255,255,0.15);
    border-radius: 12rpx;
    padding: 20rpx 24rpx;
    display: flex;
    flex-direction: column;
    box-sizing: border-box;
}

.stats-num {
    font-size: 38rpx;
    font-weight: bold;
    color: #fff;
    margin-bottom: 8rpx;
}

.stats-unit { font-size: 20rpx; font-weight: normal; }

.stats-num.reward-num { color: #fff; }
.stats-num.penalty-num { color: #FFF176; }

.stats-label {
    font-size: 22rpx;
    color: rgba(255,255,255,0.85);
    margin-bottom: 8rpx;
}

/* 统计数字下方的分割线 */
.stats-divider {
    height: 1rpx;
    background-color: rgba(255,255,255,0.3);
    margin-bottom: 10rpx;
}

.stats-sub { font-size: 20rpx; color: rgba(255,255,255,0.65); }

/* 列表头：tab栏无底部外框线 */
.list-header {
    display: flex;
    align-items: center;
    background-color: #fff;
    padding: 0 16rpx 0 30rpx;
    margin: 16rpx 30rpx 0;
    border-radius: 16rpx 16rpx 0 0;
}

.tab-bar { display: flex; flex: 1; }

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

.tab-item:first-child { padding-left: 0; }

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

/* 下划线用正常流，自然居中对齐文字 */
.tab-line {
    width: 32rpx;
    height: 3rpx;
    background-color: #FF9800;
    border-radius: 2rpx;
    margin-top: 8rpx;
    align-self: center;
}



.view-all-btn { padding: 8rpx 0; margin-left: auto; }
.view-all-text { font-size: 24rpx; color: #999; }

/* 记录列表 */
.record-list {
    background-color: #fff;
    padding: 0 30rpx;
    margin: 0 30rpx;
    border-radius: 0 0 16rpx 16rpx;
}

.record-item {
    display: flex;
    align-items: center;
    padding: 24rpx 0;
    border-bottom: 1rpx solid #f5f5f5;
}

.ri-icon {
    width: 72rpx;
    height: 72rpx;
    border-radius: 50%;
    background-color: #FFF3E0;
    display: flex;
    align-items: center;
    justify-content: center;
    margin-right: 20rpx;
    flex-shrink: 0;
}

.ri-icon.ri-penalty { background-color: #FAFAFA; }

.ri-icon-text {
    font-size: 30rpx;
    color: #FF9800;
    font-weight: bold;
}

.ri-icon.ri-penalty .ri-icon-text { color: #ccc; }

.ri-content { flex: 1; }

.ri-title-row { display: flex; align-items: center; margin-bottom: 6rpx; }
.ri-date { font-size: 26rpx; color: #333; font-weight: bold; margin-right: 10rpx; }
.ri-title { font-size: 26rpx; color: #333; }
.ri-desc { font-size: 24rpx; color: #999; }

.ri-right {
    display: flex;
    flex-direction: column;
    align-items: flex-end;
    margin-left: 16rpx;
}

.ri-amount { font-size: 32rpx; font-weight: bold; margin-bottom: 4rpx; }
.ri-amount.positive { color: #FF5722; }
.ri-amount.negative { color: #333; }

.ri-status { font-size: 22rpx; }
.ri-status.pending { color: #FF9800; }
.ri-status.credited { color: #999; }
.ri-status.deducted { color: #999; }

.more-hint { display: block; text-align: center; font-size: 24rpx; color: #ccc; padding: 30rpx 0; }

/* 月份选择器 */
.picker-mask {
    position: fixed;
    top: 0; left: 0;
    width: 100%; height: 100%;
    background-color: rgba(0,0,0,0.5);
    z-index: 999;
    display: flex;
    align-items: flex-end;
}

.picker-sheet {
    width: 100%;
    background-color: #fff;
    border-radius: 24rpx 24rpx 0 0;
}

.picker-header {
    display: flex;
    align-items: center;
    justify-content: space-between;
    padding: 24rpx 30rpx;
    border-bottom: 1rpx solid #f5f5f5;
}

.picker-cancel { font-size: 28rpx; color: #999; }
.picker-title { font-size: 30rpx; font-weight: bold; color: #333; }
.picker-confirm { font-size: 28rpx; color: #FF9800; font-weight: bold; }

.picker-body {
    display: flex;
    height: 400rpx;
    position: relative;
    overflow: hidden;
}

.picker-column {
    flex: 1;
    height: 400rpx;
}

.picker-col-item {
    height: 80rpx;
    line-height: 80rpx;
    text-align: center;
    font-size: 28rpx;
    color: #333;
}

.picker-col-item.picker-selected {
    color: #FF9800;
    font-weight: bold;
    background-color: #FFF3E0;
    border-radius: 8rpx;
}

.picker-highlight {
    position: absolute;
    top: 50%;
    left: 0;
    transform: translateY(-50%);
    width: 100%;
    height: 80rpx;
    border-top: 1rpx solid #f0f0f0;
    border-bottom: 1rpx solid #f0f0f0;
    pointer-events: none;
}
</style>
