// pages/download/download.js
const {warn} = require("../../utils/util.js");

Page({

  /**
   * Page initial data
   */
  data: {
    url: "",
    type: "",
    progress: 0,
    error: ""
  },

  /**
   * Lifecycle function--Called when page load
   */
  onLoad(options) {
    let url = decodeURIComponent(options.url);
    if (!url) {
      warn("请指定下载地址！")
      wx.navigateBack()
      return;
    }
    this.setData({url});
    // check file type
    let type = options.type;
    if (!['image', 'video'].includes(type)) {
      warn('暂不支持下载音视频及图片以外文件')
      wx.navigateBack()
      return;
    }
    this.prepare()
  },

  downloadToFixed() {
    let { url } = this.data;
    let filename = url.split("/").pop();
    let task = wx.downloadFile({
      url, filePath: wx.env.USER_DATA_PATH + '/' + filename,
      success: ({filePath}) => {
        this.saveToPhone(filePath)
      },
      fail: (e) => {
        warn("下载失败")
        wx.navigateBack()
      }
    })
    task.onProgressUpdate(({progress}) => {
      this.setData({progress})
    });
  },

  saveToPhone(filePath, retry) {
    let { type } = this.data;
    if (type === 'image') {
      wx.saveImageToPhotosAlbum({
        filePath,
        success: () => {
          warn("图片已保存至相册", 2000, () => wx.navigateBack())
        },
        fail: (e) => {
          if (retry) {
            this.downloadToFixed()
          } else {
            warn("图片保存失败！", 5000)
            this.setData({error: e.errMsg})
          }
        }
      })
    } else {
      wx.saveVideoToPhotosAlbum({
        filePath,
        success: () => {
          warn("视频已保存至相册", 2000, () => wx.navigateBack())
        },
        fail: (e) => {
          if (retry) {
            this.downloadToFixed()
          } else {
            this.setData({error: e.errMsg})
            warn("视频保存失败！", 5000)
          }
        }
      })
    }
  },
  download() {
    let { url } = this.data;
    const task = wx.downloadFile({
      url: url,
      success: ({tempFilePath}) => {
        this.saveToPhone(tempFilePath, true)
      },
      fail: (e) => {
        warn("下载失败")
        wx.navigateBack()
      }
    });
    task.onProgressUpdate(({progress}) => {
      this.setData({progress})
    });
  },

  prepare() {
    wx.getSetting({
      withSubscriptions: true,
      success: (res) => {
        if (!res.authSetting['scope.writePhotosAlbum']) {
          wx.authorize({
            scope: 'scope.writePhotosAlbum',
            success: () => {
              this.download()
            },
            fail: () => {
              warn('保存文件需要授权写入相册', 2000, () => wx.navigateBack())
            }
          })
        } else {
          this.download()
        }
      }
    })
  },
  /**
   * Lifecycle function--Called when page is initially rendered
   */
  onReady() {

  },

  /**
   * Lifecycle function--Called when page show
   */
  onShow() {

  },

  /**
   * Lifecycle function--Called when page hide
   */
  onHide() {

  },

  /**
   * Lifecycle function--Called when page unload
   */
  onUnload() {

  },

  /**
   * Page event handler function--Called when user drop down
   */
  onPullDownRefresh() {

  },

  /**
   * Called when page reach bottom
   */
  onReachBottom() {

  },

  /**
   * Called when user click on the top right corner to share
   */
  onShareAppMessage() {

  }
})
