  var t = function(t) {
    return t && t.__esModule ? t : {
        default: t
    };
}(require("../../../utils/LoadMore.js")), e = getApp(), a = new t.default(), oo = e.globalData.setting, ut = require("../../../utils/util.js");
var regeneratorRuntime = require('../../../utils/runtime.js');
var com_fil= require('../com_screen.js');

Page({ 
    data: {
        url: e.globalData.setting.imghost,
        resourceUrl: e.globalData.setting.resourceUrl,
        iurl: e.globalData.setting.imghost,
        currentPage: 1,
        requestData: null,
        allData: null,
        openFilterModal: !1,
        baseUrl: "/api/weshop/goods/page?1=1&isnewwhere=1",
        requestUrl: "",
        old_req_url:'',

        tabname:"sort",   //排序的字段
        adname:"asc",        //升降的字段
		is_new:0,
        is_hot:0,
        is_no_plus:1,
        prom_goods_list:null,
        rq_data:null,
		isToggle: false, //切换商品视图控制符
        show_all:1,      //判断显示

        is_retail_price:0,  //是否显示零售价

        more_sort_arr:[
            {name:'综合',value:'sort'},
            {name:'新品',value:'on_time'},
            {name:'评论',value:'comment_count'},
        ],

        fil_cate_state:0,
        fil_nation_state:0,
        fil_brand_state:0,
        fil_price_state:0,
        limit_num:0,
        gr_fir:0,  //分组第一次
        share_imgurl:'', //分享图片
        add_purchase:false,

        pro_good:null,  //优惠促销活动
        pro_good_err:null,  //优惠促销活动
    },

    onLoad: async function(t) {
      //----------商品分组自定义分享图片----------
      if (t.gid || t.group_id) {
        let id = t.gid || t.group_id
        this.get_share_imgurl(id) //获取分享图片
      }

      //---------------------end------------
       this.data.rq_data=t;

       //接受有没有导购的参数
       var first_leader=t.first_leader;
       if(first_leader){
            getApp().globalData.first_leader=first_leader;
            //调用接口判断是不是会员
            getApp().request.promiseGet("/api/weshop/shoppingGuide/get/"+oo.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 th=this;
      var url = this.data.baseUrl;

      if (0 != t.prom_id && t.prom_id != undefined) { url += "&prom_id=" + t.prom_id; }
      if (0 != t.prom_type && t.prom_type != undefined) { url += "&prom_type=" + t.prom_type; }


      //先查看一下是不是系统会员
      getApp().waitfor_login(async ()=> {
          if (!getApp().globalData.user_id) {
              ut.new_user_go(oo.stoid, first_leader);
          }

          await th.get_prom_act(t);
          if(t.prom_type==3 && !th.data.pro_good){
              if(th.data.pro_good_err.indexOf("无权限")>-1){
                   ut.m_toast('您无权限参与优惠促销活动');
              }else{
                  ut.m_toast('未找到优惠促销活动');
              }
              setTimeout(()=>{
                 getApp().goto('/pages/index/index/index');
              },1500)
              return false
          }

          this.data.is_new=t.is_new;
          this.data.is_hot=t.is_hot;
          if (0 != t.cat_id && t.cat_id != undefined) {
                url += "&cat_id=" + t.cat_id;
                if (t.pid == undefined || t.pid == null){
                    url +=  "&parent_id=0";
                }else{
                    if(t.pid!="three"){
                        url +=  "&parent_id="+t.pid;
                    }
                }
                this.data.cat_id=t.cat_id;
            }

          if (0 != t.brand_id && t.brand_id != undefined) { url += "&brand_id=" + t.brand_id; }
          if (0 != t.nation_id && t.nation_id != undefined) { url += "&nation_id=" + t.nation_id; }

          if (0 != t.group_id && t.group_id != undefined) { url += "&group_id=" + t.group_id; this.data.gr_fir=1; }
          if (0 != t.gid && t.gid != undefined) { url += "&group_id=" + t.gid; this.data.gr_fir=1; }

          if (0 != t.max_price && t.max_price != undefined) { url += "&min_pirce=" + t.min_pirce + "&max_price=" + t.max_price; }

          if (0 != t.is_new && t.is_new != undefined) { url += "&is_new=" + t.is_new; }
          if (0 != t.is_hot && t.is_hot != undefined) { url += "&is_hot=" + t.is_hot; }
          if (0 != t.ladder_id && t.ladder_id != undefined) {
               url += "&ladder_id=" + t.ladder_id;
               this.setData({
                ladder_id:t.ladder_id,
                baseUrl:url,
               })
            }

          var user_id=getApp().globalData.user_id;
          if(!user_id) user_id=0;
          url += "&user_id="+user_id;

          // 优惠促销列表
          if(t.prom_goods_id) {
                url += '&prom_goods_id=' + t.prom_goods_id;
          };


          if(getApp().globalData.userInfo) {
              url += "&user_id=" + getApp().globalData.userInfo.user_id;
          }

          //--- 阶梯优惠活动的凑单 ---
          if(t.ladder_id){
              var user_id=getApp().globalData.user_id;
              if(!user_id) user_id=0;
              getApp().request.promiseGet("/api/weshop/prom/ladderForm/getNew/"+oo.stoid+"/"+user_id+"/"+t.ladder_id,{
              }).then(res=>{
                  if(res.data.code==0 && res.data.data){
                      var arr= res.data.data;

                      if(arr.is_end==1){
                          th.setData({show_all:0,err_txt:'活动已结束'});
                          return false;
                      }
                      if(arr.start_time>ut.gettimestamp()){
                          th.setData({show_all:0,err_txt:'活动还未开始'});
                          return false;
                      }
                      if(arr.end_time<ut.gettimestamp()){
                          th.setData({show_all:0});
                          th.setData({show_all:0,err_txt:'活动已结束'});
                          return false;
                      }

                      var url1="/api/weshop/prom/ladderList/list?store_id="+oo.stoid+"&form_id="+arr.id;
                      getApp().request.promiseGet(url1, {}).then(rs=>{
                          if(rs.data.code==0 && rs.data.data && rs.data.data.length) {
                              var prom_content="";
                              for(let jj in  rs.data.data){
                                  if(rs.data.data[jj].discount==10){
                                      prom_content+="第"+(parseInt(jj)+1)+"件原价，";
                                  }else{
                                      prom_content+="第"+(parseInt(jj)+1)+"件"+rs.data.data[jj].discount+"折，";
                                  }
                              }
                              prom_content=ut.sub_last(prom_content);
                              th.setData({jieti_prom:prom_content})
                          }
                      })
                  }
                  else{
                      th.setData({show_all:0,err_txt:'未找到活动或者身份不符'});
                  }
              })
          }


          this.data.old_req_url=url;
          //进行筛选
          this.set_screen(url);

          this.requestGoodsList(url);

          getApp().getConfig2(function(rs){
              //计算等级价相关
              var swithc_list=rs.switch_list;
              var sw_arr=JSON.parse(swithc_list);
              //---如果后台又开等级卡的开关---
              if(sw_arr.rank_switch && sw_arr.rank_switch=="2"){
                  th.setData({rank_switch:true});
                  var user=getApp().globalData.userInfo;
                  var ti=setInterval(function(){
                      if(!user) return false;
                      clearInterval(ti);
                      //---回调卡的列表---
                      th.getPlusCardType(function(ob){
                          th.setData({card_list:ob.card_list});
                          if(user.card_field ){
                              var str = user['card_expiredate'].replace(/-/g, '/');
                              var end = new Date(str);
                              end = Date.parse(end) / 1000;
                              var now = ut.gettimestamp();

                              //--- 判断是等级会员，且在有效期范围内 ---
                              if(user.card_field && now<end){
                                  var card_name=ob.name_map.get(user.card_field);
                                  // if(card_name.length>4) card_name=card_name.substring(0,4);
                                  th.setData({card_field:user.card_field,card_name:card_name,card_list:ob.card_list});
                              }
                          }
                      })
                  },500)
              }

              if(sw_arr.is_retail_price){
                  th.setData({is_retail_price:1});
              }

          });

      })




      //调用接口判断商家plus有没有过期
      getApp().request.promiseGet("/store/storemoduleendtime/page?store_id=" + oo.stoid + "&type=3", {}).then(res => {
        if (res.data.code == 0) {
          var arr = res.data.data.pageData;
          if (arr.length > 0) {
            var item = arr[0];
            if (item.is_sy == 0) {
              var now = Date.parse(new Date()); now = now / 1000;
              if (item.end_time < now) {
                th.setData({ is_no_plus: 0 })
              }
            }
          }
        }
      })
    },


   async get_prom_act(t){
        var th=this;
        //优惠活动的凑单
        if(t.prom_type==3){
            if (t.prom_id) {
                await this.getprom(t.prom_id);
                if(!th.data.pro_good){
                    return false;
                }
            }

            //-- 获取 --
            getApp().request.promiseGet("/api/weshop/promgoodslist/list",{
                data:{prom_id:t.prom_id }
            }).then(res=>{
                if(res.data.code==0){
                    var arr= res.data.data;
                    th.set_prom_list(arr);
                }
            })

        }
    },

    onShow:function () {
        getApp().check_can_share();
    },
    //获取商品分组分享图片
    get_share_imgurl(gid){
      getApp().request.promiseGet("/api/weshop/goodsGroup/get/" + oo.stoid + "/" + gid, {}).then(res => {
        if (res.data.code == 0) {
          let prom = res.data.data;
          let share_imgurl =prom.share_imgurl
          this.setData({
            share_imgurl
          })
        }
      })
    },
    //获取优惠活动
    async getprom(prom_id){
      let th=this;
      var uid=getApp().globalData.user_id || 0;
      await getApp().request.promiseGet("/api/weshop/promgoods/getUser/" + oo.stoid + "/" + prom_id+"/"+uid, {}).then(res => {
        if (res.data.code == 0) {
          let prom = res.data.data;
          th.data.pro_good=prom;
          let limit_num =prom.limit_num
          this.setData({
            limit_num
          })
        }else{
            th.data.pro_good_err=res.data.msg;
        }

      })
    },
    //设置优惠券的
    set_prom_list:async function(arr){
        var th=this;
        for(var i in arr){
             //优惠的实际内容
            var content=JSON.parse(arr[i].preferential_type);
            arr[i].content=content;


            //--送券--
            if(parseInt(content.is_coupon)) {
                //-- 获取 --
                await getApp().request.promiseGet("/api/weshop/prom/coupon/get/"+content.coupon, {
                }).then(res => {
                    if(res.data.code==0 && res.data.data )
                        arr[i].content.coupon_money=res.data.data.money;
                })
            }
            
             //--送礼包--
             if(parseInt(content.is_libao)) {
                //-- 获取 --
                await getApp().request.promiseGet("/api/weshop/libao/libaoForm/page?id="+content.libao+"&store_id="+oo.stoid, {
                }).then(res => {
                    if(res.data.code==0 && res.data.data && res.data.data.pageData && res.data.data.pageData.length>0)
                        arr[i].content.lb_name=res.data.data.pageData[0].lbtitle;
                })
             }
             //--送赠品--
            if(parseInt(content.is_gift) && content.zp_mode==0) {
                //-- 获取 --
                await getApp().request.promiseGet("/api/weshop/prom/gift/page?id="+content.gift+"&store_id="+oo.stoid, {
                }).then(res => {
                    if(ut.ajax_ok(res)) {
                        arr[i].content.gift_name = res.data.data.pageData[0].goods_name;
                        if (!content.zpname_type) content.zpname_type = '';

                        if (parseInt(content.zpname_type) > 0) {
                            arr[i].content.gift_name = res.data.data.pageData[0].title;
                        }
                    }
                })
            }

            //--送专享礼包--
            if(parseInt(content.is_zxlibao)) {
                //-- 获取 --
                await getApp().request.promiseGet("/api/weshop/marketing/giftbag/detail/getNew1?storeId="+oo.stoid+"&giftBagId="+content.zxlibao, {
                }).then(res => {
                    if(res.data.code==0 && res.data.data)
                        arr[i].content.zxlb_name=res.data.data.lbTitle;
                })
            }

            //--送专享礼包--
            if(parseInt(content.is_monthgiftbag)) {
                //-- 获取 --
                await getApp().request.promiseGet("/api/weshop/marketing/marketingMonthgiftbagForm/get/"+oo.stoid+"/"+content.monthgiftbag, {
                }).then(res => {
                    if(res.data.code==0 && res.data.data)
                        arr[i].content.monthgift_name=res.data.data.act_name;
                })
            }


        }
        th.setData({prom_goods_list:arr});
    },

    changeTab: function(t) {

       //清空
       this.data.gr_fir=0;

       var ord = t.currentTarget.dataset.href;
       var ad = t.currentTarget.dataset.ad;
       var url = this.data.requestUrl;

      if (this.data.tabname!=ord){
         this.setData({ tabname: ord, adname: "desc" });
      }else{
         ad = ad == "desc" ? "asc" :"desc";
        this.setData({adname: ad });
      }  
      this.resetData(), this.requestGoodsList(url);
    },

    requestGoodsList:function(t) {
        if(this.data.loading) return false;
        this.data.loading=1;
        var e = this,th=e;
        this.data.requestUrl = t;


        var user_id=getApp().globalData.user_id;
        if(!user_id) user_id=0;


        //不是商品分组的，不是默认排序的
        if (t.indexOf("group_id") == -1 || !this.data.gr_fir) {
            t += "&orderField=" + e.data.tabname;
            t += "&orderType=" + e.data.adname;
        }

		
        t +="&page=" + e.data.currentPage;
        wx.showLoading({});

		getApp().request.promiseGet(t, {data:{is_mainshow: 1, isonsale: 1, store_id: oo.stoid}}).then(async res=>{
          th.data.loading=0;
          wx.hideLoading();

          e.setData({is_go:1});
		  if(ut.ajax_ok(res)){
              e.data.currentPage++;
              if(!e.data.requestData) e.data.requestData=[];
              for(let i in res.data.data.pageData){
                  let item=res.data.data.pageData[i];
                  item.original_img = th.data.url + item.original_img;
                  /*--
                  var url="/api/weshop/activitylist/getGoodActInfo";
                  var req_data={
                      store_id:oo.stoid,goodsidlist:item.goods_id,is_detail:1,user_id:user_id
                  };
                  //获取商品的实际活动
                  await getApp().request.promiseGet(url, {data:req_data}).then(res=>{
                      if(res.data.code==0 && res.data.data && res.data.data.length==1){
                          item.prom_type=res.data.data[0].prom_type;
                          item.prom_id=res.data.data[0].act_id;
                      }
                  })--*/

                  var prom_type = item.prom_type; //0普通商品  1秒杀  6拼单 2团购 4积分购
                  var prom_id=item.prom_id;
                  var now=ut.gettimestamp();
                  var url = "";
                  var user_id=getApp().globalData.user_id;
                  if(!user_id) user_id=0;

                  switch (prom_type){
                      case 1:
                          url = "/api/ms/flash_sale/getNew/" +oo.stoid + "/" +user_id+"/"+ prom_id;
                          break;
                      case 2:
                          url ="/api/weshop/goods/groupBuy/getNewActInfo/" +oo.stoid + "/" +item.goods_id+"/"+ prom_id+"/"+user_id;
                          break;
                      case 4:
                          url ="/api/weshop/integralbuy/get/"+oo.stoid +"/"+prom_id;
                          break;
                      case 6:
                          url = "/api/weshop/teamlist/get/" + oo.stoid + "/" + prom_id;
                          break;
                      case 8:
                          var presell_id = prom_id;
                          var url1 = "/api/weshop/marketing/marketingPresellList/list";
                          var rd= {
                              store_id: oo.stoid,
                              presell_id: presell_id,
                              goods_id: item.goods_id
                          }
                          //------获取预售从表----------
                          await getApp().request.promiseGet(url1, {
                              data: rd
                          }).then(res => {
                              if (res.data.code == 0 && res.data.data && res.data.data.length > 0) {
                                  var arr = res.data.data[0];
                                  item.prom_price = arr.luck_goods_price;
                                  // item.sales_sum=arr.buy_goodnum+(arr.virtual_qty?arr.virtual_qty:0);
                              }
                          })
                          break;
                      default:
                          break
                  }
                  if(url!=null && url!=''){
                      await getApp().request.promiseGet(url, {}).then(res => {
                          var prom =null;
                          if(res && res.data) prom=res.data.data;
                          if (prom != null && prom.is_end==0 && prom.end_time>now && (prom.start_time<now || (prom_type!=2 &&  prom.show_time && prom.show_time<now)) ) {
                              item.prom_price = res.data.data.price;
                              if(prom_type==4){
                                  item.prom_price= res.data.data.addmoney;
                              }
                              if(res.data.data.user_price) item.prom_price=res.data.data.user_price;
                              // var vNum=res.data.data.virtual_num?res.data.data.virtual_num:0;
                              // var vNum1=res.data.data.virtualNum?res.data.data.virtualNum:0;
                              // var vNum2=res.data.data.virtual?res.data.data.virtual:0;
                              // item.sales_sum=res.data.data.buy_num+(vNum+vNum1+vNum2);
                          }else{
                              item.prom_type=0;
                              item.prom_id=0;
                              item.prom_price=null;
                          }
                      })
                  }

                  e.data.requestData.push(item);
                  e.setData({requestData: e.data.requestData})
              }
		  }
		})
        wx.stopPullDownRefresh();
    },
    onReachBottom: function() {
        a.canloadMore() && this.requestGoodsList(this.data.requestUrl);
    },
    onPullDownRefresh: function() {
        this.resetData(), this.requestGoodsList(this.data.requestUrl);
    },
    openFilterModal: function() {
        this.setData({
            openFilterModal: !0
        });
    },
    closeFilterModal: function() {
        this.setData({
            openFilterModal: !1
        });
    },
    filterGoods: function(t) {
        this.resetData(), this.requestGoodsList(t.currentTarget.dataset.href), this.closeFilterModal();
    },
    resetData: function() {
        a.resetConfig(), this.data.requestData = null, this.data.currentPage = 1;
    },

    //---回复最初的设置---
    restoreData: function() {
        this.setData({
            requestData: null,
        });
        this.data.currentPage = 2;
    },
//---------分享配置--------
  onShareAppMessage: function (e) {
      getApp().globalData.no_clear=1;
      var curPage=this;
      var pagePath = curPage.route; //当前页面url
      if (pagePath.indexOf('/') != 0) {
          pagePath = '/' + pagePath;
      }

      if(this.data.rq_data && JSON.stringify(this.data.rq_data) != "{}") {
          var parm = ut.ob_to_parm(this.data.rq_data);
          pagePath += "?" + parm;
      }

      if(getApp().globalData.user_id){
          if(pagePath.indexOf("?")>0){
              pagePath+="&first_leader="+getApp().globalData.user_id;
          }else{
              pagePath+="?first_leader="+getApp().globalData.user_id;
          }
      }
      console.log("11-11"+pagePath);


      //分享的数组
      let share_dd={
          title: "商品列表",
          path:pagePath,
      }
      //有图片才分享图片
      if(this.data.share_imgurl){
          let share_imgurl=this.data.iurl + this.data.share_imgurl;
          share_dd.imageUrl=share_imgurl;
      }

      return share_dd;
  },
    //---图片失败，默认图片---
    bind_bnerr2: function (e) {
    var _errImg = e.target.dataset.errorimg;
    var _errurl = e.target.dataset.url;
    var ii = _errurl.indexOf(oo.imghost);
    if (ii != -1) {
      var _errObj = {};
      _errObj[_errImg] = this.data.iurl+"/miniapp/images/default_g_img.gif";
      this.setData(_errObj) //注意这里的赋值方式,只是将数据列表中的此项图片路径值替换掉 ; 
    }
  },
  
	
	
  //---  获取卡类列表 ---
  getPlusCardType: function (func) {
     var storid = oo.stoid;
     var th = this;
     getApp().request.promiseGet("/api/weshop/plus/vip/mem/bership/list?" + "storeId=" + storid, {}).then(res => {
       var plusCard = res.data.data;
       var arr = [1219, 2089, 3031];
       var new_arr = new Array();
        var card_name_map=new Map();
        var user = getApp().globalData.userInfo;
       for (var i = 0; i < plusCard.length; i++) {	   
        if ((!user || user.card_field==null || user.card_field=="") && (plusCard[i].IsStopBuy==true)) {
          continue;
        }   
  			var name="card"+plusCard[i].CorrPrice.toLowerCase();
        card_name_map.set(name,plusCard[i].CardName);		
        new_arr.push(plusCard[i]);			       
       }
      			  
  		  var ob={"card_list":new_arr,"name_map":card_name_map};
  		  func(ob);	
     })
   },
	 

	 // 切换显示
	 bindToggleDisplay() {
			this.setData({
				isToggle: !this.data.isToggle,
			});
	 },

    go_url:function (e) {
       var url = e.currentTarget.dataset.url;
			 var rq_data = JSON.stringify(this.data.rq_data);
			 url += `&o=${rq_data}`;
			 // console.log('url!!!=======<<<<', url);
       getApp().goto(url);
    },

    /*-- 和筛选相关的 --*/
    bind_pk_sort(e){  //清空
        this.data.gr_fir=0; com_fil.bind_pk_sort(e,this);
    },
    set_screen(url){  com_fil.set_screen(url,this); },
    filterGoods(e){
        //清空
        this.data.gr_fir=0;com_fil.filterGoods(e,this);
    },
    open_more(e){ com_fil.open_more(e,this); },
    clear_fil(){  //清空
        this.data.gr_fir=0;com_fil.clear_fil(this);
    },
        // 加购方法show
        addPurchase(even){  
          this.setData({
            add_purchase:true
          })
          let gid = even.currentTarget.dataset.gid
          let prom_id = even.currentTarget.dataset.prom_id
          let prom_type = even.currentTarget.dataset.prom_type
          let goods_type= even.currentTarget.dataset.goods_type
          let add_purchase = this.selectComponent("#add_purchase");
          if (add_purchase) {
            add_purchase.init(gid,prom_type,prom_id,goods_type)
          }
        },
        // 加购方法 hide
        hide_add_purchase(){
          setTimeout(()=>{
            this.setData({
              add_purchase:false
            })
          },1000)
        }


});