Task.js 10 KB
// packageStudyCenter/pages/myTask/components/Task/Task.js
import { getSystemInfoSync } from '~/utils/systemInfo'
import api from "../../../../api"
const IMG_URL = 'https://img02.glsx.com.cn/weapp/resource/dj-car-boutique-work-wechat/'
const dayjs = require('dayjs');

Component({
  properties: {
    // 可以添加需要的属性
  },

  data: {
    IMG_URL,
    tabList: ['待完成', '已完成'],
    tabIndex: 0,
    finishIndex: 2,
    nothing: false,
    total: 0,
    pageNum: 1,
    pageSize: 10,
    scrollTop: 0,
    taskList: [],
    timer: null,
    scrollViewHeight: 0,
    formItems: [{
      key: 'taskTitle',
      type: 'title'
    }, {
      label: '任务进度',
      type: 'progress',
      statusKey: 'completeStatus',
      statusEvent: '0',
      key: '_taskProgress'
    }, {
      label: '课程数',
      arr: ['courseTotalCount', 'totalDuration'],
      unitArr: ['节', 'min']
    }, {
      label: '完成时间',
      key: '_taskTime'
    }],
    slitFormItems: [{
      key: 'taskTitle',
      type: 'title'
    }, {
      label: '任务进度',
      type: 'progress',
      statusKey: 'completeStatus',
      statusEvent: '0',
      key: '_taskProgress'
    }, {
      label: '完成时间',
      key: '_taskTime'
    }, {
      type: 'empty'
    }]
  },

  lifetimes: {
    attached() {
      this.calculateScrollViewHeight();
      this.getCourseTaskPage(this.data.tabIndex);
    },

    detached() {
      this.clearCountdownTimer();
    }
  },

  methods: {
    calculateScrollViewHeight() {
      const systemInfo = getSystemInfoSync();
      const { windowHeight, windowWidth } = systemInfo;
      // 根据设计稿比例计算滚动区域高度
      const baseHeight = 1334; // 设计稿高度
      const currentHeight = (windowHeight * 750) / windowWidth;
      const scrollHeight = this.data.tabIndex === 0 ? 210 : 138;
      const calculatedHeight = (currentHeight - scrollHeight) * (windowWidth / 750);
      
      this.setData({
        scrollViewHeight: calculatedHeight
      });
    },

    clearCountdownTimer() {
      if (this.data.timer) {
        clearInterval(this.data.timer);
        this.setData({ timer: null });
      }
    },

    startCountdownForAll() {
      this.clearCountdownTimer();
      this.updateAllCountdowns();
      
      const timer = setInterval(() => {
        this.updateAllCountdowns();
      }, 1000);
      
      this.setData({ timer });
    },

    updateAllCountdowns() {
      const now = new Date();
      let hasCountdown = false;
      const taskList = this.data.taskList.map(item => {
        if (this.data.tabIndex === 0 && item.punishType == 1 && item.taskDeadline) {
          const deadline = new Date(dayjs(item.taskDeadline));
          const diff = deadline - now;
          const oneDayMs = 24 * 60 * 60 * 1000;
          
          if (diff > 0 && diff < oneDayMs) {
            hasCountdown = true;
            const hours = Math.floor(diff / (1000 * 60 * 60));
            const minutes = Math.floor((diff % (1000 * 60 * 60)) / (1000 * 60));
            const seconds = Math.floor((diff % (1000 * 60)) / 1000);
            
            return {
              ...item,
              _countdownHour: hours.toString().padStart(2, '0'),
              _countdownMinute: minutes.toString().padStart(2, '0'),
              _countdownSecond: seconds.toString().padStart(2, '0'),
              _showCountdown: true,
              _showDays: false,
              _leftDays: null,
              _timeout: false
            };
          } else if (diff >= oneDayMs) {
            let days = Math.ceil(diff / oneDayMs) - 1;
            if (days < 1) days = 1;
            
            return {
              ...item,
              _showCountdown: false,
              _showDays: true,
              _leftDays: days,
              _countdownHour: null,
              _countdownMinute: null,
              _countdownSecond: null,
              _timeout: false
            };
          } else if (diff <= 0) {
            return {
              ...item,
              _timeout: true,
              _showCountdown: false,
              _showDays: false,
              _leftDays: null,
              _countdownHour: null,
              _countdownMinute: null,
              _countdownSecond: null
            };
          }
        }
        return {
          ...item,
          _showCountdown: false,
          _showDays: false,
          _leftDays: null,
          _timeout: false
        };
      });

      this.setData({ taskList });

      if (!hasCountdown) {
        this.clearCountdownTimer();
      }
    },
    
    formatTime(time, formatStr) {
      if (!time) return '-';
      return dayjs(time).format(formatStr);
    },

    initCountdownFieldsForList(list) {
      const now = new Date();
      return list.map(item => {
        if (this.data.tabIndex === 0 && item.punishType == 1 && item.taskDeadline) {
          const deadline = new Date(dayjs(item.taskDeadline));
          const diff = deadline - now;
          
          if (diff > 0 && diff <= 24 * 60 * 60 * 1000) {
            const hours = Math.floor(diff / (1000 * 60 * 60));
            const minutes = Math.floor((diff % (1000 * 60 * 60)) / (1000 * 60));
            const seconds = Math.floor((diff % (1000 * 60)) / 1000);
            
            return {
              ...item,
              _countdownHour: hours.toString().padStart(2, '0'),
              _countdownMinute: minutes.toString().padStart(2, '0'),
              _countdownSecond: seconds.toString().padStart(2, '0'),
              _showCountdown: true,
              _showDays: false,
              _leftDays: null,
              _timeout: false
            };
          } else if (diff > 24 * 60 * 60 * 1000) {
            const days = Math.ceil(diff / (24 * 60 * 60 * 1000));
            return {
              ...item,
              _showCountdown: false,
              _showDays: true,
              _leftDays: days,
              _countdownHour: null,
              _countdownMinute: null,
              _countdownSecond: null,
              _timeout: false
            };
          } else if (diff <= 0) {
            return {
              ...item,
              _timeout: true,
              _showCountdown: false,
              _showDays: false,
              _leftDays: null,
              _countdownHour: null,
              _countdownMinute: null,
              _countdownSecond: null
            };
          }
        }
        return {
          ...item,
          _showCountdown: false,
          _showDays: false,
          _leftDays: null,
          _timeout: false
        };
      });
    },

    async getCourseTaskPage(completeStatus, courseType) {
      try {
        const { pageNum, pageSize, tabIndex } = this.data;
        const params = {
          completeStatus,
          recommendStatus: 0,
          pageNum,
          pageSize
        };
        
        if (courseType) {
          params.courseType = courseType;
        }
        
        const res = await api.getCourseTaskPage(params);
        let newList = res?.data?.list || [];
        newList?.forEach(val => {
          val._taskDeadline = this.formatTime(val.taskDeadline, 'YYYY.MM.DD HH:mm')
          val._finishDate = this.formatTime(val.finishDate, 'YYYY.MM.DD HH:mm')
          val._progressWidth = `${Math.floor(val.taskProgress)}%`
          val._taskProgress = `${Math.floor(val.taskProgress)}%`
          val._taskTime = tabIndex == 0 ? val._taskDeadline : val._finishDate
        })
        if (completeStatus === 0) {
          newList = this.initCountdownFieldsForList(newList);
        }
        
        if (pageNum == 1) {
          this.setData({ taskList: newList });
        } else {
          this.setData({ 
            taskList: this.data.taskList.concat(newList) 
          });
        }
        this.setData({ 
          total: res.data?.total,
          nothing: newList.length > 0 
        });
        if (completeStatus === 0) {
          this.startCountdownForAll();
        } else {
          this.clearCountdownTimer();
        }
      } catch (error) {
        wx.showToast({
          title: error.message || '请求失败',
          icon: "none",
        });
      }
    },

    pageonReachBottom() {
      const { pageNum, total, pageSize, tabIndex, finishIndex } = this.data;
      if (Math.ceil(total / pageSize) > pageNum) {
        this.setData({ pageNum: pageNum + 1 });
        if (tabIndex == 0) {
          this.getCourseTaskPage(tabIndex);
        } else {
          this.getCourseTaskPage(tabIndex, finishIndex);
        }
      } else {
        this.setData({ nothing: true });
      }
    },

    handleTabClick(e) {
      const index = e.currentTarget.dataset.index;
      this.setData({
        tabIndex: index,
        pageNum: 1,
        nothing: false,
        taskList: [],
        scrollTop: 1
      });
      
      this.clearCountdownTimer();
      
      if (index == 1) {
        this.setData({ finishIndex: 2 });
        this.getCourseTaskPage(index, 2);
      } else {
        this.getCourseTaskPage(index);
      }
      
      this.calculateScrollViewHeight();
      this.triggerEvent('needScrollTop')
    },

    handleFinishTabClick(e) {
      const index = parseInt(e.currentTarget.dataset.index);
      this.setData({
        finishIndex: index,
        pageNum: 1,
        nothing: false,
        taskList: []
      });
      
      this.clearCountdownTimer();
      this.getCourseTaskPage(this.data.tabIndex, index);
      this.triggerEvent('needScrollTop')
    },

    handleTaskItemClick(e) {
      const item = e.currentTarget.dataset.item;
      let userInfo = wx.$util.getUserInfo()
      const { courseType, id } = item;
      // 埋点
      wx.$track.setTrackData(0, courseType == 1 ? 'short_course' : 'long_course', {}, '', userInfo?.sceneType)
      // 这里添加跳转逻辑
      wx.navigateTo({
        url: `/packageStudyCenter/pages/taskDetail/${courseType == 1 ? 'shortCourse' : 'longCourse'}/${courseType == 1 ? 'shortCourse' : 'longCourse'}?row=${encodeURIComponent(JSON.stringify(item))}&completeStatus=${this.data.tabIndex}`,
        fail: (err) => {
          console.error('页面跳转失败:', err);
        }
      });
    }
  }
});