var e = getApp(),
  i = e.request,
  a = e.globalData.setting,
  os = a,
  ut = require("../../../utils/util.js");
var regeneratorRuntime = require('../../../utils/runtime.js');

Page({
  data: {
    url: a.imghost,
    killtime: null,
    currentPage: 1,
    goodlist: null,
    type: 1,  //1是进行中  0是即将开始
    timer: null,
    ismore: 1, //是否可以加载更多
    isshow: 0,
    ad_data: null,
    max_sw_height: 200,
    is_retail_price:0,

    timer_js:[]
  },

  //------初始化加载----------
  onLoad: function (t) {
    //群id
    if(t && t.groupchat_id){
      getApp().globalData.groupchat_id=t.groupchat_id
    }
    wx.setNavigationBarTitle({
      title: "商品秒杀",
    })
    var first_leader = t.first_leader;
    var type = t.type;
    if (type != undefined) {
      this.setData({
        type: type
      });
    }

    var th = this;
    console.log("------------");
    console.log(first_leader);
    getApp().getConfig();

    var th=this;
    getApp().getConfig2(function (e) {
      var swithc_list = e.switch_list;
      var sw_arr = JSON.parse(swithc_list);
      if(sw_arr.is_retail_price){
        th.setData({is_retail_price:1});
      }
    },1);


    if (first_leader) {
      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=701&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 narr = [];
        for (var i in a) {
          var tt = {
            'ad_code': os.imghost + a[i].ad_code,
            'media_link': '',
            'ad_weapplink': a[i].ad_weapplink
          };
          narr.push(tt);
        }
        th.setData({
          ad_data: narr
        });
      }
    })
    this.requestSalelist();
  },


  onShow: function (t) {
    getApp().check_can_share();
    this.data.is_timer = 1;
    //this.data.currentPage = 1;不能清空未1
    var th = this;
    //设置全局定时器
    th.data.timer = setInterval(function () {
      th.countDown();
    }, 1000);
  },
  onHide: function () {
    //--清理定时器--
    clearInterval(this.data.timer);
    this.data.is_timer=0;
    this.setData({
      isshow: 0
    });
  },
  //---小于10的格式化函数----
  timeFormat(param) {
    return param < 10 ? '0' + param : param;
  },

  //----倒计时函数,优化定时器只显示在可视范围内的-----
  countDown() {
    if (!this.data.goodlist) return false;
    if (!this.data.is_timer) return false;

    var th = this;
    // 获取当前时间，同时得到活动结束时间数组
    let newTime = ut.gettimestamp();
    var endTimeList = this.data.goodlist;
    if (endTimeList == null) return null
    // 对结束时间进行处理渲染到页面
    for (var i = 0; i < endTimeList.length; i++) {
      var oo = endTimeList[i];
      if(!oo) continue;

      if (!this.data.is_timer) break;

      // 创建查询对象
      let query = wx.createSelectorQuery();
      // 获取目标元素，并获取目标元素的信息
      query.select("#kill-item"+i).boundingClientRect();
      // 获取视口，并获取视口信息
      query.selectViewport().boundingClientRect();
      //--  执行查询,元素要在显示中的才显示定时器 --
      query.exec(([target, view]) => {

        if (!th.data.is_timer) return;
        if (!target) return;
        if (!target.id) return;

        let idx=  target.id.replace('kill-item','');
        var o=endTimeList[idx];
        var endTime = o.end_time;
        if (th.data.type == 0) endTime = o.start_time;


        // 条件1：当目标顶部距离视口顶部距离小于视口的高度时
        // 条件2：当目标底部距离视口顶部距离大于0时
        // 当以上两个条件同时成立时，目标元素在视口中
        if (target.top < view.height && target.bottom > 0) {
          let obj = null;
          // 如果活动未结束，对时间进行处理
          if (endTime - newTime > 0) {
            let time = (endTime - newTime);
            // 获取天、时、分、秒
            let day = parseInt(time / (60 * 60 * 24));
            let hou = parseInt(time % (60 * 60 * 24) / 3600);
            let min = parseInt(time % (60 * 60 * 24) % 3600 / 60);
            let sec = parseInt(time % (60 * 60 * 24) % 3600 % 60);
            obj = {
              day: this.timeFormat(day),
              hou: this.timeFormat(hou),
              min: this.timeFormat(min),
              sec: this.timeFormat(sec),
              hide: 1
            }
          } else {
            //活动已结束，全部设置为'00'
            obj = {
              day: '00',
              hou: '00',
              min: '00',
              sec: '00'
            }
          }
          var txt = "timer_js[" + idx + "]";

          if (!th.data.is_timer) return;

          th.setData({
            [txt]: obj
          });
        } else {
          console.log("隐藏中");
        }
      });

    }
  },

  async requestSalelist() {
    //--没有更多就不调用--
    if (!this.data.ismore) return false;
    if(this.data.lding) return false;
    this.data.lding=1;
    this.data.is_timer=0;  //暂停一下定时器


    var e = this,
      th = e,
      i = "/api/ms/flash_sale/spikepage?page=" + e.data.currentPage;
    var plist = [],
      alllist = th.data.goodlist;
    if (!alllist) alllist = [];
    var user_id = getApp().globalData.user_id;
    if (!user_id) user_id = user_id;

    var req = {
      store_id: os.stoid,
      timetype: th.data.type,
      is_end: 0,
      is_show: 1,
      user_id: user_id,
      isRedis:1
    };

    wx.showLoading();

    await getApp().request.promiseGet(i, {
      isShowLoading: 0,
      data: req
    }).then(res => {
      if (ut.ajax_ok(res)) plist = res.data.data.pageData;
    });

    if (!plist || plist.length <= 0) {

      wx.hideLoading();

      th.data.ismore = 0;
      this.data.is_timer=1;
      if (e.data.currentPage == 1 && this.data.type == 1) {

          //-- 弄到即将开始 --
          req.timetype=0;
          await getApp().request.promiseGet(i, {
            isShowLoading: 0,
            data: req
          }).then(res => {
             if (ut.ajax_ok(res)) th.data.b_plist = res.data.data.pageData;
          });

           wx.hideLoading();
           if(th.data.b_plist){
             //让秒杀跳转后能下拉加载
             th.data.ismore = 1;
              //组件的id
              var auto_go = th.selectComponent("#auto_go");
              auto_go.show();
           }else{
              getApp().showWarning("没有更多数据");
           }
          //   setTimeout(function () {
          //     th.data.ismore = 1;
          //     th.setData({
          //       type: 0
          //     });
          //     th.requestSalelist();
          //   }, 1000);
      }else{
        wx.hideLoading();
        getApp().showWarning("没有更多数据");
      }

      this.data.lding=0;
      this.data.is_timer=1;
      return false;
    }

    //--循环读取接口---
    for (var i = 0; i < plist.length; i++) {

      if (plist[i].user_price) plist[i].price = plist[i].user_price;
      let price=plist[i].price+''
      if (price && price.indexOf('.')>-1) {
        let priceArr = price.split(".")
        plist[i].price_n = priceArr[0]
        plist[i].price_xs = priceArr[1]
      }else{
        plist[i].price_n = price
      }
      var prom_id = plist[i].id;

      // await getApp().request.promiseGet("/api/weshop/activitylist/getActLen/" +
      //   os.stoid + "/1/" + prom_id, {}
      // ).then(res => {
      //   if (res.data.code == 0) {
      //     plist[i].status = 1;
      //     if (res.data.data <= 0) plist[i].status = 3;
      //   }
      // })

      plist[i].status = 1;
      if (plist[i].actLen <= 0) {
        plist[i].status = 3;
      }


      alllist.push(plist[i]);
    }
    e.data.currentPage++;
    console.log("秒杀商品列表", alllist);
    th.setData({
      goodlist: alllist,
      isshow: 1
    });

    setTimeout(()=>{
      wx.hideLoading();
    },200)

    this.data.lding=0;
    this.data.is_timer=1;



  },
  onPullDownRefresh: function () {
    this.reloadGoodList();
  },
  reloadGoodList: function () {
    this.data.goodlist = [], this.data.currentPage = 1, this.requestSalelist();
  },

  onReachBottom: function () {
    this.requestSalelist();
  },

  //点击tab事件
  tip: function (e) {
    var a = e.currentTarget.dataset.ty,
      th = this;
    th.data.ismore = 1;
    this.setData({
      type: a,
      goodlist: null
    });

    if(a==0){
      var auto_go = th.selectComponent("#auto_go");
      auto_go.stop();
    }

    this.reloadGoodList();
  },


  //---------分享配置--------
  onShareAppMessage: function (e) {
    getApp().globalData.no_clear=1;
    var curPage = this;
    var pagePath = curPage.route; //当前页面url
    if (pagePath.indexOf('/') != 0) {
      pagePath = '/' + pagePath;
    }
    if (getApp().globalData.user_id) {

      if (pagePath.indexOf("?") > 0) {
        pagePath += "&first_leader=" + getApp().globalData.user_id;
      } else {
        pagePath += "?first_leader=" + getApp().globalData.user_id;
      }
      //群id分享
      if (getApp().globalData.groupchat_id) {
        pagePath+="&groupchat_id="+getApp().globalData.groupchat_id
      }
    }else{
      if(pagePath.indexOf("?")>0){
        pagePath+="&groupchat_id="+getApp().globalData.groupchat_id
      }else{
        pagePath+="?groupchat_id="+getApp().globalData.groupchat_id
      }
    }


    console.log("11" + pagePath);
    return {
      title: "限时秒杀",
      path: pagePath,
    }
  },

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

    onShareTimeline() {
        getApp().globalData.no_clear=1;
        var store_name = getApp().globalData.config ? getApp().globalData.config.store_name : '';
        if (!store_name)
            store_name = getApp().globalData.setting.appName;

        var user_id=getApp().globalData.user_id;
        if(!user_id) user_id=0;
        var url=""
       //群id分享
       if (getApp().globalData.groupchat_id) {
        url+="&groupchat_id="+getApp().globalData.groupchat_id
      }


        return {
            title: '秒杀活动-' + store_name,
            query: 'first_leader='+user_id+url
        }
    },

  imageLoad: function (e) {
    var imgwidth = e.detail.width;
    var imgheight = e.detail.height;
    //宽高比
    var ratio = imgwidth / imgheight;
    //计算的高度值
    var viewHeight = 750 / ratio;
    var hei = this.data.max_sw_height;

    if (hei < viewHeight) {
      this.setData({
        max_sw_height: viewHeight
      });
    }
  },
  go_url(e) {
    let url = e.currentTarget.dataset.url;
    if (url) {
      getApp().goto(url);
    }
  },

  async auto_back(){

    var e=this,th=this;
    th.setData({ type: 0 });
    wx.showLoading();

    var plist=this.data.b_plist;
    var alllist = th.data.goodlist;
    if (!alllist) alllist = [];

    //--循环读取接口---
    for (var i = 0; i < plist.length; i++) {

      if (plist[i].user_price) plist[i].price = plist[i].user_price;
      let price=plist[i].price+''
      if (price && price.indexOf('.')>-1) {
        let priceArr = price.split(".")
        plist[i].price_n = priceArr[0]
        plist[i].price_xs = priceArr[1]
      }else{
        plist[i].price_n = price
      }
      var prom_id = plist[i].id;
      await getApp().request.promiseGet("/api/weshop/activitylist/getActLen/" +
          os.stoid + "/1/" + prom_id, {}
      ).then(res => {
        if (res.data.code == 0) {
          plist[i].status = 1;
          if (res.data.data <= 0) plist[i].status = 3;
        }
      })
      alllist.push(plist[i]);
    }
    e.data.currentPage++;
    console.log("秒杀商品列表", alllist);
    th.setData({
      goodlist: alllist,
      isshow: 1
    });

    setTimeout(()=>{
      wx.hideLoading();
    },400)
  }

});