// subPackage/page/pages/couponCenterInfo/couponCenterInfo.js
const wxService = require('../../../../utils/wxService')
const utils = require('../../../../utils/util')
wxService.page({

  /**
   * 页面的初始数据
   */
  data: {
    activityId : null,
    activityInfo : {},
    userHasBaseInfo : false,
    isLoading : true,
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    let id = options.id;
    this.data.activityId = id;
    this.getACtivityInfo();
    this.userHasLogin();
  },

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

  },

  //授权
  _getUserInfo(res = {}) {
    const userInfo = res.detail || {}
    if (res.detail.userInfo) {
      utils.getUserInfoByBtn(userInfo).then((data = {}) => {
        const { token } = data
        wx.setStorageSync('_accreditUserInfo', userInfo)
        if (token) {
          wx.setStorageSync('token', token)
        } else {
          wx.setStorageSync('token', '')
        }
        wx.setStorageSync('_baseUserInfo', data)
        const baseUserInfo = wx.getStorageSync('_baseUserInfo')
        // 获取当前会员是否是体验者
        const { member } = baseUserInfo
        const curMemberTrial = member && member.trial || false
        wx.setStorageSync('isExperiencer', curMemberTrial)
        this.setUserInfo()
      }).catch(err => {
        if (err) {
          wx.showToast({
            title: `会员系统异常请稍后重试!`,
            icon: 'none'
          })
        }
      })
    }
  },

  //获取当前用户是否登录
  userHasLogin(){
    const baseUserInfo = wx.getStorageSync('_baseUserInfo');
    if(baseUserInfo){
      this.setData({
        userHasBaseInfo : true
      })
    }
    else{
      this.setData({
        userHasBaseInfo: false
      })
    }
  },

  setUserInfo() {
    // 判断有无开卡
    const userInfo = wx.getStorageSync('_baseUserInfo')
    // 新用户去激活领卡 
    if (userInfo && userInfo.member && !userInfo.member.mobile && !userInfo.member.cardNoWeixin) {
      wxService.openCard()
      return false
    }
    // 跳转
    setTimeout(() => {
      this.getACtivityInfo();
      this.userHasLogin();
    }, 200)
  },

  //获取活动详情
  getACtivityInfo(){
    wxService.post(`/coupon/couponCenterActivity/buyer/getDetail?id=${this.data.activityId}`).then(res => {
      if(res){
        let obj = res.data.data ? res.data.data : null;
        if (obj){
          let arr  = obj.definition ? JSON.parse(obj.definition) : [];
          obj.desc = arr.filter(item => item.type == 2);
          obj.hasExpDate = arr.filter(item => item.type == 1).length > 0 ;
          this.data.activityInfo = obj;
          this.setData({
            activityInfo: this.data.activityInfo,
          });
          // 定时器为了防止触点那边没有正常返回用户就点击了
          setTimeout(() => {
            this.setData({
              isLoading : false,
            })
          },1000);
        }
      }
    })
  },

  //领取优惠券
  onTapGetCoupon(){
    if(this.data.isLoading){
      return ;
    }

    const { member } = wx.getStorageSync('_baseUserInfo');
    if(!member){
      wx.showToast({
        title: '请先去登录',
        icon : 'none'
      })
      return ;
    }

    //判断是否开卡
    if(!member.cardNoWeixin){
      wx.showToast({
        title: '请先开卡后购买',
        icon : 'none'
      });

      wxService.openCard()
      return ;
    }

    wx.showLoading({
      title: '领取中..',
    });
    
    let id = this.data.activityId;
    wxService.post(`/coupon/couponCenterActivity/buyer/coupon/draw?id=${id}`).then(res => {
      wx.hideLoading();
      if (res) {
        if (res.data.result == 0) {
          wx.showToast({
            title: '领取成功',
          });
        }
        else {
          wx.showToast({
            title: '领取失败，请稍后再试',
            icon: 'none'
          });
        }
      }
    });
  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {
    let url = this.data.activityInfo.listPicture ? this.data.activityInfo.listPicture : 'https://img3.bigaka.com/prd/3001/202003/20200331/3001649f2f08-3b4e-4b5b-97c1-30cdf646651c.png';
    return {
      title: `我分享给你一张“${this.data.activityInfo.couponName}”的优惠券，赶快领取吧~`,
      path: `/subPackage/page/pages/couponCenterInfo/couponCenterInfo?id=${this.data.activityId}`,
      imageUrl: url, // 可以更换分享的图片
    }
  }
})