const { app } = require("../../../../utils/common");
let startY = 0;
let endY = 0;
let isReachBt = 0;
let moveDistance = 0;
const t = getApp(), e = t.request, oo = t.globalData.setting;
var i = function (i) {
  return i && i.__esModule ? i : {
    default: i
  };
}(require("../../../../utils/LoadMore")), a = new i.default(), ut = require("../../../../utils/util.js");
//t = i,e = t
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,//图片地址

    //控制新旧分类版本
    is_used_share: 0,
    //国家的控制属性
    is_country: 1,
    //品牌的控制属性
    is_brand: 1,
    //选择分类的控制属性
    select_classify_on: 223,
    index: 223,
    classify_name: "国家",//项目类型
    brand_list: null,//品牌列表

    catelist: [],// 新的版本左边的边分类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/users/distribut/pagemyshop?orderType=desc",
    requestUrl: "",
    tabname: "goods_id",   //排序的字段
    adname: "desc",        //升降的字段
    is_new: 0,
    is_hot: 0,
    msgStatus: false,  //页面显示暂无数据状态
    countDownNum: 3,
    timer: '', //定时器
    lastMsg: false,
    toView: "",
    is_show_class: false,//是否添加新样式
    status_show: 0,
    currentTab: 0, //预设当前项的值
    load: 0,
  },


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

  onLoad: function (tt) {
    wx.setNavigationBarTitle({
      title: "分类",
    });
    var that = this;//保存全局指针
    t.isLogin().then(function (data) {//进入页面前已经授权登录成功
      console.log(data);
      that.setData({
        userInfo: data,
      });
    });
    var first_leader = tt.first_leader;
    if (first_leader) {
      //--  user_id代过来免登录 --
      getApp().globalData.first_leader = first_leader;
    }

    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,

    });

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

    getApp().getConfig2(function (e) {
      var data = e;
      var switch_list_data = data.switch_list;
      var switch_list = JSON.parse(switch_list_data);
      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 }); }
      that.setData({ store_config: e, is_do: 1 });

      //---有勾品类---
      //if (that.data.is_show_pl) {
      //  that.getGoodsCategoris();
      //}
      if (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.catelist.length > 0) {
            console.log(catelist);
            var item = that.data.catelist[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: "品牌" });
      }

      //---如果后台又开等级卡的开关---
      if (switch_list.rank_switch && switch_list.rank_switch == "2") {
        that.setData({ rank_switch: true });
        var user = getApp().globalData.userInfo;
        var ti = setInterval(function () {
          if (!user) return false;
          clearInterval(ti);
          //---回调卡的列表---
          that.getPlusCardType(function (ob) {
            that.setData({ card_list: ob.card_list });
            if (user.card_field && user['card_expiredate']) {
              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);
                that.setData({ card_field: user.card_field, card_name: card_name, card_list: ob.card_list });
              }
            }
          })
        }, 500)
      }
      var catelist = that.data.catelist;

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

      //----求传参过来的控制-----
      if (getApp().globalData.cat_type == 1 && that.data.is_show_gb) {
        that.setData({ currentTab: 1 });
        that.get_nation();
      } else if (getApp().globalData.cat_type == 2 && that.data.is_show_pp) {
        that.setData({ currentTab: 2 });
        that.get_brand();
      } else if (that.data.is_show_pl) {
        that.setData({ currentTab: 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;
    })
  },
  onShow: function () {

      getApp().check_can_share();
    if (t.globalData.userInfo) {
      let currentData = {
        store_id: t.globalData.setting.stoid,
        user_id: t.globalData.user_id,
      };
      this.setData({
        userInfo: t.globalData.userInfo,
        imghost: t.globalData.setting.imghost,
        currentData,
      });
      this.getGoodsCategoris();
    }

  },



  //获取分类
  async getGoodsCategoris() {

    let { currentData } = this.data;
    let Plurl = `/api/weshop/users/distribut/listmyshopCat`;
    const categoris = await e.promiseGet(Plurl, {
      data: currentData,
      isShowLoading: false,
    });
    console.log(categoris);
    if (categoris.data.code == 0 && categoris.data.data.length > 0) {
      let catelist = categoris.data.data;
      this.setData({
        catelist,
      })
    }

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

  //跳转到分类的商品列表
  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 bid = t.currentTarget.dataset.bid;
    // getApp().globalData.bid=bid;
    // console.log(getApp().globalData.bid);
    // let page=getCurrentPages();
    // let prePage=page[page.length-2];
    // console.log(prePage);
    // prePage.setData({
    //   brand_id:cid,
    // })   
    var lurl = "/packageA/pages/distribution/shop/shop?brand_id=" + bid;
    wx.navigateTo({ url: lurl })
    // wx.navigateBack()
  },

  //跳转到国别的商品列表
  go_nation: function (t) {
    var nid = t.currentTarget.dataset.nid;
    // getApp().globalData.nid=nid;
    var lurl = "/packageA/pages/distribution/shop/shop?nation_id=" + nid;
    // var lurl = "/packageA/pages/distribution/shop/shop";
    wx.navigateTo({ url: lurl });
    
    // wx.navigateBack()
  },
  //获取国别
  get_nation: function () {
    var s = this;
    e.get("/api/weshop/users/distribut/listmyshopNation", {
      data: {
        store_id: oo.stoid,
        user_id: t.globalData.user_id,
      },
      success: function (e) {
        console.log(e);
        var dda = e.data.data;
        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/users/distribut/listmyshopBrand", {
      data: {
        store_id: oo.stoid,
        user_id: t.globalData.user_id,
      },
      success: function (e) {
        console.log(e);
        var arr = new Array();
        var dda = e.data.data;
        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);
        }

        s.setData({ groups: arr });
        //console.log(s.data.groups)
      }
    });
  },
  //---------分享配置--------
  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;
    }
    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) //注意这里的赋值方式,只是将数据列表中的此项图片路径值替换掉 ;  
  },


  getInput(e) {
    this.setData({
      keyword: e.detail.value.trim(),
    });
  },

  search: function (t) {
    let keyword = this.data.keyword;
    if (!keyword) {
      t.showWarning("请输入搜索关键词");
      return false
    }
    // this.search(val);
    // wx.navigateTo({
    //     url: `/packageA/pages/distribution/shop/shop?key_word=${val}`,
    // });
    wx.navigateBack({
      delta: 1
    });
    getApp().globalData.key_word = keyword;
  },
  //图片失败，默认图片
  bind_bnerr_t3: function (e) {
    var _errImg = e.target.dataset.errorimg;
    var _errObj = {};
    _errObj[_errImg] = "/miniapp/images/default_g_img.gif";
    this.setData(_errObj) //注意这里的赋值方式,只是将数据列表中的此项图片路径值替换掉 ;

  },

  async click_classify(e) {

    clearInterval(this.data.timer);

    let { cid, current } = e.currentTarget.dataset;
    this.setData({
      select_classify_on: current,
      cat_id: cid,
      is_no_more: 0,
      isLoading: 0,
      countDownNum: 3,
      stylePage: 1,
      is_none: 0,
    });
    if (current == 220 || current == 223) {
      console.log(111);
      let classify_name = null;
      current == 220 ? classify_name = '品牌' : classify_name = '国家';
      this.setData({
        classify_name,
      })
    } else {
      this.setData({
        classify_name: this.data.catelist[current].name,
      })
      wx.pageScrollTo({
        scrollTop: 0
      })
      this.checkCor();
      this.requestGoodsList();
    }
    // classify_name 
  },
  /* //分销小店的商品
  async getShopGoods() {
    let { currentData, baseUrl } = this.data;
    console.log(currentData);
    currentData.pageSize = 2000;
    console.log(currentData);
    const distriGoods = await e.promiseGet(baseUrl, {
      data: currentData,
      isShowLoading: false,
    });
    console.log(distriGoods);
    if (distriGoods.data.code == 0 && distriGoods.data.data.pageData.length > 0) {
      this.setData({
        shopGoodsData: distriGoods.data.data.pageData,
      })
    }
  }, */

  requestGoodsList() {
    if(this.data.isLoading) return false;
    if(this.data.is_no_more) return false
    this.data.isLoading = 1;
    var th=this;

    let { currentData } = this.data;
    currentData.cat_id = this.data.cat_id;
    currentData.page = this.data.stylePage;
    currentData.parent_id = 0;

    let url = '/api/weshop/users/distribut/pagemyshop';
    getApp().promiseGet(url, {
      isShowLoading: true,
      data: currentData,
    }).then(res=>{
        var res=res.data;
        let index = this.getCurrentIndex();
        let next_classify_name = this.data.catelist[index].name;
        th.setData({
            isLoading: 0,
            is_get: 1,
            select_classify_on: index,
            classify_name: next_classify_name,
            next_classify_name,
        });

        if (res.code == 0 && res.data.pageData.length > 0) {
            if (res.data.page > 1) {
                th.setData({
                    requestData: th.data.requestData.concat(res.data.pageData),
                });
            } else {
                th.setData({
                    requestData: res.data.pageData,
                });
            }
            isReachBt = 0;

            if(res.data.pageData.length<10){
                this.setData({
                    is_no_more: 1,
                })
            }

        } else {
            //上拉加载
            if (res.data.page > 1) {
                th.setData({
                    is_no_more: 1,
                })
            } else {
                th.setData({
                    requestData: [],
                });

                //如果类目为空则3秒后加载下一类目
                if(th.data.timer) {
                    th.data.timer=clearInterval(th.data.timer);
                    th.data.timer=0;
                }
                th.data.timer = setInterval(() => {
                    if(th.data.countDownNum<0){
                      clearInterval(th.data.timer);
                      return false;
                    }

                    th.setData({
                        countDownNum: this.data.countDownNum - 1,
                    });
                    if (th.data.countDownNum <= 0) {
                        clearInterval(th.data.timer);
                        th.get_next_cate(index);
                        return false;
                    }
                }, 1000);
            }
        }
    })


  },

  //查找当前类目在 catelist的下标  为后面下一个类目使用
  getCurrentIndex() {

    let index = this.data.catelist.findIndex(item => {
      return item.id == this.data.cat_id
    });
    //当前处于类目最后一个
    if (index + 1 == this.data.catelist.length) {
      this.setData({
        is_none: 1,
      })
    };
    return index;
  },

  get_next_cate(index) {
    if(this.data.isLoading) return false;
    index = index + 1;
    if(index==this.data.catelist.length){
      this.setData({
        is_none:1
      })
      return false;
    }
    let nex_cat_id = this.data.catelist[index].id;
    this.setData({
      cat_id: nex_cat_id,
      stylePage: 1,
      is_get: 0,
      is_no_more:0,
      next_classify_name: this.data.catelist[index].name,
    });
    this.data.car_scroll=0;
    isReachBt = 0;
    this.requestGoodsList();
  },

  //选择更多
  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 () {
    // 允许从相机和相册扫码
      getApp().globalData.no_clear=1;
    wx.scanCode({
      success: (res) => {
        var key_word = res.result;
        wx.navigateBack({
          delta: 1
        });
        getApp().globalData.key_word = key_word;
      }
    })
  },
  onUnload: function () {
    //this.destroyActivityTimer();
  },

  onPullDownRefresh: function () {

  },
  touchstart(e) {
    startY=0;
    if (!this.data.is_no_more) return false;
    if(isReachBt<=0) return false;
    startY = e.changedTouches[0].clientY;

  },
  touchend(e) {
    var th=this;
    let {select_classify_on}=th.data;
    setTimeout(function () {     
        if(!th.data.car_scroll){
          console.log('df');
            th.get_next_cate(select_classify_on);
            return false;
        }

        if(!startY) return false;
        endY = e.changedTouches[0].clientY;
        moveDistance = startY - endY;
        if(moveDistance<=0){
            isReachBt=0;
            return false;
        }
        if (th.data.is_no_more && moveDistance >= 10 && isReachBt > 0) {
            th.get_next_cate(select_classify_on);
        }
    },50)


  },
  // 左侧更新
  scrollLower: function () {

    console.log("low111");
    if (this.data.isLoading) return false;
    if (this.data.is_no_more) {
        isReachBt = 1;
        return false;
    }

    this.setData({
      stylePage: this.data.stylePage + 1,
      countDownNum: 3,
    });
    !this.data.is_none && this.requestGoodsList();

  },

  //---  获取卡类列表 ---
  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.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);
    })
  },

    bd_scroll:function (e) {
       this.data.car_scroll=1;
    }

});