<template>
    <view class="wrong-list-page">
        <scroll-view class="page-scroll" scroll-y :show-scrollbar="false" @scrolltolower="loadMore">
            <view class="content">
                <view class="filter-row">
                    <picker
                        class="filter-picker"
                        :range="timeRangeLabels"
                        :value="timeRangeIndex"
                        @change="onTimeRangeChange"
                    >
                        <view class="filter-pill">
                            <text>{{ timeRangeLabels[timeRangeIndex] }}</text>
                            <view class="filter-arrow"></view>
                        </view>
                    </picker>
                </view>

                <view v-if="listLoading" class="loading-wrap">
                    <xy-Empty type="loading" content="正在整理错题..." />
                </view>

                <view v-else-if="wrongQuestions.length" class="question-list">
                    <view v-for="item in wrongQuestions" :key="item.id" class="question-card">
                        <view class="question-main" @click="toggleExpand(item)">
                            <view class="question-preview rich-content">
                                <rich-text :nodes="item.previewHtml" />
                            </view>
                            <view class="meta-row">
                                <view class="meta-item">
                                    <text class="meta-label">错误次数</text>
                                    <text class="meta-value error-count">{{ item.errorCount ?? 0 }}</text>
                                </view>
                                <view class="meta-item">
                                    <text class="meta-label">首次错误</text>
                                    <text class="meta-value">{{ item.firstErrorTimeText }}</text>
                                </view>
                                <view class="meta-item">
                                    <text class="meta-label">最近错误</text>
                                    <text class="meta-value">{{ item.lastErrorTimeText }}</text>
                                </view>
                            </view>
                            <view class="card-head-actions">
                                <view class="expand-arrow" :class="{ expanded: item.expanded }"></view>
                            </view>
                        </view>

                        <view v-if="item.expanded && item.questionTitle" class="expand-section">
                            <view v-if="item.questionTitle.typeName" class="expand-item">
                                <text class="expand-label">题型</text>
                                <text class="expand-value">{{ item.questionTitle.typeName }}</text>
                            </view>
                            <view v-if="item.questionTitle.difficultyLevel" class="expand-item">
                                <text class="expand-label">难度</text>
                                <text class="expand-value">{{ item.questionTitle.difficultyLevel }}</text>
                            </view>
                            <view v-if="item.questionTitle.score" class="expand-item">
                                <text class="expand-label">分值</text>
                                <text class="expand-value">{{ item.questionTitle.score }}分</text>
                            </view>
                            <view v-if="item.questionTitle.submitAnswer" class="expand-item full">
                                <text class="expand-label">提交答案</text>
                                <text class="expand-value submit-answer">{{ item.questionTitle.submitAnswer }}</text>
                            </view>
                            <view v-if="item.expandContent?.stemHtml" class="expand-item full">
                                <text class="expand-label">题干</text>
                                <view class="expand-value rich-content">
                                    <rich-text :nodes="item.expandContent.stemHtml" />
                                </view>
                            </view>
                            <view v-if="item.expandContent?.parsedOptions?.length" class="expand-item full">
                                <text class="expand-label">选项</text>
                                <view class="expand-value rich-content">
                                    <view
                                        v-for="opt in item.expandContent.parsedOptions"
                                        :key="opt.index"
                                        class="option-item"
                                    >
                                        <text class="option-index">{{ opt.index }}.</text>
                                        <view class="option-html">
                                            <rich-text :nodes="opt.html" />
                                        </view>
                                    </view>
                                </view>
                            </view>
                            <view
                                v-else-if="item.expandContent?.optionHtmlFallback"
                                class="expand-item full"
                            >
                                <text class="expand-label">选项</text>
                                <view class="expand-value rich-content">
                                    <rich-text :nodes="item.expandContent.optionHtmlFallback" />
                                </view>
                            </view>
                            <view v-if="item.expandContent?.answerHtml" class="expand-item full">
                                <text class="expand-label">正确答案</text>
                                <view class="expand-value answer-text rich-content">
                                    <rich-text :nodes="item.expandContent.answerHtml" />
                                </view>
                            </view>
                            <view v-if="item.expandContent?.explanationHtml" class="expand-item full">
                                <text class="expand-label">解析</text>
                                <view class="expand-value rich-content">
                                    <rich-text :nodes="item.expandContent.explanationHtml" />
                                </view>
                            </view>
                        </view>
                    </view>
                </view>

                <view v-else class="empty-wrap">
                    <xy-Empty type="learn" :content="emptyText" />
                </view>

                <view v-if="loadingMore" class="load-more">加载中...</view>
            </view>

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

<script setup lang="ts">
import { computed, ref } from 'vue';
import { onLoad } from '@dcloudio/uni-app';
import { useParentStore } from '@/state/modules/parent';
import {
    TIME_RANGE_OPTIONS,
    ensureExpandContent,
    fetchWrongQuestionPage,
    getTimeRange,
    resolveWrongUserId,
    type WrongQuestion,
} from './shared';

const parentStore = useParentStore();
const listLoading = ref(false);
const loadingMore = ref(false);
const hasMore = ref(true);
const currentPage = ref(1);
const wrongQuestions = ref<WrongQuestion[]>([]);
const selectedSubject = ref('');
const selectedSubjectId = ref('');
const cachedUserId = ref('');
const timeRange = ref('');
const emptyText = ref('暂无错题');

const timeRangeLabels = TIME_RANGE_OPTIONS.map((item) => item.label);
const timeRangeIndex = computed(() => {
    const idx = TIME_RANGE_OPTIONS.findIndex((item) => item.value === timeRange.value);
    return idx >= 0 ? idx : 0;
});

const onTimeRangeChange = (e: any) => {
    const index = Number(e.detail.value);
    timeRange.value = TIME_RANGE_OPTIONS[index]?.value ?? '';
    initList();
};

const toggleExpand = (item: WrongQuestion) => {
    if (!item.expanded) {
        ensureExpandContent(item);
    }
    item.expanded = !item.expanded;
};

const getUserId = async () => {
    if (cachedUserId.value) return cachedUserId.value;
    const userId = parentStore.activeChild.id
        || parentStore.activeChildId
        || await resolveWrongUserId();
    cachedUserId.value = userId;
    return userId;
};

const fetchQuestions = async (append = false) => {
    const userId = await getUserId();
    if (!userId) {
        wrongQuestions.value = [];
        hasMore.value = false;
        emptyText.value = '未找到孩子信息，请先绑定孩子';
        return;
    }

    const page = append ? currentPage.value : 1;
    const { startTime, endTime } = getTimeRange(timeRange.value);
    const { rows, totalRows } = await fetchWrongQuestionPage({
        userId,
        subjectId: selectedSubjectId.value || undefined,
        current: page,
        startTime,
        endTime,
    });

    if (append) {
        const exists = new Set(wrongQuestions.value.map((item) => item.id));
        wrongQuestions.value = wrongQuestions.value.concat(
            rows.filter((item: WrongQuestion) => !exists.has(item.id)),
        );
    } else {
        wrongQuestions.value = rows;
    }
    hasMore.value = wrongQuestions.value.length < totalRows;
};

const initList = async () => {
    if (listLoading.value) return;
    listLoading.value = true;
    currentPage.value = 1;
    hasMore.value = true;
    try {
        await fetchQuestions(false);
        emptyText.value = wrongQuestions.value.length ? '' : '暂无错题';
    } catch (err) {
        console.error('[wrong/list] load failed', err);
        wrongQuestions.value = [];
        emptyText.value = '网络出问题了啦～';
        hasMore.value = false;
    } finally {
        listLoading.value = false;
    }
};

const loadMore = async () => {
    if (listLoading.value || loadingMore.value || !hasMore.value) return;
    loadingMore.value = true;
    currentPage.value += 1;
    try {
        await fetchQuestions(true);
    } catch {
        currentPage.value -= 1;
    } finally {
        loadingMore.value = false;
    }
};

onLoad((options) => {
    const subject = options?.subject ? decodeURIComponent(options.subject) : '';
    selectedSubject.value = subject;
    selectedSubjectId.value = options?.subjectId ? String(options.subjectId) : '';
    cachedUserId.value = options?.userId ? String(options.userId) : '';
    const title = subject ? `${subject}错题` : '错题列表';
    uni.setNavigationBarTitle({ title });
    timeRange.value = '';
    initList();
});
</script>

<style lang="scss" scoped>
.wrong-list-page {
    min-height: 100vh;
    background: #f8fafc;
}

.page-scroll {
    height: 100vh;
}

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

.filter-row {
    display: flex;
}

.filter-picker {
    min-width: 0;
    flex: 1;
}

.filter-pill {
    height: 70rpx;
    padding: 0 16rpx;
    border: 2rpx solid #e2e8f0;
    border-radius: 22rpx;
    display: flex;
    align-items: center;
    justify-content: center;
    gap: 8rpx;
    color: #334155;
    background: rgba(255, 255, 255, 0.95);
    font-size: 22rpx;
    font-weight: 700;
}

.filter-pill text {
    overflow: hidden;
    text-overflow: ellipsis;
    white-space: nowrap;
}

.filter-arrow {
    width: 0;
    height: 0;
    border-left: 7rpx solid transparent;
    border-right: 7rpx solid transparent;
    border-top: 9rpx solid #0891b2;
    flex-shrink: 0;
}

.question-list {
    display: flex;
    flex-direction: column;
    gap: 24rpx;
    margin-top: 26rpx;
}

.question-card {
    border-radius: 34rpx;
    background: #ffffff;
    box-shadow: 0 14rpx 34rpx rgba(15, 23, 42, 0.08);
    overflow: hidden;
}

.question-main {
    padding: 28rpx;
}

.question-preview {
    color: #0f172a;
    font-size: 28rpx;
    font-weight: 700;
    line-height: 1.65;
    display: -webkit-box;
    -webkit-line-clamp: 2;
    -webkit-box-orient: vertical;
    overflow: hidden;
}

.question-preview :deep(image),
.rich-content :deep(image),
.option-html :deep(image) {
    max-width: 100%;
    height: auto;
}

.rich-content :deep(.formula-text) {
    font-family: 'Times New Roman', 'STIXGeneral', Georgia, serif;
    font-style: italic;
}

.rich-content :deep(.formula-img) {
    max-width: 100%;
    vertical-align: middle;
}

.meta-row {
    display: grid;
    grid-template-columns: repeat(3, 1fr);
    gap: 12rpx;
    margin-top: 22rpx;
}

.meta-item {
    padding: 16rpx 12rpx;
    border-radius: 18rpx;
    background: #f8fafc;
    text-align: center;
}

.meta-label {
    display: block;
    color: #94a3b8;
    font-size: 20rpx;
}

.meta-value {
    display: block;
    margin-top: 6rpx;
    color: #334155;
    font-size: 22rpx;
    font-weight: 700;
}

.error-count {
    color: #e64340;
    font-size: 28rpx;
    font-weight: 900;
}

.card-head-actions {
    display: flex;
    align-items: center;
    justify-content: flex-end;
    margin-top: 22rpx;
}

.expand-arrow {
    width: 0;
    height: 0;
    border-left: 10rpx solid transparent;
    border-right: 10rpx solid transparent;
    border-top: 12rpx solid #94a3b8;
    transition: transform 0.25s ease;
}

.expand-arrow.expanded {
    transform: rotate(180deg);
}

.expand-section {
    padding: 0 28rpx 28rpx;
    border-top: 2rpx solid #f1f5f9;
}

.expand-item {
    display: flex;
    align-items: flex-start;
    gap: 16rpx;
    margin-top: 20rpx;
}

.expand-item.full {
    flex-direction: column;
    gap: 10rpx;
}

.expand-label {
    flex-shrink: 0;
    width: 120rpx;
    color: #94a3b8;
    font-size: 22rpx;
    font-weight: 700;
}

.expand-item.full .expand-label {
    width: auto;
}

.expand-value {
    flex: 1;
    min-width: 0;
    color: #334155;
    font-size: 24rpx;
    line-height: 1.6;
}

.submit-answer {
    color: #e64340;
    font-weight: 700;
}

.answer-text {
    color: #15803d;
    font-weight: 700;
}

.option-item {
    display: flex;
    align-items: flex-start;
    gap: 10rpx;
    margin-bottom: 10rpx;
}

.option-index {
    flex-shrink: 0;
    color: #0891b2;
    font-weight: 900;
}

.option-html {
    flex: 1;
    min-width: 0;
}

.empty-wrap,
.loading-wrap {
    height: 560rpx;
}

.load-more {
    padding: 24rpx 0 12rpx;
    text-align: center;
    color: #94a3b8;
    font-size: 24rpx;
}

.safe-bottom {
    height: 48rpx;
}
</style>
