yiming
2024-03-13 f9d4b09377c5471e1202be2fef2c89de27b6654d
pages/resourceDetails/myAudio/index.js
@@ -1,52 +1,673 @@
// audio.js
// pages/resourceDetails/index.js
const app = getApp()
const myAudio = wx.createInnerAudioContext();
Page({
  /**
   * 页面的初始数据
   */
  data: {
    poster: 'http://y.gtimg.cn/music/photo_new/T002R300x300M000003rsKF44GyaSk.jpg?max_age=2592000',
    name: '此时此刻',
    author: '许巍',
    src: 'http://182.92.203.7:3001/file/api/ApiDownload?md5=aa72e586dd93b7c2633bee6320bc6c76',
    noteList: [],
    navBarHeight: '',
    barHeight: '',
    flag: true, // 输入框是否显示
    tabPanelstyle: 'display:flex;justify-content:center;align-items:center;',
    activeValues: [0],
    dialogKey: false,
    style: 'border: 2rpx solid rgba(220,220,220,1);border-radius: 12rpx;',
    activeId: '',
    bookId: '',
    bookName: '',
    cmsId: '',
    parentName: '',
    parentProductLinkPath: '',
    productLinkPath: '',
    threeLeveData: [],
    showData: '',
    src: '',
    selectedId: null,
    topicId: '',
    titleName: '',
    submitTitle: "",
    inputStyle: 'border: 2rpx solid rgba(220,220,220,1);border-radius: 12rpx; padding:16rpx',
    textvalue: '',
    style: 'height: 248rpx',
    submitType: "new", //  新建 or 编辑
    noteId: '',
    myAudioDuration: '',  // 视频时间
    myAudioCurrent: '',   // 当前播放进度
    isplay: false, //是否默认播放,
    selectId: '',
    speed: 1.0,
  },
  audio: null,
  // 格式化笔记时间
  convertTimestamp(timestamp) {
    const isoDate = new Date(timestamp)
    const year = isoDate.getFullYear()
    const month = String(isoDate.getMonth() + 1).padStart(2, '0')
    const day = String(isoDate.getDate()).padStart(2, '0')
    const hours = String(isoDate.getHours()).padStart(2, '0')
    const minutes = String(isoDate.getMinutes()).padStart(2, '0')
    const seconds = String(isoDate.getSeconds()).padStart(2, '0')
    const formattedDate = `${year}-${month}-${day} ${hours}:${minutes}:${seconds}`
    return formattedDate
  },
  // 时间格式化
  format(t) {
    let time = Math.floor(t / 60) >= 10 ? Math.floor(t / 60) : '0' + Math.floor(t / 60);
    t = time + ':' + ((t % 60) / 100).toFixed(2).slice(-2);
    return t;
  },
  /**
   * 生命周期函数--监听页面加载
   */
  onLoad(options) {
    const systInfo = wx.getSystemInfoSync();
    const menu = wx.getMenuButtonBoundingClientRect(); // 胶囊信息
    const navBarHeight = (menu.top - systInfo.statusBarHeight) * 2 + menu.height; // 导航栏高度
    // console.log(options, 'options');
    this.setData({
      navBarHeight: navBarHeight,
      barHeight: systInfo.statusBarHeight,
      activeId: options.activeId,
      bookId: options.bookId,
      bookName: options.bookName,
      cmsId: options.cmsId,
      parentName: options.parentName,
      parentProductLinkPath: options.parentProductLinkPath,
      productLinkPath: options.productLinkPath
    })
  },
  onReady: function (e) {
    // 使用 wx.createAudioContext 获取 audio 上下文 context
    this.audioCtx = wx.createAudioContext('myAudio')
    this.resourceDetailsData()
    this.getNoteList()
  },
  audioPlay: function () {
    this.audioCtx.play()
  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady() {
  },
  audioPause: function () {
    this.audioCtx.pause()
  /**
   * 生命周期函数--监听页面显示
   */
  onShow() {
  },
  audio14: function () {
    this.audioCtx.seek(14)
  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide() {
  },
  audioStart: function () {
    this.audioCtx.seek(0)
  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload() {
  },
  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh() {
  },
  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom() {
  },
  /**
   * 用户点击右上角分享
   */
  onShareAppMessage() {
  },
  onTabsChange(event) {
  },
  onTabsClick(event) {
  }, handleChange(e) {
    this.setData({
      activeValues: e.detail.value,
    });
  },
  onTakeNotes() {
  },
  showDialog(e) {
    this.setData({
      submitTitle: this.data.bookName,
      dialogKey: true,
      // textvalue: ''
    });
  },
  closeDialog() {
    this.setData({
      dialogKey: false
    });
  },
  goBack() {
    wx.navigateBack()
    wx.navigateBack();
  },
  resourceDetailsData() {
  MusicStart: function (e) {
    var progress = parseInt((e.detail.currentTime / e.detail.duration) * 100)
    var that = this
    that.setData({
      progress: progress
    let query = {
      path: '*',
      queryType: '*',
      productId: this.data.bookId,
      cmsPath: this.data.parentProductLinkPath,
      itemFields: {
        SysType: 'CmsFolder',
        // 资源类型,试读文件,是否允许下载等参数
        selectType: [],
        freeFile: [],
        file: [],
        protectedFile: [],
        resourcesClassification: [],
        isDownload: [],
        jsek_resourceBrief: [],
        jsek_link: [],
        jsek_questionBank: [],
        learnSelectType: []
      },
      pading: {
        start: 0,
        size: 999
      }
    }
    app.MG.store.getProductDetail(query).then(res => {
      res.datas.cmsDatas[0].datas.forEach((item, index) => {
        if (item.selectType === "audio") {
          this.data.threeLeveData.push(item)
          this.setData({
            threeLeveData: this.data.threeLeveData
    })
    console.log('音乐播放进度为' + progress + '%')
          if (this.data.productLinkPath == item.productLinkPath) {
            console.log(item.id, 'index');
            this.setData({
              showData: app.config.requestCtx + '/file/api/ApiDownload?md5=' + item.file,
              titleName: item.name
            })
            this.pubulicPlayFun()
            // this.setData({
            //   selectedId: index
            // })
          }
        }
      })
      this.data.threeLeveData.forEach((item) => {
        // console.log(item.name);
      })
    })
  },
  onVideo(e) {
    const item = e.currentTarget.dataset.item
    if (this.data.showData != '') {
      this.setData({
        showData: ''
      })
    }
    this.setData({
      selectedId: e.currentTarget.dataset.index,
    })
    this.setData({
      titleName: item.name,
      selectId: item.id
    })
    if (item.selectType == "audio") {
      this.setData({
        showData: app.config.requestCtx + '/file/api/ApiDownload?md5=' + item.file
      })
      this.pubulicPlayFun()
    }
  },
  getProductUserSubmitTopicGet() {
    app.MG.ugc.getProductUserSubmitTopic({
      productId: this.data.bookId,
      appRefCode: app.config.appRefCode
    }).then((res) => {
      // console.log(res);
      this.setData({
        topicId: res.id
      })
    })
  },
  newTopicMessageGet() {
    let query = {
      topicIdOrRefCode: topicId + '',
      name: titleText.value,
      content: form.value.noteContent,
      type: 'note',
      cmsTypeRefCode: '',
      newDataListRequest: []
    }
    app.MG.ugc.newTopicMessage(query).then(res => {
      // console.log(res);
    })
  },
  // 标题改变
  changeTitle(e) {
    // console.log(e.currentTarget.dataset.value);
    this.setData({
      flag: e.currentTarget.dataset.value
    })
  },
  // 标题输入框值
  inputChange(e) {
    this.setData({
      titleName: e.detail.value
    })
  },
  confirmSuggest() {
    if (!this.data.textvalue) {
      return wx.showToast({
        icon: 'error',
        title: '请填写笔记内容',
      })
    } else if (!this.data.titleName) {
      return wx.showToast({
        icon: 'error',
        title: '请填写笔记标题',
      })
    }
    if (this.data.submitType == 'new') {
      this.makeNote()
    } else if (this.data.submitType == 'edit') {
      this.updateNote()
    }
    // console.log(this.data.textvalue);
    // console.log(this.data.titleName);
    this.setData({
      dialogKey: false
    });
  },
  onTextarea() {
    // console.log(this.data.textvalue);
  },
  textareaChange(e) {
    this.setData({
      textvalue: e.detail.value
    })
  },
  // 获取笔记列表
  async getNoteList() {
    // this.setData({
    //   loading: true
    // })
    let topicId
    await app.MG.ugc
      .getProductUserSubmitTopic({
        productId: this.data.bookId,
        appRefCode: app.config.appRefCode
      })
      .then((res) => {
        if (res) {
          topicId = res.id
        } else {
          return wx.showToast({
            icon: "error",
            title: '查询失败',
          })
        }
      })
    // loadings.value.bookResource = true
    let query = {
      start: 0,
      size: 999,
      messageType: 'note',
      sort: {
        type: 'Desc',
        field: 'CreateDate'
      },
      appRefCode: app.config.appRefCode,
      topicIdOrRefCode: topicId + ''
    }
    await app.MG.ugc.getTopicMessageList(query).then((res) => {
      // notePage.value.total = res.totalSize
      res.datas.forEach((item) => {
        // item.compliceHover = false
        // item.deleteHover = false
        item.createDate = this.convertTimestamp(item.createDate)
      })
      this.setData({
        "pageCount.total": res.totalSize,
        noteList: res.datas,
        loading: false
      })
      // console.log('笔记列表', res.datas);
    })
  },
  // 编辑按钮
  editNote(e) {
    const note = e.currentTarget.dataset.note
    this.setData({
      submitType: "edit",
      textvalue: note.content,
      submitTitle: note.name,
      noteId: note.id
    })
    this.showDialog()
  },
  // 删除笔记
  deleteNote(e) {
    const id = e.currentTarget.dataset.id
    const messageIds = []
    messageIds.push(id)
    wx.showModal({
      title: '提示',
      content: '确认删除该笔记吗?',//editable如果为true,这就是输入框的内容
      editable: false,//是否显示输入框
      placeholderText: '请输入内容吧',//输入框的默认内容
      success: (res) => {
        if (res.confirm) {
          app.MG.ugc
            .delTopicMessage({ messageIds })
            .then((res) => {
              wx.showToast({
                title: '删除成功',
              })
              // if ((notePage.value.total % 3) - 1 == 0) {
              //   notePage.value.page -= 1
              // }
              this.getNoteList()
            })
        } else if (res.cancel) {
          // console.log('用户点击取消')
        }
      }
    })
  },
  // 新建笔记接口
  async makeNote() {
    const token = wx.getStorageSync('jsek-token')
    if (!token) {
      return wx.getUserProfile({
        desc: '用户登录',
        success: (res) => {
          // console.log(res);
        }
      })
    }
    let topicId
    await app.MG.ugc
      .getProductUserSubmitTopic({
        productId: this.data.bookId,
        appRefCode: app.config.appRefCode
      })
      .then((res) => {
        if (res) {
          topicId = res.id
        } else {
          return wx.showToast({
            icon: 'error',
            title: '新建失败',
          })
        }
      })
    let query = {
      topicIdOrRefCode: topicId + '',
      name: this.data.submitTitle,
      content: this.data.textvalue,
      type: 'note',
      cmsTypeRefCode: '',
      newDataListRequest: []
    }
    await app.MG.ugc.newTopicMessage(query).then((res) => {
      wx.showToast({
        title: '新建成功',
      })
      this.closeDialog()
      this.getNoteList()
    })
  },
  // 编辑笔记接口
  updateNote() {
    const token = wx.getStorageSync('jsek-token')
    if (!token) {
      return wx.getUserProfile({
        desc: '用户登录',
        success: (res) => {
          // console.log(res);
        }
      })
    }
    if (!this.data.submitTitle) {
      return wx.showToast({
        icon: 'error',
        title: '请填写笔记标题',
      })
    } else if (!this.data.textvalue) {
      return wx.showToast({
        icon: 'error',
        title: '请填写笔记内容',
      })
    }
    let query = {
      id: this.data.noteId,
      name: this.data.submitTitle,
      description: 'string',
      icon: 'string',
      type: 'note',
      content: this.data.textvalue,
      newDataRequests: [],
      updateDataRequests: []
    }
    app.MG.ugc.updateTopicMessage(query).then((res) => {
      wx.showToast({
        title: '编辑成功',
      })
      this.closeDialog()
      this.getNoteList()
    })
    this.setData({
      submitType: "new"
    })
  },
  // 播放公共代码
  pubulicPlayFun() {
    myAudio.src = this.data.showData
    console.log(myAudio.src);
    // 在onCanplay里获取并设置音频时长和播放进度
    myAudio.onCanplay(() => {
      myAudio.duration; //必须写,不然获取不到。。。
      setTimeout(() => {
        console.log(myAudio.duration);
        this.setData({
          myAudioDuration: this.format(myAudio.duration),
          myAudioCurrent: this.format(myAudio.currentTime)
        });
      }, 1000);
    });
    // 播放完成处理,按钮变一下
    myAudio.onEnded((res) => {
      this.setData({
        isplay: false
      })
    });
    //进度条变化
    myAudio.onTimeUpdate(() => {
      this.setData({
        myAudioPos: myAudio.currentTime / myAudio.duration * 100,
        myAudioCurrent: this.format(myAudio.currentTime)
      });
    })
  },
  //播放
  play() {
    console.log(22222);
    myAudio.startTime = this.data.myAudioCurrent; //考虑到进度条被拖动,不一定从00:00:00开始
    myAudio.play();
    this.setData({
      isplay: true
    });
  },
  // 停止
  stop() {
    console.log(11111);
    myAudio.pause();
    this.setData({
      isplay: false
    });
  },
  adsfhaewlf() {
    myAudio.pause();
    this.setData({
      isplay: false
    });
  },
  //右切换
  onLeftSwitch() {
    this.setData({
      speed: 1.0,
      myAudioCurrent: 0
    })
    const index = this.data.threeLeveData.findIndex((item) => item.id == this.data.selectId)
    if (this.data.threeLeveData[index - 1]) {
      this.changeItem(this.data.threeLeveData[index - 1])
      this.setData({
        selectedId: index - 1,
      })
    } else {
      console.log('已经是第一首了');
    }
  },
  //右切换
  onRightSwitch() {
    this.setData({
      speed: 1.0,
      myAudioCurrent: 0
    })
    console.log('右切换');
    const index = this.data.threeLeveData.findIndex((item) => item.id == this.data.selectId)
    if (this.data.threeLeveData[index + 1]) {
      this.changeItem(this.data.threeLeveData[index + 1])
      this.setData({
        selectedId: index + 1,
      })
    } else {
      console.log('已经是最后一首了');
    }
  },
  changeItem(item) {
    console.log(item);
    if (this.data.showData != '') {
      this.setData({
        showData: ''
      })
    }
    this.setData({
      titleName: item.name,
      selectId: item.id
    })
    if (item.selectType == "audio") {
      this.setData({
        showData: app.config.requestCtx + '/file/api/ApiDownload?md5=' + item.file
      })
      this.pubulicPlayFun()
    }
  },
  // 播放倍速
  onSpeed() {
    let c = this.data.speed;
    c += 0.5;
    if (c <= 2) {
      this.setData({
        speed: c,
      })
    } else {
      c = 0.5;
      this.setData({
        speed: c,
      })
    }
    setTimeout(() => {
      myAudio.startTime = this.data.myAudioDuration  //开始时间
      myAudio.playbackRate = this.data.speed; //  播放速率
    }, 200);
  },
  handleChange(e) {
    console.log(e.detail.value);
  },
  // 拖动进度条,到指定位置
  hanle_slider_change(e) {
    const position = e.detail.value;
    var currentTime = position / 100 * myAudio.duration;
    myAudio.seek(currentTime);
    this.setData({
      myAudioPos: position,
      myAudioCurrent: this.format(currentTime)
    })
  }
})