// pages/yhq/yhq.js
var e = function (e) {
  return e && e.__esModule ? e : {
    default: e
  };
}(require("../../../../utils/LoadMore.js")), t = getApp(), a = t.request, o = t.globalData.setting, os = o,
  i = require("../../../../utils/util.js"), ut = i, b = require("../../../../app.js"), app = b, s = require("../../../../utils/common.js"), n = new e.default();
var regeneratorRuntime = require('../../../../utils/runtime.js');
var t_pay = require("../../../../utils/pay2.js");

Page({

  /**
   * 页面的初始数据
   */
  data: {
    details: [], //数据
    is_no_more:0,
    current_page: 0, 
    showModal:false,//积分弹框的控制器
    number:0,
    jfmx:true,
    jfcz:false,
    val:1,
    /**
        * 页面配置
        */
    winWidth: 0,
    winHeight: 0,
    // tab切换
    currentTab: 0,
    money:1.00,
    integral:50,
    iurl: o.imghost,

    is_show_jfcz:0,
    tab:0,
    is_no_more_e:0,  //充值使用
    current_page_e:0,  //充值使
    is_loading:0,  //避免重复request请求
    is_loading_c:0  //避免重复request请求
  },
      /**
        * 刷出积分劵
        */ 
  async exchange() {

    if (this.data.is_no_more_e) return;
    if (this.data.is_loading_c) return;
    this.data.current_page_e++;
    this.data.is_loading_c=1;

    var e = this, result=[];
    var user_id = getApp().globalData.user_id;
    var store_id = os.stoid;
    var get_data = {
      user_id: user_id, store_id: store_id,
      pageSize: 10, page: e.data.current_page_e
                                  ///api/weshop/users/listExchangeCoupons
    };                            //api/index/yuck

    wx.showLoading();
    await getApp().request.promiseGet("/api/weshop/users/listExchangeCoupons", {
      data:get_data
    }).then(res => {

      wx.hideLoading();
      e.data.is_loading_c=0;
      if(ut.ajax_ok(res)){
        var msg = res.data;
        let result2 = msg.data.pageData;  
        let arr=e.data.result;
        result = arr.concat(result2);

        //-- 显示没有更多的优化 --
        if (msg.data.total <=10*e.data.current_page_e) {
          e.setData({
            is_no_more_e: 1
          })
        }

      }else{
        e.setData({
          is_no_more_e: 1
        })
      }
     
    })
    e.setData({
      result: result,is_get_c:1
    })

  },
  /**
    * 积分明细
     */
  async detaileds() {
    if (this.data.is_no_more) return;
    if (this.data.is_loading) return;
    this.data.current_page++;
    this.data.is_loading=1;

    var e = this, details;
    var user_id = getApp().globalData.user_id;
    var store_id = os.stoid;
    var get_data = {
      user_id: user_id, store_id: store_id,
      pageSize: 15, page: e.data.current_page
    };                             
    var big_arr = this.data.details;

    wx.showLoading();

    await getApp().request.promiseGet("/api/weshop/users/listPoints", {
      data: get_data
    }).then(res => {

      wx.hideLoading();
      e.data.is_loading=0;

      if(ut.ajax_ok(res)){
          var msg = res.data;
     
          details = msg.data.pageData;
          details.forEach(function (val, ind) {
            big_arr.push(val);
          })
        
          //-- 显示没有更多的优化 --
          if (msg.data.total <=15*e.data.current_page) {
            e.setData({
              is_no_more: 1
            })
          }
      }else{
         e.setData({
          is_no_more: 1
        })
      }

      
      
    })


    this.setData({
        details: big_arr,is_get_d:1
    });

    var get_datas= {
      user_id: user_id, store_id: store_id,  
    };    
    await getApp().request.promiseGet("/api/weshop/users/getAllPoints", {
      data: get_datas
    }).then(res => {
      var msg = res.data;
      var integrals=msg.data.Integral;
      console.log(integrals);
      this.setData({number: integrals})
    })

   

  },
  //---加载更多是靠这个函数----
  onReachBottom: function () {
    //0是积分明细  1是积分充值
    if(this.data.currentTab==0){
       this.detaileds();
    }else{
       this.exchange();
    }
  

  },
  //积分弹框控制器
  integral:function(e){
    var integral = e.target.dataset.integral;
    var money = e.target.dataset.money;
   console.log(money, "积分", integral);
    this.setData({
      showModal: true, money: money, integral: integral
    })
  },
  //弹窗的方法
  preventTouchMove: function () {

  },
  // 票数量的加
  plus:function(e){
    
    var val = this.data.val;
    val++;
    console.log("加",val);
     this.setData({
       val: val
     })
  },
  //票数量的减
  reduce:function(e){
  
    var val = this.data.val;
    //console.log("减", val);
    if (val>1){
      val--;
      //console.log("减", val);
      this.setData({
        val: val
      })
    }
    
  },
  //关闭弹框
  shut: function (e) {
    
    this.setData({ showModal: false })
    console.log("bb");

  },
  /**
 * 点击tab切换
 */
  swichNav: function (e) {
    console.log("是什么", e.target.dataset.current);
    var val=e.target.dataset.current;
	
	var that = this;
	if (this.data.currentTab== parseInt(e.target.dataset.current)) {
	  return false;
	} else {	  
	  //如果是积分充值，但是不显示的话，不响应点击事件，退出
	  if(val!=0 && !this.data.is_show_jfcz){
		  return false;
	  }	  	
	  that.setData({
	    currentTab: e.target.dataset.current
	  })
	}
	
    if (val==0){
      console.log("积分明细", e.target.dataset.current);
      var jfmx=true;
       var jfcz= false;
      this.setData({ jfmx: jfmx, jfcz: jfcz, current_page: 0,details:[],is_get_d:0,is_no_more:0 });
      this.detaileds();
    }else{
      if(this.data.is_show_jfcz) {
		  console.log("积分充值", e.target.dataset.current);
		  var jfmx = false;
		  var jfcz = true;
		  this.setData({jfmx: jfmx, jfcz: jfcz, current_page_e:0,result:[],is_get_c:0,is_no_more_e:0});
		  this.exchange();
	  }else{
		  return false;
	  }		  
    }
    
    
  },
  // 积分收支明细
  detailed:function(){
     wx:wx.navigateTo({
       url: 'query/index',
       
     })
  },
  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {

    //定义第一次进入
    this.data.fir_in=1;

   	var th=this;	  
    getApp().request.get("/api/wx/weappSendlist/page", {
      data: {
        store_id: os.stoid,
        typeid: "1002"
      },
      success: function(res) {
        if (res.data.code == 0 && res.data.data.pageData.length > 0) {
            var template_id = res.data.data.pageData[0].template_id;
            th.setData({template_id:template_id});
        }  
      }
    });    

    if(options.tab==1){
       th.data.tab=1;
    }


	  

  },

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

  //点击确定
  determine(event) {

    if(this.data.paying) return false;
    this.data.paying=1;

    console.log(event.currentTarget.dataset.money);
    var money = event.currentTarget.dataset.money;
    var integral = event.currentTarget.dataset.integral;
    var val = event.currentTarget.dataset.val
    //console.log(money, integral, val,"参数", a);
    var user_id = getApp().globalData.user_id;
    var store_id = os.stoid;
    var th= this, number;
	
	this.sendsm(function(){
	   getApp().request.promiseGet("/api/weshop/users/getPay"
		  , {
		    data: { user_id: user_id, store_id: store_id, buynum: val, mon: money, integ: integral, recharge_type:1}
		  }).then(res => {
		   // console.log("1" + res);
		    var msg = res.data.data;
		    var parentSn = msg.order_sn;
		    var store_id = os.stoid;

         t_pay.set_pay_url("/api/weshop/order/pay/createRechargeOrder");

         th.data.ok_order_sn=parentSn;
         t_pay.pay({
           parentSn: parentSn,
           store_id: store_id
         }, function () {
           th.jumpPaymentPage();
         }, function (e) {
           th.data.paying=0;
           wx.showToast({
             title: e,
             icon: 'none',
             duration: 2000
           });
         })
		   
		    // getApp().request.post("/api/weshop/order/pay/createRechargeOrder", {
		    //   data: {
		    //     parentSn: parentSn,
		    //     store_id: store_id
		    //   },
		    //   success: function (su) {
		    //     var n = su.data.data;
		    //     th.weixinPay(n,
		    //       function () {
		    //         console.log("支付成功页面2333");
		    //         th.jumpPaymentPage();
		    //       }, function () {
		    //         getApp().showWarning("支付失败");
		    //       })
		    //   }
		    // })
		 })
	})

  },
  //------支付成功页面--------
  jumpPaymentPage: function () {
    console.log("支付成功页面2333");
    wx.redirectTo({
      url: "msg/msg"
    });
  },

  //------调起支付框--------
  weixinPay: function (n, success, fail) {
	if(!n) return false;
      getApp().globalData.no_clear=1;

    wx.requestPayment({
      timeStamp: String(n.timeStamp),
      nonceStr: n.nonceStr,
      package: n.packageValue,
      signType: n.signType,
      paySign: n.paySign,
      success: function (n) {
        console.log(n), getApp().showSuccess("支付成功！");
        "function" == typeof success && success();
        // wx.redirectTo({
        //   url: "jf"
        // });
      },
      fail: function (n) {
        console.log(n), "requestPayment:fail" == n.errMsg ? getApp().showWarning("支付失败") : "requestPayment:fail cancel" == n.errMsg ? getApp().showWarning("您已取消支付") : getApp().showWarning("支付失败：" + n.errMsg.substr("requestPayment:fail ".length)),
          "function" == typeof fail && fail();
      }
    });
  },
  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {


    var th=this;
    //判断是不是第一次进入
    if(this.data.fir_in){
      this.data.fir_in=0;
    }else{
       //-- 富友的插件 --
       ut.fy_back('',0);
       t_pay.set_fir();

       //-- 通联的第三方支付的返回优化 --
       ut.is_pay_ok(th.data.ok_order_sn,"/packageD/pages/user/integral/msg/msg",'none',function (){

          console.log('show--11')
          console.log(th.data.ok_order_sn);

          if(!th.data.ok_order_sn) return false;
          var ck_url="/api/weshop/recharge/get/"+os.stoid+"/"+th.data.ok_order_sn;
          getApp().request.promiseGet(ck_url,{}).then(res=>{
            if(res.data.code==0 && res.data.data){
              var item=res.data.data;
              if(item.pay_status==1){
                //支付支付，返回首页
                ut.m_toast('支付成功');
                setTimeout(()=>{
                  getApp().re_to("/packageD/pages/user/integral/msg/msg");
                },1000)

              }else{
                 //支付支付，返回首页
                 ut.m_toast('支付失败');
              }
            }
          })
        });
    }

    this.data.paying=0;
    getApp().check_can_share();
    //--先判断会员状态--
    var user_info = getApp().globalData.userInfo;
    if (user_info == null || user_info.mobile == undefined || user_info.mobile == "" || user_info.mobile == null) {
      wx.navigateTo({ url: '/packageE/pages/togoin/togoin', })
      return false;
    }
    
    wx.setNavigationBarTitle({
      title: "我的积分",
    })


    if(this.data.has_init) return false;
    this.data.has_init=1;
  
    this.detaileds();
   
      //要实时获取开关是显示
    getApp().getConfig2(function(ee){
          var json_d = JSON.parse(ee.switch_list);
          th.setData({ is_show_jfcz: json_d.jfcz_switch });
          //-- 如果有开启积分充值，就调用积分充值的界面 --
          if(json_d.jfcz_switch && th.data.tab==1 ){
                th.data.tab=0;
                var jfmx = false;
                var jfcz = true;
                th.setData({jfmx: jfmx, jfcz: jfcz, current_page_e:0,result:[],currentTab:1 });
                th.exchange();
           
          }

    },1)

  },
 

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

  },


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

  },

  
  /**
   * 用户点击右上角分享
   */
   onShareAppMessage: function () {   	  getApp().globalData.no_clear=1

  },
  
  //订阅消息提醒
  sendsm:function(func)
    {  
           var template_id = this.data.template_id;    
            // //授权订阅
            wx.requestSubscribeMessage({
              tmplIds: [template_id],
              success(res) {
                  func();
              },
              fail(res) {
                  func();
              }
            })
          
    },
})