// packageA//pages/chongzhiDetails/chongzhiDetails.js
var util = require('../../../utils/util.js');
const app = getApp(),os = app.globalData.setting;
var regeneratorRuntime = require('../../../utils/runtime.js');
var t_pay = require("../../../utils/pay2.js");
 
Page({

  /**
   * 页面的初始数据
   */
  data: {
		showCode: false,
		result: null,
		show_img:null,
		url: app.globalData.setting.imghost,
		type:0,  //0是立即充值  1是购买后的
		is_buying:0,
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {

	   wx.showLoading();
	   const self = this;
	   if(options.type)
	      self.setData({type:options.type});
	  	   
	    var UserInfo=app.globalData.userInfo;
	    if(!UserInfo) {
			getApp().goto("/packageE/pages/togoin/togoin");
			return false;			
		}
		
				
		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;
			  self.setData({template_id:template_id});
			  
			 }
		   },
		})
		
		   
	   getApp().request.promiseGet("/api/weshop/ad/page",{
		 data:{store_id:os.stoid,enabled:1,pid:1210}
	   }).then(res=>{
		   if(res.data.code==0 && res.data.data.pageData && res.data.data.pageData.length>0){
			   var a = res.data.data.pageData;			   
			   self.setData({show_img:a[0].ad_code,ad_color:a[0].bgcolor,ad:a[0] });
		   }
	   })	
	   
	   var api="/api/weshop/users/getAddmoneyactDetails";
	   if(options.type==1){
		   api="/api/weshop/users/getBuyaddmoneyactDetails";
	   }

	   this.data.op_id=options.id;
	   app.request.get(api, {
		  data: {
				Id:options.id,
				store_id:os.stoid,
				user_id: UserInfo.user_id,
			},
		  success: function (res) {			  

			    var result=res.data.data;
				var now=new Date();
				var reg = RegExp("-", "g");
                var endtime = result.EndDate.replace(reg, '/');  
				var end=new Date(endtime);
				result.is_acting=1;
				if(end<now)  result.is_acting=0;
				
				
			    var givelist=result.givelist;
				if(!givelist) givelist=new Array();				
				if(result.Integral){
					var ob={Integral:result.Integral};
					givelist.push(ob);
				}
				if(result.GradeSum){
					var ob={GradeSum:result.GradeSum};
					givelist.push(ob);
				}
						 			  
				self.setData({
					result: result,
				});

				wx.hideLoading();

		  },
		});
				
		// this.data.result.WriteOffCode
  },

 
  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {
	  this.data.is_buying=0;
	  util.fy_back('',0)
	  t_pay.set_fir();
      getApp().check_can_share();
  },

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

  },

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

  },

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

  },
	
  async onUse() {
	    //-- 如果过期就不可用 ---
	    if(this.data.result.IsGQ){
		   return false;
	    }


	  //var code=this.data.result.WriteOffCode;
	  var code='';

	  //获取二维码
	  let res= await  getApp().request.promisePut("/api/weshop/store/updateErpApi",{
		  data:{
			  store_id:os.stoid,
			  ApiName:"/api/erp/vip/buyaddmoneyactDetails/updateMainCode",
			  Id:this.data.op_id,
			  VIPId:getApp().globalData.userInfo.erpvipid
		  }
	  })
	  if(res){
		  if(res.data.code==-1){
			  util.m_toast(res.data.msg);
			  return false;
		  }
		  if(res.data.data)
			  code = res.data.data.WriteOffCode;
	  }
	  if(!code){
		  util.m_toast('未找到二维码');
		  return false;
	  }

	  var qrcode = this.selectComponent("#qrcode"); //组件的id
	  var e={is_fw:1,val:code,code:code}
	  qrcode.open(e);
   },
	
	
	bind_err:function(e){
		var _errImg = e.target.dataset.errorimg;		
		var _errObj = {};
		_errObj[_errImg] = "/miniapp/images/default_g_img.gif";
		this.setData(_errObj); 
	},
	
	     //-- 确定充值 --
	    go_buy: function(e) {
		  if(this.data.is_buying) return false;
		  this.data.is_buying=1;
	    	 
	      var money = e.target.dataset.money;
	      var advance = e.target.dataset.advance;
		  var th=this;
		  this.sendsm(function(){
			  th.recharge(money, advance);
		  })
		  	      
	    },
	    //确定接口
	    async recharge(money, advancek) {
	      console.log(money, "有进来吗银行卡", advancek);
	      var user_id = getApp().globalData.user_id;
	      var store_id = os.stoid;
	      var recharge_type = 6;
	      var buynum = 1;
	      console.log(money, "有进来吗预存劵", advancek, user_id, store_id );
	      var e = this,th=this,
	      perpaid = "";
	      await getApp().request.promiseGet("/api/weshop/users/getPay", {
	        data: {
	          account: money,
	          yucun_id: advancek,
	          user_id: user_id,
	          store_id: store_id,
	          recharge_type: recharge_type,
	          buynum: buynum ,
	        }
	      }).then(res => {
	           console.log(res);
			   this.data.is_buying=0;			   
			   if(res.data.code!=0){
				   getApp().confirmBox(res.data.msg);				  
				   return false;
			   }
	
	
	        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");
		    t_pay.pay({
			  parentSn: parentSn,
			  store_id: store_id
		    }, function () {
				th.data.is_buying=0;
				e.jumpPaymentPage();
		    }, function (e) {
				th.data.is_buying=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) {
	        //     console.log("su是什么",su);
	        //     var n=su.data.data;
	        //     console.log("su是什么", su);
	        //
	        //     e.weixinPay(n,
	        //       function () {
	        //        e.jumpPaymentPage();
	        //       }, function () {
	        //         getApp().showWarning("支付失败");
	        //       })
	        //   }
	        // })
	      })    
	    },
	//------支付成功页面--------
	jumpPaymentPage: function () {
	  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: "../deposit/deposit"
	      });
	    },
	    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();
	    }
	  });
	},
	
	//订阅消息提醒
	sendsm:function(func)
	  {  
	          var template_id = this.data.template_id;
	          //授权订阅
	          wx.requestSubscribeMessage({
	            tmplIds: [template_id],
	            success(res) {
	                func();
	            },
	            fail(res) {
	                func();
	            }
	        })
	  },


	go_url:function (e){
        var url=e.currentTarget.dataset.url;
		if(url){
           getApp().goto(url);
		}
	},
	
	//-- 显示二维码 --
	getcode(e) {
		var idx = e.currentTarget.dataset.index;
		var item = this.data.result.givelist[idx];
		this.get_code_next(item);
	},

	async get_code_next(item){
		var th = this;
		//--获取成功的时候--
		var no = '';

		var id=item.GiftsId;
		var IsRetrieval=item.IsRetrieval;

		//-- 有调起的时候 --
		if(IsRetrieval){
			no=item.WriteOffCodeOne;
		}else {
			//获取二维码
			let res = await getApp().request.promisePut("/api/weshop/store/updateErpApi", {
				data: {
					store_id: os.stoid,
					ApiName: "/api/erp/vip/buyaddmoneyactDetails/updateMainCodeOne",
					Id: id,
					VIPId: getApp().globalData.userInfo.erpvipid
				}
			})
			if (res) {
				if (res.data.code == -1) {
					util.m_toast(res.data.msg);
					return false;
				}
				if (res.data.data)
					no = res.data.data.WriteOffCode;
			}
		}
		if(!no){
			util.m_toast('未找到二维码');
			return false;
		}


		var qc_com = th.selectComponent("#qrcode"); //组件的id
		var e={is_fw:1,val:no,code:no}
		qc_com.open(e)
	}
})