<template>
    <view class="teacher-page">
        <view class="bg-decor bg-decor-a"></view>
        <view class="bg-decor bg-decor-b"></view>

        <scroll-view class="page-scroll" scroll-y enhanced :show-scrollbar="false">
            <view class="content">
                <view class="profile-card clay-card">
                    <image class="avatar" :src="avatarUrl" mode="aspectFill" />
                    <view class="profile-main">
                        <text class="hello">您好，{{ teacherName }}</text>
                        <text class="school ellipsis">{{ teacherInfo.schoolName || '欢迎使用灵犀学AI教师端' }}</text>
                    </view>
                    <view class="logout-btn" @click="handleLogout">退出</view>
                </view>

                <view class="quick-grid">
                    <view class="quick-card clay-card" @click="goReportFilter">
                        <view class="quick-icon">
                            <text class="quick-icon-text">报</text>
                        </view>
                        <text class="quick-title">学情报告</text>
                        <text class="quick-desc">查看班级作业完成情况</text>
                    </view>
                    <view class="quick-card clay-card" @click="goWeakFilter">
                        <view class="quick-icon orange">
                            <text class="quick-icon-text orange">弱</text>
                        </view>
                        <text class="quick-title">薄弱知识点</text>
                        <text class="quick-desc">定位 Top10 高频薄弱点</text>
                    </view>
                </view>

                <view class="filter-card clay-card">
                    <view class="section-head">
                        <view>
                            <text class="section-title">AI 批改看板</text>
                            <text class="section-sub">按班级、学科和日期查看效率数据</text>
                        </view>
                    </view>

                    <picker :range="classNames" :value="classPickerIndex" @change="onClassPickerChange">
                        <view class="picker-row">
                            <text class="picker-label">班级</text>
                            <text class="picker-value ellipsis">{{ selectedClassName || '请选择班级' }}</text>
                        </view>
                    </picker>

                    <scroll-view v-if="subjectList.length" class="subject-scroll" scroll-x enhanced :show-scrollbar="false">
                        <view class="subject-list">
                            <view
                                v-for="item in subjectList"
                                :key="item.value"
                                class="subject-pill"
                                :class="{ active: selectedSubjectIds.includes(item.value) }"
                                @click="toggleSubject(item.value)"
                            >
                                {{ item.label }}
                            </view>
                        </view>
                    </scroll-view>

                    <view class="date-row">
                        <picker mode="date" :value="startTime" @change="onStartChange">
                            <view class="date-box">{{ startTime || '开始日期' }}</view>
                        </picker>
                        <text class="date-sep">至</text>
                        <picker mode="date" :value="endTime" @change="onEndChange">
                            <view class="date-box">{{ endTime || '结束日期' }}</view>
                        </picker>
                    </view>

                    <view class="query-btn clay-button" @click="fetchOverview">查询数据</view>
                </view>

                <view v-if="loading" class="state-card">
                    <xy-Loading text="加载看板中..." />
                </view>
                <view v-else-if="!selectedClassId" class="state-card">
                    <xy-Empty type="task" content="请选择班级查看看板" />
                </view>
                <view v-else-if="errorMsg" class="state-card">
                    <xy-Empty type="network" :content="errorMsg" />
                </view>
                <view v-else-if="overviewData" class="overview">
                    <view class="metric-grid">
                        <view class="metric-card clay-card">
                            <text class="metric-value">{{ overviewData.aiPaperCount || 0 }}</text>
                            <text class="metric-label">批改试卷</text>
                        </view>
                        <view class="metric-card clay-card">
                            <text class="metric-value">{{ overviewData.aiTitleCount || 0 }}</text>
                            <text class="metric-label">批改题目</text>
                        </view>
                    </view>

                    <view class="save-card clay-card">
                        <text class="save-title">节省批阅时间</text>
                        <text class="save-text">{{ saveTimeText }}</text>
                    </view>

                    <view class="grade-card clay-card">
                        <view class="section-head compact">
                            <text class="section-title">成绩分布</text>
                        </view>
                        <view class="grade-list">
                            <view v-for="item in gradeItems" :key="item.label" class="grade-item">
                                <view class="grade-top">
                                    <text class="grade-name">{{ item.label }}</text>
                                    <text class="grade-count">{{ item.count }}人 · {{ formatRate(item.rate) }}</text>
                                </view>
                                <view class="grade-bar">
                                    <view class="grade-fill" :class="item.type" :style="{ width: rateWidth(item.rate) }"></view>
                                </view>
                            </view>
                        </view>
                    </view>
                </view>

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

<script setup lang="ts">
import { computed, ref, watch } from 'vue';
import { onShow } from '@dcloudio/uni-app';
import { storeToRefs } from 'pinia';
import { useTeacherStore } from '@/state/modules/teacher';
import { useUserStore } from '@/state/modules/user';
import {
    getAiCorrectionOverview,
    getClassListByTeacher,
    getSubjectListByClassId,
    type AiCorrectionOverview,
} from '@/api/teacher';

const OSS_URL = 'https://xxl-1313840333.cos.ap-guangzhou.myqcloud.com';
const defaultAvatar = `${OSS_URL}/urm/logo.png`;

const teacherStore = useTeacherStore();
const userStore = useUserStore();
const { teacherInfo, schoolId } = storeToRefs(teacherStore);

const classList = ref<{ id: string; name: string }[]>([]);
const classPickerIndex = ref(0);
const selectedClassId = ref('');
const subjectList = ref<{ value: number; label: string }[]>([]);
const selectedSubjectIds = ref<number[]>([]);
const loading = ref(false);
const errorMsg = ref('');
const overviewData = ref<AiCorrectionOverview | null>(null);

const avatarUrl = computed(() => teacherInfo.value.avatarUrl || teacherInfo.value.avatar || defaultAvatar);
const teacherName = computed(() => teacherInfo.value.nickName || teacherInfo.value.name || teacherInfo.value.account || '老师');
const classNames = computed(() => classList.value.map((item) => item.name));
const selectedClassName = computed(() => classList.value.find((item) => item.id === selectedClassId.value)?.name || '');

const getTodayStr = () => {
    const d = new Date();
    return `${d.getFullYear()}-${String(d.getMonth() + 1).padStart(2, '0')}-${String(d.getDate()).padStart(2, '0')}`;
};
const startTime = ref(getTodayStr());
const endTime = ref(getTodayStr());

const saveTimeText = computed(() => {
    const mins = overviewData.value?.teacherSaveTimeMinutes || 0;
    if (mins <= 0) return 'AI 小助手已准备好为您分担批阅工作。';
    if (mins >= 1440) return `AI 小助手已为您节省 ${(mins / 1440).toFixed(1).replace(/\.0$/, '')} 天。`;
    if (mins >= 60) return `AI 小助手已为您节省 ${(mins / 60).toFixed(1).replace(/\.0$/, '')} 小时。`;
    return `AI 小助手已为您节省 ${mins} 分钟。`;
});

const gradeItems = computed(() => {
    const data = overviewData.value;
    return [
        { label: '优秀', count: data?.excellentCount || 0, rate: data?.excellentRate || 0, type: 'excellent' },
        { label: '良好', count: data?.goodCount || 0, rate: data?.goodRate || 0, type: 'good' },
        { label: '合格', count: data?.passCount || 0, rate: data?.passRate || 0, type: 'pass' },
        { label: '未提交', count: data?.unsubmittedCount || 0, rate: data?.unsubmittedRate || 0, type: 'unsubmit' },
    ];
});

const normalizeRate = (rate?: number | null) => {
    if (!rate) return 0;
    return rate > 1 ? rate : rate * 100;
};
const formatRate = (rate?: number | null) => `${normalizeRate(rate).toFixed(1).replace(/\.0$/, '')}%`;
const rateWidth = (rate?: number | null) => `${Math.min(100, Math.max(0, normalizeRate(rate)))}%`;

const normalizeClassList = (data: any) => {
    const rows = Array.isArray(data) ? data : data?.rows || data?.list || [];
    return rows.map((item: any) => ({
        ...item,
        id: String(item.id ?? item.classId ?? ''),
        name: item.name ?? item.className ?? '未命名班级',
    })).filter((item: any) => item.id);
};

const fetchTeacherInfo = async () => {
    if (!userStore.token) return;
    await teacherStore.getLoginUser();
};

const fetchClassList = async () => {
    const res = await getClassListByTeacher();
    classList.value = normalizeClassList(res.data);
    if (!selectedClassId.value && classList.value.length) {
        selectedClassId.value = classList.value[0].id;
        classPickerIndex.value = 0;
    }
};

watch(selectedClassId, async (value) => {
    subjectList.value = [];
    selectedSubjectIds.value = [];
    overviewData.value = null;
    if (!value) return;
    try {
        const res = await getSubjectListByClassId(value);
        const rows = Array.isArray(res.data) ? res.data : [];
        subjectList.value = rows.map((item: any) => ({
            value: Number(item.subjectId ?? item.id ?? item.value),
            label: item.subjectName ?? item.name ?? item.label ?? '',
        })).filter((item) => item.value && item.label);
        const teacherSubjectId = Number(teacherInfo.value.subjectId);
        if (teacherSubjectId && subjectList.value.some((item) => item.value === teacherSubjectId)) {
            selectedSubjectIds.value = [teacherSubjectId];
        }
    } catch (err) {
        console.error('获取学科失败', err);
    }
    fetchOverview();
});

const onClassPickerChange = (e: any) => {
    const index = Number(e.detail.value);
    const item = classList.value[index];
    if (!item) return;
    classPickerIndex.value = index;
    selectedClassId.value = item.id;
};

const toggleSubject = (value: number) => {
    selectedSubjectIds.value = selectedSubjectIds.value.includes(value)
        ? selectedSubjectIds.value.filter((item) => item !== value)
        : [...selectedSubjectIds.value, value];
};

const onStartChange = (e: any) => { startTime.value = e.detail?.value || ''; };
const onEndChange = (e: any) => { endTime.value = e.detail?.value || ''; };

const fetchOverview = async () => {
    if (!selectedClassId.value) return;
    loading.value = true;
    errorMsg.value = '';
    try {
        const res = await getAiCorrectionOverview({
            classId: selectedClassId.value,
            schoolId: schoolId.value || undefined,
            subjectIds: selectedSubjectIds.value.length ? selectedSubjectIds.value : undefined,
            startTime: startTime.value,
            endTime: endTime.value,
        });
        overviewData.value = res.data;
    } catch (err) {
        console.error('获取看板失败', err);
        errorMsg.value = '看板数据加载失败，请稍后重试';
        overviewData.value = null;
    } finally {
        loading.value = false;
    }
};

const goReportFilter = () => {
    uni.navigateTo({ url: '/pages/teacher/homework/filter' });
};
const goWeakFilter = () => {
    uni.navigateTo({ url: '/pages/teacher/homework/filter?target=weakKnowledge' });
};

const handleLogout = () => {
    uni.showModal({
        title: '提示',
        content: '确定退出老师端吗？',
        success: async (res) => {
            if (!res.confirm) return;
            teacherStore.clear();
            await userStore.logout();
        },
    });
};

onShow(async () => {
    try {
        await fetchTeacherInfo();
        if (!classList.value.length) await fetchClassList();
    } catch (err) {
        console.error('老师首页初始化失败', err);
    }
});
</script>

<style lang="scss" scoped>
.teacher-page {
    height: 100vh;
    background: linear-gradient(180deg, #eef2ff 0%, #f5f7ff 54%, #ffffff 100%);
    position: relative;
    overflow: hidden;
    display: flex;
    flex-direction: column;
}

.bg-decor {
    position: absolute;
    border-radius: 50%;
    filter: blur(60rpx);
    pointer-events: none;
}

.bg-decor-a {
    width: 360rpx;
    height: 360rpx;
    top: 120rpx;
    right: -140rpx;
    background: rgba(129, 140, 248, 0.35);
}

.bg-decor-b {
    width: 320rpx;
    height: 320rpx;
    bottom: 140rpx;
    left: -130rpx;
    background: rgba(34, 197, 94, 0.18);
}

.page-scroll {
    flex: 1;
    height: 0;
    position: relative;
    z-index: 1;
}

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

.profile-card {
    display: flex;
    align-items: center;
    gap: 20rpx;
    padding: 28rpx;
}

.avatar {
    width: 96rpx;
    height: 96rpx;
    border-radius: 32rpx;
    background: #eef2ff;
}

.profile-main {
    flex: 1;
    min-width: 0;
    display: flex;
    flex-direction: column;
    gap: 8rpx;
}

.hello {
    font-size: 34rpx;
    font-weight: 800;
    color: #312e81;
}

.school {
    font-size: 24rpx;
    color: #6366f1;
}

.logout-btn {
    padding: 14rpx 22rpx;
    border-radius: 999rpx;
    color: #ef4444;
    background: #fff1f2;
    font-size: 24rpx;
    font-weight: 600;
}

.quick-grid,
.metric-grid {
    display: grid;
    grid-template-columns: repeat(2, 1fr);
    gap: 20rpx;
    margin-top: 20rpx;
}

.quick-card {
    padding: 28rpx 24rpx;
}

.quick-icon {
    width: 72rpx;
    height: 72rpx;
    border-radius: 24rpx;
    background: #eef2ff;
    display: flex;
    align-items: center;
    justify-content: center;
    margin-bottom: 18rpx;

    &.orange {
        background: #fff7ed;
    }

}

.quick-icon-text {
    color: #4f46e5;
    font-size: 34rpx;
    font-weight: 900;

    &.orange {
        color: #f97316;
    }
}

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

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

.filter-card,
.grade-card,
.save-card {
    margin-top: 20rpx;
    padding: 28rpx;
}

.section-head {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-bottom: 22rpx;

    &.compact {
        margin-bottom: 12rpx;
    }
}

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

.section-sub {
    display: block;
    margin-top: 4rpx;
    font-size: 22rpx;
    color: #64748b;
}

.picker-row {
    display: flex;
    align-items: center;
    justify-content: space-between;
    padding: 24rpx;
    border-radius: 24rpx;
    background: #f8fafc;
    border: 2rpx solid #e0e7ff;
}

.picker-label {
    color: #64748b;
    font-size: 26rpx;
}

.picker-value {
    max-width: 420rpx;
    color: #4f46e5;
    font-size: 28rpx;
    font-weight: 700;
}

.subject-scroll {
    margin-top: 20rpx;
    white-space: nowrap;
}

.subject-list {
    display: inline-flex;
    gap: 16rpx;
}

.subject-pill {
    padding: 14rpx 24rpx;
    border-radius: 999rpx;
    background: #f8fafc;
    color: #64748b;
    font-size: 24rpx;
    border: 2rpx solid #e2e8f0;

    &.active {
        background: #4f46e5;
        color: #ffffff;
        border-color: #4f46e5;
    }
}

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

.date-box {
    min-width: 210rpx;
    padding: 18rpx 20rpx;
    text-align: center;
    border-radius: 22rpx;
    background: #f8fafc;
    border: 2rpx solid #e0e7ff;
    color: #4f46e5;
    font-size: 24rpx;
}

.date-sep {
    color: #94a3b8;
}

.query-btn {
    height: 88rpx;
    margin-top: 24rpx;
    display: flex;
    align-items: center;
    justify-content: center;
    font-size: 30rpx;
    font-weight: 800;
}

.state-card {
    height: 420rpx;
    margin-top: 20rpx;
}

.metric-card {
    min-height: 160rpx;
    padding: 28rpx;
    display: flex;
    flex-direction: column;
    justify-content: center;
}

.metric-value {
    font-size: 52rpx;
    line-height: 1;
    color: #4f46e5;
    font-weight: 900;
}

.metric-label {
    margin-top: 14rpx;
    color: #64748b;
    font-size: 24rpx;
}

.save-title {
    display: block;
    color: #16a34a;
    font-size: 26rpx;
    font-weight: 800;
}

.save-text {
    display: block;
    margin-top: 8rpx;
    color: #334155;
    font-size: 26rpx;
}

.grade-list {
    display: flex;
    flex-direction: column;
    gap: 24rpx;
}

.grade-top {
    display: flex;
    align-items: center;
    justify-content: space-between;
    margin-bottom: 10rpx;
}

.grade-name {
    font-size: 26rpx;
    color: #334155;
    font-weight: 700;
}

.grade-count {
    font-size: 24rpx;
    color: #64748b;
}

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

.grade-fill {
    height: 100%;
    border-radius: 999rpx;
    transition: width 240ms ease;

    &.excellent { background: #22c55e; }
    &.good { background: #3b82f6; }
    &.pass { background: #f59e0b; }
    &.unsubmit { background: #ef4444; }
}

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