const util = require('../../../../utils/util.js');
const app = getApp();
import VODUpload from '../../../../utils/aliyun-upload-sdk-1.0.0.min.js'

Page({
  data: {
    index: null,
    show: false,
    info: {},
    isRestUpload: false,
    courseId: '',
    alert: {}
  },
  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {
    var that = this;
    let imgUrl
    var uploader = new VODUpload({
      timeout: 60000,
      region: "cn-shanghai",
      // 添加文件成功
      addFileSuccess: function (uploadInfo) {
        console.log("添加文件成功")
      },

      // 开始上传
      onUploadstarted: function (uploadInfo) {
        console.log('文件开始上传...');
        var url;
        let filName = that.data.playerId + '.mp4'
        url = util.config.apiServer + "vod/auth.do?fileName=" + filName + '&cate=course';
        wx.request({
          'url': url,
          success: (res => {
            if (res.data.code === 0) {
              imgUrl = res.data.url + res.data.address.FileName
              var akInfo = res.data;
              uploader.setUploadAuthAndAddress(uploadInfo, akInfo.uploadAuth, akInfo.uploadAddress, akInfo.videoId);
            } else {
              util.showTips('上传失败，请重新上传');
              uploader.stopUpload();
            }
          }),
          fail: (res => {
            util.showTips(res.reason);
            uploader.stopUpload();
          })
        });
      },

      // 文件上传成功
      onUploadSucceed: function (uploadInfo) {
        console.log('文件上传成功!')
        that.setData({
          percent: 100
        });
        that.data.info.myVideo = imgUrl;
        that.setData({
          info: that.data.info
        });
        that.uploadAli()
        wx.hideLoading();
      },
      // 文件上传失败
      onUploadFailed: function (uploadInfo, code, message) {
        console.log('文件上传失败!')
        util.showTips('上传失败，请重新上传');
        uploader.stopUpload();
      },
      // 上传凭证超时
      onUploadTokenExpired: function (uploadInfo) {},
      // 全部文件上传结束
      onUploadEnd: function (uploadInfo) {

      }
    });
    this.setData({
      uploader: uploader
    });
  },
  onLoad(options) {
    this.setData({
      courseId: options.courseId || '',
      playerId: options.playerId || ''
    });
    this.getInfo();
  },
  getInfo() {
    let that = this;
    util.ajax({
      func: 'v2/course/video/detail',
      data: {
        "courseId": that.data.courseId,
        "playerId": that.data.playerId
      }
    }, function (res) {
      if (res.code == 0) {
        that.setData({
          info: res.data,
          isRestUpload: !util.isEmpty(res.data.myVideo)
        });
      } else
        util.showTips(res.reason);
    })
  },
  videoPlay(event) {
    let e = event.currentTarget,
      index = e.dataset['index'];

    if (!this.data.index) {
      this.setData({
        index
      });
      this.videoContext = wx.createVideoContext('video_' + index)
      this.videoContext.play();
      this.videoContext.requestFullScreen();
    } else {
      this.videoContext = wx.createVideoContext('video_' + this.data.index)
      this.videoContext.stop();
      this.videoContext.exitFullScreen();
      this.setData({
        index
      });
      this.videoContext = wx.createVideoContext('video_' + index);
      this.videoContext.play();
      this.videoContext.requestFullScreen();
    }
  },
  playEnd() {
    this.setData({
      index: null
    });
  },
  fullscreen(e) {
    if (!e.detail.fullScreen) {
      this.videoContext.stop();
      this.setData({
        index: null
      });
    }
  },
  close() {
    this.setData({
      isRestUpload: true
    });
  },
  // 视频上传
  addVideo() {
    let that = this;
    wx.chooseMedia({
      count: 1,
      mediaType: ["video"],
      type: "video",
      sourceType: ["album", "camera"],
      maxDuration: 30,
      camera: "back",
      success(res) {
        if (parseInt(res.tempFiles[0].duration / 60) > util.config.duration) {
          util.showTips("您上传的视频时间太长，请限制在" + util.config.duration + "分钟之内。");
          return false;
        }
        wx.showLoading({
          title: "上传中…",
        });
        // api拿不到真实文件名
        let name = res.tempFiles[0].tempFilePath.split('tmp/')
        var file = {
          url: res.tempFiles[0].tempFilePath,
          name: name
        };
        that.setData({
          videosName: file.name
        });
        var uploader = that.data.uploader;
        var userData = '{"Vod":{}}'
        uploader.addFile(file, null, null, null, userData)
        that.data.uploader.startUpload();
      },
    });
  },

  uploadAli() {
    var _this = this;
    util.ajax({
      func: "v2/course/video/confirm",
      data: {
        video: _this.data.info.myVideo,
        sampleId: _this.data.info.id,
        playerId: _this.data.playerId
      },
      method: 'POST',
      contentType: 'application/x-www-form-urlencoded'
    }, function (res) {
      if (res.code == 0) {
        let alert = {
          title: res.data.reupload == 0 ? "恭喜您，上传成功" : "恭喜您，重传成功"
        };
        if (res.data.status == 1) {
          alert.icon = 'upload-ok';
          alert.score = res.data.score;
        } else {
          alert.content = res.data.message;
          alert.icon = res.data.overtime == 0 ? 'reset-upload' : 'time-out';
          alert.status = 1;
        }
        _this.setData({
          alert,
          show: true
        });
      } else
        util.showTips(res.reason);
    });
  }
})