<template>
    <view class="container">
        <!-- 顶部筛选：类型标签 + 日期选择 -->
        <view class="filter-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="date-filter">
                <picker mode="date" fields="month" :value="currentPickerDate" @change="onDateChange">
                    <view class="picker-trigger">
                        <text>{{ selectedYear }}年{{ String(selectedMonth).padStart(2, '0') }}月</text>
                        <text class="arrow-icon">▼</text>
                    </view>
                </picker>
            </view>
        </view>

        <!-- 按月分组列表 -->
        <scroll-view scroll-y class="main-scroll">
            <view v-for="(group, gIdx) in filteredGroups" :key="gIdx" class="month-group">
                <!-- 月份标题 -->
                <view class="month-header">
                    <text class="month-title">{{ group.month }}月</text>
                    <view class="month-summary">
                        <text class="month-sum-text">已入账¥{{ group.credited.toFixed(2) }}</text>
                        <text class="month-sum-text"> 待入账¥{{ group.pending.toFixed(2) }}</text>
                    </view>
                </view>

                <!-- 记录列 -->
                <view class="record-item" v-for="(item, rIdx) in group.items" :key="rIdx">
                    <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>
            </view>
            <view style="height: 40rpx;"></view>
        </scroll-view>
    </view>
</template>

<script>
import { listOnAppReward } from '@/api/fulfiller/log';
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.getMonth() + 1,
            // 原始分组数据
            allGroups: [],
            loading: false
        };
    },
    computed: {
        currentPickerDate() {
            return `${this.selectedYear}-${String(this.selectedMonth).padStart(2, '0')}`;
        },
        filteredGroups() {
            if (this.activeTab === 0) return this.allGroups;
            const typeKey = this.activeTab === 1 ? 'reward' : 'penalty';
            return this.allGroups.map(g => ({
                ...g,
                items: g.items.filter(i => i.type === typeKey)
            })).filter(g => g.items.length > 0);
        }
    },
    onShow() {
        this.fetchMonthData();
    },
    methods: {
        async fetchMonthData() {
            if (this.loading) return;
            this.loading = true;
            try {
                const params = {
                    year: this.selectedYear,
                    month: this.selectedMonth
                };
                const res = await listOnAppReward(params);
                const data = res.data || [];

                if (data.length === 0) {
                    this.allGroups = [];
                    return;
                }

                let credited = 0;
                const items = data.map(item => {
                    const isAdd = item.type === 'add';
                    const amountVal = Math.abs(item.amount) / 100;
                    if (isAdd) credited += amountVal;

                    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'
                    };
                });

                this.allGroups = [{
                    month: this.selectedMonth,
                    year: this.selectedYear,
                    credited: credited,
                    pending: 0,
                    items: items
                }];
            } catch (err) {
                console.error('获取奖惩明细失败:', err);
                uni.showToast({ title: err.message || err.msg || '请求失败', icon: 'none' });
            } finally {
                this.loading = false;
            }
        },
        onDateChange(e) {
            const val = e.detail.value;
            const parts = val.split('-');
            this.selectedYear = parseInt(parts[0]);
            this.selectedMonth = parseInt(parts[1]);
            this.fetchMonthData();
        },
        switchTab(idx) { this.activeTab = idx; }
    }
};
</script>

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

/* 筛选头部：标签 + 日期 */
.filter-header {
    display: flex;
    align-items: center;
    justify-content: space-between;
    background-color: #fff;
    padding: 0 30rpx;
    border-bottom: 1rpx solid #f5f5f5;
}

.tab-bar {
    display: flex;
}

.date-filter {
    padding: 8rpx 0;
}

.picker-trigger {
    background-color: #f7f8fa;
    padding: 8rpx 20rpx;
    border-radius: 30rpx;
    display: flex;
    align-items: center;
}

.picker-trigger text {
    font-size: 24rpx;
    color: #333;
}

.arrow-icon {
    font-size: 18rpx;
    color: #999;
    margin-left: 8rpx;
}

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

.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;
}

.main-scroll { flex: 1; padding: 16rpx 0; }

.month-group {
    background-color: #fff;
    border-radius: 16rpx;
    padding: 0 24rpx;
    margin: 0 30rpx 16rpx;
    overflow: hidden;
}

.month-header {
    display: flex;
    align-items: center;
    padding: 20rpx 0;
    border-bottom: 1rpx solid #f5f5f5;
}

.month-title {
    font-size: 30rpx;
    font-weight: bold;
    color: #333;
    margin-right: 12rpx;
}

.month-summary { display: flex; }

.month-sum-text { font-size: 22rpx; color: #999; margin-right: 10rpx; }

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

.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: 30rpx; 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; }
</style>
