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

Page({
    data: {
        url: os.imghost,
        goodlist:[],
        page: 1,
        timer: null,
        ismore: 1,  //是否可以加载更多
        isshow: 0,
        ad_data: null,
        max_sw_height: 200,
        type: 0,
    },

    //------初始化加载----------
    onLoad: function (t) {
        var first_leader = t.first_leader;
        var th = this;
        getApp().getConfig();
        this.data.act_id=t.act_id;
              //群id
    if(t && t.groupchat_id){
      getApp().globalData.groupchat_id=t.groupchat_id
    }
        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=1202&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});
            }
        })

        var userInfo=getApp().globalData.userInfo;
        if(userInfo && this.data.goodlist.length==0){
            //调用列表
            this.get_list();
        }else{
            getApp().goto("/packageE/pages/togoin/togoin");
        }

        var  room_id = t.room_id;
        var  room_user_share = t.room_user_share; //如果是会员分享带有room_id的话，那么接下来会员分享就不传room_id
        //-- 如果有房间号 --
        if (room_id) {
            getApp().globalData.room_id = room_id;
            //如果是会员分享过来的要记录
            if (room_user_share)  getApp().globalData.room_user_share = room_user_share;
        }


        if(this.data.act_id){
            getApp().promiseGet("/api/weshop/marketing/marketingPresellForm/get/"+os.stoid+"/"+this.data.act_id,{}).then(res=>{
                if(res.data.code==0)
                    th.data.pre_act=res.data.data
            })
        }

    },
    onShow: function (t) {
        // var userInfo=getApp().globalData.userInfo;
        // if(userInfo && this.data.goodlist.length==0){
        //     //调用列表
        //     this.get_list();
        // }else{
        //     if(getApp().globalData.pre_back==1){
        //         getApp().globalData.pre_back=0;
        //         getApp().goto("/pages/index/index/index");
        //     }
        // }

        this.setData({no_more: 0})
        this.get_list();

    },
    //---小于10的格式化函数----
    timeFormat(param) {
        return param < 10 ? '0' + param : param;
    },

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

    //图片失败，默认图片
    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) //注意这里的赋值方式,只是将数据列表中的此项图片路径值替换掉 ;
        }
    },


    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});
        }
    },


    //获取数据
    get_list(){
        var self = this;
        if (this.data.loading) return false;
        if (this.data.no_more) return false;
        this.data.loading = 1;

        var req = {
            is_end: 0,
            store_id: os.stoid,
            page: this.data.page,
            pageSize: 10,
            // timetype: self.data.type,
            isuse:1,
            timetype:3
        }
        if(getApp().globalData.userInfo){
            req.user_id=getApp().globalData.userInfo.user_id;
        }
        if(this.data.act_id){
            req.prom_type=8;
            req.prom_id=this.data.act_id;
        }
        //调用接口获取数据
        getApp().request.get("/api/weshop/marketing/marketingPresellList/page", {
            data: req,
            success: function (res) {
                let now = ut.gettimestamp();
                self.data.loading = 0;
                if (res.data.code == 0 && res.data.data && res.data.data.pageData && res.data.data.pageData.length > 0) {
                    var list = self.data.goodlist ? self.data.goodlist : [];
                    var arr = res.data.data.pageData;
                    //数组合起来
                    for (var i in arr) {
                        arr[i].type =  arr[i].show_time&&(now>=arr[i].show_time&&now<arr[i].start_time)?0:(now>arr[i].start_time&&now<arr[i].end_time)?1:2;
                        arr[i].djs = { 
                          day: '00',
                          hou: '00',
                          min: '00',
                          sec: '00',
                        };
                        list.push(arr[i]);
                    }
                    self.data.page++;
                    self.setData({goodlist: list});
                    if (arr.length < 10) {
                        self.setData({no_more: 1})
                    }

                     // 预热活动设置倒计时
                    if (self.data.type == 0) {
                        clearInterval(self.data.timer);
                        self.data.timer = setInterval(function () {
                            self.countDown();
                        }, 1000);
                        
                    }
                } else {
                    self.setData({no_more: 1})
                }
                self.setData({is_get: 1})
               
            }
        })
    },


    go_index:function () {
        getApp().goto("/pages/index/index/index");
    },


    tip: function(e){
        // 获取模板Data数据 1进行中 0预热中
        var typeValue = e.currentTarget.dataset.ty;
        // 初始化数据
        this.data.type = typeValue;
        this.data.loading = 0;
        this.data.no_more = 0;
        this.data.page = 1;
        this.data.goodlist = [];
        var goodslist = this.data.goodlist;
        // 设置模板Data数据
        this.setData({
            type: typeValue,
            goodlist: goodslist,
        });
        // 请求接口数据
        this.get_list();
    },

      //----倒计时函数-----
   countDown() {
    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 o = endTimeList[i];
        var endTime = o.start_time;
        let obj = null;
        var type = 1;
        var tend = false;
        // if (o.show_time && newTime < endTime && newTime >= o.show_time) {
        //   type = 0;
        // }
        // 如果活动未结束，对时间进行处理
        if (o.show_time && newTime < endTime && newTime > o.show_time){
            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
            }
            type = 0;
        }else{
          //活动已结束，全部设置为'00'
          obj = { 
              day: '00', 
              hou: '00', 
              min: '00', 
              sec: '00' 
          }
          tend = true
        }
        var txt ="goodlist["+i+"].djs";
        var typ ="goodlist["+i+"].type";
        var end ="goodlist["+i+"].end";
        th.setData({ 
          [txt]: obj,
          [typ]: type,
          [end]: tend,
        });
    }
   },
   go_url(e){
        let url=e.currentTarget.dataset.url;
        if(url){
            getApp().goto(url);
        }
   },

   onShareAppMessage: async function (t) {
       getApp().globalData.no_clear=1;
       var img="";
       if(this.data.ad_data && this.data.ad_data.length ){
           img=  this.data.ad_data[0];
       }else{
          var url="/api/weshop/store/get/"+os.stoid;
          await getApp().promiseGet(url,{}).then(res=>{
             if(res.data.code==0){
                 img= os.imghost+res.data.data.store_logo
             }
          })
       }

       var url = "/packageC/pages/presell/list/list";

       if(this.data.act_id){
           url += "?act_id=" + this.data.act_id;
       }
       if (getApp().globalData.user_id) {

           if(url.indexOf("?")==-1)
               url += "?first_leader=" + getApp().globalData.user_id;
           else
               url += "&first_leader=" + getApp().globalData.user_id;
            
            url+="&groupchat_id="+getApp().globalData.groupchat_id

       }else{
          if(url.indexOf("?")>0){
            url+="&groupchat_id="+getApp().globalData.groupchat_id
          }else{
            url+="?groupchat_id="+getApp().globalData.groupchat_id
          }

      }
       //-- 如果房间分享，且不是会员分享的 --
       if (getApp().globalData.room_id &&
           this.data.data.goods_id == getApp().globalData.room_goods_id &&
           !getApp().globalData.room_user_share
       ) {
           url += "&room_id=" + getApp().globalData.room_id + "&room_user_share=1";
       }

       var ob={};
       if(this.data.pre_act){
           ob = { title: this.data.pre_act.share_title, path: url,imageUrl:os.imghost+this.data.pre_act.share_img };
       }else{

           ob = { title: "预售列表", path: url, };
           if(img){
               ob.imageUrl=img;
           }
       }


       return ob;
   }


 });
