var t = getApp(), e = t.request, oo = t.globalData.setting;
var i = function (i) {
  return i && i.__esModule ? i : {
    default: i
  };
}(require("../../../utils/LoadMore.js")), a = new i.default(), ut = require("../../../utils/util.js");
//t = i,e = t
var nextTimeOff=null
Page({
  data: {
    is_date: true,
    scrollHeight: 0,
    currentTab: -1,
    abc: 0,
    windowHeight: 0,
    windowWidth: 0,
    eachLetterHeight: 0,
    lettersPosition: 0,
    catelist: null,   //分类读取
    nationlist: null,//国家读取
    groups: null,    //品牌读取
    iurl: oo.imghost,//图片地址
    nextShow:false, //是否跳转下个类型
    nextShow2:false, //是否跳转下个类型
    toupper:true,
    sClientY:0,   //滑动初始值
    eClientY:0,  //滑动终值
    // 当前选择的导航字母
    selected: 0,
    // 选择字母视图滚动的位置id
    scrollIntoView: 'A',
    // 导航字母
    letters: ['A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T',
      'U', 'V', 'W', 'X', 'Y', 'Z'],
    //控制新旧分类版本
    is_used_share: 0,
    //国家的控制属性
    is_country: 1,
    //品牌的控制属性
    is_brand: 1,
    //选择分类的控制属性
    select_classify_on: 223,
    index: 223,
    classify_name: "国家",//项目类型
    brand_list: null,//品牌列表

    one_level_classify: [],// 新的版本左边的边分类1级
    is_level_three: 0,//判断有没有3级
    cat_id: 0,
    pl_timer: null,//只有品类的定时器
    is_pl_time: 0,
    requestData: null, //风格三的商品数据列表 分页
    stylePage: 1, //商品列表分页标识

    //风格三使用
    url: t.globalData.setting.imghost,
    currentPage: 1,
    allData: null,
    openFilterModal: !1,
    baseUrl: "api/weshop/goods/page?1=1&cat_id=1&parent_id=0&orderField=sort&orderType=asc&page=1&is_mainshow=1&isonsale=1&store_id=" + oo.stoid + "&is_recommend=1",
    requestUrl: "",
    tabname: "goods_id",   //排序的字段
    adname: "desc",        //升降的字段
    is_new: 0,
    is_hot: 0,
    msgStatus: false,  //页面显示暂无数据状态
    countDownNum: 3,
    timer: null, //定时器
    lastMsg: false,
    toView: "",
    is_show_class: false,//是否添加新样式
    status_show: 0,
    currentTab: 0, //预设当前项的值

    load: 0,
    xmlist: null,

    is_retail_price:0,  //是否显示零售价
    banner: null, //分类广告

  },


  //判断当前滚动超过一屏时，设置tab标题滚动条。
  checkCor: function () {
    let that = this;
    //这里计算按照实际情况进行修改，动态数据要进行动态分析
    //思路：窗体高度/单个分类高度 200rpx 转px计算 =>得到一屏幕所显示的个数，结合后台传回分类总数进行计算
    //数据很多可以多次if判断然后进行滚动距离计算即可
    if (that.data.currentTab > 7) {
      that.setData({
        scrollTop: 500
      })
    } else {
      that.setData({
        scrollTop: 0
      })
    }
  },


  onLoad: function (tt) {
    // wx.createSelectorQuery().select('#sview').boundingClientRect(function(rect){
    //   console.log('显示下滑区域');
    //   console.log(rect);
    // }).exec()

    //群id
    if(tt && tt.groupchat_id){
      getApp().globalData.groupchat_id=tt.groupchat_id
    }

    var that = this;
    var first_leader = tt.first_leader;
    if (first_leader) {
      //--  user_id代过来免登录 --
      getApp().globalData.first_leader = first_leader;
    }

    //if (tt.type) this.data.type = parseInt(tt.type);
    //switchTab无法传参数
    if(getApp().globalData.cat_type){
       this.data.type = parseInt(getApp().globalData.cat_type);
       getApp().globalData.cat_type=0;
    }

    that.get_brand();

    clearInterval(that.data.timer);
    that.setData({ countDownNum: 3, stylePage: 1 });

    const res = wx.getSystemInfoSync(),
      letters = this.data.letters;
    this.setData({
      abc: t.globalData.heigth - 88 - 88 - 16,
      windowHeight: res.windowHeight,
      windowWidth: res.windowWidth,

    });

    var bli = res.windowWidth / 750;
    //--------第一个字母距离顶部高度，单位使用的是rpx,须除以bli------
    //才能与touch事件中的数值相加减，css中定义nav高度为94%，所以 *0.94
    const eachLetterHeight = 35.4 * bli,
      comTop = (88 + 88) * bli,
      temp = [];

    this.setData({
      eachLetterHeight: eachLetterHeight
    });
    //---------求各字母距离设备左上角所处位置---------
    for (let i = 0, len = letters.length; i < len; i++) {
      const x = (this.data.windowWidth - (30 + 50)) * bli,
        y = comTop + (i * eachLetterHeight);
      temp.push([x, y]);
    }
    this.setData({
      lettersPosition: temp
    });

    if (this.data.is_used_share == 0) {
      this.get_nation();
      this.getServiceCategory();
    }

    //风格三
    //t = i,e = t
    var th = this;
    a.init(this, "", "requestData");
    var url = this.data.baseUrl;
    this.data.is_new = i.is_new;
    this.data.is_hot = i.is_hot;
    if (0 != this.data.cat_id) {
      url += "&cat_id=" + this.data.cat_id;
    }
    
    // this.requestGoodsList(url);
    getApp().getConfig2(function (rs) {
      //计算等级价相关
      var swithc_list = rs.switch_list;
      var sw_arr = JSON.parse(swithc_list);

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

    });
  },
  onShow: function () {
    getApp().check_can_share();

    if (typeof this.getTabBar === 'function' && this.getTabBar()) {
      var index = getApp().getPageIndex(this);
      this.getTabBar().setData({
        active: index //数字是当前页面在tabbar的索引
      });
      getApp().requestCardNum(this);
    }


    var that = this;
    //调用底部导航
    //t.editTabBar(that,getApp().globalData.setting.stoid,getApp().globalData.url);
    //this.requestFirstCategoris();
    // setTimeout(function () {
      //if (getApp().globalData.user_id) getApp().requestCardNum(that);
    // }, 500)

    if (this.data.load) return false;

    getApp().getConfig2(function (e) {
      console.log('card------------>>>>', e);
      var data = e;
      var switch_list_data = data.switch_list;
      var switch_list = JSON.parse(switch_list_data);

      //---如果后台又开等级卡的开关---
      ut.get_plus_name_price(switch_list,that);


      var is_newsgoodstype = switch_list.is_newsgoodstype;
      if (is_newsgoodstype == undefined) {
        is_newsgoodstype = 0;
      }
      that.setData({ is_used_share: is_newsgoodstype });
      if (e.categoryset.indexOf("," + 1 + ",") != -1) { that.setData({ is_show_pl: 1 }); }
      if (e.categoryset.indexOf("," + 3 + ",") != -1) { that.setData({ is_show_pp: 1 }); }
      if (e.categoryset.indexOf("," + 2 + ",") != -1) { that.setData({ is_show_gb: 1 }); }
      if (e.categoryset.indexOf("," + 4 + ",") != -1) { that.setData({ is_show_xm: 1 }); }
      that.setData({ store_config: e, is_do: 1 });
      //请求自定义分类数据
      // that.requestFirstCategoris_diy()
      //---有勾品类---
      if (that.data.is_show_pl) {
        if (is_newsgoodstype==1) { //如果是风格2，则请求自定义分类
          that.requestFirstCategoris_diy();
        }else{
          that.requestFirstCategoris();
        }
      }

      if (that.data.is_show_xm != 1 && that.data.is_show_gb != 1 && that.data.is_show_pp != 1 && that.data.is_show_pl) {
        that.data.pl_timer = setInterval(function () {
          if (that.data.one_level_classify.length > 0) {
            var item = that.data.one_level_classify[0], arr = item.array;
            //----如果有下级的时候-----
            if (item.array && item.array.length > 0) {
              var is_lev_thr = 0
              for (var i = 0; i < arr.length; i++) {
                if (arr[i].arrays.length > 0) { is_lev_thr = 1; break; }
              }
              that.setData({ is_level_three: is_lev_thr });
              if (is_lev_thr != 1) {
                that.setData({ select_classify_on: 0, index: 0, classify_name: item.items.name, cat_id: item.items.id, goodslist: item.array });
                console.log("id:=" + item.items.id)
                that.style(that.data.stylePage, that.data.cat_id);
              } else {
                that.setData({ select_classify_on: 0, index: 0, classify_name: item.items.name, cat_id: item.items.id, goodslist: arr });
                console.log("id:=" + item.items.id)
                that.style(that.data.stylePage, that.data.cat_id);
              }
            }
            else {
              that.setData({ select_classify_on: 0, index: 0, goodslist: null, classify_name: item.items.name, is_level_three: 0 });
            }
            clearInterval(that.data.pl_timer);
          }
        }, 1000);

      } else if (that.data.is_show_gb != 1 && that.data.is_show_pp) {
        that.setData({ select_classify_on: 220, classify_name: "品牌" });
      }


      var one_level_classify = that.data.one_level_classify;

      if (that.data.is_show_pl) that.setData({ currentTab: 0 });
      else if (that.data.is_show_gb) { that.setData({ currentTab: 1 }); that.get_nation(); }
      else if (that.data.is_show_pp) { that.setData({ currentTab: 2 }); that.get_brand(); }
      else if (that.data.is_show_xm) { that.setData({ currentTab: 3 }); that.getServiceCategory(); }


      var t_type = that.data.type;
      //----求传参过来的控制-----
      if (t_type == 1 && that.data.is_show_gb) {
        that.setData({ currentTab: 1, select_classify_on: 223 });
        that.get_nation();
      } else if (t_type == 2 && that.data.is_show_pp) {
        that.setData({ currentTab: 2, select_classify_on: 220 });
        that.get_brand();
      } else if (t_type == 3 && that.data.is_show_xm) {
        that.setData({ currentTab: 3, select_classify_on: 221 });
        that.getServiceCategory();
      } else if (that.data.is_show_pl) {
        that.setData({ currentTab: 0, select_classify_on: 0 });
      }
      // 获取默认选中的第一个
      if (that.data.is_show_gb && that.data.select_classify_on == 223) {
        that.setData({ status_show: 1 });
      } else if (that.data.is_show_pp && that.data.select_classify_on == 220) {
        that.setData({ status_show: 2 });
      }

      that.data.load = 1;
    })

  },

  
  //---------------自定义分类请求接口,数据进行拼装------------------
  requestFirstCategoris_diy: function () {
    var t = this;
    let that=this;
    e.get("/api/weshop/customizeCategory/page", {
      data: { store_id: oo.stoid, pageSize: 6600, is_show: 1 },
      success: function (e) {

        if (e.data.code !=0) {
          that.requestFirstCategoris();
          return
        }
        var arr = new Array();
        var dda = e.data.data.pageData;
        if (dda != null && dda != "" && dda != undefined) {
          t.setData({ is_pl_time: 1 });
        } 

        if (t.data.is_used_share == 0) {//is_used_share控制新旧版本
          for (var i = 0; i < dda.length; i++) {
            if (parseInt(dda[i].level) == 1) {
              var item = { items: dda[i], array: new Array(),diy_class:1 } //增加一个diy_class 标识表示为自定义分类
              arr.push(item);
            } else if (parseInt(dda[i].level) == 2) {
              for (var j = 0; j < arr.length; j++) {
                if (parseInt(dda[i].parent_id) == parseInt(arr[j].items.id)) {
                  arr[j].array.push(dda[i]); break;
                }
              }
            } else {
              continue;
            }
          }
          t.setData({ catelist: arr });
        } else if (t.data.is_used_share == 1 || t.data.is_used_share == 2) {

          //---------新的版本----------------
          for (var i = 0; i < dda.length; i++) {
            //--要排队的元素---
            var need_to_insert = dda[i];
            if (parseInt(need_to_insert.level) == 1) {
             //判断数组的长度看看有没有2级菜单
              var item = { items: need_to_insert, array: new Array(),diy_class:1 } //增加一个diy_class 标识表示为自定义分类
              arr.push(item);
            } else if (parseInt(need_to_insert.level) == 2) {

              for (var j = 0; j < arr.length; j++) {


                if (parseInt(need_to_insert.parent_id) == parseInt(arr[j].items.id)) {

                  var ishaf_two = { items: need_to_insert, arrays: new Array(),diy_class:1 };
                  arr[j].array.push(ishaf_two); arr.ishaf_two = 0;
                }
              }
            } else if (parseInt(need_to_insert.level) == 3) {//判断有3级的时候在二级里添加一个数组

              for (var dd = 0; dd < arr.length; dd++) {
                for (var pp = 0; pp < arr[dd].array.length; pp++) {
                  //--判断二级--
                  var two_item = arr[dd].array;

                  if (two_item && two_item.length > 0) {

                    if (parseInt(need_to_insert.parent_id) == parseInt(two_item[pp].items.id)) {

                      arr[dd].array[pp].arrays.push(need_to_insert); arr.ishaf_three = 0; break;
                    }
                  }
                }
              }
            }
          }
          for (var i = 0; i < arr.length; i++) {
            arr[i]['items']['is_show_class'] = false;
            var mobile_name = arr[i]['items']['name']
            //if(mobile_name.length > 4){
            //arr[i]['items']['name'] = mobile_name.substring(0, 4)
            //}
          }
          if (t.data.is_show_pl == 1 && t.data.is_show_pp != 1 && t.data.is_show_gb != 1) {
            arr[0]['items']['is_show_class'] = true;
          }
          //console.log(arr) 
            t.setData({ one_level_classify: arr });
          //---有勾品类---
          // if (that.data.is_show_pl) {
            that.requestFirstCategoris();
          // }
            if (t.data.select_classify_on == 0) {
              var item = arr[0];
  
              var name = item.items.name;
              var cid = item.items.id;
              var arr = item.array;
  
              console.log("11111", item);
              console.log(arr.length);
  
              if (arr.length == 0) {
                t.setData({
                  select_classify_on: 0, index: 0, classify_name: name, cat_id: cid,
                  goodslist: null, is_level_three: 0
                });
  
                if (t.data.is_used_share == 2)
                  t.style(t.data.stylePage, cid)
  
                return false;
              }
              if (arr.length != 0) {
                var is_lev_thr = 0
                for (var i = 0; i < arr.length; i++) {
                  if (arr[i].arrays.length > 0) { is_lev_thr = 1; break; }
                }
                t.setData({ is_level_three: is_lev_thr ,cat_id:cid});
  
                if (this.data.is_level_three != 1) {
                  t.setData({ index: 0, classify_name: name, goodslist: arr });
                  // t.setData({ index: 0, classify_name: name });
                } else {
                  // t.setData({ index: 0});
                  t.setData({ index: 0, goodslist: arr });
                }
              }
  
              if (t.data.is_used_share == 2){
                t.style(t.data.stylePage, cid)
              }
  
            }
          
        }
      }
    });
  },

  //---------------分类请求接口,数据进行拼装------------------
  requestFirstCategoris: function () {
    
    var t = this;
    e.get("/api/weshop/goodscategory/page", {
      data: { store_id: oo.stoid, pageSize: 6600, is_show: 1 },
      success: function (e) {
        if (e.data.code !=0) {
          return
        }
        var arr = new Array();
        var dda = e.data.data.pageData;
        if (dda != null && dda != "" && dda != undefined) {
          t.setData({ is_pl_time: 1 });
        } 

        if (t.data.is_used_share == 0) {//is_used_share控制新旧版本
          for (var i = 0; i < dda.length; i++) {
            if (parseInt(dda[i].level) == 1) {
              var item = { items: dda[i], array: new Array() }
              arr.push(item);
            } else if (parseInt(dda[i].level) == 2) {
              for (var j = 0; j < arr.length; j++) {
                if (parseInt(dda[i].parent_id) == parseInt(arr[j].items.id)) {
                  arr[j].array.push(dda[i]); break;
                }
              }
            } else {
              continue;
            }
          }
          t.setData({ catelist: arr });
        } else if (t.data.is_used_share == 1 || t.data.is_used_share == 2) {

          //---------新的版本----------------
          for (var i = 0; i < dda.length; i++) {
            //--要排队的元素---
            var need_to_insert = dda[i];
            if (parseInt(need_to_insert.level) == 1) {
              var item = { items: need_to_insert, array: new Array() }//判断数组的长度看看有没有2级菜单
              arr.push(item);
            } else if (parseInt(need_to_insert.level) == 2) {

              for (var j = 0; j < arr.length; j++) {


                if (parseInt(need_to_insert.parent_id) == parseInt(arr[j].items.id)) {

                  var ishaf_two = { items: need_to_insert, arrays: new Array() };
                  arr[j].array.push(ishaf_two); arr.ishaf_two = 0;
                }
              }
            } else if (parseInt(need_to_insert.level) == 3) {//判断有3级的时候在二级里添加一个数组

              for (var dd = 0; dd < arr.length; dd++) {
                for (var pp = 0; pp < arr[dd].array.length; pp++) {
                  //--判断二级--
                  var two_item = arr[dd].array;

                  if (two_item && two_item.length > 0) {

                    if (parseInt(need_to_insert.parent_id) == parseInt(two_item[pp].items.id)) {

                      arr[dd].array[pp].arrays.push(need_to_insert); arr.ishaf_three = 0; break;
                    }
                  }
                }
              }
            }
          }
          for (var i = 0; i < arr.length; i++) {
            arr[i]['items']['is_show_class'] = false;
            var mobile_name = arr[i]['items']['name']
            //if(mobile_name.length > 4){
            //arr[i]['items']['name'] = mobile_name.substring(0, 4)
            //}
          }
          if (t.data.is_show_pl == 1 && t.data.is_show_pp != 1 && t.data.is_show_gb != 1) {
            arr[0]['items']['is_show_class'] = true;
          }
          //console.log(arr)
          if (t.data.one_level_classify.length>0) {
            let one_level_classify = t.data.one_level_classify;
            one_level_classify.push(...arr)
            t.setData({ one_level_classify: one_level_classify });
          }else{
            t.setData({ one_level_classify: arr });
            if (t.data.select_classify_on == 0) {
              var item = arr[0];
  
              var name = item.items.name;
              var cid = item.items.id;
              var arr = item.array;
  
              console.log("11111", item);
              console.log(arr.length);
  
              if (arr.length == 0) {
                t.setData({
                  select_classify_on: 0, index: 0, classify_name: name, cat_id: cid,
                  goodslist: null, is_level_three: 0
                });
  
                if (t.data.is_used_share == 2)
                  t.style(t.data.stylePage, cid)
  
                return false;
              }
              if (arr.length != 0) {
                var is_lev_thr = 0
                for (var i = 0; i < arr.length; i++) {
                  if (arr[i].arrays.length > 0) { is_lev_thr = 1; break; }
                }
                t.setData({ is_level_three: is_lev_thr ,cat_id:cid});
  
                if (this.data.is_level_three != 1) {
                  t.setData({ index: 0, classify_name: name, goodslist: arr });
                } else {
                  t.setData({ index: 0, goodslist: arr });
                }
              }
              if (t.data.is_used_share == 2){

                t.style(t.data.stylePage, cid)
              }
  
            }
          }
        }
      }
    });
  },

  requestCategories: function (t) {
    var s = this;
    e.get("/api/goods/goodsSecAndThirdCategoryList", {
      data: {
        parent_id: t
      },
      success: function (e) {
        s.setData({
          categories: e.data.result,
          currentCategoryId: t
        });
      }
    });
  },

  switchFirstCategory: function (t) {
    this.requestCategories(t.currentTarget.dataset.id);
  },

  //-----------滑动切换----------
  swiperTab: function (e) {
    var that = this;
    if (e.detail.source == "touch") {
      this.setData({
        currentTab: e.detail.current,
      });
    }

    //获取国别
    if (e.detail.current == 1 && that.data.nationlist == null) {
      that.get_nation();
    }
    //获取品牌
    if (e.detail.current == 2 && that.data.groups == null) {
      that.get_brand();
    }

    //获取服务卡项
    if (e.detail.current == 3 && that.data.xmlist == null) {
      that.getServiceCategory();
    }


  },
  //-----------点击切换-----------
  clickTab: function (e) {
    var that = this;
    if (this.data.currentTab === e.target.dataset.current) {
      return false;
    } else {
      that.setData({
        currentTab: e.target.dataset.current
      })
    }
    //获取国别
    if (e.detail.current == 1 && that.data.nationlist == null) {
      that.get_nation();
    }

    //获取品牌
    if (e.detail.current == 2 && that.data.groups == null) {
      that.get_brand();
    }

    //获取服务卡项
    if (e.detail.current == 3 && that.data.xmlist == null) {
      that.getServiceCategory();
    }

  },

  tabLetter(e) {
    const index = e.currentTarget.dataset.index;
    this.setData({
      selected: index,
      scrollIntoView: index
    })
    this.cleanAcitvedStatus();
  },
  //-------------------清除字母选中状态---------------
  cleanAcitvedStatus() {
    setTimeout(() => {
      this.setData({ selected: 0 })
    }, 500);
  },

  //------------手指滑动------------------
  touchmove(e) {
    console.log("手指滑动")
    const x = e.touches[0].clientX,
      y = e.touches[0].clientY,
      lettersPosition = this.data.lettersPosition,
      eachLetterHeight = this.data.eachLetterHeight,
      letters = this.data.letters;
    // 判断触摸点是否在字母导航栏上
    if (x >= lettersPosition[0][0]) {
      for (let i = 0, len = lettersPosition.length; i < len; i++) {
        // 判断落在哪个字母区域，取出对应字母所在数组的索引，根据索引更新selected及scroll-into-view的值
        const _y = lettersPosition[i][1], // 单个字母所处高度
          __y = _y + eachLetterHeight; // 单个字母最大高度取值范围， 50为字母高50rpx
        if (y >= _y && y <= __y) {
          this.setData({
            selected: letters[i],
            scrollIntoView: letters[i],
          });
          break;
        }
      }
    }
  },
  touchend(e) {
    this.cleanAcitvedStatus();
  },

  //跳转到分类的商品列表
  go_cate: function (t) {
    var cid = t.currentTarget.dataset.cid;
    var pid = t.currentTarget.dataset.pid;
    var lurl = "/pages/goods/goodsList/goodsList?cat_id=" + cid;
    lurl += "&pid=" + pid;
    wx.navigateTo({ url: lurl });
  },

  //跳转到品牌的商品列表
  go_brand: function (t) {
    var cid = t.currentTarget.dataset.bid;
    var lurl = "/pages/goods/goodsList/goodsList?brand_id=" + cid;
    wx.navigateTo({ url: lurl });
  },

  //跳转到国别的商品列表
  go_nation: function (t) {
    var cid = t.currentTarget.dataset.nid;
    var lurl = "/pages/goods/goodsList/goodsList?nation_id=" + cid;
    wx.navigateTo({ url: lurl });
  },

  //获取国别
  get_nation: function () {
    var s = this;
    e.get("/api/weshop/nation/page", {
      data: {
        is_hot: 1,
        store_id: oo.stoid,
        pageSize: 300,
      },
      success: function (e) {
        var dda = e.data.data.pageData;
        s.setData({ nationlist: dda })
      }
    });
  },

  //获取品牌
  get_brand: function () {
    var compare = function (prop) {
      return function (obj1, obj2) {
        var val1 = obj1[prop]; var val2 = obj2[prop];
        if (!isNaN(Number(val1)) && !isNaN(Number(val2))) {
          val1 = Number(val1); val2 = Number(val2);
        }
        if (val1 < val2) {
          return -1;
        } else if (val1 > val2) {
          return 1;
        } else { return 0; }
      }
    }

    var s = this;
    e.get("/api/weshop/brand/page", {
      data: {
        is_hot: 1,
        store_id: oo.stoid,
        pageSize: 10000,
      },
      success: function (e) {
        var arr = new Array();
        var dda = e.data.data.pageData;
        s.setData({ brand_list: dda });


        for (var i = 0; i < dda.length; i++) {
          //console.log(dda[i].logo)				
          if (dda[i].logo == "") {
            dda[i].logo = s.data.iurl + "/miniapp/images/no_brand_def.jpg";
          } else if (dda[i].logo && dda[i].logo.indexOf("http") < 0) {
            dda[i].logo = oo.imghost + dda[i].logo;
          }

          //进行排序，只有是默认排序的时候，才按首字母排序
          // if(parseInt(s.data.is_used_share)!=0) continue;

          if (arr.length > 0) {
            var find = 0;
            //寻找字母在arr数组中是否存在，不存在就要添加，存在就在要这个数组添加元素
            for (var k = 0; k < arr.length; k++) {
              if (dda[i].zm == arr[k].zm) { find = k + 1; break; }
            }
            if (find == 0) {
              var item = { zm: dda[i].zm, array: new Array() }
              item.array.push(dda[i]);
              arr.push(item);
            } else {
              arr[find - 1].array.push(dda[i]);
            }
          } else {
            var item = { zm: dda[i].zm, array: new Array() }
            item.array.push(dda[i]);
            arr.push(item);
          }
        }
        // if(parseInt(s.data.is_used_share)==0){
        //  arr.sort(compare("zm"));		
        // }else{
        //  var ob={array:dda};
        //  arr.push(ob);
        // }

        arr.sort(compare("zm"));

        s.setData({ groups: arr });
        //console.log(s.data.groups)
      }
    });
  },


  // 获取服务卡项分类
  getServiceCategory: function () {
    var s = this;
    e.get("/api/weshop/serviceCategory/page", {
      data: {
        is_show: 1,
        store_id: oo.stoid,
        pageSize: 1000,
      },
      success: function (e) {
        var dda = e.data.data.pageData;
        s.setData({
          xmlist: dda,
        });
      }
    });
  },


  goServiceCategoryList: function (t) {
    var cid = t.currentTarget.dataset.cid;
    var lurl = "/packageA/pages/cardList/cardList?cat_id=" + cid;
    wx.navigateTo({ url: lurl });
  },

  //---------分享配置--------
  onShareAppMessage: function (e) {
    getApp().globalData.no_clear = 1;
    var url = "pages/goods/categoryList/categoryList";
    var userInfo = getApp().globalData.userInfo;
    //是分销商才带
    if (userInfo) {
      url += "?first_leader=" + userInfo.user_id;
        //群id分享
      if (getApp().globalData.groupchat_id) {
        url+="&groupchat_id="+getApp().globalData.groupchat_id
      }
    }else{
      //群id分享
      if (getApp().globalData.groupchat_id) {
        url+="?groupchat_id="+getApp().globalData.groupchat_id
      }
    }



    console.log("--分类分享---分享--");
    console.log(url);

    return {
      title: "商品分类",
      path: url,
    }
  },
  //图片失败，默认图片
  bind_bnerr: function (e) {
    var _errImg = e.target.dataset.errorimg;
    var _errObj = {};
    _errObj[_errImg] = this.data.iurl + "/miniapp/images/default_g_img.gif";
    this.setData(_errObj) //注意这里的赋值方式,只是将数据列表中的此项图片路径值替换掉 ;  
  },
  //图片失败，默认图片
  bind_bnerr_pp: function (e) {
    var list = this.data.groups
    var _errImg = e.target.dataset.errorimg;
    var idx = e.target.dataset.idx;
    var pix = e.target.dataset.pix;

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

  goseach: function () {
    wx.navigateTo({
      url: "/packageG/pages/goods/search/search"
    });
  },

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

  },


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

  },



  // 新的版本分类点击一级分类
  click_classify: function (e) {
    // 在风格三的时候，才会有current
    clearInterval(this.data.timer);
    console.log('类别切换---------------');
    this.setData({
      toupper:true,
      nextShow:false,
      nextShow2:false
    })
    let cur = e.currentTarget.dataset.current;
    console.log(cur);
    console.log(this.data.currentTab);
    if (cur > -1) {

      if (this.data.currentTab == cur) {

        if (this.data.select_classify_on != 220 && this.data.select_classify_on != 221 && this.data.select_classify_on != 223) {
          return false;
        } else if (cur != 0) {
          return false;
        } 
      } else {
        wx.pageScrollTo({
          scrollTop: 0
        })
        this.setData({
          currentTab: cur,
          select_classify_on: cur
        })
        this.checkCor();
      }
    }
    this.setData({
      countDownNum: 3,
    });

    var arr2 = this.data.one_level_classify
    for (var i = 0; i < arr2.length; i++) {
      if (i == e.currentTarget.dataset.index) {
        arr2[i]['items']['is_show_class'] = true
      } else {
        arr2[i]['items']['is_show_class'] = false
      }
    }
    this.setData({ one_level_classify: arr2 });
    //this.data.one_level_classify[e.currentTarget.dataset.index]['items']['is_show_class'] = true
    // console.log(e.currentTarget.dataset.index)
    clearInterval(this.data.timer);
    this.setData({ countDownNum: 3, stylePage: 1, scrollTop: 0 });
    this.data.ishaf_three = 0;
    var indexs = e.currentTarget.dataset.index;
    var name = e.currentTarget.dataset.name;
    var cid = e.currentTarget.dataset.cid;
    var pid = e.currentTarget.dataset.pid;
    var arr = e.currentTarget.dataset.arr;
    console.log("cid:=" + name)
    if (indexs == 220) { this.get_brand(); }
    //==2的时候 请求数据为商品，不为分类
    if (this.data.is_used_share == 2) {
      this.setData({ select_classify_on: indexs, index: indexs, classify_name: name, cat_id: cid, lastMsg: false, });
      console.log("edqdqw:=" + this.data.select_classify_on)
      this.style(this.data.stylePage, cid)
    } else {
      if (arr != "undefined" && arr != undefined) {
        if (arr.length == 0) {
          this.setData({
            select_classify_on: indexs, index: indexs, classify_name: name, cat_id: cid,
            goodslist: null, is_level_three: 0
          });
          return false;
        }
        if (arr.length != 0) {
          var is_lev_thr = 0
          for (var i = 0; i < arr.length; i++) {
            if (arr[i].arrays.length > 0) { is_lev_thr = 1; break; }
          }
          this.setData({ is_level_three: is_lev_thr });

          if (this.data.is_level_three != 1) {
            this.setData({ select_classify_on: indexs, index: indexs, classify_name: name, goodslist: arr });
          } else {
            this.setData({ select_classify_on: indexs, index: indexs, goodslist: arr });
          }
        }
      }
      this.setData({ select_classify_on: indexs, index: indexs, classify_name: name, cat_id: cid, stylePage: 1, lastMsg: false, });
    }
    //==1的时候，样式2的时候分类广告切换
    if (this.data.is_used_share==1) {
      let banner=null;

      this.setData({
        banner
      })
    }

  },


  //图片失败
  bind_bnerr_xc: function (e) {
    var _errImg = e.target.dataset.errorimg;
    var _errurl = e.target.dataset.url;

    var _errObj = {};
    _errObj[_errImg] = "/miniapp/images/default_g_img.gif";
    this.setData(_errObj) //注意这里的赋值方式,只是将数据列表中的此项图片路径值替换掉 ;
  },


  //选择更多
  select_more: function (e) {
    var cid = e.currentTarget.dataset.cid;
    var pid = e.currentTarget.dataset.pid;
    var lurl = "/pages/goods/goodsList/goodsList?cat_id=" + cid + "&pid=" + pid;
    wx.navigateTo({ url: lurl });

  },


  //扫一扫
  getScancode: function () {
    var _this = this;
    getApp().globalData.no_clear = 1;
    // 允许从相机和相册扫码
    wx.scanCode({
      success: (res) => {
        var result = res.result;
        wx.navigateTo({
          url: "/packageG/pages/goods/search/search?s_key=" + result,
        });
      }
    })
  },


  onUnload: function () {
    //this.destroyActivityTimer();
  },


  //风格三使用
  changeTab: function (t) {
    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) {
    var that = this;
    var user=getApp().globalData.user_id || 0;
    that.data.requestUrl = t;
    console.error(666666);
    e.get("/api/weshop/goods/page?1=1&isnewwhere=1", {
      data: { page: that.data.stylePage, cat_id: that.data.cat_id, parent_id: 0, orderField: 'sort', orderType: 'asc', is_mainshow: 1, isonsale: 1, store_id: oo.stoid, is_recommend: 1,user_id:user_id },
      success: function (data) {
        console.log(data.data.data.pageData)
        that.setData({
          requestData: data.data.data.pageData,
          is_go: 1
        });
        that.setData({ is_go: 1 });
        that.data.stylePage++, null == that.data.allData && (that.data.allData = Object.assign({}, data.data.data.pageData)),
          wx.stopPullDownRefresh();
      }
    });

  },


  // 左侧更新
  scrollLower: function (data) {
    if (this.data.is_no_more) return false;
    var that = this;
    clearInterval(that.data.timer);
    that.setData({
      stylePage: that.data.stylePage + 1,
      countDownNum: 3,
      lastMsg: false,
    });
    // if (nextTimeOff) {
    //   clearTimeout(nextTimeOff)
    // }
    // nextTimeOff = setTimeout(()=>{
      that.style(that.data.stylePage, that.data.cat_id);
    // },1000)    
  },
  scrolltoupper(){
    console.log('到顶部--------');
    this.setData({
      toupper:true
    })
  },
  bScroll(even){
    console.log('滑动开始');
    console.log(even);
    this.setData({
      sClientY:even.changedTouches.length>0 ? even.changedTouches[0].clientY : 0
    })
  },
  btouMove(even){
    console.log('滑动结束');
    console.log(even);
    let eClientY = even.changedTouches.length>0 ? even.changedTouches[0].clientY : 0
    let sClientY = this.data.sClientY
    console.log(eClientY - sClientY);
    if (eClientY - sClientY > 0) {
      console.log('下滑');
      console.log(this.data.toupper);
      if (this.data.toupper) {
        console.log('下滑请求数据');
        this.setData({msgStatus:false,is_no_more:false})
        clearInterval(this.data.timer);
        this.nextCategory(true)
      }else{
        this.disNexCat()
      }
    }else{
      console.log('上滑');
      if (!this.data.msgStatus) {        
        this.setData({
          toupper:false
        })
      }
      this.disNexCat()
    }
  },
  disNexCat(){
    let that = this
    const { windowHeight } = wx.getSystemInfoSync()
    wx.createSelectorQuery().select('#sview').boundingClientRect(function(rect){
      if (rect) {        
        const { top,height }  = rect
        if ((top < windowHeight) && (top + height >0) ) {
          let nextShow2 = that.data.nextShow2
          if (nextShow2) {
            that.nextCategory()
          }else{
            that.setData({
              nextShow2:true
            })
          }
        }else{
          that.setData({
            nextShow2:false
          })
        }
      }
    }).exec()
  },
  //页面版面风格三的时候请求推荐商品 返回 
  style: function (page, cid) {
    console.log("page:=" + page)
    console.log("cid:=" + cid)
    console.log("cid:=" + this.data.cat_id);
    var s = this
    var user_id=getApp().globalData.user_id || 0;
    e.get("/api/weshop/goods/page?1=1&isnewwhere=1", {
      data: { page: page, cat_id: cid, parent_id: 0, orderField: 'sort', orderType: 'asc', is_mainshow: 1, isonsale: 1, store_id: oo.stoid, is_recommend: 1,user_id:user_id },
      success: function (e) {
        console.log('上拉加载。。。。。。。。。');
        console.log(e.data.data.pageData)

        if (e.data.data.pageData.length > 0) {
          clearInterval(s.data.timer);
          s.setData({
            msgStatus: false, is_no_more: 0
          });
          //如果有数据 判断分页为第一页的时候直接渲染数据
          if (page > 1) {
            //如果分页不是在第一页 那么就把返回的数据追加到原有数据后面
            var arr = s.data.requestData

            for (var i = 0; i < e.data.data.pageData.length; i++) {
              arr.push(e.data.data.pageData[i]);
            }

            if (e.data.data.pageData.length < e.data.data.pageSize) {
                s.setData({
                  nextShow:true,
                  // nextShow2:true
                })
            }

            s.setData({
              requestData: arr
            });

          } else {
            s.setData({
              requestData: e.data.data.pageData
            });
            if ( e.data.data.pageData.length && (e.data.data.pageData.length < e.data.data.pageSize)) {    
              s.setData({
                nextShow:true,
                // nextShow2:true
              })
              const { windowHeight } = wx.getSystemInfoSync()
              wx.createSelectorQuery().select('#sview').boundingClientRect(function(rect){
                if (rect) {        
                  const { top,height }  = rect
                  if ((top < windowHeight) && (top + height >0) ) {
                    s.setData({
                      nextShow2:true
                    })                   
                  }
                }
              }).exec()
            }
            if (wx.pageScrollTo) {
              wx.pageScrollTo({
                scrollTop: 0
              })
            }
          }

          s.setData({
            dataLength: s.data.requestData.length,
          });

        } else {
          //没有数据页面显示暂无数据
          if (page != 1) {
            let nextShow = s.data.nextShow
           
            if (!nextShow) {
              s.setData({
                nextShow:true
              })
           }
          } else {
            //没有数据而且是第一页的时候
            s.setData({
              stylePage: 1,
            });
            let countDownNum = 3; //获取倒计时初始值 
            s.setData({
              msgStatus: true,
              countDownNum: countDownNum,
              requestData: [],
              is_no_more: 0,
            });
            clearInterval(s.data.timer);
            s.data.timer = setInterval(function () {
              if (countDownNum == 0) {
                clearInterval(s.data.timer);
                //关闭定时器之后，可作其他处理   
                s.setData({
                  msgStatus: false,
                })

                //如果没有数据就把分页初始化成第一页
                //没有数据根据当前分类id去找到下一个分类id再次传递给服务端请求数据
                var dataArray = s.data.one_level_classify
                var index = s.data.index
                console.log(dataArray[index + 1])
                if (dataArray[index + 1] == undefined || dataArray[index + 1] == "undefined") {
                  console.log("dataArray[index + 1] = undefined")
                  s.setData({
                    stylePage: 1,
                    msgStatus: true,
                    lastMsg: true
                  });
                } else {
                  dataArray[index]['items']['is_show_class'] = false
                  dataArray[index + 1]['items']['is_show_class'] = true
                  s.setData({
                    stylePage: 1,
                    index: index + 1,
                    select_classify_on: index + 1,
                    cat_id: dataArray[index + 1]['items']['id'],
                    classify_name: dataArray[index + 1]['items']['name'],
                    one_level_classify: dataArray
                  });
                  s.style(s.data.stylePage, dataArray[index + 1]['items']['id']);
                }

              }
              countDownNum--;
              s.setData({
                countDownNum: countDownNum
              })
              var arr2 = s.data.one_level_classify
              for (var i = 0; i < arr2.length; i++) {
                if (i == s.data.index) {
                  arr2[i]['items']['is_show_class'] = true
                } else {
                  arr2[i]['items']['is_show_class'] = false
                }
              }
              s.setData({ one_level_classify: arr2 });
            }, 1000)
          }


        }
      }
    });
  },
  //下一个品类
  nextCategory(up=false){
    console.log('跳转下一个页面');
    clearInterval(this.data.timer);
    this.setData({
      nextShow:false
    })
    var dataArray = this.data.one_level_classify
    var index = this.data.index
    let s = 1
    if (up) {
      s = -1
    }
    dataArray[index]['items']['is_show_class'] = false
    //没有下一个类别的时候
    if (index + s >= dataArray.length || index+s < 0) {
      this.setData({ is_no_more: 1 });
    } else {
      dataArray[index + s]['items']['is_show_class'] = true
      console.log(dataArray[index + s]['items'])
      this.setData({
        msgStatus: true,
        stylePage: 1,
        index: index + s,
        select_classify_on: index + s,
        cat_id: dataArray[index + s]['items']['id'],
        classify_name: dataArray[index + s]['items']['name'],
        one_level_classify: dataArray,
        is_no_more: 0,
        currentTab:index + s
      });
      this.style(this.data.stylePage, dataArray[index + s]['items']['id'])
    }
  },

  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;
  },
  go_ad: function (e) {
    var url = e.currentTarget.dataset.url;
    if (!url || url == '') return;
    if (url[0] != '/') url = '/' + url;
    getApp().goto(url);
  },
  //---回复最初的设置---
  restoreData: function () {
    this.setData({
      requestData: null,
    });
    this.data.page = 1;
  },

  //---  获取卡类列表 ---
  getPlusCardType: function (func) {
    var storid = oo.stoid;
    var th = this;
    var user = getApp().globalData.userInfo;
    if(!user) return false;
    
    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();

      for (var i = 0; i < plusCard.length; i++) {
        if ((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);
    })
  },

  //导航跳转
  nav_goto: function (e) {
    var url = e.currentTarget.dataset.url;
    if (!url || url == '') return;
    if (url[0] != '/') url = '/' + url;
    getApp().goto(url);
  },

  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
    }
  }

});