const { default: activity } = require("../../api/activity");
const util = require('../../utils/util.js')
const app = getApp();
import { getMobileCache, getPhoneNumberNew as getPhoneNumberSync } from '../../utils/user'
Page({

  /**
   * 页面的初始数据
   */
  data: {
    activityId:'', //活动id
    userMobile:'', //电话
    codeId:'',//code唯一码
    memberMobile:'',//领取人手机号
    isEffective:false, //是否过期,默认过期
    activityInfo:[],
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    let _self = this;
    if(options.q) {
      let url = decodeURIComponent(options.q);
      let id = util.getQueryVariable('id',url);
      if(id) {
        _self.setData({
          codeId:id,
        })
        //根据codeId查出该活动是否过期
        _self.getShareActivityCode(id);
      }
    }
    
  },
  //根据code-id获取券详情信息 判断该codeId是否过期
  async getShareActivityCode(codeId) {
    let _self = this;
    try {
      let result = await activity.getShareActivityCode(codeId);
      _self.setData({
        // activityInfo:result.activityInfo,
        activityId:result.activityInfo.activityId
      })
      _self.activityInfo(result.activityInfo.activityId);
      let expireTime = result.expireTime;
      //失效的时间
      let expireTimeTime = util.getUnixTime(expireTime);
      //获取当前的时间戳
      var nowTime = Date.parse(new Date())/1000;
      if(expireTimeTime-nowTime>0) {
        _self.setData({
          isEffective:true
        })
      }
    }catch(error) {
      _self.setData({
        isEffective:false
      })
    }
  },
  /**
   *
   */
  getNowCoupon() {
    let _self = this;
    //判断是否过期
    if(_self.isEffective==false) {
      wx.showToast('券码包已过期')
      return;
    }
    _self.createOrder();
  },
  /**
   * 创建订单
   */
  async createOrder() {
    let _self = this;
    try {
      let order = await activity.createOrder(_self.data.activityId,_self.data.memberMobile);
      let orderSn = order.orderSn;
      _self.setData({
        orderSn:orderSn
      })
      let codeId = _self.data.codeId;
      try {
        //插入 订单 和 codeId  bind-share-code
        let res = await activity.bindShareCode(orderSn,codeId);
      }catch(e) {
        console.log(e)
      }
      if (_self.data.activityInfo.isPay == 1 && orderSn) {
        // console.log(22222)
        //TODO::暂时屏蔽
        // _self.goPay();
        app.showToast('领取成功','success',1000,function(){
          wx.redirectTo({
            url: '/pages/myCoupons/myCoupons?mobile='+_self.data.memberMobile,
          })
        })
      } else {
        //领取成功
        app.showToast('领取成功','success',1000,function(){
          wx.redirectTo({
            url: '/pages/myCoupons/myCoupons?mobile='+_self.data.memberMobile,
          })
        })
      }


    }catch(e) {

    }

  },

  /**
   * 获取订单参数
   */
  async goPay() {
    var _self = this;
    try {
      let res = await activity.getOrderParams(_self.data.orderSn,_self.activityInfo.name);
      console.log(res);
      res = res.wxPrePayVo
      wx.requestPayment({
        timeStamp: res.timeStamp,
        package: res.pack,
        nonceStr: res.nonceStr,
        signType: res.signType,
        paySign: res.paySign,
        success: function (res) {
          //领取成功
          app.showToast('领取成功','success',1000,function(){
            wx.redirectTo({
              url: '/pages/myCoupons/myCoupons?mobile='+_self.data.memberMobile,
            })
          })
        },
        fail: function (res) {

        }
      })
    } catch (err) {
      console.log(err)
    }
  },

  //获取手机号
  getPhoneNumber(e) {
    let _self = this;
    getPhoneNumberSync(e, _ => {
      let userMobile = activity.getMobileCache();
      if (userMobile.length !== 0) {
        _self.setData({
          memberMobile: userMobile,
        })
        _self.createOrder();
      }
    })
    // let _self = this;
    // var encryptedData = e.detail.encryptedData;
    // console.log(encryptedData);
    // var iv = e.detail.iv;
    // if (!encryptedData || encryptedData.length == 0 || !iv || iv.length == 0) {
    //   return;
    // }
    // //获取手机号
    // getApp().doDecodePhone(encryptedData, iv, function () {
    //   let userMobile = activity.getMobileCache();
    //   if (userMobile.length !== 0) {
    //     _self.setData({
    //       memberMobile: userMobile,
    //     })
    //     _self.createOrder();
    //   }
    //
    // });
  },

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

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {

  },

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

  },

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

  },

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

  },

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

  },

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

  },

  /**
   * 获取活动详细信息
   * @param {*} activityId
   */
  async activityInfo(activityId){
    let result = await activity.getActivityDetail(activityId);
    // console.log('获取活动详细信息');
    // console.log(result)
    var objSwitch = getApp().globalData.typeSwitchObj

    var couponTypeAndNumObj = {};
    var couponList = result.activityCouponList;
    for (let j = 0; j < couponList.length; j++) {
      var couponNum = couponList[j]['num'] ? couponList[j]['num'] : 1;

      var value = couponList[j]['coupon']['type'];
      var showText = objSwitch[couponList[j]['coupon']['type']];

      var nowNume = 0;
      if (couponTypeAndNumObj[value]) {
        nowNume = couponTypeAndNumObj[value]['num'];
        console.log(nowNume)
      }
      couponTypeAndNumObj[value] = {
        "typeText": showText,
        "num": couponNum + nowNume
      }

    }
    result.couponTypeAndNumObj = couponTypeAndNumObj
    this.setData({
      activityInfo:result
    })
  },
})