<template>
    <view class="hist-page">
        <!-- 装饰背景 -->
        <view class="bg-decor bg-decor-a"></view>
        <view class="bg-decor bg-decor-b"></view>

        <!-- 状态筛选 (sticky 段控件) -->
        <view class="filter-bar">
            <view class="filter-segment">
                <view
                    v-for="item in statusList"
                    :key="item.value"
                    :class="['filter-tab', { active: activeStatus === item.value }]"
                    @click="onChangeStatus(item.value)"
                >
                    <text>{{ item.label }}</text>
                </view>
            </view>
        </view>

        <!-- 学科横向滚动 -->
        <view v-if="subjectList.length" class="subject-bar">
            <scroll-view scroll-x :show-scrollbar="false" class="subject-scroll">
                <view class="subject-list">
                    <view
                        v-for="item in subjectListAll"
                        :key="item.id"
                        :class="['subject-pill', { active: activeSubjectId === item.id }]"
                        @click="onSelectSubject(item.id)"
                    >
                        <text>{{ item.name }}</text>
                    </view>
                </view>
            </scroll-view>
        </view>

        <!-- 列表区 -->
        <scroll-view class="list-scroll" scroll-y :show-scrollbar="false">
            <view v-if="jobList.length" class="job-list">
                <view
                    v-for="item in jobList"
                    :key="item.id"
                    class="job-card"
                    @click="onTapJob(item)"
                >
                    <!-- 上方左右两栏 -->
                    <view class="job-head">
                        <view class="job-subject">
                            <view class="job-subject-emoji">{{ getSubjectEmoji(item.subjectName) }}</view>
                            <text>{{ item.subjectName || activeSubjectName }}</text>
                        </view>
                        <view :class="['job-status', item.gradingStatus === 1 ? 'corrected' : 'pending']">
                            <view class="status-dot"></view>
                            <text>{{ item.gradingStatus === 1 ? '已批改' : '待批改' }}</text>
                        </view>
                    </view>

                    <view class="job-title">{{ item.paperName }}</view>

                    <!-- 已批改 -> 显示得分卡 -->
                    <view v-if="item.gradingStatus === 1" class="job-score" :class="getRateType(item)">
                        <view class="score-left">
                            <text class="score-label">得分率</text>
                            <view class="score-num">
                                <text class="num">{{ getScoreRate(item) }}</text>
                                <text class="unit">%</text>
                            </view>
                            <ProgressBar
                                :rate="(item.score || 0) / (item.totalScore || 1)"
                                :width="280"
                                v-bind="getProgressColor(item)"
                            />
                        </view>
                        <view class="score-right">
                            <view class="score-circle">
                                <text class="rank-emoji">{{ getRankEmoji(item) }}</text>
                            </view>
                            <view v-if="item.addDiamond || item.addExp" class="reward-row">
                                <view v-if="item.addDiamond" class="reward-pill diamond">
                                    <view class="reward-icon">
                                        <svg viewBox="0 0 16 16" fill="none">
                                            <path d="M3 6 8 2l5 4-5 9-5-9z" fill="#0EA5E9" stroke="#0369A1"
                                                stroke-width="1" stroke-linejoin="round" />
                                        </svg>
                                    </view>
                                    <text>+{{ item.addDiamond }}</text>
                                </view>
                                <view v-if="item.addExp" class="reward-pill exp">
                                    <view class="reward-icon">
                                        <svg viewBox="0 0 16 16" fill="none">
                                            <path d="m8 1 2.2 4.5 5 .7-3.6 3.5.9 5-4.5-2.4-4.5 2.4.9-5L.7 6.2l5-.7L8 1z"
                                                fill="#F59E0B" stroke="#B45309" stroke-width="1" />
                                        </svg>
                                    </view>
                                    <text>+{{ item.addExp }}</text>
                                </view>
                            </view>
                        </view>
                    </view>

                    <!-- 未批改 -> 提示信息 -->
                    <view v-else class="job-pending">
                        <view class="pending-icon">
                            <svg viewBox="0 0 24 24" fill="none">
                                <circle cx="12" cy="12" r="9" stroke="#94A3B8" stroke-width="1.6" />
                                <path d="M12 7v5l3 2" stroke="#94A3B8" stroke-width="1.6"
                                    stroke-linecap="round" />
                            </svg>
                        </view>
                        <text>等待老师批改中…</text>
                    </view>

                    <!-- 时间信息 -->
                    <view class="job-meta">
                        <view v-if="item.createTime" class="meta-line">
                            <text class="meta-label">发布</text>
                            <text class="meta-value">{{ formatTime(item.createTime) }}</text>
                        </view>
                        <view v-if="item.markTime" class="meta-line">
                            <text class="meta-label">批改</text>
                            <text class="meta-value">{{ formatTime(item.markTime) }}</text>
                        </view>
                    </view>
                </view>
            </view>

            <!-- 空状态 -->
            <Empty
                v-else-if="!listLoading"
                class="empty"
                :type="pageError ? 'network' : 'learn'"
                :content="pageError ? '网络出问题了啦' : '暂无作业记录，快去做作业吧！'"
            />

            <view style="height: 80rpx"></view>
        </scroll-view>

        <view v-if="listLoading" class="page-loader">
            <Loading text="加载中..." />
        </view>
    </view>
</template>

<script setup lang="ts">
import { ref, computed, onMounted } from 'vue';
import { onShow } from '@dcloudio/uni-app';
import Empty from '@/components/Empty/index.vue';
import Loading from '@/components/Loading/index.vue';
import ProgressBar from '@/components/ProgressBar/index.vue';
import { getListCompleteRecord, normalizeListCompleteRecord } from '@/api/homework';
import { formatTime } from '@/utils/format';

const statusList = [
    { label: '全部', value: '' },
    { label: '已批改', value: '1' },
    { label: '未批改', value: '0' },
];

interface SubjectItem {
    id: string;
    name: string;
}

const activeStatus = ref('');
const subjectList = ref<SubjectItem[]>([]);
const activeSubjectId = ref<string>('');
const jobList = ref<any[]>([]);
const listLoading = ref(false);
const pageError = ref(false);

const subjectListAll = computed<SubjectItem[]>(() => {
    return [{ id: '', name: '全部' }, ...subjectList.value];
});

const activeSubjectName = computed(() => {
    return subjectList.value.find((i) => i.id === activeSubjectId.value)?.name || '';
});

const colorConfig: Record<string, any> = {
    success: { color: '#16A34A', border: '#16A34A', bg: '#DCFCE7', activeBg: '#22C55E' },
    primary: { color: '#4F46E5', border: '#4F46E5', bg: '#E0E7FF', activeBg: '#818CF8' },
    warning: { color: '#D97706', border: '#D97706', bg: '#FEF3C7', activeBg: '#F59E0B' },
    error:   { color: '#DC2626', border: '#DC2626', bg: '#FEE2E2', activeBg: '#EF4444' },
};

const getScoreRate = (item: any) => {
    if (!item.totalScore) return 0;
    return Math.round((item.score / item.totalScore) * 100);
};

const getRateType = (item: any) => {
    const r = getScoreRate(item);
    if (r >= 80) return 'success';
    if (r >= 60) return 'primary';
    if (r >= 40) return 'warning';
    return 'error';
};

const getProgressColor = (item: any) => colorConfig[getRateType(item)] || colorConfig.primary;

const getRankEmoji = (item: any) => {
    const r = getScoreRate(item);
    if (r >= 95) return '🏆';
    if (r >= 80) return '🌟';
    if (r >= 60) return '👍';
    if (r >= 40) return '💪';
    return '📚';
};

const getSubjectEmoji = (name: string) => {
    if (!name) return '📘';
    if (name.includes('语文')) return '📖';
    if (name.includes('数学')) return '🧮';
    if (name.includes('英语')) return '🔤';
    if (name.includes('物理')) return '🔬';
    if (name.includes('化学')) return '⚗️';
    if (name.includes('生物')) return '🌿';
    if (name.includes('历史')) return '📜';
    if (name.includes('地理')) return '🌏';
    if (name.includes('政治')) return '⚖️';
    return '📘';
};

const onChangeStatus = (val: string) => {
    activeStatus.value = val;
    refresh();
};

const onSelectSubject = (id: string) => {
    activeSubjectId.value = id;
    refresh();
};

const onTapJob = (item: any) => {
    if (item.gradingStatus !== 1) {
        uni.showToast({ title: '作业未批改，请耐心等待老师批改', icon: 'none' });
        return;
    }
    uni.navigateTo({
        url: `/pages/homework/reports/index?id=${item.id}&name=${encodeURIComponent(item.paperName || '')}`,
    });
};

const initSubject = async () => {
    try {
        const res = await getListCompleteRecord({});
        const { rows: records } = normalizeListCompleteRecord(res.data);
        const map = new Map<string, SubjectItem>();
        records.forEach((item: any) => {
            const sid = String(item.subjectId);
            if (!map.has(sid)) {
                map.set(sid, { id: sid, name: item.subjectName });
            }
        });
        subjectList.value = Array.from(map.values());
    } catch (err) {
        console.error('[history] init subject err', err);
    }
};

const fetchJobList = async () => {
    const params: Record<string, any> = {};
    if (activeStatus.value !== '') params.gradingStatus = activeStatus.value;
    if (activeSubjectId.value) params.subjectId = activeSubjectId.value;
    const res = await getListCompleteRecord(params);
    const { rows } = normalizeListCompleteRecord(res.data);
    jobList.value = rows;
};

const refresh = async () => {
    pageError.value = false;
    listLoading.value = true;
    jobList.value = [];
    try {
        await fetchJobList();
    } catch (err) {
        pageError.value = true;
        console.error('[history] fetch job err', err);
    } finally {
        listLoading.value = false;
    }
};

onMounted(async () => {
    listLoading.value = true;
    try {
        await initSubject();
        await fetchJobList();
    } catch (err) {
        pageError.value = true;
    } finally {
        listLoading.value = false;
    }
});

onShow(() => {
    if (subjectList.value.length || jobList.value.length) {
        refresh();
    }
});
</script>

<style lang="scss" scoped>
.hist-page {
    height: 100vh;
    background: #f5f7ff;
    position: relative;
    overflow: hidden;
    display: flex;
    flex-direction: column;
}

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

    &-a {
        top: -120rpx;
        left: -100rpx;
        width: 360rpx;
        height: 360rpx;
        background: radial-gradient(circle, rgba(34, 197, 94, 0.35), transparent 70%);
    }

    &-b {
        top: 320rpx;
        right: -120rpx;
        width: 320rpx;
        height: 320rpx;
        background: radial-gradient(circle, rgba(129, 140, 248, 0.35), transparent 70%);
    }
}

/* 状态筛选 */
.filter-bar {
    padding: 24rpx 32rpx 8rpx;
    position: relative;
    z-index: 1;
}

.filter-segment {
    display: flex;
    background: rgba(255, 255, 255, 0.7);
    border-radius: 999rpx;
    padding: 8rpx;
    box-shadow: inset 0 4rpx 8rpx rgba(99, 102, 241, 0.1);
}

.filter-tab {
    flex: 1;
    height: 64rpx;
    border-radius: 999rpx;
    display: flex;
    align-items: center;
    justify-content: center;
    font-size: 26rpx;
    color: #94a3b8;
    font-weight: 500;
    transition: color 200ms ease;

    &.active {
        background: linear-gradient(180deg, #818cf8 0%, #4f46e5 100%);
        color: #ffffff;
        font-weight: 700;
        box-shadow:
            0 6rpx 14rpx rgba(79, 70, 229, 0.3),
            inset 0 -3rpx 0 rgba(0, 0, 0, 0.12);
    }
}

/* 学科横滚 */
.subject-bar {
    padding: 12rpx 0 8rpx;
    position: relative;
    z-index: 1;
}

.subject-scroll {
    width: 100%;
    white-space: nowrap;
}

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

.subject-pill {
    flex-shrink: 0;
    padding: 12rpx 28rpx;
    background: #ffffff;
    border-radius: 999rpx;
    font-size: 26rpx;
    font-weight: 500;
    color: #6366f1;
    box-shadow:
        0 4rpx 10rpx rgba(99, 102, 241, 0.1),
        inset 0 -3rpx 0 rgba(199, 210, 254, 0.5);

    &.active {
        background: linear-gradient(180deg, #4ade80 0%, #16a34a 100%);
        color: #ffffff;
        font-weight: 700;
        box-shadow:
            0 8rpx 16rpx rgba(22, 163, 74, 0.3),
            inset 0 -4rpx 0 rgba(0, 0, 0, 0.15);
    }
}

/* 列表 */
.list-scroll {
    flex: 1;
    height: 0;
    position: relative;
    z-index: 1;
}

.job-list {
    padding: 24rpx 32rpx;
    display: flex;
    flex-direction: column;
    gap: 24rpx;
}

.job-card {
    background: #ffffff;
    border-radius: 32rpx;
    padding: 28rpx;
    box-shadow:
        0 12rpx 24rpx rgba(99, 102, 241, 0.12),
        inset 0 -5rpx 0 rgba(199, 210, 254, 0.5);
    transition: transform 150ms ease;

    &:active {
        transform: scale(0.98);
    }
}

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

.job-subject {
    display: flex;
    align-items: center;
    gap: 8rpx;
    padding: 6rpx 18rpx 6rpx 12rpx;
    background: linear-gradient(135deg, #eef2ff, #e0e7ff);
    border-radius: 999rpx;

    .job-subject-emoji {
        font-size: 26rpx;
    }

    text {
        font-size: 22rpx;
        color: #4f46e5;
        font-weight: 600;
    }
}

.job-status {
    display: flex;
    align-items: center;
    gap: 8rpx;
    padding: 6rpx 18rpx;
    border-radius: 999rpx;
    font-size: 22rpx;
    font-weight: 600;

    &.corrected {
        background: #dcfce7;
        color: #16a34a;

        .status-dot {
            background: #22c55e;
        }
    }

    &.pending {
        background: #fef3c7;
        color: #d97706;

        .status-dot {
            background: #f59e0b;
        }
    }

    .status-dot {
        width: 12rpx;
        height: 12rpx;
        border-radius: 50%;
    }
}

.job-title {
    font-size: 32rpx;
    font-weight: 700;
    color: #312e81;
    line-height: 1.4;
    margin-bottom: 18rpx;
    overflow: hidden;
    text-overflow: ellipsis;
    display: -webkit-box;
    -webkit-line-clamp: 2;
    -webkit-box-orient: vertical;
    word-break: break-all;
}

/* 已批改得分卡 */
.job-score {
    display: flex;
    align-items: center;
    padding: 24rpx;
    border-radius: 24rpx;
    margin-bottom: 18rpx;
    gap: 20rpx;

    &.success {
        background: linear-gradient(135deg, rgba(220, 252, 231, 0.7), rgba(187, 247, 208, 0.5));
    }

    &.primary {
        background: linear-gradient(135deg, rgba(224, 231, 255, 0.7), rgba(199, 210, 254, 0.5));
    }

    &.warning {
        background: linear-gradient(135deg, rgba(254, 243, 199, 0.7), rgba(253, 230, 138, 0.5));
    }

    &.error {
        background: linear-gradient(135deg, rgba(254, 226, 226, 0.7), rgba(254, 202, 202, 0.5));
    }
}

.score-left {
    flex: 1;
    min-width: 0;

    .score-label {
        font-size: 22rpx;
        color: #6366f1;
        font-weight: 500;
        opacity: 0.8;
    }

    .score-num {
        display: flex;
        align-items: baseline;
        gap: 4rpx;
        margin: 4rpx 0 12rpx;

        .num {
            font-size: 64rpx;
            font-weight: 800;
            color: #312e81;
            line-height: 1;
        }

        .unit {
            font-size: 28rpx;
            color: #6366f1;
            font-weight: 600;
        }
    }
}

.score-right {
    width: 140rpx;
    flex-shrink: 0;
    display: flex;
    flex-direction: column;
    align-items: center;
    gap: 12rpx;
}

.score-circle {
    width: 88rpx;
    height: 88rpx;
    border-radius: 50%;
    background: #ffffff;
    display: flex;
    align-items: center;
    justify-content: center;
    box-shadow:
        0 6rpx 12rpx rgba(99, 102, 241, 0.18),
        inset 0 -3rpx 0 rgba(199, 210, 254, 0.6);

    .rank-emoji {
        font-size: 48rpx;
    }
}

.reward-row {
    display: flex;
    flex-wrap: wrap;
    gap: 6rpx;
    justify-content: center;
}

.reward-pill {
    display: flex;
    align-items: center;
    gap: 4rpx;
    padding: 4rpx 10rpx;
    border-radius: 999rpx;
    font-size: 20rpx;
    font-weight: 700;

    &.diamond {
        background: #e0f2fe;
        color: #0369a1;
    }

    &.exp {
        background: #fef3c7;
        color: #b45309;
    }

    .reward-icon {
        width: 22rpx;
        height: 22rpx;

        svg {
            width: 100%;
            height: 100%;
        }
    }
}

/* 未批改提示 */
.job-pending {
    display: flex;
    align-items: center;
    gap: 12rpx;
    padding: 20rpx 24rpx;
    background: #f5f7ff;
    border-radius: 20rpx;
    margin-bottom: 18rpx;

    .pending-icon {
        width: 40rpx;
        height: 40rpx;

        svg {
            width: 100%;
            height: 100%;
        }
    }

    text {
        font-size: 26rpx;
        color: #94a3b8;
    }
}

/* meta */
.job-meta {
    display: flex;
    flex-wrap: wrap;
    gap: 20rpx;
}

.meta-line {
    display: flex;
    align-items: center;
    gap: 8rpx;
    font-size: 22rpx;

    .meta-label {
        color: #94a3b8;
        padding: 2rpx 10rpx;
        background: #f1f5f9;
        border-radius: 6rpx;
    }

    .meta-value {
        color: #6366f1;
        font-weight: 500;
    }
}

.empty {
    padding: 200rpx 0;
}

.page-loader {
    position: fixed;
    inset: 0;
    background: rgba(245, 247, 255, 0.6);
    display: flex;
    align-items: center;
    justify-content: center;
    z-index: 99;
}
</style>
