var i = require("../../../../utils/util.js")
const ut = require("../../../../utils/util.js");
var e = getApp(),
  a = e.globalData.setting,
  os = a,
  t = e.request,
  d = e.globalData;
Page({
  data: {
    iurl: a.imghost, //图片前缀网址
    getDate: "",
    getStorageID: '',
    getUserID: '',
    wareCard: [],
    // pages: 0,
    // pageSize: 10,
    isEmpty: false,
    loadingType: 0, //定义加载方式 0---contentdown  1---contentrefresh 2---contentnomore
    contentText: {
      contentdown: '加载更多',
      contentrefresh: '加载中...',
      contentnomore: '已加载全部'
    },
    ismore: 0, //数据是否全部加载完成
    is_read: 0, //是否查询过我的礼包接口
    curpage: 1, //当前分页数
    pageSize: 10, //页大小
    total: 0, //总数量
    ad_data: null,
    first_leader: e.globalData.first_leader || 0, // 推荐人ID

    sear_key:'' //顶部搜索关键子
  },
  onLoad: function (options) {
    if(options.transfer){
      let obj=getApp().globalData.ts_trans_data;
      options= JSON.parse(JSON.stringify(obj));
      getApp().globalData.ts_trans_data=null;
 }

    this.setData({
      params: options,
    })
  },

  init() {
    let options = this.data?.params;
    var th = this;
    this.setData({
      getStorageID: a.stoid,
      getUserID: d.user_id,
      loadingType: 0,
      getDate: i.formatTime(new Date().getTime())
    });
    //-- 获取分享人的ID --
    var first_leader = options.first_leader || getApp().globalData.first_leader;
    if (first_leader) {
      this.setData({
        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
        }
      })
    }

    getApp().request.promiseGet("/api/weshop/ad/page?pid=902&store_id=" + os.stoid, {
      data: {
        enabled: 1
      }
    }).then(res => {
      if (res.data.code == 0 && res.data.data && res.data.data.pageData && res.data.data.pageData.length > 0) {
        var a = res.data.data.pageData;
        var tt = {
          'ad_code': os.imghost + a[0].ad_code,
          'media_link': '',
          'ad_weapplink': a[0].ad_weapplink,
          'bgcolor': a[0].bgcolor,
        };
        th.setData({ ad_data: tt });
      }
    })
    this.getList();
  },
  onShow: function () {
      getApp().check_can_share();
    //--先判断会员状态--
    getApp().is_Single_page(this, function () {
      var user_info = getApp().globalData.userInfo;
      if (user_info == null || user_info.mobile == undefined || user_info.mobile == "" || user_info.mobile == null) {
        getApp().goto('/packageE/pages/togoin/togoin');
        return false;
      }
      this.init()
    })


  },
  getList: function () {

    if(this.data.ismore) return false;
    if(this.data.searching) return false;
    this.data.searching=1;

    wx.showLoading({
      title: '加载中.',
    })

    var th = this;
    let r_q={
      storeId: th.data.getStorageID, //商家ID
      userId: th.data.getUserID, //用户ID
      page: th.data.curpage,
      pageSize: th.data.pageSize
    }

    if(this.data.sear_key){
      r_q.key_str=this.data.sear_key;
    }

    getApp().request.get('/api/weshop/marketing/my/giftbag/page', {
      isShowLoading: true,
      data: r_q,
      success: function (res) {

        th.data.searching=0;

        if (res.data.code == 0) {
          th.data.curpage++;
          var arr1 = th.data.wareCard;
          var arr2 = res.data.data.pageData;

          for (let j = 0; j <arr2.length ; j++) {

            var t_now = ut.gettimestamp();

            //---获取日期的时间戳---
            var t_endtime = arr2[j].endTime;
            t_endtime = t_endtime.replace(/-/g, '/');
            var t_date = new Date(t_endtime) / 1000;


            var t_starttime = arr2[j].starTime;
            t_starttime = t_starttime.replace(/-/g, '/');
            var t_sdate = new Date(t_starttime) / 1000;

            if (!arr2[j].iswarelbtype)
              arr2[j].c_state=-2  //无核销商品
            else if (arr2[j].goodsUseState)
              arr2[j].c_state=1   //已核销
            else if (t_date <= t_now)
              arr2[j].c_state=2   //已过期
            else if (t_sdate > t_now)
              arr2[j].c_state=-1  //未开始
            else
              arr2[j].c_state=0   //正常
          }


          var arr3 = [...arr1, ...arr2];
          var ismore = 0;
          if (arr3.length == res.data.data.total) ismore = 1
          th.setData({
            wareCard: arr3,
            total: res.data.data.total,
            ismore: ismore,
            is_read: 1,
            is_get:1,
          }), wx.stopPullDownRefresh(); //停止下拉刷新
        } else {
          th.setData({
            is_read: 1,
            ismore: 1,
            is_get:1,
          })
        }

        wx.hideLoading();

      }

    });

  },
  //销毁界面跳转
  redirectTo: function (e) {
    var th = this;
    var url = e.currentTarget.dataset.url;
    //销毁跳转
    wx.redirectTo({
      url: url
    });
  },
  //不销毁界面跳转
  navigateTo: function (e) {
    var th = this;
    var url = e.currentTarget.dataset.url;
    let is_back = e.currentTarget.dataset.is_back
    if (is_back==1) {
      wx.showToast({
        title: '该礼包已退款',
        icon: 'none',
        duration: 2000
      })
    }else {
      getApp().goto(url);
    }
  },
  //下拉事件
  onReachBottom: function () {
    var th = this;
    if (th.data.total <= th.data.pageSize) return;
    if (th.data.ismore) return;
    th.getList();
  },

  //图片失败，默认图片
  bind_bnerr2: function (e) {
    var _errImg = e.target.dataset.errorimg;
    var _errObj = {};
    _errObj[_errImg] = "/miniapp/images/default_g_img.gif";
    this.setData(_errObj) //注意这里的赋值方式,只是将数据列表中的此项图片路径值替换掉 ; 
  },


  //--- 分享设置 --
  onShareAppMessage: function (e) {
    getApp().globalData.no_clear=1;
    var curPage = this;
    var pagePath = curPage.route; //当前页面url
    if (pagePath.indexOf('/') != 0) {
      pagePath = '/' + pagePath;
    }
    pagePath += "?first_leader=" + this.data.getUserID;
    return {
      title: "专享礼包",
      path: pagePath,
    }
  },

  onShareTimeline() {
        getApp().globalData.no_clear=1;
        return {
            title: '专享礼包',
            imageUrl: this.data.ad_data.ad_code,
            query: "first_leader=" + this.data.getUserID
        }
  },

  search_lb(){
    this.data.curpage=0;
    this.searching=0;
    this.setData({ismore:0,is_get:0,wareCard:[]});
    this.getList();
  },

  input_sear(e){
    let value = e.detail;
    this.data.sear_key=value;
  }

});