<template>
    <view class="report-page">
        <view class="summary-card clay-card" @click="goBackFilter">
            <view>
                <text class="summary-title">{{ className || reportData?.className || '班级作业完成情况' }}</text>
                <text class="summary-desc">{{ filterSummary }}</text>
            </view>
            <text class="summary-action">修改</text>
        </view>

        <view v-if="loading" class="state-card">
            <xy-Loading text="加载报告中..." />
        </view>
        <view v-else-if="errorMsg" class="state-card">
            <xy-Empty type="network" :content="errorMsg" />
        </view>
        <scroll-view v-else class="report-scroll" scroll-y enhanced :show-scrollbar="false">
            <view v-if="reportData" class="content">
                <view class="overview-card clay-card">
                    <view class="overview-item">
                        <text class="overview-value">{{ studentCount }}</text>
                        <text class="overview-label">学生数</text>
                    </view>
                    <view class="overview-item">
                        <text class="overview-value">{{ totalHomework }}</text>
                        <text class="overview-label">作业总数</text>
                    </view>
                    <view class="overview-item">
                        <text class="overview-value">{{ completeRate }}</text>
                        <text class="overview-label">完成率</text>
                    </view>
                </view>

                <view v-if="!reportData.studentList?.length" class="state-card in-scroll">
                    <xy-Empty type="task" content="暂无学生作业数据" />
                </view>

                <view v-for="student in reportData.studentList" :key="student.userId" class="student-card clay-card">
                    <view class="student-head">
                        <view class="avatar">{{ firstName(student.userName) }}</view>
                        <view class="student-main">
                            <text class="student-name">{{ student.userName || '未命名学生' }}</text>
                            <view class="progress-row">
                                <view class="progress-bar">
                                    <view class="progress-fill" :class="{ full: studentRate(student) >= 100 }" :style="{ width: studentRate(student) + '%' }"></view>
                                </view>
                                <text class="progress-text">{{ studentRate(student) }}%</text>
                            </view>
                        </view>
                    </view>

                    <view class="stat-grid">
                        <view class="stat-item">
                            <text class="stat-value">{{ student.totalCount || 0 }}</text>
                            <text class="stat-label">总数</text>
                        </view>
                        <view class="stat-item done">
                            <text class="stat-value">{{ student.completedCount || 0 }}</text>
                            <text class="stat-label">完成</text>
                        </view>
                        <view class="stat-item undone">
                            <text class="stat-value">{{ student.uncompletedCount || 0 }}</text>
                            <text class="stat-label">未完成</text>
                        </view>
                    </view>

                    <view v-if="student.subjectStats?.length" class="subject-wrap">
                        <view
                            v-for="item in student.subjectStats"
                            :key="item.subjectId"
                            class="subject-chip"
                            :class="{ full: item.homeworkCount > 0 && item.completedCount >= item.homeworkCount }"
                        >
                            <text>{{ item.subjectName }}</text>
                            <text>{{ item.completedCount }}/{{ item.homeworkCount }}</text>
                        </view>
                    </view>
                </view>

                <view class="bottom-space"></view>
            </view>
            <view v-else class="state-card in-scroll">
                <xy-Empty type="task" content="暂无报告数据" />
            </view>
        </scroll-view>
    </view>
</template>

<script setup lang="ts">
import { computed, ref } from 'vue';
import { onLoad } from '@dcloudio/uni-app';
import { getClassHomeworkReport, type ClassHomeworkReportData, type ClassHomeworkStudentItem } from '@/api/teacher';

const subjectMap: Record<number, string> = {
    2: '语文',
    3: '数学',
    4: '英语',
    5: '科学',
    6: '物理',
    7: '化学',
    8: '历史',
    9: '道德与法治',
    10: '地理',
    11: '生物',
    12: '政治',
    13: '信息',
    14: '通用',
    15: '日语',
};

const classId = ref('');
const className = ref('');
const subjectIds = ref<number[]>([]);
const startTime = ref('');
const endTime = ref('');
const reportData = ref<ClassHomeworkReportData | null>(null);
const loading = ref(false);
const errorMsg = ref('');

const studentCount = computed(() => reportData.value?.studentList?.length || 0);
const totalHomework = computed(() => (reportData.value?.studentList || []).reduce((sum, item) => sum + (item.totalCount || 0), 0));
const completedHomework = computed(() => (reportData.value?.studentList || []).reduce((sum, item) => sum + (item.completedCount || 0), 0));
const completeRate = computed(() => totalHomework.value ? `${Math.round(completedHomework.value / totalHomework.value * 100)}%` : '0%');

const filterSummary = computed(() => {
    const parts: string[] = [];
    if (subjectIds.value.length) {
        const labels = subjectIds.value.map((id) => subjectMap[id]).filter(Boolean);
        parts.push(labels.length ? labels.join('、') : `${subjectIds.value.length}个学科`);
    } else {
        parts.push('全部学科');
    }
    if (startTime.value || endTime.value) {
        parts.push(`${startTime.value || '...'} 至 ${endTime.value || '...'}`);
    }
    return parts.join(' · ');
});

const parseSubjectIds = (value: any) => {
    if (!value) return [];
    return decodeURIComponent(String(value)).split(',').map(Number).filter((item) => !Number.isNaN(item));
};

const firstName = (name?: string) => (name || '学').slice(0, 1);
const studentRate = (student: ClassHomeworkStudentItem) => {
    if (!student.totalCount) return 0;
    return Math.min(100, Math.round(student.completedCount / student.totalCount * 100));
};

const fetchReport = async () => {
    if (!classId.value) {
        errorMsg.value = '缺少班级参数，请重新筛选';
        return;
    }
    loading.value = true;
    errorMsg.value = '';
    try {
        const res = await getClassHomeworkReport({
            classId: classId.value,
            subjectIds: subjectIds.value.length ? subjectIds.value : undefined,
            startTime: startTime.value || undefined,
            endTime: endTime.value || undefined,
        });
        reportData.value = res.data;
        if (!className.value) className.value = res.data?.className || '';
    } catch (err) {
        console.error('获取学情报告失败', err);
        errorMsg.value = '学情报告加载失败，请稍后重试';
        reportData.value = null;
    } finally {
        loading.value = false;
    }
};

const goBackFilter = () => {
    uni.navigateBack();
};

onLoad((options: any) => {
    classId.value = options?.classId ? decodeURIComponent(String(options.classId)) : '';
    className.value = options?.className ? decodeURIComponent(String(options.className)) : '';
    subjectIds.value = parseSubjectIds(options?.subjectIds);
    startTime.value = options?.startTime ? decodeURIComponent(String(options.startTime)) : '';
    endTime.value = options?.endTime ? decodeURIComponent(String(options.endTime)) : '';
    fetchReport();
});
</script>

<style lang="scss" scoped>
.report-page {
    min-height: 100vh;
    background: linear-gradient(180deg, #eef2ff 0%, #f8fafc 60%, #ffffff 100%);
    overflow: hidden;
}

.summary-card {
    margin: 20rpx 28rpx 0;
    padding: 24rpx 28rpx;
    display: flex;
    align-items: center;
    justify-content: space-between;
    gap: 20rpx;
}

.summary-title {
    display: block;
    color: #312e81;
    font-size: 32rpx;
    font-weight: 800;
}

.summary-desc {
    display: block;
    margin-top: 6rpx;
    color: #64748b;
    font-size: 24rpx;
}

.summary-action {
    padding: 12rpx 22rpx;
    border-radius: 999rpx;
    color: #4f46e5;
    background: #eef2ff;
    font-size: 24rpx;
    font-weight: 700;
    flex-shrink: 0;
}

.report-scroll {
    height: calc(100vh - 160rpx);
}

.content {
    padding: 20rpx 28rpx 0;
}

.overview-card {
    display: grid;
    grid-template-columns: repeat(3, 1fr);
    gap: 10rpx;
    padding: 28rpx 16rpx;
    margin-bottom: 20rpx;
}

.overview-item {
    display: flex;
    flex-direction: column;
    align-items: center;
    gap: 8rpx;
}

.overview-value {
    color: #4f46e5;
    font-size: 40rpx;
    font-weight: 900;
}

.overview-label {
    color: #64748b;
    font-size: 22rpx;
}

.student-card {
    padding: 28rpx;
    margin-bottom: 20rpx;
}

.student-head {
    display: flex;
    align-items: center;
    gap: 20rpx;
}

.avatar {
    width: 82rpx;
    height: 82rpx;
    border-radius: 28rpx;
    background: linear-gradient(180deg, #818cf8 0%, #4f46e5 100%);
    color: #ffffff;
    display: flex;
    align-items: center;
    justify-content: center;
    font-size: 34rpx;
    font-weight: 900;
    flex-shrink: 0;
}

.student-main {
    flex: 1;
    min-width: 0;
}

.student-name {
    display: block;
    color: #312e81;
    font-size: 30rpx;
    font-weight: 800;
}

.progress-row {
    margin-top: 12rpx;
    display: flex;
    align-items: center;
    gap: 14rpx;
}

.progress-bar {
    flex: 1;
    height: 14rpx;
    border-radius: 999rpx;
    background: #eef2ff;
    overflow: hidden;
}

.progress-fill {
    height: 100%;
    border-radius: 999rpx;
    background: #f59e0b;

    &.full {
        background: #22c55e;
    }
}

.progress-text {
    width: 72rpx;
    text-align: right;
    color: #4f46e5;
    font-size: 24rpx;
    font-weight: 800;
}

.stat-grid {
    display: grid;
    grid-template-columns: repeat(3, 1fr);
    gap: 14rpx;
    margin-top: 24rpx;
}

.stat-item {
    padding: 18rpx 0;
    border-radius: 22rpx;
    background: #f8fafc;
    display: flex;
    flex-direction: column;
    align-items: center;
    gap: 4rpx;

    &.done .stat-value {
        color: #16a34a;
    }

    &.undone .stat-value {
        color: #ef4444;
    }
}

.stat-value {
    color: #312e81;
    font-size: 34rpx;
    font-weight: 900;
}

.stat-label {
    color: #64748b;
    font-size: 22rpx;
}

.subject-wrap {
    display: flex;
    flex-wrap: wrap;
    gap: 14rpx;
    margin-top: 22rpx;
}

.subject-chip {
    display: flex;
    gap: 10rpx;
    padding: 12rpx 18rpx;
    border-radius: 999rpx;
    color: #475569;
    background: #f8fafc;
    border: 2rpx solid #e2e8f0;
    font-size: 22rpx;

    &.full {
        color: #16a34a;
        background: #f0fdf4;
        border-color: #bbf7d0;
    }
}

.state-card {
    height: 520rpx;
    display: flex;
    align-items: center;
    justify-content: center;

    &.in-scroll {
        height: 420rpx;
    }
}

.bottom-space {
    height: calc(60rpx + env(safe-area-inset-bottom));
}
</style>
