// pages/peoblem_report/peoblem_report.js
import { routers, viewImage, sharePage, isFn, getGlobalVal, formatDateTime, formateNumber, formatDate } from '../../utils/util.js'
import { FindProblemPictureDetail } from '../../utils/api.js'
const { navigateTo, redirectTo, navigateBack } = routers()
const { globalData } = getApp()
const { baseImgUrl, thumbnail } = globalData
const app = getApp()
const { formatNumber } = require('../../utils/util.js')
Page({

  /**
   * 页面的初始数据
   */
  data: {
    baseImgUrl,
    thumbnail,
    voiceKeyIndex:-1,
    imgNum:3,
    isPlay:0,
    times:0,
    isMusic:0,
    isEnd:0,
    voiceKeyList:[]
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    this.setData(options);
    this.getData();
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {
  
  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {
    
  },

 /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {
    let pages = getCurrentPages();
    const {isMusic,voiceKeyList, voiceKeyIndex}=this.data
    console.log( '生命周期函数--监听页面隐藏'+isMusic)
   //  this.setData({isEnd:1})
   // this.innerAudioContext.destroy();
     if(isMusic){
       this.stopPlay()
       // this.innerAudioContext.onStop(() => {
         this.innerAudioContext.stop();
         clearInterval(this.setIntervalAudio)
         this.pauseAudio(voiceKeyList, voiceKeyIndex)
       // })
     }
     
 },

 /**
  * 生命周期函数--监听页面卸载
  */
 onUnload: function () {
   const {isMusic,voiceKeyList, voiceKeyIndex}=this.data
   console.log( '生命周期函数--监听页面卸载'+isMusic)
   // this.setData({isEnd:1})
 // this.innerAudioContext.destroy();
   if(isMusic){
     this.stopPlay()
     // this.innerAudioContext.onStop(() => {
       this.innerAudioContext.stop();
       clearInterval(this.setIntervalAudio)
       this.pauseAudio(voiceKeyList, voiceKeyIndex)
     // })
   }
 },
  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {
  
  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {
  
  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {
    if (app.sharePageDefaultCtl) {
      return app.sharePageDefaultCtl()
    }
  },

  //查看图片
  viewImageCtl: app.viewImageCtl,

  // 获取难题详情
  // getPuzzleReport:function(){
  //   const postData = { fn: this.getPuzzleReport, param: { ...arguments } }
  //   const { problemPictureId, nodes, answerNodes } = this.data;
  //   const fn = res => {
  //     const { derverFileKey, problemFeedbackVideoPath, problemPictureId, problemPicturePath, recommendedQuestions, similarQuestions, teacherMessage} = res.data;
  //     const correctListTemp = (res => {
  //       for (let i in res) {
  //         if (res[i].question.indexOf("img") != -1){
  //           res[i].question = res[i].question.replace(/\<img/gi, '<img style="max-width:100%;height:auto" ')
  //         }
  //       }
  //       return res
  //     })(similarQuestions)
  //     const listTemp = (res => {
  //       for (let i in res) {
  //         if (res[i].analysis.indexOf("img") != -1) {
  //           res[i].analysis = res[i].analysis.replace(/\<img/gi, '<img style="max-width:100%;height:auto" ')
  //         }
  //         if (res[i].question.indexOf("img") != -1) {
  //           res[i].question = res[i].question.replace(/\<img/gi, '<img style="max-width:100%;height:auto" ')
  //         }
  //       }
  //       return res
  //     })(recommendedQuestions)
  //     this.setData({ derverFileKey, problemFeedbackVideoPath, problemPictureId, problemPicturePath, recommendedQuestions: listTemp, similarQuestions: correctListTemp, teacherMessage});
  //   }
  //   app.post('/api/parents/parents/V2/findProblemPictureDetail', { problemPictureId}, 0, postData).then(fn)
  // },
   /**
   * 获取数据
   */
  getData: function (cb) {
    const continuousFn = { fn: this.getData, param: { ...arguments } }
    const { problemPictureId } = this.data
    FindProblemPictureDetail({ data: { problemPictureId }, continuousFn }).then(res => {
      const { derverFileKey, problemFeedbackVideoPath, problemPictureId, problemPicturePath, recommendedQuestions, similarQuestions, teacherMessage,fileKeys,voiceKeyList } = res.data;
      const voiceListTemp = (res => {
        for (let i in res) {
          res[i].voiceType =  0
          res[i].durationNum = 0;
          res[i].progress = 0;
          res[i].isHands = false;
          // res[i].audioTotal = formatNumber(Math.floor(voiceList[i].duration / 60)) + ':' + formatNumber(Math.floor(voiceList[i].duration % 60));
        }
        return res
      })(voiceKeyList)
      const correctListTemp = (res => {
        for (let i in res) {
          if (res[i].question.indexOf("img") != -1) {
            res[i].question = res[i].question.replace(/\<img/gi, '<img style="max-width:100%;height:auto" ')
          }
        }
        return res
      })(similarQuestions)
      const listTemp = (res => {
        for (let i in res) {
          if (res[i].analysis.indexOf("img") != -1) {
            res[i].analysis = res[i].analysis.replace(/\<img/gi, '<img style="max-width:100%;height:auto" ')
          }
          if (res[i].question.indexOf("img") != -1) {
            res[i].question = res[i].question.replace(/\<img/gi, '<img style="max-width:100%;height:auto" ')
          }
        }
        return res
      })(recommendedQuestions)
      this.setData({ derverFileKey, problemFeedbackVideoPath, problemPictureId, problemPicturePath, recommendedQuestions: listTemp, similarQuestions: correctListTemp, teacherMessage,voiceKeyList:voiceListTemp,fileKeys });
      if (isFn(cb)) cb()
    }).catch(res => {
      this.setData({ isLoaded: true })
      if (isFn(cb)) cb()
    })
  },
  
  /**
  * 开始计时
  */
 startSetInter: function () {
  let time = 1000;
  var that = this;
  let { times,isEnd} = this.data;
  // console.log(times)
  var setTime = this.data.times + 1
  console.log(setTime)
  that.setData({ times: setTime,imgNum:setTime })
  that.data.setInter = setTimeout(this.startSetInter, time);
  if (setTime>2) {
      that.endSetInter();
      if(setTime==3&&!isEnd){
        setTimeout(
          function () {
            that.startSetInter()
          }, 1000)
      }
  } 
  },
 /**
   * 结束计时
   */
  endSetInter:function(){
    var that = this;
    clearTimeout(that.data.setInter)
    that.setData({ times: 0})
  },
  /**
   * 结束计时
   */
  stopPlay:function(){
    var that = this;
    that.endSetInter();
    that.setData({ imgNum:3})
    console.log('结束')
  },
  /**
      * 音频控制按钮
      */
  audioCtl: function (e) {
    const { index } = e.currentTarget.dataset
    const { voiceKeyList, voiceKeyIndex} = this.data
    const { voiceType } = voiceKeyList[index];
    this.setData({isMusic:1})
    var that=this
    // console.log(index,voiceKeyIndex,voiceType)
    if (index == voiceKeyIndex) {
      if (voiceType == 1) {
        console.log('1---停止')
        that.stopPlay()
        if (this.innerAudioContext) this.innerAudioContext.stop()
      } else if (voiceType == 2) {
        console.log('1---播放')
        if (this.innerAudioContext) this.innerAudioContext.play()
      } else {
        this.audioManager()
      }
    } else {
      const temp = {}
      temp['voiceKeyIndex'] = index
      this.setData(temp)
      this.audioManager()
    }
  },
  /**
     * 开始播放语音
     */
  playAudio: function (voiceKeyList, voiceKeyIndex) {
    const { voiceKey, voiceType, durationNum, duration, progress } = voiceKeyList[voiceKeyIndex];
    console.log('开始播放语音')
    this.startSetInter()
    const temp = {}
    temp[`voiceKeyList[${voiceKeyIndex}].voiceType`] = 1;
    temp[`voiceKeyList[${voiceKeyIndex}].isHands`] = true;
    this.setData(temp)
    let d = voiceType == 2 ? durationNum - 1 : duration
    if (this.setIntervalAudio) {
      clearInterval(this.setIntervalAudio)
    }
    // console.log(d)
    this.setIntervalAudio = setInterval(() => {
      if (d > 0) {
        d--
        temp[`voiceKeyList[${voiceKeyIndex}].durationNum`] = d
        temp[`voiceKeyList[${voiceKeyIndex}].progress`] = Math.floor((duration - d) / duration * 100)
        this.setData(temp)
      } else {
        clearInterval(this.setIntervalAudio)
      }
    }, 1000)
  },

  /**
   * 暂停播放语音
   */
  pauseAudio: function (voiceKeyList, voiceKeyIndex) {
    console.log('2---停止')
    const {isEnd}=this.data
    this.setData({isEnd:!isEnd})
    const temp = {}
    temp[`voiceKeyList[${voiceKeyIndex}].voiceType`] = 2
    this.setData(temp)
  },

  /**
   * 结束播放语音
   */
  endAudio: function (voiceKeyList, voiceKeyIndex, listIndex) {
    console.log('3---停止')
    const {isEnd}=this.data
    this.setData({isEnd:!isEnd})
    const { voiceKey, voiceType, durationNum, duration, progress } = voiceKeyList[voiceKeyIndex]
    this.stopPlay()
    const temp = {}
    temp[`voiceKeyList[${voiceKeyIndex}].voiceType`] = 0
    temp[`voiceKeyList[${voiceKeyIndex}].duration`] = duration
    temp[`voiceKeyList[${voiceKeyIndex}].progress`] = 0
    temp[`voiceKeyList[${voiceKeyIndex}].isHands`] = false;
    this.setData(temp)
  },

  /**
   * 语音播放管理器
   */
  audioManager: function () {
    const { voiceKeyList, voiceKeyIndex, baseImgUrl } = this.data
    if (this.innerAudioContext) {
      this.innerAudioContext.destroy()
      clearInterval(this.setIntervalAudio)
      for (const i in voiceKeyList) {
        const temp = {};
        temp[`voiceKeyList[${i}].voiceType`] = 0;
        this.setData(temp)
      }
    }
    const { voiceKey } = voiceKeyList[voiceKeyIndex]
    if (!voiceKey) return
    this.innerAudioContext = wx.createInnerAudioContext()
    this.innerAudioContext.autoplay = true
    this.innerAudioContext.src = baseImgUrl+voiceKey
    console.log(baseImgUrl + voiceKey)
    this.innerAudioContext.onPlay(() => {
      this.playAudio(voiceKeyList, voiceKeyIndex)
    })

    this.innerAudioContext.onStop(() => {
      clearInterval(this.setIntervalAudio)
      this.pauseAudio(voiceKeyList, voiceKeyIndex)
    })

    this.innerAudioContext.onEnded(() => {
      this.innerAudioContext.destroy()
      clearInterval(this.setIntervalAudio)
      this.endAudio(voiceKeyList, voiceKeyIndex)
    })

    this.innerAudioContext.onError(res => {
      console.log(res)
      wx.showToast({
        title: '播放语音失败',
        icon: 'none'
      })
    })
  },
  /**
   * 结束语音
   */
  nextAudio: function () {
    const { voiceKeyList, voiceKeyIndex} = this.data;
    this.stopPlay()
    if (voiceKeyIndex != -1 && listIndex != -1) {
      const { voiceKey, voiceType, durationNum, duration, progress } = voiceKeyList[voiceKeyIndex]
      const temp = {}
      temp[`voiceKeyList[${voiceKeyIndex}].voiceType`] = 0
      temp[`voiceKeyList[${voiceKeyIndex}].duration`] = duration
      temp[`voiceKeyList[${voiceKeyIndex}].progress`] = 0
      if (this.innerAudioContext) this.innerAudioContext.pause()
      this.setData(temp)
    }
  }

})