//index.js
//获取应用实例
const app = getApp()
const { uuid, warn } = require("../../utils/util")
const Upyun = require('../../utils/upyun-wxapp-sdk')
const upyun = new Upyun({
    bucket: app.globalData.upyun.bucket,
    operator: app.globalData.upyun.operator,
    getSignatureUrl: `${app.globalData.server}/api/v1/uc/upyun_token`,
})

const upload = (src, callback) => {
  let { host } = app.globalData.upyun;
  let ext = src.split(".").reverse()[0]
  let name = `${uuid()}.${ext}`;
  let remotePath = `/daily-music/records/${name}`

  upyun.upload({
      localPath: src,
      remotePath,
      success: function (res) {
          wx.hideLoading()
          callback(host + remotePath)
      },
      fail: function ({ errMsg }) {
          wx.hideLoading();
          callback(false, errMsg)
          console.log('upload fail, errMsg is', errMsg)
      }
  })
}

Page({
  data: {
    audio: null,
    video: null,
    recorder: null,
    recording: false,
    playing: false,
    record: '',
    replaying: false,
    redo: false
  },
  //事件处理函数
  bindRecord: function() {
    let { recorder, video, recording } = this.data;
    
    this.setData({record: '', redo: recording, playing: true}, () => {
      if(recording) recorder.stop();
      else {
        video.seek(0)
        video.play();
        console.log('recorder start...')
        recorder.start({format: 'mp3'})
      }
    })
    
  },
  bindPlayRecord(){
    let { audio, record, video, playing } = this.data;
    if(!record) {
      warn("您还没有进行录音")
      return;
    }
    if(playing) {
      video.stop();
    }
    audio.src = record;
    audio.play();
    this.setData({replaying: true})
  },
  bindPlay(){
    let { video, audio, replaying } = this.data;
    if(replaying) {
      audio.stop();
    }
    video.seek(0)
    this.setData({playing: true}, () => {
      video.play();
    })
  },
  bindStop(){
    let { video } = this.data;
    video.stop()
    this.setData({playing: false})
  },
  bindSubmit(){
    wx.showLoading({
      title: '正在提交数据...',
      success(){
        setTimeout(() => {
          wx.hideLoading({
            success: (res) => {
              warn("您的录音已提交！")
            },
          })
        }, 3000)
      }
    })
  },
  onVideoEnd(){
    let { recording, recorder } = this.data;
    if(recording){
      wx.showLoading({
        title: '正在处理录音，请稍候...',
      })
      recorder.stop();
    }
  },
  onVideoPause(){
    let { recording, recorder } = this.data;
    if(recording){
      recorder.pause();
    }
  },
  onLoad: function () {
    let audio = wx.createInnerAudioContext()
    let video = wx.createVideoContext('sample')
    let recorder = wx.getRecorderManager();
    
    recorder.onError((err) => {
      console.log('error...', err)
      this.setData({recording: false})
    })
    recorder.onStart(() => {
      console.log("...start....")
      this.setData({recording: true})
    })
    recorder.onStop(({tempFilePath, duration, fileSize}) => {
      this.setData({recording: false})
      if(this.data.redo) {
        video.seek(0)
        video.play();
        recorder.start({format: 'mp3'})
        this.setData({redo: false})
        return;
      }
      upload(tempFilePath, (filename, errorMsg) => {
        if(!filename) {
          warn("录音出现了问题，再来一遍吧～")
        } else {
          this.setData({record: filename})
        }
      })
    })
    this.setData({recorder, video, audio})
  },
})
