studentPage.vue 35.2 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 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173
<!--
 * @Author: hookehuyr hookehuyr@gmail.com
 * @Date: 2025-06-19 17:12:19
 * @LastEditors: hookehuyr hookehuyr@gmail.com
 * @LastEditTime: 2025-10-28 11:13:52
 * @FilePath: /mlaj/src/views/teacher/studentPage.vue
 * @Description: 学生详情页面
-->
<template>
  <van-config-provider :theme-vars="themeVars">
    <div class="bg-gradient-to-br from-green-50 via-green-100/30 to-blue-50/30 min-h-screen">
      <!-- 学生基本信息 -->
      <div class="bg-white p-4">
        <div class="flex items-start mb-4">
          <van-image round width="4rem" height="4rem"
            :src="studentInfo.avatar || 'https://cdn.ipadbiz.cn/mlaj/images/icon_1.jpeg'" fit="cover" class="mr-4" />
          <div class="flex-1">
            <div class="flex items-center mb-2">
              <h2 class="text-xl font-bold text-gray-800 mr-2">{{ studentInfo.name }}</h2>
              <!-- <font-awesome-icon v-if="studentInfo.gender === 'male'" icon="venus" color="#3b82f6" class="mr-2" style="font-size: 0.85rem;" />
              <font-awesome-icon v-else icon="mars" color="#ec4899" class="mr-2" style="font-size: 0.85rem;" /> -->
            </div>
            <div class="flex items-center mb-2">
              <van-icon name="chat-o" size="16" color="#10b981" class="mr-1" />
              <span class="text-sm text-gray-600 mr-4">
                <span class="mr-1" v-for="(item, index) in studentInfo.class_list" :key="index">{{ item.class_name }}</span>
              </span>
              <van-icon name="phone-o" size="16" color="#10b981" class="mr-1" />
              <span class="text-sm text-gray-600">{{ formatPhone(studentInfo.mobile) }}</span>
            </div>
            <!-- 标签 -->
            <div class="flex flex-wrap gap-2">
              <van-tag v-for="grade in studentInfo.grade_list" :key="grade.id" type="success" size="large" plain>
                {{ grade.grade_name }}
              </van-tag>
            </div>
          </div>
        </div>
      </div>

      <!-- 所学课程 -->
      <div class="bg-white mt-2 p-4">
        <div class="flex items-center mb-3">
          <van-icon name="bookmark-o" size="16" color="#10b981" class="mr-2" />
          <span class="text-sm font-medium text-gray-700">所学课程</span>
        </div>
        <div class="flex flex-wrap gap-2">
          <van-tag v-for="course in studentInfo.lesson_list" :key="course.id"
            :type="selectedCourses.includes(course) ? 'primary' : 'default'"
            :color="selectedCourses.includes(course) ? '#10b981' : '#f0f0f0'"
            :text-color="selectedCourses.includes(course) ? '#ffffff' : '#666666'" size="large"
            @click="toggleCourseSelection(course)" class="cursor-pointer transition-all duration-200 hover:opacity-80">
            {{ course.title }}
          </van-tag>
        </div>
      </div>

      <!-- 统计数据 -->
      <div class="mt-2">
        <van-row>
          <!-- 出勤率 -->
          <van-col span="12">
            <div class="bg-white p-4 text-center">
              <div class="relative w-16 h-16 mx-auto mb-2">
                <van-circle v-model:current-rate="checkinCount" :rate="checkinCount"
                  :text="`${checkinCountText}`" stroke-width="70" 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="bg-white p-4 text-center">
              <div class="relative w-16 h-16 mx-auto mb-2">
                <van-circle v-model:current-rate="uploadCount" :rate="uploadCount"
                  :text="`${uploadCountText}`" stroke-width="70" color="#3b82f6" size="64" layer-color="#eee" />
              </div>
              <div class="text-sm text-gray-600">作业完成率</div>
            </div>
          </van-col>
          <!-- 测验成绩 -->
          <!-- <van-col span="8">
            <div class="bg-white p-4 text-center">
              <div class="relative w-16 h-16 mx-auto mb-2">
                <van-circle v-model:current-rate="studentStats.testScore" :rate="studentStats.testScore" :speed="100"
                  :text="`${studentStats.testScore}%`" stroke-width="70" color="#f59e0b" size="64" />
              </div>
              <div class="text-sm text-gray-600">测验成绩</div>
            </div>
          </van-col> -->
        </van-row>
      </div>


      <!-- 使用van-sticky包裹van-tabs实现粘性布局 -->
      <div class="bg-white" style="margin: 1rem;">
        <van-sticky :offset-top="0">
          <van-tabs v-model:active="activeTab" color="#4caf50" animated swipeable @change="handleTabChange">
            <van-tab title="作业记录" name="homework"></van-tab>
            <van-tab title="班主任点评" name="evaluation"></van-tab>
            <van-tab title="打卡统计" name="statistics"></van-tab>
          </van-tabs>
        </van-sticky>
      </div>
      <!-- 功能按钮 -->
      <div v-show="activeTab === 'statistics'" class="mt-4 px-4" style="padding-right: 1.25rem;">
        <!-- 状态筛选 -->
        <div class="flex items-center justify-end mb-4">
          <div @click="showStatusPopup = true" class="flex items-center text-sm text-gray-600 cursor-pointer">
            <span>{{ formatStatus(statusFilter) }}</span>
            <van-icon name="arrow-down" size="14" class="ml-1" />
          </div>
        </div>
      </div>

      <!-- 记录列表 -->
      <van-list v-show="activeTab === 'statistics'" v-model:loading="recordLoading" :finished="recordFinished"
        finished-text="没有更多了" @load="onRecordLoad" class="px-4">
        <div v-for="record in filteredRecords" :key="record.id"
          class="bg-white rounded-lg shadow-sm p-4 mb-3 border border-gray-100">
          <!-- 左右布局:左侧日期时间,右侧状态 -->
          <div class="flex items-center justify-between">
            <!-- 左侧:日期时间 -->
            <div class="flex flex-col">
              <div class="flex items-center mb-1">
                <van-icon name="calendar-o" size="16" color="#10b981" class="mr-2" />
                <span class="text-sm text-gray-600">{{ record.date }}</span>
              </div>
              <div class="flex items-center">
                <van-icon name="clock-o" size="16" color="#3b82f6" class="mr-2" />
                <span class="text-sm text-gray-600">{{ record.time }}</span>
              </div>
            </div>

            <!-- 右侧:状态 -->
            <div class="flex items-center">
              <span v-if="record.status === 'checked'" class="text-green-600 text-sm mr-2">{{ formatStatus(record.status) }}</span>
              <span v-else-if="record.status === 'absence'" class="text-orange-500 text-sm mr-2">{{ formatStatus(record.status) }}</span>
              <span v-else class="text-red-500 text-sm mr-2">{{ formatStatus(record.status) }}</span>

              <van-icon v-if="record.status === 'checked'" name="passed" color="#10b981" size="16" />
              <van-icon v-else-if="record.status === 'absence'" name="warning-o" color="#f59e0b" size="16" />
              <van-icon v-else-if="record.status === 'late'" name="warning-o" color="#f59e0b" size="16" />
              <van-icon v-else name="close" color="#ef4444" size="16" />
            </div>
          </div>
        </div>
      </van-list>

      <!-- 班主任点评列表 -->
      <van-list v-show="activeTab === 'evaluation'" v-model:loading="evaluationLoading" :finished="evaluationFinished"
        finished-text="没有更多了" @load="onEvaluationLoad" class="px-4">
        <div v-for="evaluation in evaluationList" :key="evaluation.id"
          class="bg-white rounded-lg shadow-sm p-4 mb-3 border border-gray-100">
          <!-- 第一行:时间 + 日历图标 + 删除按钮 -->
          <div class="flex items-center justify-between mb-3">
            <div class="flex items-center">
              <van-icon name="calendar-o" size="16" color="#10b981" class="mr-2" />
              <span class="text-sm text-gray-600">{{ dayjs(evaluation.created_time).format('YYYY-MM-DD HH:mm:ss') }}</span>
            </div>
            <van-icon
              name="delete-o"
              size="16"
              color="#ef4444"
              class="cursor-pointer hover:opacity-70"
              @click="deleteEvaluation(evaluation.id)"
            />
          </div>

          <!-- 第二行:点评内容 + 图标 -->
          <div class="flex items-start mb-3">
            <van-icon name="chat-o" size="16" color="#3b82f6" class="mr-2 mt-0.5" />
            <div class="flex-1">
              <p class="text-gray-800 text-sm leading-relaxed">{{ evaluation.note }}</p>
            </div>
          </div>

          <!-- 第三行:点评分数 + rate评分组件 -->
          <div class="flex items-center">
            <van-icon name="star-o" size="16" color="#f59e0b" class="mr-2" />
            <span class="text-sm text-gray-600 mr-3">评分:</span>
            <van-rate v-model="evaluation.score" :size="16" color="#ffd21e" void-color="#eee" readonly />
          </div>
        </div>
      </van-list>

      <!--作业记录 -->
      <van-list v-show="activeTab === 'homework' && checkinDataList.length" v-model:loading="loading"
        :finished="finished" finished-text="没有更多了" @load="onLoad" class="space-y-4 px-4">
        <div class="post-card shadow-md" v-for="post in checkinDataList" :key="post.id">
          <div class="post-header">
            <van-row>
              <van-col span="4">
                <van-image round width="2.5rem" height="2.5rem"
                  :src="post.user.avatar || 'https://cdn.ipadbiz.cn/mlaj/images/icon_1.jpeg'" fit="cover" />
              </van-col>
              <van-col span="17">
                <div class="user-info">
                  <div class="username">{{ post.user.name }}</div>
                  <div class="post-time">{{ post.user.time }}</div>
                </div>
              </van-col>
              <van-col span="3">
              </van-col>
            </van-row>
          </div>
          <div class="post-content">
            <div class="post-text">{{ post.content }}</div>
            <div class="post-media">
              <div v-if="post.images.length" class="post-images">
                <van-image width="30%" fit="cover" v-for="(image, index) in post.images" :key="index" :src="image"
                  radius="5" @click="openImagePreview(index, post)" />
              </div>
              <van-image-preview v-if="currentPost" v-model:show="showImagePreview" :images="currentPost.images"
                :start-position="startPosition" :show-index="true" @change="onChange" />
              <div v-for="(v, idx) in post.videoList" :key="idx">
                <!-- 视频封面和播放按钮 -->
                <div v-if="v.video && !v.isPlaying" class="relative w-full rounded-lg overflow-hidden"
                  style="aspect-ratio: 16/9; margin-bottom: 1rem;">
                  <img :src="v.videoCover || 'https://cdn.ipadbiz.cn/mlaj/images/cover_video_2.png'" :alt="v.content"
                    class="w-full h-full object-cover" />
                  <div class="absolute inset-0 flex items-center justify-center cursor-pointer bg-black/20"
                    @click="startPlay(v)">
                    <div
                      class="w-16 h-16 rounded-full bg-black/50 flex items-center justify-center hover:bg-black/70 transition-colors">
                      <van-icon name="play-circle-o" class="text-white" size="40" />
                    </div>
                  </div>
                </div>
                <!-- 视频播放器 -->
                <VideoPlayer v-if="v.video && v.isPlaying" :video-url="v.video"
                  class="post-video rounded-lg overflow-hidden" :ref="el => {
                    if (el) {
                      // 确保不重复添加
                      if (!videoPlayers?.includes(el)) {
                        videoPlayers?.push(el);
                      }
                    }
                  }" @onPlay="handleVideoPlay(player, post)" @onPause="handleVideoPause(post)" />
              </div>
              <AudioPlayer v-if="post.audio.length" :songs="post.audio" class="post-audio" :id="post.id" :ref="el => {
                if (el) {
                  // 确保不重复添加
                  if (!audioPlayers?.includes(el)) {
                    audioPlayers?.push(el);
                  }
                }
              }" @play="(player) => handleAudioPlay(player, post)" />
            </div>
          </div>
          <div class="post-footer flex items-center justify-between">
            <!-- 左侧:点赞 -->
            <div class="flex items-center">
              <van-icon @click="handLike(post)" name="good-job" class="like-icon" :color="post.is_liked ? 'red' : ''" />
              <span class="like-count ml-1">{{ post.likes }}</span>
            </div>

            <!-- 右侧:点评 -->
            <div class="flex items-center cursor-pointer" @click="openCommentPopup(post)">
              <van-icon
                name="comment-o"
                :color="post?.is_feedback ? '#10b981' : '#999'"
                size="19"
                class="mr-1"
                style="margin-top: 0.2rem;"
              />
              <span class="text-sm" :class="post?.is_feedback ? 'text-green-600' : 'text-gray-500'">
                {{ post?.is_feedback ? '已点评' : '待点评' }}
              </span>
            </div>
          </div>
        </div>
      </van-list>
      <van-empty v-show="activeTab === 'homework' && !checkinDataList.length" description="暂无数据" />
      <div style="height: 5rem;"></div>

      <!-- 状态筛选弹窗 -->
      <van-popup v-model:show="showStatusPopup" position="bottom" round>
        <div class="p-4">
          <div class="text-center text-lg font-bold mb-4">选择状态</div>
          <van-cell-group>
            <van-cell v-for="option in statusOptions" :key="option.value" :title="option.text" clickable
              @click="onStatusSelect(option)" :border="false"
              :class="{ 'text-green-600': statusFilter === option.value }">
              <template #right-icon>
                <van-icon v-if="statusFilter === option.value" name="success" color="#10b981" />
              </template>
            </van-cell>
          </van-cell-group>
          <div class="mt-4">
            <van-button block @click="showStatusPopup = false">取消</van-button>
          </div>
        </div>
      </van-popup>

      <!-- 点评弹窗 -->
      <van-popup v-model:show="showCommentPopup" position="bottom" round class="comment-popup">
        <div class="p-6 w-100">
          <div class="text-center text-lg font-bold mb-4">作业点评</div>

          <!-- 评分 -->
          <div class="mb-4">
            <div class="text-sm text-gray-600 mb-2">评分</div>
            <van-rate v-model="commentForm.score" :size="24" color="#ffd21e" void-color="#eee" :readonly="currentCommentPost?.is_feedback" />
          </div>

          <!-- 点评内容 -->
          <div class="mb-6">
            <div class="text-sm text-gray-600 mb-2">点评内容</div>
            <van-field
              v-model="commentForm.note"
              type="textarea"
              placeholder="请输入点评内容..."
              rows="4"
              maxlength="200"
              show-word-limit
              :border="false"
              class="bg-gray-50 rounded-lg"
              :readonly="currentCommentPost?.is_feedback"
            />
          </div>

          <!-- 操作按钮 -->
          <div v-if="!currentCommentPost?.is_feedback" class="flex gap-3">
            <van-button
              block
              type="default"
              @click="closeCommentPopup"
              class="flex-1"
            >
              取消
            </van-button>
            <van-button
              block
              type="primary"
              @click="submitComment"
              class="flex-1"
            >
              提交
            </van-button>
          </div>
          <div v-else class="flex gap-3">
            <van-button
              block
              type="default"
              @click="closeCommentPopup"
              class="flex-1"
            >
              关闭
            </van-button>
          </div>
        </div>
      </van-popup>

      <!-- 删除确认对话框 -->
      <van-dialog
        v-model:show="showDeleteDialog"
        title="温馨提示"
        :show-cancel-button="true"
        :show-confirm-button="true"
        confirm-button-text="确定删除"
        cancel-button-text="取消"
        confirm-button-color="#ef4444"
        @confirm="confirmDelete"
        @cancel="cancelDelete"
      >
        <div class="p-4">
          <p class="text-gray-700 text-center">确定要删除这条点评吗?</p>
        </div>
      </van-dialog>

      <van-back-top right="5vw" bottom="25vh" offset="600" />
    </div>
  </van-config-provider>
</template>

<script setup>
import { ref, computed, onMounted, onBeforeUnmount, nextTick } from 'vue'
import { useRouter, useRoute } from 'vue-router'
import { showConfirmDialog, showSuccessToast, showFailToast, showLoadingToast } from 'vant';
import VideoPlayer from "@/components/ui/VideoPlayer.vue";
import AudioPlayer from "@/components/ui/AudioPlayer.vue";
import { useTitle } from '@vueuse/core';
import dayjs from 'dayjs';

import { getCheckinTeacherListAPI, delUploadTaskInfoAPI, likeUploadTaskInfoAPI, dislikeUploadTaskInfoAPI } from "@/api/checkin";
import { getStudentDetailAPI, getStudentCheckinListAPI, getStudentUploadListAPI, getCheckinFeedbackListAPI, addCheckinFeedbackAPI, delCheckinFeedbackAPI, getStudentStatAPI } from "@/api/teacher";


const router = useRouter()
const route = useRoute()
useTitle(route.meta.title);

const themeVars = reactive({
  buttonNormalFontSize: '1rem',
})

// 学生信息
const studentInfo = ref({})

// 选中的课程列表(默认选中第一个课程)
const selectedCourses = ref([])

// 当前选中的标签页
const activeTab = ref('homework')

// 状态筛选
const statusFilter = ref('按状态')
const showStatusPopup = ref(false)

// 点评相关
const showCommentPopup = ref(false)
const currentCommentPost = ref(null)
const commentForm = ref({
  checkin_id: '',
  score: 0,
  note: ''
})

/**
 * 打开点评弹窗
 * @param {Object} post - 作业帖子对象
 */
const openCommentPopup = (post) => {
  console.warn(post);
  currentCommentPost.value = post
  commentForm.value.checkin_id = post.id
  // 如果已有点评,填充表单
  if (post.feedback_id) {
    commentForm.value.score = post.feedback_score || 0
    commentForm.value.note = post.feedback || ''
  } else {
    // 重置表单
    commentForm.value.score = 0
    commentForm.value.note = ''
  }
  showCommentPopup.value = true
}

/**
 * 关闭点评弹窗
 */
const closeCommentPopup = () => {
  // 如果已点评,关闭弹窗
  if (currentCommentPost.value && currentCommentPost.value.is_feedback) {
    showCommentPopup.value = false
    return
  }
  // 未点评的关闭重置显示
  showCommentPopup.value = false
  currentCommentPost.value = null
  commentForm.value.score = 0
  commentForm.value.note = ''
}

/**
 * 提交点评
 */
const submitComment = async () => {
  if (!commentForm.value.note.trim()) {
    showFailToast('请输入点评内容')
    return
  }

  if (commentForm.value.score === 0) {
    showFailToast('请选择评分')
    return
  }

  try {
    showLoadingToast('提交中...')

    // 这里应该调用API提交点评
    const { code, data } = await addCheckinFeedbackAPI(commentForm.value)
    if (code) {
      commentForm.value.feedback_id = data.id
      // 更新本地数据
      currentCommentPost.value.is_feedback = true
      checkinDataList.value.forEach(item => {
        if (item.id === currentCommentPost.value.id) {
          item.feedback_id = commentForm.value.feedback_id
          item.feedback_score = commentForm.value.score
          item.feedback = commentForm.value.note
        }
      })

      showSuccessToast('点评提交成功')
      closeCommentPopup()
    }

  } catch (error) {
    console.error('提交点评失败:', error)
    showFailToast('提交失败,请重试')
  }
}

/**
 * 切换课程选中状态(单选模式)
 * @param {string} course - 课程名称
 */
const toggleCourseSelection = (course) => {
  if (selectedCourses.value.includes(course)) {
    // 如果已选中,则取消选中
    selectedCourses.value = []
  } else {
    // 如果未选中,则设置为当前选中的课程(单选)
    selectedCourses.value = [course]
  }

  // 可以在这里添加其他业务逻辑,比如筛选相关数据
  console.log('当前选中的课程:', selectedCourses.value)

  resetAndReload()
  resetAndReloadRecords()
  resetAndReloadEvaluations()
  // 重新获取统计数据以匹配当前选中的课程
  getStatList()
}

// 状态选项
const statusOptions = ref([
  { text: '按状态', value: '按状态' },
  { text: '正常', value: 'checked' },
  { text: '缺勤', value: 'absence' }
]);

const formatStatus = (status) => {
  const statusMap = {
    checked: '正常',
    absence: '缺勤'
  }
  return statusMap[status] || status
}

// 记录列表
const records = ref([])

// 列表加载状态
const recordLoading = ref(false)
const recordFinished = ref(false)
const recordLimit = ref(100)
const recordPage = ref(0)

// 删除对话框相关状态
const showDeleteDialog = ref(false)
const currentDeleteId = ref(null)

// 班主任点评列表数据
const evaluationList = ref([])

// 班主任点评列表加载状态
const evaluationLoading = ref(false)
const evaluationFinished = ref(false)
const evaluationLimit = ref(100)
const evaluationPage = ref(0)

/**
 * 过滤后的记录列表
 */
const filteredRecords = computed(() => {
  let filtered = records.value

  // 按状态筛选
  if (statusFilter.value !== '按状态') {
    filtered = filtered.filter(record => record.status === statusFilter.value)
  }

  return filtered
})

/**
 * 格式化手机号
 * @param {string} phone - 手机号
 * @returns {string} 格式化后的手机号
 */
const formatPhone = (phone) => {
  if (!phone) return ''
  return phone.replace(/(\d{3})(\d{4})(\d{4})/, '$1****$3')
}

/**
 * 处理状态选择
 * @param {Object} option - 选中的状态选项
 */
const onStatusSelect = (option) => {
  statusFilter.value = option.value
  showStatusPopup.value = false
}

/**
 * 加载更多记录数据
 */
const onRecordLoad = async () => {
  const nextPage = recordPage.value;
  //
  const res = await getStudentCheckinListAPI({
    limit: recordLimit.value,
    page: nextPage,
    user_id: route.params.id,
    group_id: selectedCourses.value.length ? selectedCourses.value[0]['id'] : '',
  });
  if (res.code) {
    // 整理数据结构
    records.value = [...records.value, ...res.data];
    recordFinished.value = res.data.length < recordLimit.value;
    recordPage.value = nextPage + 1;
  }
  recordLoading.value = false;
}

/**
 * 加载更多班主任点评数据
 */
const onEvaluationLoad = async () => {
  const nextPage = evaluationPage.value;
  //
  const res = await getCheckinFeedbackListAPI({
    limit: evaluationLimit.value,
    page: nextPage,
    user_id: route.params.id,
    group_id: selectedCourses.value.length ? selectedCourses.value[0]['id'] : '',
  });
  if (res.code) {
    // 整理数据结构
    evaluationList.value = [...evaluationList.value, ...res.data];
    evaluationFinished.value = res.data.length < evaluationLimit.value;
    evaluationPage.value = nextPage + 1;
  }
  evaluationLoading.value = false;
}

/**
 * 删除点评
 * @param {number} evaluationId - 点评ID
 */
const deleteEvaluation = (evaluationId) => {
  currentDeleteId.value = evaluationId
  showDeleteDialog.value = true
}

/**
 * 确认删除操作
 */
const confirmDelete = async () => {
  // 这里应该调用API删除点评,暂时模拟删除操作
  const { code } = await delCheckinFeedbackAPI({
    i: currentDeleteId.value
  })
  if (code) {
    const index = evaluationList.value.findIndex(item => item.id === currentDeleteId.value)
    if (index !== -1) {
      evaluationList.value.splice(index, 1)
      showSuccessToast('删除成功')
    }
  }
  showDeleteDialog.value = false
  currentDeleteId.value = null
}

/**
 * 取消删除操作
 */
const cancelDelete = async () => {
  showDeleteDialog.value = false
  currentDeleteId.value = null
  console.log('用户取消删除操作')
}

/**
 * 组件挂载时初始化数据
 */
const checkinDataList = ref([]);
onMounted(async () => {
  // 从路由参数获取学生ID
  const studentId = route.params.id

  // 这里可以根据studentId调用API获取学生详细信息
  await loadStudentData(studentId)
  // 加载统计数据
  await getStatList()

  // 加载作业记录
  await onLoad()

  // 加载签到记录
  await onRecordLoad()

  // 加载班主任点评
  await onEvaluationLoad()

})

/**
 * 加载学生数据
 * @param {string} studentId - 学生ID
 */
const loadStudentData = async (studentId) => {
  const { code, data } = await getStudentDetailAPI({ i: studentId })
  if (code) {
    studentInfo.value = data;
    studentInfo.value?.lesson_list.sort((a, b) => a.title.length - b.title.length)
    selectedCourses.value = [studentInfo.value.lesson_list[0] || '']
  }
}

// 处理标签页切换
const handleTabChange = (name) => {
  // 先更新activeTab值
  activeTab.value = name;

  nextTick(() => {
    // 停止所有视频和音频播放
    if (videoPlayers.value) {
      videoPlayers.value.forEach(player => {
        if (player && typeof player?.pause === 'function') {
          player?.pause();
        }
      });
    }

    stopAllAudio();
  })

  if (name === 'homework') {
    resetAndReload()
  } else if (name === 'evaluation') {
    resetAndReloadEvaluations()
  } else if (name === 'statistics') {
    resetAndReloadRecords()
  }
};

// 存储所有视频播放器的引用
const videoPlayers = ref([]);

// 存储所有音频播放器的引用
const audioPlayers = ref([]);

// 组件卸载前清理播放器引用和事件监听器
onBeforeUnmount(() => {
  // 停止所有视频和音频播放
  if (videoPlayers.value) {
    videoPlayers.value.forEach(player => {
      if (player && typeof player?.pause === 'function') {
        player?.pause();
      }
    });
  }

  stopAllAudio();

  // 清空引用数组
  if (videoPlayers.value) videoPlayers.value = [];
  if (audioPlayers.value) audioPlayers.value = [];
});

/**
 * 开始播放指定帖子的视频
 * @param {Object} post - 要播放视频的帖子对象
 */
const startPlay = (post) => {
  // 确保checkinDataList.value是一个数组
  if (checkinDataList.value) {
    // 先暂停所有其他视频
    checkinDataList.value.forEach(p => {
      p.videoList.forEach(v => {
        if (v.id !== post.id) {
          v.isPlaying = false;
        }
      });
    });
  }

  // 设置当前视频为播放状态
  post.isPlaying = true;
};

/**
 * 处理视频播放事件
 * @param {Object} player - 视频播放器实例
 * @param {Object} post - 包含视频的帖子对象
 */
const handleVideoPlay = (player, post) => {
  stopAllAudio();
};

/**
 * 处理视频暂停事件
 * @param {Object} post - 包含视频的帖子对象
 */
const handleVideoPause = (post) => {
  // 视频暂停时不改变isPlaying状态,保持播放器可见
  // 这样用户可以继续从暂停处播放
};

/**
 * 停止除当前播放器外的所有其他视频
 * @param {Object} currentPlayer - 当前播放的视频播放器实例
 * @param {Object} currentPost - 当前播放的帖子对象
 */
const stopOtherVideos = (currentPlayer, currentPost) => {
  // 确保videoPlayers.value是一个数组
  if (videoPlayers.value) {
    // 暂停其他视频播放器
    videoPlayers.value.forEach(player => {
      if (player !== currentPlayer && player.pause) {
        player.pause();
      }
    });
  }

  // 更新其他帖子的播放状态
  checkinDataList.value.forEach(p => {
    p.videoList.forEach(v => {
      if (v.id !== currentPost.id) {
        v.isPlaying = false;
      }
    });
  });
};

/**
 * 处理音频播放事件
 * @param {Object} player - 音频播放器实例
 * @param {Object} post - 包含音频的帖子对象
 */
const handleAudioPlay = (player, post) => {
  // 停止其他音频播放
  stopOtherAudio(player, post);
};

const stopOtherAudio = (currentPlayer, currentPost) => {
  // 确保audioPlayers.value是一个数组
  if (audioPlayers.value) {
    // 暂停其他音频播放器
    audioPlayers.value.forEach(player => {
      if (player.id !== currentPost.id && player.pause) {
        player.pause();
      }
    });
  }
  // 更新其他帖子的播放状态
  checkinDataList.value.forEach(post => {
    if (post.id !== currentPost.id) {
      post.isPlaying = false;
    }
  });
  // 停止所有视频播放
  stopAllVideos();
}

const stopAllAudio = () => {
  // 确保audioPlayers.value是一个数组
  if (!audioPlayers.value) return;
  audioPlayers.value?.forEach(player => {
    // 使用组件暴露的pause方法
    if (typeof player.pause === 'function') {
      player?.pause();
    }
  });
  // 更新所有帖子的播放状态
  checkinDataList.value.forEach(post => {
    if (post.audio.length) {
      post.isPlaying = false;
    }
  });
}

/**
 * 停止所有视频播放
 */
const stopAllVideos = () => {
  // 确保videoPlayers.value是一个数组
  if (!videoPlayers.value) return;

  // 更新所有帖子的播放状态
  checkinDataList.value.forEach(p => {
    p.videoList.forEach(v => {
      v.isPlaying = false;
    });
  });
};

// 图片预览相关
const showImagePreview = ref(false);
const startPosition = ref(0);
const currentPost = ref(null);

// 打开图片预览
const openImagePreview = (index, post) => {
  currentPost.value = post;
  startPosition.value = index;
  showImagePreview.value = true;
}

// 图片切换事件处理
const onChange = (index) => {
  startPosition.value = index;
}

const handLike = async (post) => {
  if (!post.is_liked) {
    const { code, data } = await likeUploadTaskInfoAPI({ checkin_id: post.id, })
    if (code) {
      showSuccessToast('点赞成功')
      post.likes++;
      post.is_liked = true;
    }
  } else {
    const { code, data } = await dislikeUploadTaskInfoAPI({ checkin_id: post.id, })
    if (code) {
      showSuccessToast('取消点赞成功')
      post.likes--;
      post.is_liked = false;
    }
  }
}

const loading = ref(false)
const finished = ref(false)
const limit = ref(10)
const page = ref(0)

const onLoad = async (date) => {
  const nextPage = page.value;
  //
  const res = await getStudentUploadListAPI({
    limit: limit.value,
    page: nextPage,
    user_id: route.params.id,
    group_id: selectedCourses.value.length ? selectedCourses.value[0]['id'] : '',
  });
  if (res.code) {
    // 整理数据结构
    checkinDataList.value = [...checkinDataList.value, ...formatData(res.data)];
    finished.value = res.data.length < limit.value;
    page.value = nextPage + 1;
  }
  loading.value = false;
};

const formatData = (data) => {
  let formattedData = [];
  formattedData = data?.map((item, index) => {
    let images = [];
    let audio = [];
    let videoList = [];
    if (item.file_type === 'image') {
      images = item.files.map(file => {
        return file.value;
      });
    } else if (item.file_type === 'video') {
      videoList = item.files.map(file => {
        return {
          id: file.meta_id,
          video: file.value,
          videoCover: file.cover,
          isPlaying: false,
        }
      })
    } else if (item.file_type === 'audio') {
      audio = item.files.map(file => {
        return {
          title: file.name ? file.name : '打卡音频',
          artist: file.artist ? file.artist : '',
          url: file.value,
          cover: file.cover ? file.cover : '',
        }
      })
    }
    return {
      id: item.id,
      task_id: item.task_id,
      user: {
        name: item.username,
        avatar: item.avatar,
        time: item.created_time_desc,
      },
      content: item.note,
      images,
      videoList,
      audio,
      isPlaying: false,
      likes: item.like_count,
      is_liked: item.is_like,
      is_my: item.is_my,
      file_type: item.file_type,
      is_feedback: item.feedback_id || false, // 是否已点评
      feedback : item.feedback || '',
      feedback_id : item.feedback_id || '',
      feedback_score : item.feedback_score || 0,
      comment: item.comment || null, // 点评内容
    }
  })
  return formattedData;
}

/**
 * 重置分页参数并重新加载数据
 */
const resetAndReload = () => {
  page.value = 0;
  checkinDataList.value = [];
  finished.value = false;
  loading.value = true;
  onLoad();
}

/**
 * 重置分页参数并重新加载数据
 */
const resetAndReloadRecords = () => {
  recordPage.value = 0;
  records.value = [];
  recordFinished.value = false;
  recordLoading.value = true;
  onRecordLoad();
}

/**
 * 重置分页参数并重新加载数据
 */
const resetAndReloadEvaluations = () => {
  evaluationPage.value = 0;
  evaluationList.value = [];
  evaluationFinished.value = false;
  evaluationLoading.value = true;
  onEvaluationLoad();
}

// 统计数据
const checkinCount = ref(0);
const checkinCountText = computed(() => checkinCount.value.toFixed(1) + '%');
const uploadCount = ref(0);
const uploadCountText = computed(() => uploadCount.value.toFixed(1) + '%');

const getStatList = async () => {
  try {
    const { code, data } = await getStudentStatAPI({
      i: route.params.id,
      group_id: selectedCourses.value.length ? selectedCourses.value[0]['id'] : '',
    })

    if (code) {
      checkinCount.value = data.real_checkin_count/data.need_checkin_count * 100;
      uploadCount.value = data.real_upload_count/data.need_upload_count * 100;
    }
  } catch (error) {
    console.error('获取统计数据失败:', error);
  }
}
</script>

<style lang="less">
.van-back-top {
  background-color: #4caf50;
}

/* 自定义样式 */
.van-circle {
  font-size: 12px;
  font-weight: bold;
}

.van-tag {
  margin-right: 0.5rem;
  margin-bottom: 0.25rem;
}

.van-list {
  min-height: 200px;
}

/* 标签页样式 */
.border-b-2 {
  border-bottom-width: 2px;
}

.post-card {
  // margin: 1rem 0;
  padding: 1rem;
  background-color: #FFF;
  border-radius: 5px;

  .post-header {
    margin-bottom: 1rem;
  }

  .user-info {
    margin-left: 0.5rem;

    .username {
      font-weight: 500;
    }

    .post-time {
      color: gray;
      font-size: 0.8rem;
    }
  }

  .post-menu {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-bottom: 1rem;
  }

  .post-content {
    .post-text {
      color: #666;
      margin-bottom: 1rem;
      white-space: pre-wrap;
      word-wrap: break-word;
    }

    .post-media {
      .post-images {
        display: flex;
        flex-wrap: wrap;
        gap: 0.5rem;
      }

      .post-video {
        margin: 1rem 0;
        width: 100%;
        border-radius: 8px;
        overflow: hidden;
        box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
      }

      .post-audio {
        margin: 1rem 0;
      }
    }
  }

  .post-footer {
    margin-top: 1rem;
    color: #666;

    .like-icon {
      margin-right: 0.25rem;
    }

    .like-count {
      font-size: 0.9rem;
    }
  }
}

/* 点评弹窗样式 */
.comment-popup {
  .van-popup {
    max-width: 90vw;
  }

  .van-rate {
    display: flex;
    justify-content: center;
  }

  .van-field {
    padding: 12px;
    border-radius: 8px;
  }

  .van-button {
    height: 44px;
    border-radius: 8px;
  }
}
</style>