<template>
    <ParentPage active="home">
        <view class="profile">
            <image class="avatar" :src="parentAvatarUrl" mode="aspectFill" />
            <view class="profile-main">
                <view class="name-row">
                    <text class="child-name">{{ activeChild.name }}家长</text>
                    <text class="vip-tag">家长会员</text>
                </view>
                <text class="school ellipsis">{{ activeChild.school }} · {{ activeChild.className }}</text>
                <text class="exam-no">考号：{{ activeChild.examNo }}</text>
            </view>
        </view>

        <view class="grade-card">
            <ParentCard>
                <view v-if="weeklyLoading" class="weekly-loading">
                    <xy-Empty type="loading" content="加载中..." />
                </view>
                <template v-else>
                    <view v-for="band in gradeBands" :key="band.level" class="band-row">
                        <view class="band-badge" :class="band.level">{{ band.label.slice(0, 2) }}</view>
                        <view v-if="band.subjects.length" class="subject-list">
                            <view v-for="item in band.subjects" :key="`${band.level}-${item.subject}`" class="subject-chip">
                                <text>{{ item.subject }}</text>
                                <text v-if="trendLabel(item)" class="trend" :class="item.status">{{ trendLabel(item) }}</text>
                            </view>
                        </view>
                        <text v-else class="empty-text">暂无需要关注的学科</text>
                    </view>
                </template>
            </ParentCard>
        </view>

        <!-- <view class="member-card">
            <ParentCard clickable @click="showComingSoon('家长会员')">
                <view class="member-tag">家长会员</view>
                <view class="member-main">
                    <view>
                        <text class="member-title">心理关怀 · 习惯规划 · 深度学情</text>
                        <text class="member-desc">不只看分数，陪孩子建立稳定学习节奏。</text>
                    </view>
                    <text class="member-arrow">查看</text>
                </view>
            </ParentCard>
        </view> -->

        <!-- <view class="read-card">
            <ParentCard title="本周家长必读" subtitle="系统按孩子最近表现生成关注建议">
                <text class="read-text">数学周练后情绪略低，建议先肯定一次认真订正，再安排一条免费话术在「家长关怀」里。</text>
                <view class="read-link" @click="showComingSoon('家长关怀')">进入家长关怀中心</view>
            </ParentCard>
        </view> -->

        <view class="quick-grid">
            <ParentCard v-for="item in quickActions" :key="item.title" class="quick-card" clickable @click="handleQuickAction(item)">
                <view class="quick-icon" :class="item.tone">{{ item.title.slice(0, 1) }}</view>
                <text class="quick-title">{{ item.title }}</text>
                <text class="quick-desc">{{ item.desc }}</text>
            </ParentCard>
        </view>
    </ParentPage>
</template>

<script setup lang="ts">
import { computed, ref } from 'vue';
import { onShow } from '@dcloudio/uni-app';
import { storeToRefs } from 'pinia';
import { getWeeklySubject, type WeeklySubjectLevel } from '@/api/parent';
import { useParentStore } from '@/state/modules/parent';
import { useUserStore } from '@/state/modules/user';
import ParentCard from '../components/ParentCard.vue';
import ParentPage from '../components/ParentPage.vue';
import { quickActions, type GradeBand, type QuickAction, type SubjectTrend } from '../utils/data';

const DEFAULT_AVATAR = 'https://xxl-1313840333.cos.ap-guangzhou.myqcloud.com/urm/logo.png';

const LEVEL_BAND_DEFAULTS: GradeBand[] = [
    { label: '优势保持', level: 'excellent', subjects: [] },
    { label: '良好巩固', level: 'good', subjects: [] },
    { label: '重点提升', level: 'middle', subjects: [] },
    { label: '及时补弱', level: 'weak', subjects: [] },
];

const LEVEL_CLASS_MAP: Record<number, GradeBand['level']> = {
    1: 'excellent',
    2: 'good',
    3: 'middle',
    4: 'weak',
};

const userStore = useUserStore();
const parentStore = useParentStore();
const { userInfo } = storeToRefs(userStore);
const { activeChild } = storeToRefs(parentStore);
const parentAvatarUrl = computed(() => userInfo.value.avatarUrl || DEFAULT_AVATAR);

const gradeBands = ref<GradeBand[]>(LEVEL_BAND_DEFAULTS.map((item) => ({ ...item, subjects: [] })));
const weeklyLoading = ref(false);

const createEmptyGradeBands = () =>
    LEVEL_BAND_DEFAULTS.map((item) => ({
        ...item,
        subjects: [] as SubjectTrend[],
    }));

const mapTrendStatus = (trendCode?: string): SubjectTrend['status'] => {
    if (trendCode === 'PROGRESS') return 'up';
    if (trendCode === 'REGRESSION') return 'down';
    if (trendCode === 'STABLE') return 'stable';
    if (trendCode === 'NO_COMPARE') return 'none';
    return undefined;
};

const mapLevelsToBands = (levels?: WeeklySubjectLevel[]): GradeBand[] => {
    const byCode = new Map((levels || []).map((item) => [item.levelCode, item]));
    return LEVEL_BAND_DEFAULTS.map((fallback, index) => {
        const levelCode = index + 1;
        const apiLevel = byCode.get(levelCode);
        return {
            label: apiLevel?.levelName || fallback.label,
            level: LEVEL_CLASS_MAP[levelCode] || fallback.level,
            subjects: (apiLevel?.subjects || [])
                .filter((item) => item.subjectName)
                .map((item) => {
                    const status = mapTrendStatus(item.trendCode);
                    return {
                        subject: item.subjectName || '',
                        status,
                        trendName: item.trendName,
                    };
                }),
        };
    });
};

const fetchWeeklySubject = async () => {
    const userId = activeChild.value.id;
    if (!userId) {
        gradeBands.value = createEmptyGradeBands();
        return;
    }

    weeklyLoading.value = true;
    try {
        const res = await getWeeklySubject({ userId });
        gradeBands.value = mapLevelsToBands(res.data?.levels);
    } catch (err) {
        console.error('[parent-home] weeklySubject error', err);
        gradeBands.value = createEmptyGradeBands();
    } finally {
        weeklyLoading.value = false;
    }
};

onShow(async () => {
    try {
        if (!userInfo.value.id) {
            await userStore.fetchParentUserInfo();
        }
        await parentStore.fetchBindChildren(userInfo.value.id);
        await fetchWeeklySubject();
    } catch {
        /* ignore */
    }
});

const trendLabel = (item: SubjectTrend) => {
    if (item.trendName) return item.trendName;
    const map: Record<NonNullable<SubjectTrend['status']>, string> = {
        up: '进步',
        down: '退步',
        stable: '持平',
        none: '',
    };
    return item.status ? map[item.status] : '';
};

const showComingSoon = (name: string) => {
    uni.showToast({
        title: `${name}建设中`,
        icon: 'none',
    });
};

const handleQuickAction = (item: QuickAction) => {
    if (item.title === '学情追踪') {
        uni.navigateTo({ url: '/pages/parent/analysis/index' });
        return;
    }
    if (item.title === '错题练习') {
        uni.navigateTo({ url: '/pages/wrong/index' });
        return;
    }
    showComingSoon(item.title);
};
</script>

<style lang="scss" scoped>
.profile {
    display: flex;
    align-items: center;
    gap: 22rpx;
    padding: 30rpx 6rpx 18rpx;
}

.avatar {
    width: 108rpx;
    height: 108rpx;
    border-radius: 36rpx;
    flex-shrink: 0;
    background: #ecfeff;
    box-shadow: 0 12rpx 28rpx rgba(8, 145, 178, 0.24);
}

.profile-main {
    flex: 1;
    min-width: 0;
}

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

.child-name {
    color: #164e63;
    font-size: 38rpx;
    font-weight: 900;
}

.vip-tag,
.member-tag {
    display: inline-flex;
    align-items: center;
    padding: 6rpx 14rpx;
    border-radius: 999rpx;
    color: #92400e;
    background: #fef3c7;
    font-size: 22rpx;
    font-weight: 800;
}

.school,
.exam-no {
    display: block;
    margin-top: 6rpx;
    color: #64748b;
    font-size: 24rpx;
}

.grade-card,
.member-card,
.read-card {
    margin-top: 40rpx;
}

.band-row {
    display: flex;
    align-items: center;
    gap: 18rpx;
    min-height: 70rpx;
}

.band-row + .band-row {
    margin-top: 18rpx;
}

.band-badge {
    width: 58rpx;
    height: 58rpx;
    border-radius: 22rpx;
    display: flex;
    align-items: center;
    justify-content: center;
    color: #ffffff;
    font-size: 22rpx;
    font-weight: 900;

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

.subject-list {
    display: flex;
    flex-wrap: wrap;
    gap: 12rpx;
}

.subject-chip {
    display: flex;
    align-items: center;
    gap: 8rpx;
    padding: 10rpx 16rpx;
    border-radius: 999rpx;
    color: #164e63;
    background: #f8fafc;
    font-size: 24rpx;
    font-weight: 700;
}

.trend {
    padding: 2rpx 8rpx;
    border-radius: 999rpx;
    color: #ffffff;
    font-size: 18rpx;

    &.up { background: #22c55e; }
    &.down { background: #f43f5e; }
    &.stable { background: #0891b2; }
    &.none { background: #94a3b8; }
}

.weekly-loading {
    padding: 24rpx 0;
}

.empty-text {
    color: #94a3b8;
    font-size: 24rpx;
}

.member-card {
    background: linear-gradient(135deg, rgba(255, 255, 255, 0.94), rgba(236, 254, 255, 0.94));
}

.member-main {
    display: flex;
    align-items: center;
    justify-content: space-between;
    gap: 20rpx;
    margin-top: 20rpx;
}

.member-title {
    display: block;
    color: #164e63;
    font-size: 30rpx;
    font-weight: 900;
}

.member-desc,
.read-text {
    display: block;
    margin-top: 8rpx;
    color: #64748b;
    font-size: 24rpx;
    line-height: 1.6;
}

.member-arrow,
.read-link {
    color: #0891b2;
    font-size: 24rpx;
    font-weight: 800;
}

.read-link {
    margin-top: 20rpx;
}

.quick-grid {
    display: grid;
    grid-template-columns: repeat(3, 1fr);
    gap: 18rpx;
    margin-top: 40rpx;
}

.quick-card {
    padding: 24rpx 14rpx;
    text-align: center;
}

.quick-icon {
    width: 72rpx;
    height: 72rpx;
    margin: 0 auto 14rpx;
    border-radius: 26rpx;
    display: flex;
    align-items: center;
    justify-content: center;
    color: #ffffff;
    font-size: 30rpx;
    font-weight: 900;

    &.cyan { background: #22d3ee; }
    &.green { background: #22c55e; }
    &.orange { background: #f59e0b; }
}

.quick-title {
    display: block;
    color: #164e63;
    font-size: 26rpx;
    font-weight: 900;
}

.quick-desc {
    display: block;
    margin-top: 6rpx;
    color: #64748b;
    font-size: 20rpx;
}
</style>
