index.js 9.09 KB
// packageActivity/pages/solitaire/index/index.js
import {
  jumpAuthMixin
} from "~/mixins/index";
const generateOptionsArray = function (count = 9) {
  return Array.from({
    length: count
  }, (_, index) => Number(index + 1))
}
Page({
  behaviors: [jumpAuthMixin],
  /**
   * 页面的初始数据
   */
  data: {
    list: []
  },
  /**
   * 生命周期函数--监听页面加载
   */
  onLoad(options) {},


  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady() {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow() {
    const {
      options
    } = this
    console.log(options,'--------')
    if (options.id) this.options.relayLotteryId = options.id
    if (options.isLogin) this.getGroupEnterInfo(options)
    else this.jumpLoading() //直接打开时跳转、防止sessionId失效
  },
  async getGroupEnterInfo(options) {
    //测试时需要分享测试
    // let query = []
    // Object.keys(options).map(key => {

    //   if (key != 'isLogin') query.push(`${key}=${options[key]}`)
    // })
    // this.shareQuery = query.join('&')
    // this.noPageAuth = true
    const res = await wx.p.router.intercept()
    if (!res) {
      const {
        userInfo
      } = this.data
      if (!userInfo.nickName) return this.getNickNameAndHeadUrl()
      try {
        const _this = this
        wx.getGroupEnterInfo({
          async success({
            iv,
            encryptedData
          }) {
            const {
              data,
              code,
              message
            } = await wx.p.api.userApi.getOpengid({
              iv,
              encryptedData
            })
            if (code == 0 && data) {
              console.log('openGid:', data)
              const res = await wx.p.api.userApi.openGIdtoChatId({
                merchantId: options.merchantId,
                openGid: data
              })
              console.log('chatId:', res.data)
              options.chatId = res.data || ''
              this.options = options
              _this.getSolitaireDetail(options)
            } else throw message
          },
          fail(err) {
            _this.getSolitaireDetail(options)
          }
        })
      } catch (error) {
        if (error) wx.p.wxApi.showToast(error)
      }
    }
  },
  /**获取用户接龙信息 */
  async getSolitaireUserInfo(params) {
    delete params.isLogin
    try {
      const {
        userInfo: {
          nickName: name,
          phone,
          openId,
          unionId
        }
      } = this.data, {
        code,
        data,
        message
      } = await wx.p.api.solitaireApi.getSolitaireUserInfo({
        ...params,
        name,
        phone,
        openId,
        unionId
      })
      if (code == 0) {
        if (data) {
          /**
           * recordId 记录id 
           * stateCode 状态码 -1.未参与 0.已参加 1.未中奖 2.已中奖
           * relayContent 接龙内容
           * prizeType	奖品类型 1.红包 2.优惠券 3.权益
           * prizeId	奖品id (已领取时返回)
           * claimState 领取状态 0.未领取 1.已领取
           */
          const {
            stateCode,
            stateName,
            relayContent,
            claimState,
            prizeType,
            recordId,
            prizeId
          } = data
          if (stateCode == 2) {
            this.setData({
              disabled: true
            })
            if (claimState == 0) {
              if (prizeType == 1) this.bindActivityRedEnvelope(recordId)
              else this.getCoupon(recordId)
            } else {
              if (prizeType == 1) this.getRedEnvelopeAwardInfo({
                awardInfoId: prizeId,
                params
              })
              else this.getCouponInfo(prizeId)
            }
          } else {
            if (stateCode == 0 || stateCode == 1) this.setData({
              ['popupConfig.type']: stateCode == 0 ? 1 : 2,
              ['popupConfig.title']: stateName || '',
            })
            this.setData({
              show: stateCode == 0 || stateCode == 1,
              disabled: stateCode == 1,
              ['popupConfig.relayContent']: relayContent
            })
          }
        }
      } else throw message
    } catch (error) {
      console.log(error)
      this.showGroupNoAccess(error)
    }
  },
  async getCoupon(recordId) {
    const {
      activityObject: {
        rewardId,
        merchantId,
        merchantName
      }
    } = this.data,
      data = await wx.p.api.solitaireApi.getCoupon({
        couponId: rewardId,
        merchantId,
        merchantName
      })
    if (data && data.length) {
      let [info] = data
      this.setCouponInfo(info)
      wx.p.api.solitaireApi.recordedPrizeInfo({
        prizeId: info.userCouponId,
        recordId
      })
    } else wx.p.wxApi.showToas('奖品已发完')
  },
  async getCouponInfo(userCouponId) {
    const info = await wx.p.api.couponsApi.couponsDetail({
      userCouponId
    })
    info.userCouponId = userCouponId
    this.setCouponInfo(info)
  },
  setCouponInfo(info) {
    info.receiveStartTime = new Date(info.receiveStartTime).format('yyyy/MM/dd')
    info.receiveEndTime = new Date(info.receiveStartTime).format('yyyy/MM/dd')
    if (info.discountIntensity) info.discountIntensity = Number(info.discountIntensity / 100)
    if (info.denomination) info.denomination = Number(info.denomination / 100)
    info.id = info.userCouponId
    this.setData({
      couponInfo: info,
      showCoupon: true
    })
  },
  /**获取接龙活动详情 */
  async getSolitaireDetail(params) {
    try {
      wx.p.wxApi.showLoading()
      const res = await wx.p.api.solitaireApi.getSolitaireDetail(params)
      this.getSolitaireUserInfo(params)
      this.getSolitaireAewardList(params)
      this.setData({
        activityDetail: decodeURIComponent(wx.p.format.encodeSearchKey(res.description)),
        title: res.title,
        array: generateOptionsArray(res.numLimit),
        loading: true,
        activityObject: res
      })
      if (new Date(wx.p.format.iosTimeFormat(res.lotteryTime)).getTime() <= Date.now()) this.setData({
        ['popupConfig.numWin']: res.numWin
      })
      wx.p.wxApi.hideLoading()
    } catch (error) {
      console.log(error)
      if (error) wx.p.wxApi.showToast(error)
    }
  },
  /**获取接龙明细 */
  async getSolitaireAewardList(params) {
    const {
      list
    } = await wx.p.api.solitaireApi.getSolitaireAewardList(params)
    this.setData({
      list: list.reverse()
    })
  },
  /**领取红包 */
  async bindActivityRedEnvelope(recordId) {
    const {
      activityObject: {
        rewardId,
        id
      },
      userInfo
    } = this.data
    wx.p.router.redirectTo('/packageActivity/pages/redEnvelope/index/index', {
      activityId: rewardId,
      merchantId: userInfo.merchantId,
      source: 2,
      recordId,
      isLogin: 1,
      businessId: id
    })
  },
  /**红包活动回显 */
  async getRedEnvelopeAwardInfo({
    awardInfoId,
    params
  }) {
    const {
      activityObject: {
        rewardId
      }
    } = this.data
    wx.p.router.redirectTo('/packageActivity/pages/redEnvelope/index/index', {
      activityId: rewardId,
      merchantId: params.merchantId,
      awardInfoId,
      isLogin: 1
    })
  },
  showGroupNoAccess(title) {
    this.setData({
      ['popupConfig.type']: 1,
      ['popupConfig.title']: title,
      ['popupConfig.showDefault']: true,
      show: true,
      disabled: true
    })
  },
  bindPickerChange(e) {
    this.setData({
      'params.num': this.data.array[e.detail.value]
    })
  },
  inSolitaire() {
    const {
      userInfo
    } = this.data
    this.setData({
      flag: true
    })
    this.setData({
      'params.name': userInfo.nickName
    })
  },
  /**提交 */
  async submit() {
    try {
      const {
        params,
      } = this.data, {
        id: relayLotteryId,
      } = this.options
      console.log(params)
      if (!params.name) throw '请输入名称!'
      if (!params.num) throw '请选择数字!'
      wx.p.wxApi.showLoading()
      const {
        code,
        data,
        message
      } = await wx.p.api.solitaireApi.commitSolitaire({
        relayLotteryId,
        name: params.name,
        relayContent: params.num,
      })
      wx.hideLoading()
      if (code == 0) {
        if (data) {
          wx.p.wxApi.showToast('提交成功!')
          this.setData({
            disabled: true
          })
          this.getSolitaireAewardList({
            relayLotteryId
          })
        } else throw message
      } else this.setData({
        show: true
      })
    } catch (error) {
      wx.hideLoading()
      if (error) wx.p.wxApi.showToast(error)
    }
  },
  input(e) {
    const {
      value
    } = e.detail, {
      name
    } = e.target.dataset
    this.setData({
      [name]: value
    })
  },
  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide() {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload() {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh() {

  },

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

  }
})