<template>
    <view class="filter-page">
        <view class="bg-decor"></view>
        <scroll-view class="filter-scroll" scroll-y enhanced :show-scrollbar="false">
            <view class="content">
                <view class="section-card clay-card">
                    <view class="section-head">
                        <text class="section-title">选择班级</text>
                        <text class="section-required">必选</text>
                    </view>
                    <view v-if="classLoading" class="state-line">加载班级中...</view>
                    <view v-else-if="!classList.length" class="state-line">暂无班级数据</view>
                    <view v-else class="option-grid">
                        <view
                            v-for="item in classList"
                            :key="item.id"
                            class="option-item"
                            :class="{ active: selectedClassId === item.id }"
                            @click="selectedClassId = item.id"
                        >
                            <text class="option-text">{{ item.name }}</text>
                            <text v-if="selectedClassId === item.id" class="check-mark">✓</text>
                        </view>
                    </view>
                </view>

                <view class="section-card clay-card">
                    <view class="section-head">
                        <text class="section-title">选择学科</text>
                        <text class="section-hint">可多选，不选默认全部</text>
                    </view>
                    <view v-if="!selectedClassId" class="state-line">请先选择班级</view>
                    <view v-else-if="subjectLoading" class="state-line">加载学科中...</view>
                    <view v-else-if="!subjectList.length" class="state-line">该班级暂无学科数据</view>
                    <view v-else class="option-grid">
                        <view
                            v-for="item in subjectList"
                            :key="item.value"
                            class="option-item"
                            :class="{ active: selectedSubjectIds.includes(item.value) }"
                            @click="toggleSubject(item.value)"
                        >
                            <text class="option-text">{{ item.label }}</text>
                            <text v-if="selectedSubjectIds.includes(item.value)" class="check-mark">✓</text>
                        </view>
                    </view>
                </view>

                <view class="section-card clay-card">
                    <view class="section-head">
                        <text class="section-title">时间范围</text>
                        <text class="section-hint">默认今天</text>
                    </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 v-if="startTime || endTime" class="clear-date" @click="clearDate">清除时间</view>
                </view>

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

        <view class="bottom-bar">
            <view class="reset-btn" @click="handleReset">重置</view>
            <view class="confirm-btn clay-button" :class="{ disabled: !selectedClassId }" @click="handleConfirm">
                {{ confirmButtonText }}
            </view>
        </view>
    </view>
</template>

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

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

const target = ref('');
const classList = ref<{ id: string; name: string }[]>([]);
const classLoading = ref(false);
const selectedClassId = ref('');
const subjectList = ref<{ value: number; label: string }[]>([]);
const subjectLoading = ref(false);
const selectedSubjectIds = ref<number[]>([]);

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 confirmButtonText = computed(() => target.value === 'weakKnowledge' ? '查看薄弱知识点' : '查询学情报告');

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 fetchClassList = async () => {
    classLoading.value = true;
    try {
        const res = await getClassListByTeacher();
        classList.value = normalizeClassList(res.data);
        if (!selectedClassId.value && classList.value.length === 1) {
            selectedClassId.value = classList.value[0].id;
        }
    } catch (err) {
        console.error('获取班级失败', err);
        classList.value = [];
    } finally {
        classLoading.value = false;
    }
};

watch(selectedClassId, async (value) => {
    subjectList.value = [];
    selectedSubjectIds.value = [];
    if (!value) return;
    subjectLoading.value = true;
    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);
    } finally {
        subjectLoading.value = false;
    }
});

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 clearDate = () => {
    startTime.value = '';
    endTime.value = '';
};

const handleReset = () => {
    selectedClassId.value = '';
    selectedSubjectIds.value = [];
    startTime.value = '';
    endTime.value = '';
};

const handleConfirm = () => {
    if (!selectedClassId.value) {
        uni.showToast({ title: '请先选择班级', icon: 'none' });
        return;
    }
    const selectedClass = classList.value.find((item) => item.id === selectedClassId.value);
    const query: string[] = [
        `classId=${encodeURIComponent(selectedClassId.value)}`,
        `className=${encodeURIComponent(selectedClass?.name || '')}`,
    ];
    if (selectedSubjectIds.value.length) {
        query.push(`subjectIds=${encodeURIComponent(selectedSubjectIds.value.join(','))}`);
    }
    if (startTime.value) query.push(`startTime=${encodeURIComponent(startTime.value)}`);
    if (endTime.value) query.push(`endTime=${encodeURIComponent(endTime.value)}`);

    const path = target.value === 'weakKnowledge'
        ? '/pages/teacher/weakKnowledge/index'
        : '/pages/teacher/homework/index';
    uni.navigateTo({ url: `${path}?${query.join('&')}` });
};

onLoad((options: any) => {
    target.value = options?.target || '';
});

onShow(async () => {
    try {
        if (!teacherInfo.value?.id) await teacherStore.getLoginUser();
        if (!classList.value.length) await fetchClassList();
    } catch (err) {
        console.error('筛选页初始化失败', err);
    }
});
</script>

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

.bg-decor {
    position: absolute;
    width: 420rpx;
    height: 420rpx;
    right: -160rpx;
    top: 180rpx;
    border-radius: 50%;
    background: rgba(129, 140, 248, 0.24);
    filter: blur(70rpx);
}

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

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

.section-card {
    padding: 30rpx 28rpx;
    margin-bottom: 22rpx;
}

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

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

.section-required,
.section-hint {
    font-size: 22rpx;
    color: #64748b;
}

.section-required {
    color: #ef4444;
}

.option-grid {
    display: flex;
    flex-wrap: wrap;
    gap: 18rpx;
}

.option-item {
    min-height: 76rpx;
    max-width: 100%;
    padding: 0 24rpx;
    display: flex;
    align-items: center;
    gap: 12rpx;
    border-radius: 24rpx;
    background: #f8fafc;
    border: 2rpx solid #e2e8f0;
    color: #475569;
    font-size: 26rpx;

    &.active {
        color: #ffffff;
        background: linear-gradient(180deg, #6366f1 0%, #4f46e5 100%);
        border-color: #4f46e5;
        box-shadow: 0 10rpx 22rpx rgba(79, 70, 229, 0.22);
    }
}

.option-text {
    max-width: 540rpx;
    overflow: hidden;
    text-overflow: ellipsis;
    white-space: nowrap;
}

.check-mark {
    font-size: 24rpx;
    font-weight: 900;
}

.state-line {
    padding: 28rpx 0;
    text-align: center;
    font-size: 26rpx;
    color: #94a3b8;
}

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

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

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

.clear-date {
    margin-top: 20rpx;
    color: #ef4444;
    font-size: 24rpx;
}

.bottom-space {
    height: 24rpx;
}

.bottom-bar {
    position: relative;
    z-index: 9;
    display: flex;
    flex-shrink: 0;
    gap: 20rpx;
    padding: 20rpx 28rpx calc(20rpx + env(safe-area-inset-bottom));
    background: rgba(255, 255, 255, 0.94);
    box-shadow: 0 -8rpx 24rpx rgba(99, 102, 241, 0.08);
}

.reset-btn,
.confirm-btn {
    height: 88rpx;
    border-radius: 999rpx;
    display: flex;
    align-items: center;
    justify-content: center;
    font-size: 30rpx;
    font-weight: 800;
}

.reset-btn {
    flex: 1;
    background: #f8fafc;
    color: #64748b;
    border: 2rpx solid #e2e8f0;
}

.confirm-btn {
    flex: 2;

    &.disabled {
        opacity: 0.55;
    }
}
</style>
