// pages/integralMallDetail/integralMallDetail.js
const app = getApp()
const wxService = require('../../../../utils/wxService')
const utils = require('../../../../utils/util')
const envInfo = require('../../../../config/index').envInfo


wxService.page({
  /**
   * 页面的初始数据
   */
  data: {
    isExchange: false,
    dialogUserLimit : false,
    dialogStockEmpty : false,
    integralMallDetail: {}
  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow() {
    const { id } = this.options
    // this.getIntegralCouponDetail('579702812007600128')
    this.getIntegralCouponDetail(id)
  },

  //btn回调
  onDialogBtnCallBack(e) {
    let pages = getCurrentPages();
    let index = pages.length - 1;
    for (let i = 0; i < pages.length; i++) {
      if (pages[i].route.indexOf('IntegralMallGoods/IntegralMallGoods') > -1) {
        index = index - i;
        break;
      }
    }

    wx.navigateBack({
      delta: index
    });
  },

  //立即兑换
  exchange() {
    const { memberId } = wx.getStorageSync('_baseUserInfo');
    const id = this.data.integralMallDetail.id;

    if (!this.data.integralMallDetail.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,
        });
      }
    });
  },

  //获取积分兑换优惠券详情
  getIntegralCouponDetail(id) {
    wx.showLoading({
      title: '加载中'
    })
    wxService.get(`/member/pointsRedemptionProductSetting/get/${id}`).then(res => {
      const { result, data } = res.data
      if (result == 0) {
        wx.hideLoading()
        data.desc = JSON.parse(data.desc)
        data.canExchange = true;
        
        this.setData({
          integralMallDetail: data
        },() => {
          this.findExchangeNumByIds(id);
        });
      }
    }).finally(() => {
      wx.hideLoading()
    })
  },
  //查询指定积分换物活动兑换数量
  findExchangeNumByIds(id) {
    //获取ids
    let ids = [id];

    wxService.post(`/member/pointsRedemptionProductSetting/getExchangeCount`, ids).then(res => {
      let data = res.data.data ? res.data.data : null;
      if (data) {
        let value = data[id];
        this.data.integralMallDetail.canExchange = this.data.integralMallDetail.stock > value;
      }
      this.setData({
        integralMallDetail: this.data.integralMallDetail
      });
    });
  },
})