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

wxService.page({
  /**
   * 页面的初始数据
   */
  data: {
    query: '',
    integralGoodsList: [], // 限量精品列表
    noMore: false,
    isExchange: false,
    exchangeId: '',
    exchangePoint: 0,
    memberPoint: {
      total: '--',
      expirePoint: 0,
      expireDate: ''
    },
    dialogStockEmpty: false,
    dialogUserLimit: false,
    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 => { })
  },

  //获取积分活动分组详情
  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.initIntegralProductList(ids);
        }
      }
    })
  },
  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {
    //获取会员积分信息
    this.getMemberIntegrateInfo();
    if (wx.getStorageSync('needReloadExchangeList')) {
      wx.removeStorageSync('needReloadExchangeList');
      this.getActivityGroupInfo();
    }
  },
  //积分换物记录
  onTapToExchangeRecords() {
    wx.navigateTo({
      url: '/subPackage/page/pages/recordList/recordList',
    });
  },
  //查询会员积分信息
  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
      });
    });
  },

  // 查询所有生效中的活动 限量精品
  initIntegralProductList(ids) {
    wx.showLoading({
      title: '加载中'
    })

    wxService.post(`/member/pointsRedemptionProductSetting/findByIds`,ids).then(res => {
      if (res) {
        const { result, data } = res.data
        if (result == 0) {
          let list = data ? data : [];
          let integralGoodsList = list;
          this.findExchangeNumByIds(integralGoodsList);
        }
      }
    }).finally(() => {
      wx.hideLoading();
    })
  },
  //查询指定积分换物活动兑换数量
  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,
      });
    });
  },
 
  // 立即兑换物品
  exchangeGoods(e) {
    const { id, point, canexchange } = e.currentTarget.dataset;
    const { memberId } = wx.getStorageSync('_baseUserInfo');

    if (!canexchange) {
      this.setData({
        dialogStockEmpty: true
      });
      return;
    }

    //检查是不是可以兑换
    wx.showLoading({
      title: '检查兑换资格中..',
    });

    wxService.post(`/member/pointsRedemptionProductRecord/checkByMemberIdAndSettingId?memberId=${memberId}&settingId=${id}`).
      then(res => {
        if (res.data.data == -1) {
          this.setData({
            dialogUserLimit: true
          })
        }
        else {
          wx.navigateTo({
            url: '/subPackage/page/pages/exchangeAddress/exchangeAddress?id=' + id,
          });
        }
      });
  },
  //跳转积分换物详情
  // subPackage/page/pages/IntegrateGoodsExchangeInfo/IntegrateGoodsExchangeInfo
  goIntegrateGoodsExchangeDetail(e) {
    const { id } = e.currentTarget.dataset
    wxService.router(`/subPackage/page/pages/IntegrateGoodsExchangeInfo/IntegrateGoodsExchangeInfo?id=${id}`)
  },
  
  /**
  * 页面相关事件处理函数--监听用户下拉动作
  */
  onPullDownRefresh: function () { },

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

  },
})