shortCourse.js 8.94 KB
// packageStudyCenter/pages/taskDetail/shortCourse/shortCourse.js
const dayjs = require('dayjs');
const IMG_URL = 'https://img02.glsx.com.cn/weapp/resource/dj-car-boutique-work-wechat/'
import api from '../../../api'

Page({
  data: {
    IMG_URL,
    chartData: {},
    labelColors: [],
    qualityTitle: ['课程标签', '不足/改善建议', '对练考核'],
    courseDetail: {
      positionList: [],
      defeatReviewDetailList: [],
      aiReviewReport: []
    },
    rowData: {},
    countdown: {
      days: 0,
      hours: 0,
      minutes: 0,
      seconds: 0
    },
    isTimeout: false,
    timer: null,
    popupTitle: '',
    popupType: '',
    popupDetail: {},
    aiAgentData: {},
    completeStatus: null,
    studyId: '',
    options: {},
    navBarHeight: 0,
    blueBtn: false,
  },

  onLoad(options) {
    this.setData({ options });
    
    const { row } = options;
    const rowData = JSON.parse(decodeURIComponent(row))
    
    this.setData({ 
      rowData,
      completeStatus: options.completeStatus 
    });

    if (!this.data.rowData.taskDeadline) {
      this.setData({
        'rowData.taskDeadline': rowData.finishTime
      });
    }

    this.refreshStudyList();
    
    if (this.data.completeStatus == 0) {
      this.initCountdown();
    }
    
    this.getAiAgentList();
  },

  navbarReady(e) {
    let navBarHeight = e.detail.height
    console.log(e)
    this.setData({
      navBarHeight
    })
  },
  back() {
    try {
      const { aiReviewReport } = this.data.courseDetail
      aiReviewReport.map(e => {
        if (e.examStatus != 2) throw 1
      })
      wx.navigateBack()
    } catch (error) {
      if (error == 1) {
        wx.showModal({
          title: '退出提醒',
          content: '您还没有完成本次短课程学习,是否确定退出?',
          cancelText: '确定退出',
          confirmColor: '#347BFF',
          confirmText: '继续学习',
          complete: (res) => {
            if (res.cancel) {
              wx.navigateBack()
            }
          }
        })
      } else  {
        wx.navigateBack()
      }
    }
  },
  onUnload() {
    // 清除定时器
    if (this.data.timer) {
      clearInterval(this.data.timer);
      this.setData({ timer: null });
    }
  },

  onShow() {
    // 页面显示时刷新数据
    this.refreshStudyList();
  },

  refreshStudyList() {
    const { options, rowData } = this.data;
    if (options.from === 'service') {
      this.setData({ studyId: rowData.detailId });
      this.getShortCourseDetail(rowData.detailId, rowData.id);
    } else {
      this.setData({ studyId: rowData.id });
      this.getShortCourseDetail(rowData.id);
    }
  },

  desensitizePhone(phone) {
    if (!phone || typeof phone !== 'string') return phone;
    // 只处理11位手机号
    if (phone.length === 11) {
      return phone.substr(0, 3) + '****' + phone.substr(7, 4);
    }
    // 其他长度不处理
    return phone;
  },

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

  async getShortCourseDetail(id, boxId) {
    wx.showLoading({ title: '加载中...' })
    const params = { id }
    if (boxId) {
      params.boxId = boxId
    }
    try {
      // 这里替换为实际的小程序API调用
      const res = await api.getShortCourseDetail(params)
      const _chartData = {
        categories: res.data?.defeatReviewTag || [],
        series: [
          {
            data: res.data?.defeatReviewValue || []
          }
        ]
      }
      // 处理标签颜色
      let _labelColors = []
      if (_chartData.series && _chartData.series[0] && Array.isArray(_chartData.series[0].data)) {
        const dataArr = _chartData.series[0].data
        if (dataArr.every(val => val === 0)) {
          _labelColors = [];
        } else {
          _labelColors = dataArr.map(val => val === 1 ? '#EB4E4E' : '#666666')
        }
      }
      // 处理职位列表
      const positionList = res.data?.position ? res.data?.position.split(',') : []
      // 处理战败明细
      res.data.defeatReviewDetailList?.forEach(val => {
        val._customerPhone = this.desensitizePhone(val.customerPhone)
        val._inspectionScore = Math.floor(val.inspectionScore)
      })
      this.setData({
        chartData: _chartData,
        labelColors: _labelColors,
        courseDetail: {
          ...res.data,
          positionList,
          defeatReviewDetailList: res.data?.defeatReviewDetailList || [],
          aiReviewReport: res.data?.aiReviewReport || [],
          _checkDate: dayjs(res?.data?.checkDate).format('YYYY年MM月DD日')
        }
      })
    } catch (error) {
    } finally {
      wx.hideLoading()
    }
  },

  desensitizePhone(phone) {
    if (!phone || typeof phone !== 'string') return phone;
    // 只处理11位手机号
    if (phone.length === 11) {
      return phone.substr(0, 3) + '****' + phone.substr(7, 4);
    }
    // 其他长度不处理
    return phone;
  },

  // 获取智能体
  async getAiAgentList() {
    try {
      const userInfo = wx.$util.getUserInfo()
      const res = await api.getAiAgentList({
        accountPhone: userInfo?.phone,
        ownerShipType: 1,
        agentCode: 'AI8'
      })
      
      this.setData({
        aiAgentData: res?.data[0] || {}
      })
    } catch (error) {
    }
  },

  initCountdown() {
    // 清除旧定时器
    if (this.data.timer) {
      clearInterval(this.data.timer);
      this.setData({ timer: null });
    }

    // 兼容rowData未加载时
    if (!this.data.rowData || !this.data.rowData.taskDeadline) {
      this.setData({ 
        isTimeout: false,
        countdown: { days: 0, hours: 0, minutes: 0, seconds: 0 }
      });
      return;
    }

    const updateCountdown = () => {
      const now = dayjs();
      const deadline = dayjs(this.data.rowData.taskDeadline);
      const diff = deadline.diff(now, 'second');
      
      if (diff <= 0) {
        this.setData({ 
          isTimeout: true,
          countdown: { days: 0, hours: 0, minutes: 0, seconds: 0 }
        });
        if (this.data.timer) {
          clearInterval(this.data.timer);
          this.setData({ timer: null });
        }
      } else {
        let seconds = diff;
        const days = Math.floor(seconds / (24 * 3600));
        seconds = seconds % (24 * 3600);
        const hours = Math.floor(seconds / 3600);
        seconds = seconds % 3600;
        const minutes = Math.floor(seconds / 60);
        seconds = seconds % 60;
        
        this.setData({
          isTimeout: false,
          countdown: { days, hours, minutes, seconds }
        });
      }
    };

    updateCountdown();
    const timer = setInterval(updateCountdown, 1000);
    this.setData({ timer });
  },
  // 去考核
  async handleExam(e) {
    const item = e.currentTarget.dataset.item
    if (item.examStatus == 0) {
      return
    }
    const { businessType, brandType, checkDate } = this.data.courseDetail
    const { agentUrl, domainName, agentCode } = this.data.aiAgentData
    const userInfo = wx.$util.getUserInfo()
    const res = await api.getMerchantBrand({
      merchantId: userInfo?.shopMerchantId
    })
    const { sceneType, uuid, phone } = userInfo || {}
    const bussinessType = sceneType == 0 ? 1 : 2 // sceneType 0延保 1精品。 bussinessType 1.延保 2.轻改
    const brand = {
      1: '问界',
      2: '比亚迪',
      3: '其他'
    }[res?.data.channelType || 1]
    if (!agentUrl) {
      return wx.$util.showToast('待开放')
    }
    let url = `${agentUrl}?no_header=1&business_type=${bussinessType}&phone=${phone}&brand=${brand}&one_id=${uuid}&platformType=1&domain=${domainName}&presuppositionProblem=${item.tagName}&needIntercept=true}&studyId=${this.data.studyId}`
    if (businessType) {
      url += `&businessType=${businessType}`
    }
    if (brandType) {
      url += `&brandType=${brandType}`
    }
    if (checkDate) {
      url += `&date=${dayjs(checkDate).format('YYYY-MM-DD')}`
    }
    wx.$router.jumpH5(url)
  },
  // 查看总结
  handleSummary() {
    this.setData({
      popupTitle: '战败总结',
      popupType: 'summary',
      okText: '关闭',
      blueBtn: false
    });
    
    const coursePopupRef = this.selectComponent('#coursePopupRef');
    if (coursePopupRef) {
      coursePopupRef.open();
    }
  },
  // 战败详情
  handleDetail(e) {
    const item = e.currentTarget.dataset.item;
    this.setData({
      popupTitle: '战败详情',
      popupType: 'detail',
      popupDetail: item,
      okText: '关闭',
      blueBtn: false
    });
    
    const coursePopupRef = this.selectComponent('#coursePopupRef');
    if (coursePopupRef) {
      coursePopupRef.open();
    }
  },
  // 学习明细查看全部
  handleShowAll(e) {
    const item = e.currentTarget.dataset.item
    this.setData({
      popupTitle: '不足/改善建议',
      popupType: 'tableDetail',
      popupTableDetail: item,
      okText: '知道了',
      blueBtn: true
    });
    
    const coursePopupRef = this.selectComponent('#coursePopupRef');
    if (coursePopupRef) {
      coursePopupRef.open();
    }
  }
})