// pages/userCenter.js
const wxService = require('../../../../utils/wxService')

wxService.page({
  /**
   * 页面的初始数据
   */
  data: {
    query: '',
    integralCouponList: [], // 积分兑换优惠券列表
    noMore: false,
    isExchange: false,
    exchangeId: '',
    exchangePoint: 0,
    memberPoint: {
      total: '--',
      expirePoint: 0,
      expireDate: ''
    },
    activityId : '',
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    this.data.activityId = options.id;
    wx.hideShareMenu();
    this.refreshPointRequest();
    this.getActivityGroupInfo();
  },
  //刷新积分请求
  refreshPointRequest() {
    const { memberId } = wx.getStorageSync('_baseUserInfo')
    if (!memberId) {
      return;
    }
    wxService.get('/member/memberPoint/refreshExpiredPoint?memberId=' + memberId).then(res => { })
  },
  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {
    //获取会员积分信息
    this.getMemberIntegrateInfo();
  },
  //查询会员积分信息
  getMemberIntegrateInfo() {
    // wx.showLoading({
    //   title: '数据请求中..',
    // });
    const { memberId } = wx.getStorageSync('_baseUserInfo')
    if (!memberId) {
      return;
    }

    wxService.get(`/member/memberPoint/getMemberPointInfo?memberId=${memberId}`).then(res => {
      let data = res.data.data ? res.data.data : {};
      this.data.memberPoint.total = data.point ? data.point : 0;
      this.data.memberPoint.expirePoint = data.pointWillExpired ? data.pointWillExpired : 0;
      let expireDate = data.pointExpiredTime ? data.pointExpiredTime : '2019-12-31 23:59:59';

      if (expireDate) {
        let dateStr = expireDate.replace(/-/g, '/');
        let da = new Date(dateStr);
        let year = da.getFullYear();
        let month = (da.getMonth() + 1) < 10 ? '0' + (da.getMonth() + 1) : da.getMonth() + 1;
        let day = da.getDate() < 10 ? '0' + da.getDate() : da.getDate();
        expireDate = `${year}年${month}月${day}日`
      }

      this.data.memberPoint.expireDate = expireDate;
      this.setData({
        memberPoint: this.data.memberPoint
      });
    });
  },


  //查询指定积分换物活动兑换数量
  findExchangeNumByIds(integralGoodsList) {
    //获取ids
    let ids = integralGoodsList.map(g => {
      return g.id;
    });

    wxService.post(`/member/pointsRedemptionProductSetting/getExchangeCount`, ids).then(res => {
      if (res) {
        let data = res.data.data ? res.data.data : null;
        if (data) {
          for (let k in data) {
            let id = k, value = data[k];
            for (let i = 0; i < integralGoodsList.length; i++) {
              if (integralGoodsList[i].id == id) {
                integralGoodsList[i].canExchange = integralGoodsList[i].stock > value;
              }
            }
          }
        }
      }

      this.setData({
        integralGoodsList: integralGoodsList,
      });
    });
  },
  //获取积分活动分组详情
  getActivityGroupInfo(){
    wxService.get(`/merchant/groupingActivities/findById?id=${this.data.activityId}`).then(res => {
      if(res){
        let data = res.data.data ? res.data.data : null;
        if(data){
          let ids = data.sons.map(item => {
            return item.activateId;
          });

          this.initIntegralCouponList(ids);
        }
      }
    })
  },
  // 积分兑换优惠券列表
  initIntegralCouponList(ids) {
    wx.showLoading({
      title: '加载中'
    });

    wxService.post(`/coupon/pointsRedemptionCouponSetting/findByIds`,ids).then(res => {
      if (res) {
        const { result, data } = res.data
        if (result == 0) {
          wx.hideLoading()
          this.setData({
            integralCouponList: data
          });
        }
      }
    }).finally(() => {
      wx.hideLoading();
    })
  },
  //立即兑换优惠券
  exchange(e) {
    const { id, point } = e.currentTarget.dataset
    this.setData({
      isExchange: true,
      exchangeId: id,
      exchangePoint: point
    })
  },
  
  // 点击跳转至会员规则页
  handleGoMemberRulesRules() {
    wxService.router(`/pages/memberRules/memberRules?type=2`)
  },
  goCouponDetail(e) {
    const { id } = e.currentTarget.dataset
    wxService.router(`/pages/integralMallDetail/integralMallDetail?id=${id}`)
  },
  /**
  * 页面相关事件处理函数--监听用户下拉动作
  */
  onPullDownRefresh: function () { },

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

  },
})