<template>
    <view class="hw-page">
        <!-- 顶部装饰 -->
        <view class="bg-decor bg-decor-a"></view>
        <view class="bg-decor bg-decor-b"></view>

        <!-- 主体 -->
        <scroll-view class="hw-scroll" scroll-y :show-scrollbar="false" :enhanced="true">
            <!-- 学科tab组 -->
            <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 subjectList"
                            :key="item.id"
                            :class="['subject-tab', { active: activeSubjectId === item.id }]"
                            @click="onSelectSubject(item)"
                        >
                            <view class="subject-emoji">{{ getSubjectEmoji(item.name) }}</view>
                            <view class="subject-name">{{ item.name }}</view>
                            <view class="subject-count">{{ getSubjectCount(item.id) }}</view>
                            <view v-if="item.warning" class="subject-dot"></view>
                        </view>
                    </view>
                </scroll-view>
            </view>

            <!-- 头部统计卡片 -->
            <view v-if="totalCount > 0" class="stats-card">
                <view class="stats-bg"></view>
                <view class="stats-content">
                    <view class="stats-left">
                        <view class="stats-number">{{ totalCount }}</view>
                        <view class="stats-label">份待完成作业</view>
                    </view>
                    <view class="stats-right">
                        <view class="stats-illu">
                            <svg viewBox="0 0 80 80" fill="none">
                                <rect x="14" y="10" width="48" height="60" rx="6"
                                    fill="#FFFFFF" stroke="#312E81" stroke-width="2" />
                                <rect x="22" y="20" width="32" height="3" rx="1.5" fill="#22C55E" />
                                <rect x="22" y="30" width="24" height="3" rx="1.5" fill="#94A3B8" />
                                <rect x="22" y="38" width="28" height="3" rx="1.5" fill="#94A3B8" />
                                <rect x="22" y="46" width="20" height="3" rx="1.5" fill="#94A3B8" />
                                <circle cx="55" cy="58" r="10" fill="#22C55E" stroke="#312E81" stroke-width="2" />
                                <path d="m51 58 3 3 6-6" stroke="#FFFFFF" stroke-width="2.4"
                                    stroke-linecap="round" stroke-linejoin="round" />
                            </svg>
                        </view>
                    </view>
                </view>
            </view>

            <!-- 作业列表 -->
            <view v-if="paperList.length" class="paper-list">
                <view
                    v-for="paper in paperList"
                    :key="paper.id"
                    class="paper-card"
                    @click="onStartPaper(paper)"
                >
                    <!-- 顶部标签 -->
                    <view class="paper-head">
                        <view :class="['paper-status', paper.costTime ? 'continue' : 'new']">
                            <view class="status-dot"></view>
                            <text>{{ paper.costTime ? '继续答题' : '未开始' }}</text>
                        </view>
                        <view class="paper-deadline">
                            <text class="deadline-label">截止</text>
                            <text class="deadline-time">{{ formatDeadline(paper.endTime) }}</text>
                        </view>
                    </view>

                    <!-- 标题 -->
                    <view class="paper-title">{{ paper.paperName }}</view>

                    <!-- 备注 -->
                    <view v-if="paper.remark" class="paper-remark">
                        <view class="remark-icon">
                            <svg viewBox="0 0 16 16" fill="none">
                                <path d="M2 4h12M2 8h12M2 12h8" stroke="#94A3B8"
                                    stroke-width="1.6" stroke-linecap="round" />
                            </svg>
                        </view>
                        <text>{{ paper.remark }}</text>
                    </view>

                    <!-- 底部信息 -->
                    <view class="paper-meta">
                        <view class="meta-item">
                            <view class="meta-avatar">
                                <text>{{ (paper.publisherName || '师').charAt(0) }}</text>
                            </view>
                            <text class="meta-text">{{ paper.publisherName || '老师' }}</text>
                        </view>
                        <view class="meta-spacer"></view>
                        <view class="meta-time">
                            <svg viewBox="0 0 16 16" fill="none">
                                <circle cx="8" cy="8" r="6" stroke="#94A3B8" stroke-width="1.4" />
                                <path d="M8 5v3l2 1" stroke="#94A3B8" stroke-width="1.4" stroke-linecap="round" />
                            </svg>
                            <text>{{ formatTime(paper.createTime) }}</text>
                        </view>
                    </view>

                    <!-- CTA 按钮 -->
                    <view :class="['paper-cta', paper.costTime ? 'continue' : 'start']">
                        <text>{{ paper.costTime ? '继续答题' : '开始答题' }}</text>
                        <view class="cta-arrow">
                            <svg viewBox="0 0 16 16" fill="none">
                                <path d="m6 4 4 4-4 4" stroke="#FFFFFF" stroke-width="2"
                                    stroke-linecap="round" stroke-linejoin="round" />
                            </svg>
                        </view>
                    </view>
                </view>
            </view>

            <!-- 空状态 -->
            <Empty
                v-else-if="!pageLoading && !paperList.length && subjectList.length"
                class="empty"
                type="task"
                content="该科目暂无待完成作业"
            />

            <!-- 整页空状态 -->
            <Empty
                v-else-if="!pageLoading && !subjectList.length"
                class="empty empty-page"
                type="task"
                content="还没有作业哦～"
            />

            <!-- 底部留白 -->
            <view style="height: 60rpx"></view>
        </scroll-view>

        <!-- 加载状态 -->
        <view v-if="pageLoading" 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 { getUnfinishedHomework, type PaperRecord } from '@/api/homework';
import { resource_type_homework } from '@/constants/doWork';
import { formatTime } from '@/utils/format';
import { getWxOpenid } from '@/utils/wxOpenid';

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

const pageLoading = ref(false);
const startingPaper = ref(false);
const subjectList = ref<SubjectItem[]>([]);
const subjectPaperMap = ref(new Map<string, PaperRecord[]>());
const activeSubjectId = ref('');

const paperList = computed<PaperRecord[]>(() => {
    if (!activeSubjectId.value) return [];
    return subjectPaperMap.value.get(activeSubjectId.value) || [];
});

const totalCount = computed(() => {
    let count = 0;
    subjectPaperMap.value.forEach((list) => {
        count += list.length;
    });
    return count;
});

const getSubjectCount = (id: string) => subjectPaperMap.value.get(id)?.length || 0;

/** 学科emoji映射 */
const getSubjectEmoji = (name: string) => {
    if (!name) return '📘';
    if (name.includes('语文') || name.includes('国学')) return '📖';
    if (name.includes('数学') || name.includes('算')) return '🧮';
    if (name.includes('英语') || 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('政治') || name.includes('道德')) return '⚖️';
    if (name.includes('音乐')) return '🎵';
    if (name.includes('美术') || name.includes('画')) return '🎨';
    if (name.includes('体育')) return '⚽';
    if (name.includes('科学')) return '🧪';
    if (name.includes('信息') || name.includes('计算机')) return '💻';
    return '📘';
};

/** 截止时间友好格式 */
const formatDeadline = (time: string) => {
    if (!time) return '不限';
    const target = new Date(time).getTime();
    const now = Date.now();
    const diff = target - now;
    if (diff < 0) return '已截止';
    const day = Math.floor(diff / 86400000);
    if (day < 1) {
        const hour = Math.floor(diff / 3600000);
        if (hour < 1) return '不足1小时';
        return `${hour}小时后`;
    }
    if (day < 7) return `${day}天后`;
    return formatTime(time, 'MM/DD');
};

const onSelectSubject = (item: SubjectItem) => {
    activeSubjectId.value = item.id;
};

const onStartPaper = async (paper: PaperRecord) => {
    if (startingPaper.value) return;
    startingPaper.value = true;
    uni.showLoading({ title: '准备中...', mask: true });
    try {
        await getWxOpenid();
        uni.navigateTo({
            url: `/pages/doWork/index?resourceType=${resource_type_homework}&recordId=${paper.id}&reportFlag=0&subjectId=${activeSubjectId.value}`,
        });
    } catch (err: any) {
        uni.showToast({ title: err?.message || '获取微信授权失败', icon: 'none' });
    } finally {
        uni.hideLoading();
        startingPaper.value = false;
    }
};

const initData = async () => {
    pageLoading.value = true;
    try {
        const res = await getUnfinishedHomework();
        const records = res.data || [];

        const map = new Map<string, PaperRecord[]>();
        const subjects: SubjectItem[] = [];

        records.forEach((item) => {
            const list = map.get(item.subjectId);
            if (list) {
                list.push(item);
            } else {
                map.set(item.subjectId, [item]);
                subjects.push({
                    id: item.subjectId,
                    name: item.subjectName,
                    warning: true,
                });
            }
        });

        subjectPaperMap.value = map;
        subjectList.value = subjects;

        if (subjects.length && (!activeSubjectId.value || !map.has(activeSubjectId.value))) {
            activeSubjectId.value = subjects[0].id;
        }
    } catch (err) {
        console.error('[homework] init err', err);
    } finally {
        pageLoading.value = false;
    }
};

onMounted(() => {
    initData();
});

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

<style lang="scss" scoped>
.hw-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: -100rpx;
        right: -120rpx;
        width: 360rpx;
        height: 360rpx;
        background: radial-gradient(circle, rgba(129, 140, 248, 0.45), transparent 70%);
    }

    &-b {
        bottom: 200rpx;
        left: -100rpx;
        width: 320rpx;
        height: 320rpx;
        background: radial-gradient(circle, rgba(34, 197, 94, 0.3), transparent 70%);
    }
}

.hw-scroll {
    flex: 1;
    height: 0;
    box-sizing: border-box;
    position: relative;
    z-index: 1;
}

/* 学科 tab */
.subject-bar {
    padding: 24rpx 0 8rpx;
}

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

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

.subject-tab {
    position: relative;
    flex-shrink: 0;
    width: 130rpx;
    padding: 20rpx 12rpx 18rpx;
    background: #ffffff;
    border-radius: 24rpx;
    text-align: center;
    transition: transform 200ms ease;
    box-shadow:
        0 6rpx 16rpx rgba(99, 102, 241, 0.12),
        inset 0 -4rpx 0 rgba(199, 210, 254, 0.5);

    &.active {
        background: linear-gradient(180deg, #818cf8 0%, #4f46e5 100%);
        box-shadow:
            0 10rpx 24rpx rgba(79, 70, 229, 0.45),
            inset 0 -5rpx 0 rgba(0, 0, 0, 0.15);

        .subject-name {
            color: #ffffff;
        }

        .subject-count {
            color: #c7d2fe;
            background: rgba(255, 255, 255, 0.16);
        }
    }

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

.subject-emoji {
    font-size: 44rpx;
    line-height: 1;
    margin-bottom: 8rpx;
}

.subject-name {
    font-size: 24rpx;
    font-weight: 600;
    color: #312e81;
    line-height: 1.2;
}

.subject-count {
    margin-top: 8rpx;
    font-size: 20rpx;
    color: #6366f1;
    font-weight: 500;
    padding: 2rpx 0;
    border-radius: 999rpx;
    background: rgba(199, 210, 254, 0.5);
}

.subject-dot {
    position: absolute;
    top: 12rpx;
    right: 12rpx;
    width: 16rpx;
    height: 16rpx;
    border-radius: 50%;
    background: #ef4444;
    border: 3rpx solid #ffffff;
    box-shadow: 0 0 0 2rpx rgba(239, 68, 68, 0.3);
}

/* 统计卡片 */
.stats-card {
    margin: 24rpx 32rpx 8rpx;
    position: relative;
    border-radius: 32rpx;
    overflow: hidden;
    background: linear-gradient(135deg, #fef3c7 0%, #fde68a 100%);
    box-shadow:
        0 12rpx 24rpx rgba(245, 158, 11, 0.25),
        inset 0 -6rpx 0 rgba(0, 0, 0, 0.05);
}

.stats-bg {
    position: absolute;
    inset: 0;
    background-image:
        radial-gradient(circle at 80% 20%, rgba(255, 255, 255, 0.6), transparent 50%),
        radial-gradient(circle at 20% 80%, rgba(245, 158, 11, 0.2), transparent 60%);
}

.stats-content {
    position: relative;
    display: flex;
    align-items: center;
    padding: 36rpx 36rpx;
}

.stats-left {
    flex: 1;
}

.stats-number {
    font-size: 88rpx;
    font-weight: 800;
    color: #92400e;
    line-height: 1;
    letter-spacing: -2rpx;
}

.stats-label {
    margin-top: 12rpx;
    font-size: 28rpx;
    color: #b45309;
    font-weight: 600;
}

.stats-right {
    width: 160rpx;
    height: 160rpx;
    flex-shrink: 0;

    svg {
        width: 100%;
        height: 100%;
        filter: drop-shadow(0 6rpx 12rpx rgba(146, 64, 14, 0.2));
    }
}

/* 作业列表 */
.paper-list {
    padding: 24rpx 32rpx 24rpx;
    display: flex;
    flex-direction: column;
    gap: 28rpx;
}

.paper-card {
    background: #ffffff;
    border-radius: 36rpx;
    padding: 28rpx;
    box-shadow:
        0 12rpx 28rpx rgba(99, 102, 241, 0.15),
        inset 0 -6rpx 0 rgba(199, 210, 254, 0.5);
    transition: transform 150ms ease;

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

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

.paper-status {
    display: inline-flex;
    align-items: center;
    gap: 8rpx;
    padding: 8rpx 20rpx;
    border-radius: 999rpx;
    font-size: 22rpx;
    font-weight: 600;

    &.new {
        background: #eef2ff;
        color: #4f46e5;

        .status-dot {
            background: #4f46e5;
        }
    }

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

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

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

.paper-deadline {
    display: flex;
    align-items: baseline;
    gap: 8rpx;

    .deadline-label {
        font-size: 22rpx;
        color: #94a3b8;
    }

    .deadline-time {
        font-size: 24rpx;
        font-weight: 700;
        color: #f59e0b;
    }
}

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

.paper-remark {
    display: flex;
    gap: 12rpx;
    padding: 18rpx 20rpx;
    background: #f5f7ff;
    border-radius: 20rpx;
    margin-bottom: 20rpx;

    .remark-icon {
        width: 28rpx;
        height: 28rpx;
        flex-shrink: 0;
        margin-top: 4rpx;

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

    text {
        flex: 1;
        font-size: 26rpx;
        color: #6366f1;
        line-height: 1.5;
        overflow: hidden;
        text-overflow: ellipsis;
        display: -webkit-box;
        -webkit-line-clamp: 2;
        -webkit-box-orient: vertical;
    }
}

.paper-meta {
    display: flex;
    align-items: center;
    margin-bottom: 20rpx;
}

.meta-item {
    display: flex;
    align-items: center;
    gap: 12rpx;
}

.meta-avatar {
    width: 44rpx;
    height: 44rpx;
    border-radius: 14rpx;
    background: linear-gradient(135deg, #818cf8, #4f46e5);
    display: flex;
    align-items: center;
    justify-content: center;
    color: #ffffff;
    font-size: 22rpx;
    font-weight: 700;
    box-shadow: 0 4rpx 8rpx rgba(79, 70, 229, 0.3);
}

.meta-text {
    font-size: 24rpx;
    color: #475569;
    font-weight: 500;
}

.meta-spacer {
    flex: 1;
}

.meta-time {
    display: flex;
    align-items: center;
    gap: 6rpx;

    svg {
        width: 24rpx;
        height: 24rpx;
    }

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

.paper-cta {
    height: 84rpx;
    border-radius: 24rpx;
    display: flex;
    align-items: center;
    justify-content: center;
    gap: 12rpx;
    color: #ffffff;
    font-size: 28rpx;
    font-weight: 700;
    letter-spacing: 4rpx;

    &.start {
        background: linear-gradient(180deg, #818cf8 0%, #4f46e5 100%);
        box-shadow:
            0 8rpx 20rpx rgba(79, 70, 229, 0.35),
            inset 0 -5rpx 0 rgba(0, 0, 0, 0.15);
    }

    &.continue {
        background: linear-gradient(180deg, #4ade80 0%, #16a34a 100%);
        box-shadow:
            0 8rpx 20rpx rgba(22, 163, 74, 0.35),
            inset 0 -5rpx 0 rgba(0, 0, 0, 0.15);
    }
}

.cta-arrow {
    width: 28rpx;
    height: 28rpx;

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

.empty {
    padding: 120rpx 0;
}

.empty-page {
    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>
