checkinPage.vue 28.5 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
<!--
  * @Date: 2025-05-29 15:34:17
 * @LastEditors: hookehuyr hookehuyr@gmail.com
 * @LastEditTime: 2025-10-27 16:21:16
 * @FilePath: /mlaj/src/views/teacher/checkinPage.vue
  * @Description: 文件描述
-->
<template>
  <AppLayout :hasTitle="false">
    <van-config-provider :theme-vars="themeVars">
      <van-sticky>
        <van-dropdown-menu active-color="#4caf50" swipe-threshold="2">
          <van-dropdown-item v-model="selectGradeValue" :options="gradeOption" @change="handleGradeChange" />
          <van-dropdown-item v-model="selectClassValue" :options="classOption" @change="handleClassChange" />
          <van-dropdown-item v-model="selectCourseValue" :options="courseOption" @change="handleCourseChange" />
        </van-dropdown-menu>
      </van-sticky>

      <van-calendar ref="myRefCalendar" :show-title="false" :poppable="false" :show-confirm="false" :style="{ height: calendarHeight }"
        switch-mode="year-month" color="#4caf50" :formatter="formatter" row-height="50" :show-mark="false"
        @select="onSelectDay"
        @panel-change="onPanelChange"
        @click-subtitle="onClickSubtitle">
      </van-calendar>
      <div style="padding: 0 1rem; margin-top: 1rem;">
        <van-row gutter="15">
          <van-col span="12">
            <van-button type="primary" block icon="edit" @click="handleAdd('checkin')">安排打卡</van-button>
          </van-col>
          <van-col span="12">
            <van-button type="primary" block icon="video" @click="handleAdd('homework')">设置作业</van-button>
          </van-col>
        </van-row>
      </div>

      <!--<div v-if="showProgress" class="text-wrapper">
        <div class="text-header">打卡统计</div>
        <div style="background-color: #FFF; margin-top: 1rem;">
          <div class="grade-percentage-main">
            <van-row justify="space-between" style="margin: 0.5rem 0; font-size: 0.9rem;">
              <van-col span="12">
                <span>年级目标</span>
              </van-col>
              <van-col span="12" style="text-align: right;">
                <span style="font-weight: bold;">{{ progress1 }}%</span>
              </van-col>
            </van-row>
            <div style="overflow: hidden;">
              <van-progress :percentage="progress1" color="#4caf50" :show-pivot="false" />
            </div>
          </div>
          <!~~ <div class="class-percentage-main">
            <van-row justify="space-between" style="margin: 0.5rem 0; font-size: 0.9rem;">
              <van-col span="12">
                <span>班级目标</span>
              </van-col>
              <van-col span="12" style="text-align: right;">
                <span style="font-weight: bold;">{{ progress2 }}%</span>
              </van-col>
            </van-row>
            <van-progress :percentage="progress2" color="#4caf50" :show-pivot="false" />
          </div> ~~>
          <div style="padding: 0.75rem 1rem;">
            <van-image round width="2.8rem" height="2.8rem" :src="item ? item : 'https://cdn.ipadbiz.cn/mlaj/images/icon_1.jpeg'" fit="contain"
              v-for="(item, index) in teamAvatars.splice(0, 8)" :key="index"
              :style="{ marginLeft: index > 0 ? '-0.5rem' : '', border: '2px solid #eff6ff', background: '#fff' }" />
          </div>
        </div>
      </div>-->

      <div class="text-wrapper mt-4" style="padding: 0 1rem; color: #4caf50;">
        <div class="text-header">学生动态</div>
        <van-list
          v-if="checkinDataList.length"
          v-model:loading="loading"
          :finished="finished"
          finished-text="没有更多了"
          @load="onLoad"
          class="space-y-4"
        >
          <div class="post-card" 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">
                  <div v-if="post.is_my" class="post-menu">
                    <van-icon name="edit" @click="editCheckin(post)" />
                    <van-icon name="delete-o" @click="delCheckin(post)" />
                  </div>
                </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>

              <!-- 右侧:审核操作 -->
              <!-- TODO: 审核操作没有什么实质作用, 未通过用户看不到提示, 用户修改之后老师也接不到提示, 唯一作用就是让其他学员看不到 -->
              <div class="flex items-center cursor-pointer" @click="openAuditDialog(post)">
                <van-icon
                  :name="post.is_audit ? 'passed' : 'close'"
                  :color="post.is_audit ? '#10b981' : '#f56c6c'"
                  size="18"
                  class="mr-1"
                />
                <span class="text-sm" :class="post.is_audit ? 'text-green-600' : 'text-red-500'">
                  {{ post.is_audit ? '已通过' : '未通过' }}
                </span>
              </div>
            </div>
          </div>
        </van-list>
        <van-empty v-else description="暂无数据" />
      </div>

      <van-back-top right="5vw" bottom="25vh" offset="600" />
      <div style="height: 5rem;"></div>
    </van-config-provider>

    <van-dialog v-model:show="dialog_show" title="标题" show-cancel-button></van-dialog>
  </AppLayout>
</template>

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

import { getTaskDetailAPI, getCheckinTeacherListAPI, checkinTaskReviewAPI, likeUploadTaskInfoAPI, dislikeUploadTaskInfoAPI,getCheckinTeacherCheckedDatesAPI } from "@/api/checkin";
import { getTeacherGradeClassListAPI } from "@/api/teacher";

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

// 审核相关
const showAuditDialog = ref(false)
const currentAuditPost = ref(null)

const selectGradeValue = ref(null);
const selectClassValue = ref(null);
const selectCourseValue = ref(null);
const gradeOption = ref([]);
const classOption = ref([]);
const courseOption = ref([]);

const currentMonth = ref(dayjs().format('YYYY-MM'));

const handleGradeChange = async (val) => {
  console.log('val', val);
  selectGradeValue.value = val;
  selectCourseValue.value = null;
  // 根据年级ID 更新过滤列表
  getFilterList(val);
  // 重新获取打卡日期
  getCheckedDates(currentMonth.value);
  // 重置分页参数
  page.value = 0
  checkinDataList.value = []
  finished.value = false
  // 重新加载数据
  onLoad()
}

const handleClassChange = (val) => {
  console.log('val', val);
  selectClassValue.value = val;
  selectCourseValue.value = null;
  // 根据年级ID和班级ID 更新过滤列表
  getFilterList(selectGradeValue.value, val);
  // 重新获取打卡日期
  getCheckedDates(currentMonth.value);
  // 重置分页参数
  page.value = 0
  checkinDataList.value = []
  finished.value = false
  // 重新加载数据
  onLoad()
}

const handleCourseChange = (val) => {
  console.log('val', val);
  selectCourseValue.value = val;
  // 重新获取打卡日期
  getCheckedDates(currentMonth.value);
  // 重置分页参数
  page.value = 0
  checkinDataList.value = []
  finished.value = false
  // 重新加载数据
  onLoad()
}

const active = ref(0);

const myRefCalendar = ref(null);

// 窗口尺寸相关的响应式数据
const windowHeight = ref(window.innerHeight);
const windowWidth = ref(window.innerWidth);

/**
 * 动态计算日历高度
 * 根据屏幕尺寸和设备类型自适应调整
 */
const calendarHeight = computed(() => {
  // 获取可视窗口高度
  const viewportHeight = windowHeight.value;

  // 预留给其他内容的空间(头部、底部等)
  const reservedSpace = 200; // 可根据实际需要调整

  // 计算可用高度
  const availableHeight = viewportHeight - reservedSpace;

  // 设置最小和最大高度限制
  const minHeight = 300; // 最小高度
  const maxHeight = 500; // 最大高度

  // 根据屏幕宽度调整高度比例
  let heightRatio = 0.5; // 默认占可用高度的55%

  if (windowWidth.value < 375) {
    // 小屏手机
    heightRatio = 0.45;
  } else if (windowWidth.value < 414) {
    // 中等屏幕手机
    heightRatio = 0.42;
  } else if (windowWidth.value >= 768) {
    // 平板或更大屏幕
    heightRatio = 0.35;
  }

  const calculatedHeight = Math.floor(availableHeight * heightRatio);

  // 确保高度在合理范围内
  const finalHeight = Math.max(minHeight, Math.min(maxHeight, calculatedHeight));

  return `${finalHeight}px`;
});

/**
 * 监听窗口尺寸变化
 */
const handleResize = () => {
  windowHeight.value = window.innerHeight;
  windowWidth.value = window.innerWidth;
};

// 组件挂载时添加事件监听
onMounted(() => {
  window.addEventListener('resize', handleResize);
  // 监听屏幕方向变化(移动端)
  window.addEventListener('orientationchange', () => {
    // 延迟更新,等待方向变化完成
    setTimeout(handleResize, 100);
  });
});

// 存储所有视频播放器的引用
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 = [];

  // 清理事件监听器
  window.removeEventListener('resize', handleResize);
  window.removeEventListener('orientationchange', handleResize);
});


/**
 * 开始播放指定帖子的视频
 * @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 themeVars = reactive({
  calendarSelectedDayBackground: '#4caf50',
  calendarHeaderShadow: 'rgba(0, 0, 0, 0.1)',
  calendarInfoLineHeight: '0.3rem',
  buttonNormalFontSize: '1rem',
})

const progress1 = ref(0);
// const progress2 = ref(76);

const teamAvatars = ref([])

// 图片预览相关
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 formatter = (day) => {
  const year = day.date.getFullYear();
  const month = day.date.getMonth() + 1;
  const date = day.date.getDate();

  let checkin_days = myCheckinDates.value;

  // 检查当前日期是否在签到日期列表中
  if (checkin_days && checkin_days.length > 0) {
    // 格式化当前日期为YYYY-MM-DD格式,与checkin_days中的格式匹配
    const formattedDate = `${year}-${month.toString().padStart(2, '0')}-${date.toString().padStart(2, '0')}`;

    // 检查是否已打卡
    if (checkin_days.includes(formattedDate)) {
      // 如果是当前选中的已打卡日期,使用特殊样式
      if (selectedDate.value === formattedDate) {
        day.className = 'calendar-selected';
        day.type = 'selected';
        day.bottomInfo = '已打卡';
      } else {
        day.className = 'calendar-checkin';
        day.type = 'selected';
        day.bottomInfo = '已打卡';
      }
    }
  }

  // 选中今天的日期
  if (dayjs(day.date).isSame(new Date(), 'day')) {
    day.className = 'calendar-today';
    day.type = 'selected';
    day.bottomInfo = '今日';
  }

  return day;
}

// 添加一个响应式变量来存储当前选中的日期
const selectedDate = ref('');

const onSelectDay = (day) => {
  getTaskDetail(dayjs(day).format('YYYY-MM'));

  // 更新当前选中的日期
  const currentSelectedDate = dayjs(day).format('YYYY-MM-DD');
  selectedDate.value = currentSelectedDate;

  // 修改浏览器地址把当前的date加入地址栏, 页面不刷新
  // 使用replace替代push,避免在浏览器历史记录中添加多个条目
  router.replace({
    path: route.path,
    query: {
      ...route.query,
      date: currentSelectedDate
    }
  })
  // 重置分页参数
  page.value = 0
  checkinDataList.value = []
  finished.value = false
  // 重新加载数据
  onLoad(currentSelectedDate)
}


const onClickSubtitle = (evt) => {
  console.warn('点击了日期标题');
}

// 切换月份时触发
const onPanelChange = ({ date }) => {
  currentMonth.value = dayjs(date).format('YYYY-MM');
  getCheckedDates(currentMonth.value);
}

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;
    }
  }
}

/**
 * 打开审核确认弹框
 * @param {Object} post - 帖子对象
 */
const openAuditDialog = (post) => {
  currentAuditPost.value = post
  // showAuditDialog.value = true
  showConfirmDialog({
    title: '温馨提示',
    closeOnClickOverlay: true,
    cancelButtonText: '不通过',
    confirmButtonText: '通过',
    confirmButtonColor: '#4caf50',
    cancelButtonColor: 'red',
    message:
      '是否确认审核通过?',
  })
    .then(() => {
      // on confirm
      handleAudit(true)
    })
    .catch(() => {
      // on cancel
      handleAudit(false)
    });
}

/**
 * 关闭审核确认弹框
 */
const closeAuditDialog = () => {
  showAuditDialog.value = false
  currentAuditPost.value = null
}

/**
 * 处理审核操作
 * @param {boolean} isApproved - 是否审核通过
 */
const handleAudit = async (isApproved) => {
  try {
    // 这里可以调用API进行审核操作
    const { code, data } = await checkinTaskReviewAPI({
      checkin_id: currentAuditPost.value.id,
      status: isApproved ? 5 : 7
    })

    // 更新本地状态
    currentAuditPost.value.is_audit = isApproved

    // 显示成功提示
    showToast(isApproved ? '审核通过' : '审核不通过')

    // 关闭弹框
    closeAuditDialog()
  } catch (error) {
    console.error('审核操作失败:', error)
    showToast('操作失败,请重试')
  }
}

/**
 * 格式化点评时间
 * @param {string} timeString - 时间字符串
 * @returns {string} 格式化后的时间
 */
const formatCommentTime = (timeString) => {
  if (!timeString) return ''
  const date = new Date(timeString)
  return date.toLocaleString('zh-CN', {
    year: 'numeric',
    month: '2-digit',
    day: '2-digit',
    hour: '2-digit',
    minute: '2-digit'
  })
}

const taskDetail = ref({});
const myCheckinDates = ref([]);
const checkinDataList = ref([]);
const showProgress = ref(true);

const getTaskDetail = async (month) => {
  const { code, data } = await getTaskDetailAPI({ i: route.query.id, month });
  if (code) {
    taskDetail.value = data;
    progress1.value = ((data.checkin_number/data.target_number)*100).toFixed(1); // 计算进度条百分比
    showProgress.value = !isNaN(progress1.value); // 如果是NaN,就不显示进度条
    teamAvatars.value = data.checkin_avatars;
  }
}

// 获取用户打卡日期的函数
const getCheckedDates = async (month) => {
  const checkedDatesResult = await getCheckinTeacherCheckedDatesAPI({
    grade_id: selectGradeValue.value,
    class_id: selectClassValue.value,
    group_id: selectCourseValue.value,
    month
  });
  if (checkedDatesResult.code) {
    myCheckinDates.value = checkedDatesResult.data.my_checkin_dates;
    // 把['2025-06-06'] 转化为 [6] 只取日期去掉0
    // myCheckinDates.value = myCheckinDates.value.map(date => {
    //   return dayjs(date).date();
    // })
  }
}

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

const onLoad = async (date) => {
  const nextPage = page.value;
  const current_date = date || route.query.date || dayjs().format('YYYY-MM-DD');
  //
  const res = await getCheckinTeacherListAPI({
    limit: limit.value,
    page: nextPage,
    date: current_date,
    grade_id: selectGradeValue.value,
    class_id: selectClassValue.value,
    course_id: selectCourseValue.value,
  });
  if (res.code) {
    // 整理数据结构
    checkinDataList.value = [...checkinDataList.value, ...formatData(res.data)];
    finished.value = res.data.checkin_list.length < limit.value;
    page.value = nextPage + 1;
  }
  loading.value = false;
};

const gradeList = ref([]);
const classList = ref([]);
const courseList = ref([]);

const getFilterList = async (grade_id=null, class_id=null) => {
  const { code, data } = await getTeacherGradeClassListAPI({ grade_id, class_id });
  if (code) {
    // 处理数据
    gradeOption.value = data.grade_list?.map(item => {
      return {
        text: item.grade_name,
        value: item.id,
      }
    });
    gradeOption.value.unshift({
      text: '全部年级',
      value: null,
    });
    classOption.value = data.class_list?.map(item => {
      return {
        text: item.class_name,
        value: item.id,
      }
    });
    classOption.value.unshift({
      text: '全部班级',
      value: null,
    });
    courseOption.value = data.group_list?.map(item => {
      return {
        text: item.title,
        value: item.id,
      }
    });
    courseOption.value.unshift({
      text: '全部课程',
      value: null,
    });
  }
}

onMounted(async () => {
  const current_date = route.query.date;
  if (current_date) {
    getTaskDetail(dayjs(current_date).format('YYYY-MM'));
    getCheckedDates(dayjs(current_date).format('YYYY-MM'));
    myRefCalendar.value?.reset(new Date(current_date));
    onLoad(current_date);
  } else {
    getTaskDetail(dayjs().format('YYYY-MM'));
    getCheckedDates(dayjs().format('YYYY-MM'));
    onLoad(dayjs().format('YYYY-MM-DD'));
  }
  // 获取老师的年级、班级、课程列表信息
  getFilterList();
})

const formatData = (data) => {
  let formattedData = [];
  formattedData = data?.checkin_list.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_audit: item.status === 5 ? true : false, // 5=审批通过,7=审批不通过
      }
    })
  return formattedData;
}

const handleAdd = (type) => {
  router.push({
    path: '/teacher/form',
    query: {
      post_id: route.query.id,
      type: type,
      status: 'add',
    }
  })
}
</script>

<style lang="less">
.van-back-top {
  background-color: #4caf50;
}
/* 下拉菜单选项文字单行显示 */
.van-dropdown-item {
  .van-cell__title {
    white-space: nowrap;
    overflow: hidden;
    text-overflow: ellipsis;
    max-width: 100%;
    flex: 0 0 80%; /* title占80%宽度 */
  }

  .van-cell__value {
    flex: 0 0 20%; /* value占20%宽度 */
  }
}

/* 下拉菜单按钮文字单行显示 */
// .van-dropdown-menu__title {
//   white-space: nowrap;
//   overflow: hidden;
//   text-overflow: ellipsis;
//   max-width: 100%;
// }
.calendar-checkin {
  .van-calendar__selected-day {
    background: #a2d8a3 !important;
  }
}

.calendar-today {
  .van-calendar__selected-day {
    background: #FAAB0C !important;
  }
}

.text-wrapper {
  padding: 1rem;
  color: #4caf50;

  .text-header {
    font-size: 1.15rem;
  }

  .grade-percentage-main {
    padding: 0.75rem 1rem;
  }

  .class-percentage-main {
    padding: 0.75rem 1rem;
  }

  .upload-wrapper {
    display: flex;
    margin: 1rem 0;
    gap: 1rem;
    .upload-boxer {
      text-align: center;
      border: 1px solid #a2d8a3;
      border-radius: 5px;
      padding: 1rem 0;
      flex: 1;
      background-color: #fff;
    }
  }
}

.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;
    }
  }
}
</style>