// pages/previewTxtWork/previewTxtWork.js
const myBgm = wx.createInnerAudioContext()
//const mytxtVoice = wx.createInnerAudioContext()
var bgm = [[], []]
var isAddbgm = 0
var bgmA
var bgmB
var src1
Page({

  /**
   * 页面的初始数据
   */
  data: {
    falg: '',
    multiArray: [['不添加', '哀伤', '欢乐', '抒情', '古典'], []],
    objectArray: [
      {
        id: 0,
        name: '不添加'
      },
      {
        id: 1,
        name: '哀伤'
      },
      {
        id: 2,
        name: '欢乐'
      },
      {
        id: 3,
        name: '抒情'
      },
      {
        id: 4,
        name: '古典'
      },

    ],
    playnow:false,
    multiIndex: [],
    bgm: [[], []],
    sadBgm: [[], []],
    happyBgm: [[], []],
    lyricBgm: [[], []],
    classicalBgm: [[], []],
    list: '',
    picturePath:'',
    Title:''
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    this.onQuery('哀伤', 1);
    this.onQuery('欢乐', 2);
    this.onQuery('抒情', 3);
    this.onQuery('古典', 4);
    console.log("picture=" + options.picturepath);
    this.setData({
      list: options.list,
      picturePath:options.picturepath,
      Title:options.title
    })
    myBgm.volume = 0.2;
    console.log(this.data.list)
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {
    this.myVoice = wx.createInnerAudioContext('');
  },

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

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {
    myBgm.destroy();
    this.myVoice.destroy();
  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {

  },

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

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {

  },
  //查询所有的bgm信息
  onQuery: function (style, falg) {
    const db = wx.cloud.database()
    var i;
    db.collection('bgm').where({
      style: style
    }).get({
      success: res => {
        this.setData({
          queryResult: JSON.stringify,
        })
        console.log('[数据库] [查询记录] 成功: ', res)
        var j = res.data.length
        for (i = 0; i < j; i++) {
          var bgmI = "bgm[" + 0 + "]" + "[" + i + "]"
          var bgmII = "bgm[" + 1 + "]" + "[" + i + "]"
          var path = res.data[i].cloudPath
          var bgmName = res.data[i].name;
          this.setData({
            [bgmI]: path,
            [bgmII]: bgmName,
          })
          if (falg == 1) {
            this.data.sadBgm[0][i] = res.data[i].cloudPath;
            this.data.sadBgm[1][i] = res.data[i].name;

          }

          if (falg == 2) {
            this.data.happyBgm[0][i] = res.data[i].cloudPath;
            this.data.happyBgm[1][i] = res.data[i].name;
          }
          if (falg == 3) {
            this.data.lyricBgm[0][i] = res.data[i].cloudPath;
            this.data.lyricBgm[1][i] = res.data[i].name;
          }
          if (falg == 4) {
            this.data.classicalBgm[0][i] = res.data[i].cloudPath;
            this.data.classicalBgm[1][i] = res.data[i].name;
          }
        }
      }
    })
  },
  //修改类型
  bindMultiPickerChange: function (e) {
    this.setData({
      multiIndex: e.detail.value
    })
  },
  bindMultiPickerColumnChange: function (e) {
    var data = {
      multiArray: this.data.multiArray,//第二列的值
      multiIndex: this.data.multiIndex
    };
    data.multiIndex[e.detail.column] = e.detail.value;

    switch (e.detail.column) {
      case 0:
        switch (data.multiIndex[0]) {
          case 0:
            data.multiArray[1] = [''];
            isAddbgm = 'false';
            break;
          case 1:
            data.multiArray[1] = this.data.sadBgm[1];
            isAddbgm = 'ture'
            break;
          case 2:
            data.multiArray[1] = this.data.happyBgm[1];
            isAddbgm = 'ture'
            break;
          case 3:
            data.multiArray[1] = this.data.lyricBgm[1];
            isAddbgm = 'ture'
            break;
          case 4:
            data.multiArray[1] = this.data.classicalBgm[1];
            isAddbgm = 'ture'
            break;
        }
        break;
    }
    this.setData(data);
    isAddbgm=1;
    bgmA = this.data.multiIndex[0];//第0列类型的序号
    bgmB = this.data.multiIndex[1];//第1列歌曲序号
    console.log(bgmA);
    console.log(bgmB);
  },
  //根据选定的歌曲名查询BGM的路径
  onQueryPath: function () {
    console.log("开始执行")
    if (bgmA == 0) {
      myBgm.src = ''
    }
    if (bgmA == 1) {
      myBgm.src = this.data.sadBgm[0][bgmB];
      console.log('src1' + myBgm.src)
      console.log('src1=' + myBgm.src +
        'this.data.classicalBgm[0][bgmB]=' + this.data.sadBgm[0][bgmB])
    }
    if (bgmA == 2) {
      myBgm.src = this.data.happyBgm[0][bgmB];
      console.log('src2' + myBgm.src)
      console.log('src2=' + myBgm.src +
        'this.data.classicalBgm[0][bgmB]=' + this.data.happyBgm[0][bgmB])
    }
    if (bgmA == 3) {
      myBgm.src = this.data.lyricBgm[0][bgmB];
      console.log('src3' + myBgm.src)
      console.log('src3=' + myBgm.src +
        'this.data.classicalBgm[0][bgmB]=' + this.data.lyricBgm[0][bgmB])
    }
    if (bgmA == 4) {
      myBgm.src = this.data.classicalBgm[0][bgmB];
      console.log('src4=' + myBgm.src +
        'this.data.classicalBgm[0][bgmB]=' + this.data.classicalBgm[0][bgmB])
    }
  },
  //开始播放或暂停播放
  conPlaying() {
    /*
    if (this.data.playnow) {
      this.myVoice.pause();
      myBgm.pause();
      this.setData({
        playnow: false
      })
    }
    else {
      this.setData({
        playnow: true
      })
      wx.showToast({
        title: '开始播放',
      });
      */
      this.myVoice.src = getApp().globalData.workPath;
      console.log('this.myVoice.src' + this.myVoice.src)
      
      this.onQueryPath();
      console.log('myBgm.src=' + myBgm.src)
      console.log('isAddbgm='+isAddbgm)
      if(bgmA==0||isAddbgm==false){
        this.myVoice.play();
      }else{
      myBgm.play();
      myBgm.onPlay(() => {
        this.myVoice.play();
        console.log('bmg开始播放')
         console.log("txtsrc=" + this.myVoice.src)
        console.log('mybgm=' + myBgm.src)
      });
      }
      this.myVoice.onPlay(() => {
        console.log('录音开始播放');
        wx.showToast({
          title: '开始播放',
          duration: 200
        });
      })
      this.myVoice.onStop(()=>{
        myBgm.stop();
        wx.showToast({
          title: '播放结束',
          duration: 200
        });
      })
      
  
  },

  onAdd(cloudpath) {
    const db = wx.cloud.database()
    db.collection('user-text').add({
      data: {
        BgmPath:'',
        TextPath:this.data.list,
        CloudPath: cloudpath,
        Picture:this.data.picturePath,
        name:this.data.Title
      },
      success: res => {
        // 在返回结果中会包含新创建的记录的 _id
        this.setData({
          counterId: res._id,
          count: 1,
          fileID: '',
          cloudPath: ''
        })
        wx.showToast({
          title: '保存成功',
        })
        wx.switchTab({
          url: '../mine/mine',
        })
        console.log('[数据库] [新增记录] 成功，记录 _id: ', res._id)
      },
      fail: err => {
        wx.showToast({
          icon: 'none',
          title: '新增记录失败'
        })
        console.error('[数据库] [新增记录] 失败：', err)
      }
    })
  },
  saveWork() {
    var path;
    var length = this.data.picturePath.length - 4;
    var index = this.data.picturePath.substring(77, length-1);//得到标识文本的序号
    console.log("index=" + index);
    wx.cloud.uploadFile({
      cloudPath: 'TxtWork/' + getApp().globalData.openid + index + '.mp3',
      filePath: getApp().globalData.workPath,
      success: res => {
        // get resource ID
        console.log("保存成功 fielID="+res.fileID);
        this.onAdd(res.fileID);//调用数据库
        wx.pauseVoice();
      },
      fail: err => {
        // handle error
        console.log("保存失败")
      }
    })
  },
  onShareAppMessage: function () {
  }
})