<template>
    <view class="weak-page">
        <view class="summary-card clay-card" @click="goBackFilter">
            <view>
                <text class="summary-title">{{ listData?.className || className || '薄弱知识点 Top10' }}</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="list-scroll" scroll-y enhanced :show-scrollbar="false">
            <view class="content">
                <view v-if="!topList.length" class="state-card in-scroll">
                    <xy-Empty type="learn" content="暂无薄弱知识点数据" />
                </view>

                <view v-for="(item, index) in topList" :key="`${item.knowledgeId}-${index}`" class="knowledge-card clay-card">
                    <view class="rank" :class="`rank-${index + 1}`">{{ index + 1 }}</view>
                    <view class="knowledge-main">
                        <text class="knowledge-name ellipsis-2">{{ item.knowledgeName || '未命名知识点' }}</text>
                        <view class="meta-row">
                            <text v-if="item.subjectName" class="subject-tag">{{ item.subjectName }}</text>
                            <text class="meta danger">错 {{ item.errorCount || 0 }} 次</text>
                            <text class="meta">涉及 {{ item.titleCount || 0 }} 题</text>
                        </view>
                    </view>
                </view>

                <view class="bottom-space"></view>
            </view>
        </scroll-view>
    </view>
</template>

<script setup lang="ts">
import { computed, ref } from 'vue';
import { onLoad, onShow } from '@dcloudio/uni-app';
import { storeToRefs } from 'pinia';
import { useTeacherStore } from '@/state/modules/teacher';
import { getWeakKnowledgeTop10, type WeakKnowledgeItem, type WeakKnowledgeTop10Data } from '@/api/teacher';

const teacherStore = useTeacherStore();
const { schoolId } = storeToRefs(teacherStore);

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

const topList = computed<WeakKnowledgeItem[]>(() => listData.value?.topWeakKnowledgeList || []);
const filterSummary = computed(() => {
    const parts: string[] = [];
    parts.push(subjectIds.value.length ? `${subjectIds.value.length} 个学科` : '全部学科');
    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 fetchList = async () => {
    if (!classId.value) {
        errorMsg.value = '缺少班级参数，请重新筛选';
        return;
    }
    loading.value = true;
    errorMsg.value = '';
    try {
        const res = await getWeakKnowledgeTop10({
            classId: classId.value,
            schoolId: schoolId.value || undefined,
            subjectIds: subjectIds.value.length ? subjectIds.value : undefined,
            startTime: startTime.value || undefined,
            endTime: endTime.value || undefined,
        });
        listData.value = res.data;
        if (!className.value) className.value = res.data?.className || '';
    } catch (err) {
        console.error('获取薄弱知识点失败', err);
        errorMsg.value = '薄弱知识点加载失败，请稍后重试';
        listData.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)) : '';
});

onShow(async () => {
    try {
        if (!schoolId.value) await teacherStore.getLoginUser();
    } catch (err) {
        console.error('刷新老师信息失败', err);
    }
    fetchList();
});
</script>

<style lang="scss" scoped>
.weak-page {
    min-height: 100vh;
    background: linear-gradient(180deg, #eef2ff 0%, #f8fafc 58%, #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;
}

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

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

.knowledge-card {
    display: flex;
    align-items: flex-start;
    gap: 22rpx;
    padding: 28rpx;
    margin-bottom: 20rpx;
}

.rank {
    width: 62rpx;
    height: 62rpx;
    border-radius: 22rpx;
    background: #c7d2fe;
    color: #ffffff;
    display: flex;
    align-items: center;
    justify-content: center;
    font-size: 30rpx;
    font-weight: 900;
    flex-shrink: 0;

    &.rank-1 {
        background: linear-gradient(180deg, #fb7185 0%, #ef4444 100%);
    }

    &.rank-2 {
        background: linear-gradient(180deg, #fbbf24 0%, #f97316 100%);
    }

    &.rank-3 {
        background: linear-gradient(180deg, #60a5fa 0%, #3b82f6 100%);
    }
}

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

.knowledge-name {
    display: block;
    color: #312e81;
    font-size: 30rpx;
    line-height: 1.45;
    font-weight: 800;
}

.meta-row {
    display: flex;
    flex-wrap: wrap;
    gap: 12rpx;
    margin-top: 18rpx;
}

.subject-tag,
.meta {
    padding: 8rpx 14rpx;
    border-radius: 999rpx;
    font-size: 22rpx;
}

.subject-tag {
    color: #4f46e5;
    background: #eef2ff;
}

.meta {
    color: #64748b;
    background: #f8fafc;

    &.danger {
        color: #ef4444;
        background: #fff1f2;
    }
}

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

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

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