var t = require("../../../utils/util.js"), ut = t,
  e = require("../../../utils/common.js"),
  oo = getApp().globalData,
  os = getApp().globalData.setting;


Page({
  data: {
    stoid: os.stoid,
    url: os.url,
    resourceUrl: os.resourceUrl,
    iurl: os.imghost,
    defaultAvatar: os.resourceUrl + "/static/images/user68.jpg",
    q_data: null,
    id:null,
    config2:null,
    getcurday:null

  },
  //------初始化加载----------
  onLoad: function(t) {
	  
	var th = this;
	var first_leader=t.first_leader;
	if(first_leader){
		 //--  user_id代过来免登录 --
	     getApp().globalData.first_leader=first_leader;	    	 
	     //调用接口判断是不是会员
	     getApp().request.promiseGet("/api/weshop/shoppingGuide/get/"+os.stoid+"/"+first_leader,{}).then(res=>{
	         if(res.data.code==0){
	             getApp().globalData.guide_id=res.data.data.id;
                 getApp().globalData.guide_pick_id= res.data.data.pickup_id
	         }
	     })
	 }  
	  
    var id=t.id;
    //如果二维码分享过来的
    if(!id){
        id = decodeURIComponent(t.scene);
    }
    this.data.id=id;

    var goods_list = this.selectComponent("#goods_list"); //组件的id
    goods_list.init();
    setTimeout(function() {
      goods_list.get_list();
    }, 300)
  },

  //---展示,显示券的信息---
  onShow:async function() {

    //检查能不能分享
    getApp().check_can_share();
    var th=this;
    th.setData({getcurday:ut.gettimestamp()});

    var rs=await getApp().request.promiseGet("/api/weshop/prom/coupon/get/"+th.data.id, {})
    // console.error('分享请求数据');
    // console.error(rs);
    if(!rs){
        th.setData({is_get:1});
        return false;
    }
    if(rs.data.code!=0){
        th.setData({is_get:1});
        return false;
    }
    var r_data=rs.data.data;
    //如果只限定链接的时候，要取消分享按钮
    if(r_data.is_share){
          wx.hideShareMenu();
          wx.offCopyUrl()
          //替换掉复制链接
          wx.onCopyUrl(() => {
            setTimeout(()=>{
              wx.setClipboardData({
                data: '暂不支持分享',
                success (res) { }     
              })
            },500)
            return { query: 'a=1&b=2' }
          })
    }

    if(r_data.store_id!=os.stoid){
        th.setData({is_get:1});
        return false;
    }

    //-- 券已经领取完的优化 --
    if(r_data.sum_num && r_data.sum_num<=r_data.use_sumnum){
        th.setData({is_get:1});
        return false;
    }

    if(r_data.type!=1){
        th.setData({is_get:2});
        return false;
    }

    var now=ut.gettimestamp();
    if(r_data.send_start_time>now){
       th.setData({is_get:3});
       return false;
    }

    if(r_data.send_end_time<now){
       th.setData({is_get:4});
    }

    th.setData({ q_data:r_data });

    var url2='/api/weshop/couponList/getUserCouponListMsg?store_id='+os.stoid+'&cid='+th.data.id+'&uid='+getApp().globalData.user_id;
    var rss=await getApp().request.promiseGet(url2, {})
    if(rss && rss.data.code==-1){
          if(rss.data.msg.indexOf('您下一次')>-1){
              th.setData({is_get:5,err_txt:'您已领过该券'});
          }else if(rss.data.msg.indexOf('您已领完该券')>-1){
              th.setData({is_get:5,err_txt:'您已领完该券'});
          }
    }else if(rss && rss.data.code==0){
        //获取会员已经领取了多少张券
        var n1=rss.data.data.usercounted?rss.data.data.usercounted:0;
        th.setData({'q_data.lqnum':n1})
    }



  },
  onUnload:function(){
    wx.offCopyUrl()
  },
  onHide: function() {
    wx.offCopyUrl()
  },
  //--滚动到顶部--
  doScrollTop: function() {
    wx.pageScrollTo({ scrollTop: 0 });
  },

  //---加载更多是靠这个函数----
  onReachBottom: function() {
    var goods_list = this.selectComponent("#goods_list"); //组件的id
    if (goods_list) goods_list.get_list();
  },

  //-----领取券-----
  get_quan: function() {
    var item=this.data.q_data;
    var cid = this.data.q_data.id;
    var th=this;
    var good = new Array();  //单品且是免费领取专门使用
    //--先判断会员状态--
    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;
    }
    //如果券还在领取中，不能再点
    if (th.data.linging == 1) {
      getApp().my_warnning('领取中..', 0, this);
      return false;
    }
    th.data.linging = 1;
    //如果领取的次数到了
    if (item.everyone_num > 0 && item.lqnum >= item.everyone_num) {
      getApp().my_warnning('领取失败，您已领完该券', 0, this);
      return false;
    }
    var lq_num = item.lqnum;
    var pdata = {
      'uid': oo.user_id,
      'cid': cid,
      'store_id': os.stoid,
      'type': 5
    };
    if (item.useobjecttype == 20 && item.type == 1) {
			getApp().request.get('/api/weshop/goods/list', {
				data: {
					store_id: os.stoid,
					erpwareid: item.useobjectid,
				},
				success(res) {
					if (ut.ajax_ok2(res)) {
						good = res.data.data;
					}
				}
			})
		}
	
	//-- 分享导购ID --
	if(getApp().globalData.guide_id){
		pdata.guide_id=getApp().globalData.guide_id;
	}
	
    var app = getApp(),
        th = this;
    app.request.post("/api/weshop/couponList/saveCouponList", {
      data: pdata,
      success: function(res) {
        th.data.linging = 0;
        if (res.data.code == 0) {
         
          var text3="q_data";
          var obj = {};obj[text3] = item;
          th.setData(obj);
          if (good.length > 0) {
						wx.showToast({
							title: '领取成功',
							success() {
								let item = good[0];
								let url = `/pages/goods/goodsInfo/goodsInfo?goods_id=${item.goods_id}&prom_type=${item.prom_type}&prom_id=${item.prom_id}`
								setTimeout(()=>{
									getApp().goto(url)
								},500)
							}
						})
					} else {

            //设置一下优惠券领取的数量
            var q_data=th.data.q_data;
            q_data.use_sumnum++;
            q_data.lqnum++;
						
            th.setData({
							show_success: 1,
              q_data
						})

            if(q_data.everyone_num>0 && q_data.everyone_num<= q_data.lqnum){
               th.setData({is_get:5,err_txt:'您已领完该券'});
            }else if(q_data.interval_time>0){
              th.setData({is_get:5,err_txt:'您已领过该券'});
            }

          
					}
        } else {
          app.confirmBox(res.data.msg);
        }
      }
    })
  },
  
  go_quan:function(){
   //跳转到券列表 
   this.setData({
    show_success:0
  })
	 getApp().goto("/packageD/pages/user/coupons/coupons");  
  },

  close_show(){
    this.setData({
      show_success:0
    })
  },

    //发送给好友
    onShareAppMessage:async function(e) {
        getApp().globalData.no_clear=1;
        var url= "packageA/pages/quan_pro/quan_pro?id="+this.data.id;
        var userInfo = getApp().globalData.userInfo;
        //是分销商才带
        if (userInfo) {
            url += "&first_leader=" + userInfo.user_id;
        }
        var ob = {
            title:this.data.q_data.name,
            path: url,
            //imageUrl:this.data.url+this.data.store_config.store_logo,
        };
        return ob;
    },

    //发送给朋友圈
    onShareTimeline() {
        getApp().globalData.no_clear=1;
        var user_id= getApp().globalData.user_id
        return {
            title:this.data.q_data.name,
            query: 'id='+this.data.id+'&first_leader='+user_id
        }
    },


});
