// pages/welfareMall/activityInfo/activityInfo.js
import WelfareMall from '../../../api/welfareMall';
import Activity from '../../../api/activity';
import Statistics from '../../../components/statistics/index'
const util = require('../../../utils/util.js');
const app = getApp();
import {getMobileCache, getPhoneNumberNew as getPhoneNumberSync, getColor} from '../../../utils/user'
Page({

  /**
   * 页面的初始数据
   */
  data: {
     detail:[],
     activityId:'',
     statusShowText:'',
     buttonText:'',
     userMobile: '', //用户手机号
     orderInfo: [], //下单信息
     hideWindowValue:false,
     preventDup:true,
     config: {},
     orderSn:"",
     department: '',
     valueImgList: [],
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: async function (options) {
    console.log(options)
    let  userMobile = await Activity.getMobileCache();
    if (userMobile.length !== 0) {
      this.setData({
        userMobile: userMobile,
      })
    }
    console.log(userMobile);
    if(options.activityId){
      this.setData({
        activityId: options.activityId,
        department: options.department,
      })
    this.getActivityDetail(options.activityId)
    }

    this.refStatisticsPostParam = Statistics.done({
      module: 'activity:detail',
      action: 'visit',
      businessId: options.activityId,
      channel: options.channel,
      department: options.department
    })
  },

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

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: async function () {
    wx.setStorageSync('configinfo',null);
    let info =  await getColor();
    this.setData({
      config:info.config,
      valueImgList: info.valueImgList,
    })
  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },

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

  },

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

  },

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

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {

  },
  getActivityDetail: async function(activityId) {

     let res  = await WelfareMall.getActivityDetail(activityId)

     let statusShowText = '';
     if(res.data.stock <= 0){
      statusShowText = '已售罄'
     }
     if(res.data.status ==3){
      statusShowText = '已结束'
     }

     if(res.data.status ==1){
      statusShowText = '待开始'
     }

     
     console.log(res.data.stock)
     let buttonText = res.data.isPay == 1 ? '立即抢购' : '立即领取';
     // 构建券包传参参数
     const couponList = []
     if (res.data.activityCouponList && Array.isArray(res.data.activityCouponList)) {
       res.data.activityCouponList.forEach(v => {
          const coupon = v.coupon
          if (coupon) {
            coupon.num = v.num
            couponList.push(coupon)
          }
       })
     }
     this.setData({
       detail:res.data,
       statusShowText:statusShowText,
       buttonText:buttonText,
       couponList,
     })
  },

  
  /**
   * 获取手机号
   * @param {*} e 
   */
  getPhoneNumber(e) {
    let _self = this;
      getPhoneNumberSync(e, async () => {
      let userMobile = Activity.getMobileCache();
      if (userMobile.length !== 0) {
        _self.setData({
          userMobile: userMobile,
        })
        _self.nowBuy();
      } 
  })
    // this.setData({
    //   hideWindowValue:true
    // })
    // return;
    // let _self = this;
    // var encryptedData = e.detail.encryptedData;
    // var iv = e.detail.iv;
    // if (!encryptedData || encryptedData.length == 0 || !iv || iv.length == 0) {
    //   return;
    // }
    //获取手机号
    // app.doDecodePhone(encryptedData, iv, function () {
    //   let userMobile = Activity.getMobileCache();
    //   if (userMobile.length !== 0) {
    //     _self.setData({
    //       userMobile: userMobile,
    //     })
    //     _self.nowBuy();
    //   }
    
    // });
  },

  /**
   * 下单
   */
  async nowBuy() {
    let _self = this;
    if(!this.data.preventDup){
        return;
    }
    this.setData({
      preventDup:false
    })
    try {
      let res = await WelfareMall.createOrder(_self.data.userMobile, _self.data.detail.activityId,1, "", this.refStatisticsPostParam);
      _self.setData({
        orderInfo: res.data,
      })
      if (this.data.detail.isPay == 1 && _self.data.orderInfo.orderSn) {
        _self.goPay();
      } else {
        _self.setData({
          hideWindowValue:true,
          preventDup:true,
          orderSn:_self.data.orderInfo.orderSn,
          isPay:this.data.detail.isPay
        })
      }

    } catch (err) {
      this.setData({
        preventDup:true
      })
      app.showToast(err.msg);
    }

    Statistics.done({
      module: 'activity:detail',
      action: 'click',
      businessId: this.data.activityId,
      department: this.data.department
    })

  },
   /**
   * 获取订单参数
   */
  async goPay() {
    // console.log(wx.getStorageSync('loginInfo').openId)
    var _self = this;
      let result = await WelfareMall.getOrderParams(_self.data.orderInfo.orderSn,wx.getStorageSync('loginInfo').openId,true);
      // console.log(result);
      let res = result.data
      wx.requestOrderPayment({
        timeStamp: res.wxPrePayVo.timeStamp,
        package: res.wxPrePayVo.pack,
        nonceStr: res.wxPrePayVo.nonceStr,
        signType: res.wxPrePayVo.signType,
        paySign: res.wxPrePayVo.paySign,
        orderInfo:res.orderInfo,
        success: function (res) {
          //支付成功，跳转领取成功页面
          _self.setData({
            hideWindowValue:true,
            preventDup:true,
            orderSn:_self.data.orderInfo.orderSn
          })
         
        },
        fail: function (res) {
          _self.setData({
            preventDup:true,
            orderSn:_self.data.orderInfo.orderSn
          })
          _self.goToOrderCancelInfo()
        }
      })
  },

  goToOrderCancelInfo(){
    wx.redirectTo({
      url: '/pages/welfareMall/order/orderCompletion?ordersn='+this.data.orderSn
    })
  },
  //type 1  是未支付带过去的    2 是已支付带过去的
   async goToOrderInfo(){
   
    //如果是支付的订单才去查询订单状态
    if(this.data.isPay && this.data.orderSn){
       await WelfareMall.getPayStatus(this.data.orderSn);
    }

    wx.redirectTo({
      url: '/pages/welfareMall/order/orderCompletion?ordersn='+this.data.orderSn
    })
     
  },

hideWindow(){
  this.setData({
    hideWindowValue:false
  })
}
})