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

  /**
   * 页面的初始数据
   */
  data: {
    id : null,
    checked : false,
    showModal : false,
    valueCardInfo : {},
    buyType : '2',//现金支付 2 积分兑换
    userHasBaseInfo : false
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    this.data.id = options.id;
    wx.hideShareMenu();

    this.getValueCardActivityInfo();
  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {
    this.userHasLogin();
  },

  //获取当前用户是否登录
  userHasLogin(){
    const baseUserInfo = wx.getStorageSync('_baseUserInfo');
    if(baseUserInfo){
      this.setData({
        userHasBaseInfo : true
      })
    }
    else{
      this.setData({
        userHasBaseInfo: false
      })
    }
  },
  //授权
  _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'
          })
        }
      })
    }
  },

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

  //获取活动详情
  getValueCardActivityInfo(){
    wx.showLoading({
      title: '加载中..',
    });

    wxService.post(`/merchant/superValueCardActivity/miniProgram/getDetail?id=${this.data.id}`).then(res => {
      if (res) {
        let obj = res.data.data ? res.data.data : null;
        if(obj){
          obj.activityDesc = obj.activityDesc ? JSON.parse(obj.activityDesc) : [];
          this.data.buyType = obj.payWayType;
          obj.acPayMoney = parseFloat(obj.moneyAmount / 10 / 10).toFixed(2);
          obj.startTime = obj.startTime.substring(0, 10);
          obj.endTime = obj.endTime.substring(0,10);
          obj.hasDate = obj.activityDesc.filter(item => item.type == 1).length > 0;
          //处理说明文本
          let descArr = JSON.parse(JSON.stringify(obj.activityDesc));
          descArr = descArr.filter(item => item.type != 1);
          // let tempArr = descArr.map(item => {
          //   return item.value;
          // });
          // console.log(obj)

          obj.descArr = descArr;
          this.data.valueCardInfo = obj;
          this.setData({
            buyType: this.data.buyType,
            valueCardInfo: this.data.valueCardInfo
          });
        }
      }
      wx.hideLoading();
    });
  },

  //修改选中状态
  onTapSwitchChecked(){
    this.data.checked = !this.data.checked;
    this.setData({
      checked: this.data.checked
    });
  },
  //关闭modal
  onTapCloseModal(){
    this.setData({
      showModal : false,
    });
  },
  //查看rule
  onTapViewRule(){
    this.setData({
      showModal : true
    })
  },
  //同意并阅读
  onTapModalAgree(){
    this.setData({
      showModal: false,
      checked : true,
    });
  },
  //立即购买
  onTapBuy(){
    if(!this.data.checked){
      return ;
    }

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

    let memeberId = member.id,
      // storeId = member.storeId;
      storeId = '';
    let activityId = this.data.id;  
    let url = '';
    if (this.data.buyType == 1){
      url = `/merchant/superValueCard/miniProgram/buy?activityId=${activityId}&memberId=${memeberId}&payType=1&storeId=${storeId}`;
    }
    else{
      url = `/merchant/superValueCard/miniProgram/buy?activityId=${activityId}&memberId=${memeberId}&storeId=${storeId}`;
    }
    
    wx.showLoading({
      title: '支付中..',
    });

    wxService.post(url).then(res => {
      wx.hideLoading();
      if(res.data.result == 0){
        this.setData({
          checked: false,
        });
        //现金支付
        if (this.data.buyType == 1){
          let data = res.data.data ? res.data.data : null;
          if(data){
            let wxParams = data.wxParams;
            wx.requestPayment({
              timeStamp: wxParams.timeStamp,
              nonceStr: wxParams.nonceStr,
              package: wxParams.package,
              signType: wxParams.signType,
              paySign: wxParams.paySign,
              success : res => {
                wx.showToast({
                  title: '支付成功!',
                });
                wx.showLoading({
                  title: '跳转中...',
                });
                setTimeout(() => {
                  wx.hideLoading();
                  wx.navigateTo({
                    url: '/subPackage/page/pages/myValueCard/myValueCard',
                  });
                },500);
              },
              fail : error => {
                wx.showToast({
                  title: '已取消支付',
                  icon : 'none'
                });
              }
            })
          }
        }
        else{
          wx.showModal({
            title: '购买成功',
            content: '是否跳转到我的超值卡列表查看？',
            confirmColor: '#ff2222',
            success(res){
              if (res.confirm) {
                wx.navigateTo({
                  url: '/subPackage/page/pages/myValueCard/myValueCard',
                });
              } else if (res.cancel) {
                
              }
            },
          });
        }
      }
      else{
        wx.showToast({
          title: '购买失败，请稍后再试！',
          icon : 'none'
        });
      }
    });
  },
  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {

  },

})