// packageA//pages/myGiftDetails/myGiftDetails.js
const app = getApp();
let self = null;
var os = app.globalData.setting;
var ut = require("../../../utils/util.js");
var t_pay = require("../../../utils/pay2.js");

Page({

  /**
   * 页面的初始数据
   */
  data: {
	  qr_code_object: {
		  val: "12121",
		  content: "当前核销码仅限当面使用！"
	  },
		showBtn: true,
		isClick: false,
	  is_summit_ing: 0,
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
	  //定义第一次进入
	  this.data.fir_in=1;

	  self = this;
		
		// 如果从商品详情页点击促销栏里的礼包跳转过来的话,不显示底部按钮
		// showBtn 控制按钮是否显示
		let showBtn = this.data.showBtn;
		if(options.btn == 0) {
			showBtn = false;
		}
		
		this.setData({
			options: options,
			id: options.id,
			index: options.index,
			showBtn: showBtn,
		})

	  getApp().getConfig2(function (e) {
		  var json_d = JSON.parse(e.switch_list);
		  self.setData({
			  bconfig: e,
			  is_retail_price: json_d.is_retail_price || 0
		  });
	  })

		// console.log('options', options);
		app.isLogin().then(function(data) {//进入页面前已经授权登录成功
			self.setData({
				userInfo: data,
			});
		});
  },

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

  },

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

	  this.data.is_summit_ing=0;
	  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,"/packageA/pages/libao_payment/payment?type=2","none",function (){
			  console.log('is_pay_ok');
			  console.log(th.data.ok_order_sn);
			  if(!th.data.ok_order_sn) return false;

			  var b_url="/api/weshop/libao/libaoFormvip/page";
			  var rq_data={
				  store_id: app.globalData.setting.stoid,
				  user_id: app.globalData.user_id,
				  number: th.data.ok_order_sn
			  };

			  getApp().request.promiseGet(b_url,
				  {data:rq_data}).then(res=>{

				  console.log('is_pay_ok2');
				  console.log('1111111');

				  if(ut.ajax_ok(res)){

					  var item=res.data.data.pageData[0];
					  if(item.fbillstate==1){
						  //支付支付，返回首页
						  ut.m_toast('支付成功');
						  setTimeout(()=>{
							  getApp().goto("/packageA/pages/libao_payment/payment?type=2");
						  },1000)

					  }else{
						  //支付支付，返回首页
						  ut.m_toast('支付失败');
						  setTimeout(()=>{
							  getApp().goto("/pages/index/index/index");
						  },1000)
					  }
				  }
			  })
		  });

	  }

        getApp().check_can_share();
		if(app.globalData.userInfo) {
			if(!this.data.isLogin) {
				this.setData({
					userInfo: app.globalData.userInfo,
					imghost: app.globalData.setting.imghost,
					isLogin: true,
				});
				
				let url = '';
				// let data = {
				// 	store_id: app.globalData.setting.stoid,
				// 	user_id: app.globalData.user_id,
				// };
				//购买的时候是0，购买后是1
				if(this.data.index == 0) {
					// data.lbid = this.data.id;
					// 请求数据
					app.request.promiseGet('/api/weshop/libao/libaoForm/page', {
						data: {
							store_id: app.globalData.setting.stoid,
							id: this.data.id,
						},
						isShowLoading: true,
					}).then(function(res) {

						if(res.data.code==0 &&  res.data.data  &&  res.data.data.pageData &&  res.data.data.pageData.length>0){
							var da= res.data.data.pageData[0]
                            self.setData({ details:da, });

							//活动还未开始
							if(da.startime>ut.gettimestamp()){
                                self.setData({ is_not_start:1, });
							}



							console.log(da);
							//礼包有俩种类型
							if(da.lbtype==1){
                                app.request.promiseGet('/api/weshop/libao/libaoList/page', {
                                    data: {
                                        store_id: app.globalData.setting.stoid,
                                        lbid: self.data.id,pageSize:500
                                    },
                                    isShowLoading: true,
                                }).then(function(res) {
                                    self.setData({
                                        list: res.data.data.pageData,
                                    });
                                });
							}else{
                                app.request.promiseGet('/api/weshop/libao/libaoList/listLQ', {
                                    data: {
                                        store_id: app.globalData.setting.stoid,
                                        lbid: self.data.id,
                                    },
                                    isShowLoading: true,
                                }).then(function(res) {
									console.log(res);
                                	if(res.data.code==0){
                                        self.setData({
                                            list: res.data.data,
                                        });
									}
                                });
							}

						}
					});

				} else if(this.data.index == 1) {
					app.request.promiseGet('/api/weshop/libao/libaoFormvip/page', {
						data: {
							store_id: app.globalData.setting.stoid,
							user_id: app.globalData.user_id,
							id: this.data.id
						},
						isShowLoading: true,
					}).then(function(res) {
						// console.log('res3-->', res);
						if(res.data.code==0  && res.data.data && res.data.data.pageData && res.data.data.pageData.length>0){

							var da= res.data.data.pageData[0]
							self.setData({
								details:da,
							});

							if(da.lbtype==1){
                                app.request.promiseGet('/api/weshop/libao/libaoListvip/page', {
                                    data: {
                                        store_id: app.globalData.setting.stoid,
                                        lbvipid: self.data.id,pageSize:500
                                    },
                                    isShowLoading: true,
                                }).then(function(res) {
                                    // console.log('res4-->', res);
                                    if(res.data.code==0  && res.data.data && res.data.data.pageData && res.data.data.pageData.length>0) {
                                        var list_arr=res.data.data.pageData;
                                        for(var i in list_arr){
                                            list_arr[i].alsonum= list_arr[i]['goods_num'] - list_arr[i]['usenum'];//剩余次数
                                        }
                                        self.setData({
                                            list: res.data.data.pageData,
                                        });
                                    }
                                });
							}else{
                                app.request.promiseGet('/api/weshop/libao/libaoListvip/listLQ', {
                                    data: {
                                        store_id: app.globalData.setting.stoid,
                                        lbvipid: self.data.id,
                                        user_id:app.globalData.user_id
                                    },
                                    isShowLoading: true,
                                }).then(function(res) {
									console.log(res);
                                    // console.log('res4-->', res);
                                    if(res.data.code==0  && res.data.data) {
                                        self.setData({
                                            list: res.data.data,
                                        });
                                    }
                                });
							}

						}
					});
				};
			};
		};
  },

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

  },

	//-- 礼包购买 --
	GetBuyPrice: function(e) {

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

		var th = this,that=th;
		var item=th.data.details;
		var id = item.id; //活动id
		var my_confirm = th.selectComponent("#my_confirm"); //组件的id
		var user=getApp().globalData.userInfo;

		my_confirm.open(
			"是否确定购买该礼包",
			"取消",
			"确定",
			function() {
				my_confirm.open_cancel(0);
			},
			function() {
				my_confirm.open_cancel(0);
				var json = {
					"lbid": id, //活动Id
					"paytype": 2, //1=积分兑换 2=购买
					"store_id": os.stoid, //商家Id
					"user_id": user.user_id, //用户ID
				};

				t_pay.set_pay_url("/api/weshop/libao/libaoFormvip/libaoOrder");
				t_pay.pay(json,function (){
					getApp().my_warnning("支付成功", 1, th);
					setTimeout(function (){
						getApp().goto("/packageA/pages/libao_payment/payment?type=2");
					},1000)
				},function (msg){
					th.data.is_summit_ing=0;
					getApp().my_warnning(msg, 0, th);
				},th)

				// var url = "/api/weshop/libao/libaoFormvip/libaoOrder";
				// getApp().request.post(url,
				// 	{
				// 		data:json,
				// 		success:function(res) {
				// 			if (res.data.code == 0 && res.data.data) {
				// 				res = res.data.data;
				//
				// 				getApp().globalData.no_clear=1;
				//
				// 				wx.requestPayment({
				// 					timeStamp: String(res.timeStamp),
				// 					nonceStr: res.nonceStr,
				// 					package: res.packageValue,
				// 					signType: res.signType,
				// 					paySign: res.paySign,
				// 					success: function(res) {
				// 						getApp().my_warnning("支付成功", 1, th);
				// 						setTimeout(function (){
				// 							getApp().goto("/packageA/pages/libao_payment/payment?type=2");
				// 						},1000)
				// 					},
				// 					fail: function(res) {
				// 						getApp().my_warnning("取消支付", 0, th);
				// 					}
				// 				});
				// 			} else {
				// 				getApp().my_warnning(res.data.msg, 0, th);
				// 			}
				// 		}
				// 	})
			})
	},

	//-- 积分兑换 --
	GetBuyIntegral: function(e) {
		var th = this,that=th;
		var item=th.data.details;

		var id = item.id; //活动id
		var my_confirm = th.selectComponent("#my_confirm"); //组件的id
		var user=getApp().globalData.userInfo;
		my_confirm.open(
			"是否确定兑换该礼包",
			"取消",
			"确定",
			function() {
				my_confirm.open_cancel(0);
			},
			function() {
				my_confirm.open_cancel(0);
				var json = {
					"lbid": id, //活动Id
					"paytype": 1, //1=积分兑换 2=购买
					"store_id": os.stoid, //商家Id
					"user_id": user.user_id, //用户ID
				};
				var url = "/api/weshop/libao/libaoFormvip/libaoOrder";
				getApp().request.post(url,{
					data:json,
					success:function(res) {
						if (res.data.code == 0) {
							getApp().my_warnning("兑换成功！", 1, th);
							setTimeout(function (){
								getApp().goto("/packageA/pages/libao_payment/payment?type=1");
							},1000)
						} else {
							getApp().my_warnning(res.data.msg, 0, th);
						}
					},
				})

			})
	},

	//显示二维码，进行核销
	show_hxm:function (e){
  	   var th=this;
  	   var type=e.currentTarget.dataset.type;
  	   var data={};
	   data.store_id=os.stoid;
  	   data.user_id=getApp().globalData.user_id;

  	   if(type && parseInt(type)==1){
		   data.id=this.data.id;
		   data.type=1;
	   }else{
		   var index=e.currentTarget.dataset.index;
		   var item=this.data.list[index];
		   data.id=item.id;
		   data.type=2;
	   }

  	   //获取二维码
  	   getApp().request.get("/api/weshop/libao/libaoListvip/getLibaoCode",{
  	   	   data:data,
		   success:function (res){
			   console.log(res);
               if(res.data.code==0){
				   th.data.qr_code_object.val=res.data.data;
				   var qc_com = th.selectComponent("#qrcode"); //组件的id
				   qc_com.open(th.data.qr_code_object)
			   }else{
				   wx.showToast({
					   title: res.data.msg,
					   icon: 'none',
					   duration: 2000
				   })
				   
			   }
		   }
	   })

	},

	//一键领取券
    show_get_quan:function (e) {
			if(this.data.isClick) return false;
			if(!this.data.isClick) {
					this.data.isClick = true;
					let th=this;
				  let json = {
				      store_id:os.stoid,
				      user_id:getApp().globalData.user_id,
							id:this.data.id
				  };
				  let url = "/api/weshop/libao/libaoFormvip/saveLibaoQuan";
				  getApp().request.post(url,{
				      data:json,
				      success:function(res) {
				          if (res.data.code == 0) {
				              th.setData({'details.isget':1});
				          } else {
				              wx.showToast({
				                  title: res.data.msg,
				                  icon: 'none',
				                  duration: 2000
				              })
											th.data.isClick = false;
				          }
									
				      },
				  });
					
			}
				

    }


})