import {
  getShareImg
} from '../../api/share.js'
const baseUrl = require('../../api/index').config.waimaiUrl;

const {
  app,
  Loading,
  onShareAppMessage,
  hLoading,

} = getApp();
Page({
  data: {
    showPoster: false,
    shareImageUrl: '',
    shareCode: ''
  },
  onLoad() {
    try {
      const memberId = wx.getStorageSync('memberId');
      if (memberId) {
        getShareImg(`${baseUrl}/client/${memberId}/share/create`, {}, {}, '加载中', res => {
          const {
            shareImageUrl,
            shareCode
          } = res.results
          this.setData({
            shareImageUrl: shareImageUrl,
            shareCode: shareCode
          })
          // wx.hideLoading()
        }, err => {
          // wx.hideLoading();
          wx.showToast({
            title: '获取图片出错',
            icon: 'none'
          })
        })
      } else {
        // error();
      }
    } catch (e) {
  console.error(e);
      // error(e);
    }
    wx.setNavigationBarColor({
      frontColor: '#000000',
      backgroundColor: '#ffae29',
      animation: {
        duration: 400,
        timingFunc: 'linear'
      }
    })
    wx.setNavigationBarTitle({
      title: '分享有礼'
    })
  },
  onShow() {
    // Loading();
    // hLoading();
  },
  saveShareImg() {
    const that = this;
    Loading('保存中...')
    wx.downloadFile({
      url: that.data.shareImageUrl,
      success: res => {
        console.log('保存下载之前');
        wx.saveImageToPhotosAlbum({
          filePath: res.tempFilePath,
          success: () => {
            console.log('保存本地');
            that.setData({
              showPoster: true
            })
            wx.showToast({
              title: '图片已保存到手机相册',
              icon: 'none',
              duration: 1500,
              mask: false,
            });
          },
          fail: () => {
            wx.showToast({
              title: '图片保存失败',
              icon: 'none',
              duration: 1500,
              mask: false,
            });
          },
          complete: () => {
            wx.hideLoading();
          }
        })
      }
    })
  },
  transitionEnd() {
    this.setData({
      showPoster: false
    })
  },
  onShareAppMessage
})