taskHomePage.vue 16.3 KB
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448
<!--
 * @Date: 2025-11-19 21:00:00
 * @LastEditors: hookehuyr hookehuyr@gmail.com
 * @LastEditTime: 2025-12-02 22:28:25
 * @FilePath: /mlaj/src/views/teacher/taskHomePage.vue
 * @Description: 教师端作业主页(头部介绍、统计、日历与学生完成情况;数据Mock)
-->
<template>
    <div class="TaskHomePage">
        <!-- 头部卡片:名称、介绍、细项(参考图片1结构) -->
        <div class="headCard bg-white rounded-lg shadow px-4 py-4">
            <div class="title text-2xl font-bold text-gray-900 mb-2">{{ task_title }}</div>
            <div class="intro text-base text-gray-700 leading-relaxed mb-3" v-html="task_intro"></div>
            <!-- 三图展示(可选),使用CDN示例地址并加压缩参数 -->
            <!-- <div class="images grid grid-cols-3 gap-3 mb-3">
                <img v-for="(img, idx) in task_images" :key="idx" :src="img"
                    class="rounded-md object-cover w-full h-24" />
            </div> -->
            <div class="details text-sm text-gray-600">
                <div class="detailItem">周期:{{ task_details.cycle }}</div>
                <div class="detailItem">频次:{{ task_details.frequency }}</div>
                <div class="detailItem">时间段:{{ task_details.time_range }}</div>
                <div class="detailItem">附件类型:{{ task_details.attachment_type }}</div>
            </div>
        </div>

        <!-- 统计数据(参考 myClassPage.vue 出勤率/任务完成) -->
        <div class="statsCard bg-white rounded-lg shadow px-4 py-4 mt-4">
            <van-row gutter="16">
                <!-- 出勤率 -->
                <!-- <van-col span="12">
                    <div class="text-center">
                        <div class="relative w-16 h-16 mx-auto mb-2">
                            <van-circle v-model:current-rate="checkin_count" :rate="checkin_count" :text="checkin_text"
                                stroke-width="100" color="#10b981" size="64" layer-color="#eee" />
                        </div>
                        <div class="text-sm text-gray-600">出勤率</div>
                    </div>
                </van-col> -->
                <!-- 任务完成 -->
                <van-col span="12">
                    <div class="text-center">
                        <div class="relative w-16 h-16 mx-auto mb-2">
                            <van-circle v-model:current-rate="upload_count" :rate="upload_count" :text="upload_text"
                                stroke-width="100" color="#3b82f6" size="64" layer-color="#eee" />
                        </div>
                        <div class="text-sm text-gray-600">任务完成</div>
                    </div>
                </van-col>
            </van-row>
        </div>

        <!-- 日历:选择日期后展示该日期的学生完成情况 -->
        <div class="calendarCard bg-white rounded-lg shadow px-4 py-4 mt-4">
            <div class="text-base font-semibold text-gray-800 mb-2">选择日期</div>
            <!-- 快捷方式:今日 / 昨日 / 某个日期(弹出日历) -->
            <div class="QuickDateRow flex items-center gap-3">
                <div class="quickChip inline-flex items-center rounded-full px-3 py-1 text-sm font-medium cursor-pointer"
                    :class="selected_mode === 'today' ? 'bg-green-500 text-white border border-green-500 hover:bg-green-600' : 'bg-white text-gray-700 border border-gray-300 hover:bg-gray-50'"
                    @click="select_today">
                    <!-- <van-icon v-if="selected_mode === 'today'" name="success" size="14" class="mr-1" /> -->
                    今日
                </div>
                <div class="quickChip inline-flex items-center rounded-full px-3 py-1 text-sm font-medium cursor-pointer"
                    :class="selected_mode === 'yesterday' ? 'bg-green-500 text-white border border-green-500 hover:bg-green-600' : 'bg-white text-gray-700 border border-gray-300 hover:bg-gray-50'"
                    @click="select_yesterday">
                    <!-- <van-icon v-if="selected_mode === 'yesterday'" name="success" size="14" class="mr-1" /> -->
                    昨日
                </div>
                <div class="quickChip inline-flex items-center rounded-full px-3 py-1 text-sm font-medium cursor-pointer"
                    :class="selected_mode === 'specific' ? 'bg-green-500 text-white border border-green-500 hover:bg-green-600' : 'bg-white text-gray-700 border border-gray-300 hover:bg-gray-50'"
                    @click="open_specific_date_picker">
                    <!-- <van-icon v-if="selected_mode === 'specific'" name="success" size="14" class="mr-1" /> -->
                    {{ specific_label }}
                </div>
            </div>
            <!-- 选中日期展示 -->
            <!-- <div class="mt-3 text-sm text-gray-600">当前选择:{{ current_date_text }}</div> -->
            <!-- 日历弹窗:点击“某个日期”弹出 -->
            <van-config-provider :theme-vars="themeVars">
                <van-calendar v-model:show="show_calendar_popup" :default-date="calendar_default_date" color="#10b981"
                :show-confirm="true" switch-mode="month" :formatter="formatter" @confirm="on_date_select" />
            </van-config-provider>
        </div>

        <!-- 学生完成情况(参考图片2样式) -->
        <div class="studentsCard bg-white rounded-lg shadow px-4 py-4 mt-4">
            <div class="flex items-center justify-between mb-3">
                <div class="text-base font-semibold text-gray-800">完成情况({{ completed_count }}/{{ user_list.length }})
                </div>
                <!-- <div class="text-xs text-gray-500">当前日期:{{ current_date_text }}</div> -->
                <div class="text-xs text-gray-500">点击查看作业记录</div>
            </div>
            <div class="grid grid-cols-5 gap-3 StudentsGrid">
                <div v-for="(stu, idx) in students_status" :key="stu.id"
                    class="studentItem relative rounded-md h-16 flex flex-col items-center justify-center text-center border overflow-hidden"
                    :class="stu.completed ? 'bg-white border-green-500 text-green-600' : 'bg-gray-100 border-gray-300 text-gray-500'"
                    @click="go_student_record(stu)">
                    <div class="text-[10px] font-bold opacity-60 mb-0.5">{{ idx + 1 }}</div>
                    <div class="text-xs font-medium leading-tight break-words line-clamp-2 px-1">{{ stu.name }}</div>
                    <img v-if="stu.completed" :src="checkCorner" alt="checked" class="cornerIcon" />
                </div>
            </div>
        </div>
    </div>
</template>

<script setup>
import { ref, computed, onMounted, watch } from 'vue'
import { useRoute, useRouter } from 'vue-router'
import { useTitle } from '@vueuse/core'
import checkCorner from '@/assets/images/dui.png'
import { getTeacherTaskDetailAPI } from '@/api/teacher'

const $route = useRoute()
const $router = useRouter()
useTitle('作业主页')

const themeVars = {
    calendarPopupHeight: '60%',
}

// 弹窗显示状态:是否展示“某个日期”选择日历
const show_calendar_popup = ref(false)
// Calendar 默认选中日期(为 null 时不预选)
const calendar_default_date = ref(null)
// 快捷项当前选中模式:today | yesterday | specific
const selected_mode = ref('today')
// 特定日期按钮的文字展示,选择后替换为实际日期
const specific_label = ref('特定日期')

/**
 * 选择“今日”,设置为今日日期,并触发查询逻辑
 * @returns {void}
 */
function select_today() {
    const now = new Date()
    selected_date.value = format_date(now)
    selected_mode.value = 'today'
    specific_label.value = '特定日期'
    // 清空弹窗内 Calendar 的默认选中状态
    calendar_default_date.value = null
}

/**
 * 选择“昨日”,设置为昨日日期,并触发查询逻辑
 * @returns {void}
 */
function select_yesterday() {
    const y = new Date(Date.now() - 24 * 60 * 60 * 1000)
    selected_date.value = format_date(y)
    selected_mode.value = 'yesterday'
    specific_label.value = '特定日期'
    // 清空弹窗内 Calendar 的默认选中状态
    calendar_default_date.value = null
}

/**
 * 日历日期格式化函数
 * @param {Object} day - 日历天对象
 * @returns {Object} 处理后的日历天对象
 */
const formatter = (day) => {
    const dateStr = format_date(day.date)
    const today = new Date()
    const todayStr = format_date(today)

    const yesterday = new Date(today)
    yesterday.setDate(today.getDate() - 1)
    const yesterdayStr = format_date(yesterday)

    if (dateStr === todayStr) {
        day.className = 'calendar-today';
        day.bottomInfo = '今日'
    } else if (dateStr === yesterdayStr) {
        day.className = 'calendar-yesterday';
        day.bottomInfo = '昨日'
    }

    return day
}

/**
 * 打开“某个日期”选择器弹窗
 * @returns {void}
 */
function open_specific_date_picker() {
    show_calendar_popup.value = true
}

//
// API 数据状态
//
const task_id = $route.params.id || '0'
const task_title = ref('')
const task_intro = ref('')
// 图片暂时保留 Mock 或从 API 扩展字段获取(当前 API 未返回图片列表,暂时保留为空或 Mock)
const task_images = ref([
    'https://cdn.ipadbiz.cn/mlaj/demo-task-1.png?imageMogr2/thumbnail/200x/strip/quality/70',
    'https://cdn.ipadbiz.cn/mlaj/demo-task-2.png?imageMogr2/thumbnail/200x/strip/quality/70',
    'https://cdn.ipadbiz.cn/mlaj/demo-task-3.png?imageMogr2/thumbnail/200x/strip/quality/70'
])
const task_details = ref({
    cycle: '',
    frequency: '',
    time_range: '',
    attachment_type: ''
})

//
// 统计数据
//
const checkin_count = ref(0)
const upload_count = ref(0)
const checkin_text = computed(() => `${checkin_count.value}%`)
const upload_text = computed(() => `${upload_count.value}%`)

//
// 学生与完成记录
//
const today = new Date()
const selected_date = ref(format_date(today))
const user_list = ref([])

/**
 * 获取作业详情和学生完成情况
 */
async function fetchData() {
    try {
        const res = await getTeacherTaskDetailAPI({
            id: task_id,
            date: selected_date.value
        })

        if (res.code) {
            task_title.value = res.data.title
            task_intro.value = res.data.note

            // 格式化周期显示
            const cycleMap = {
                '0': '本周期',
                '30': '每月',
                '7': '每周',
                '1': '每日' // 假设 1 代表每日
            }
            // 如果后端返回的是数字字符串,尝试映射,否则直接显示
            const cycleText = cycleMap[res.data.cycle] || res.data.cycle || '每日'

            // 格式化附件类型
            let attachmentText = '文本'
            if (Array.isArray(res.data.attachment_type)) {
                const typeMap = {
                    'text': '文本',
                    'image': '图片',
                    'video': '视频',
                    'audio': '音频'
                }
                attachmentText = res.data.attachment_type.map(t => typeMap[t] || t).join('/')
            } else if (res.data.attachment_type) {
                attachmentText = res.data.attachment_type
            }

            task_details.value = {
                cycle: cycleText,
                frequency: `每周期${res.data.frequency || 1}次`,
                time_range: `${res.data.begin_date || '00:00'} ~ ${res.data.end_date || '23:59'}`, // 注意:API返回的begin_date/end_date可能是日期也可能是时间,这里暂且直接展示
                attachment_type: attachmentText
            }

            user_list.value = res.data.user_list || []

            // 计算完成率
            if (res.data.need_commit_count > 0) {
                upload_count.value = Math.round((res.data.real_commit_count / res.data.need_commit_count) * 100)
            } else {
                upload_count.value = 0
            }
        } else {
            $router.push('/teacher/tasks')
        }
    } catch (error) {
        console.error('Failed to fetch task details:', error)
    }
}

// 监听日期变化,重新获取数据
watch(selected_date, () => {
    fetchData()
})

onMounted(() => {
    fetchData()
})

/**
 * 将日期对象格式化为 YYYY-MM-DD
 * @param {Date} d - 日期对象
 * @returns {string} 格式化后的日期字符串
 * 注释:补零并返回标准格式,便于与完成记录匹配。
 */
function format_date(d) {
    const y = d.getFullYear()
    const m = String(d.getMonth() + 1).padStart(2, '0')
    const day = String(d.getDate()).padStart(2, '0')
    return `${y}-${m}-${day}`
}

/**
 * 处理日历选择事件
 * @param {any} date - 选中的日期对象
 * @returns {void}
 * 注释:更新选中日期,并联动学生完成情况。
 */
/**
 * 字符串转日期对象(YYYY-MM-DD -> Date)
 * @param {string} s - 日期字符串
 * @returns {Date} 日期对象
 */
function parse_date_text(s) {
    const parts = String(s).split('-')
    const y = Number(parts[0]) || new Date().getFullYear()
    const m = Number(parts[1]) || (new Date().getMonth() + 1)
    const d = Number(parts[2]) || new Date().getDate()
    return new Date(y, m - 1, d)
}

/**
 * 处理日历选择事件(兼容字符串与Date对象)
 * @param {string|Date} val - 选中的日期
 * @returns {void}
 */
function on_date_select(val) {
    const is_date_obj = val instanceof Date
    const text = is_date_obj ? format_date(val) : String(val)
    selected_date.value = text
    show_calendar_popup.value = false
    selected_mode.value = 'specific'
    specific_label.value = text
    // 将所选日期作为下次弹窗的默认选中
    calendar_default_date.value = is_date_obj ? val : parse_date_text(text)
}

/**
 * 计算某日期下学生完成情况列表
 * @returns {{id:string,name:string,completed:boolean}[]} 学生状态列表
 */
const students_status = computed(() => {
    return user_list.value.map(stu => ({
        id: stu.id,
        name: stu.name || '未命名',
        completed: !!stu.is_commit,
        avatar: stu.avatar // 保留头像字段以便将来使用
    }))
})

/**
 * 完成人数统计文案
 * @returns {number} 完成人数
 */
const completed_count = computed(() => students_status.value.filter(s => s.completed).length)

/**
 * 当前日期的展示文本
 * @returns {string} 文本
 */
const current_date_text = computed(() => selected_date.value)

/**
 * 跳转至学员作业记录页面(固定ID的示例页面)
 * @param {{id:string,name:string,completed:boolean}} stu - 学员对象
 * @returns {void}
 */
function go_student_record(stu) {
    // 跳转到固定ID的作业记录页面,当前版本不使用传入ID
    $router.push({ name: 'StudentRecord', query: { created_by: stu.id, date: selected_date.value } })
}
</script>

<style lang="less" scoped>
.TaskHomePage {
    min-height: 100vh;
    background: linear-gradient(to bottom right, #f0fdf4, #f0fdfa, #eff6ff);
    padding: 1rem;
    padding-bottom: 6rem;

    .headCard {
        .title {
            line-height: 1.3;
        }

        .intro {
            color: #374151;
        }

        .details {
            border-left: 0.15rem solid #10b981;
            padding-left: 0.75rem;

            .detailItem {
                margin-bottom: 0.25rem;
            }
        }
    }

    .studentsCard {

        // 兜底:强制学生列表为5列栅格,避免一行仅1个的问题
        .StudentsGrid {
            display: grid;
            grid-template-columns: repeat(5, 1fr);
            gap: 0.75rem; // 等同于 tailwind 的 gap-3
        }

        .grid>div {
            transition: all 0.2s ease-in-out;
        }

        .studentItem {
            min-height: 4rem;
            // 卡片圆角裁切,配合右上角图片效果
            overflow: hidden;
        }

        .cornerIcon {
            // 右上角图片样式(对勾角标),贴边显示
            position: absolute;
            top: -1px;
            right: -1px;
            width: 18px;
            height: 18px;
        }
    }

    .calendarCard {
        .QuickDateRow {
            margin-top: 0.25rem;

            .quickChip {
                transition: all 0.2s ease-in-out;

                &:active {
                    opacity: 0.85;
                }
            }
        }
    }
}
</style>