var util = require('../../utils/util.js');
var status = require('../../utils/index.js');
var a = require("../../utils/public");
var e = require('../../wxParse/wxParse.js');
var countDownInit = require("../../utils/countDown");
var wcache = require('../../utils/wcache.js');
var app = getApp();
var timerOut = '';

Page(Object.assign({}, countDownInit.default, {
  data: {
    needAuth: false,
    stopClick: false,
    community: {},
    rushList: [],
    commingList: [],
    countDownMap: [],
    actEndMap: [],
    skuList: [],
    pageNum: 1,
    notice_list: [],
    slider_list: [],
    shop_info: {},
    showEmpty: false,
    indexBottomImage: '',
    classification: {
      tabs: [],
      activeIndex: 0
    },
    commingClassification: {
      tabs: [],
      activeIndex: 0
    },
    isShowCommingClassification: true,
    isShowClassification: true,
    showChangeCommunity: false,
    isTipShow: false,
    isShowGuide: false,
    index_lead_image: '',
    theme: 0,
    cartNum: 0,
    navigat: [],
    tabIdx: 0,
    scrollDirect: "",
    isSticky: false,
    showCommingEmpty: false,
    stopNotify: true,
    reduction: {},
    is_share_html: true,
    commingNum: 0,
    couponRefresh: false,
    index_change_cate_btn: 0,
    newComerRefresh: false,
    showNewCoupon: false,
    copy_text_arr: [],
    showCopyText: false
  },
  isFirst: 0,
  $data: {
    stickyFlag: false,
    scrollTop: 0,
    overPageNum: 1,
    loadOver: false,
    hasOverGoods: false,
    countDownMap: {},
    actEndMap: {},
    timer: {},
    scrollHeight: 1300,
    stickyTop: 0,
    hasCommingGoods: true,
    groupInfo: {
      group_name: '社区',
      owner_name: '团长'
    },
  },
  tpage: 1,
  hasRefeshin: false,
  postion: {},
  options: '',

  /**
   * 监控滚动事件
   */
  onPageScroll: function (t) {
    if (!this.$data.isLoadData) {
      if (t.scrollTop < this.$data.scrollHeight) {
        if (t.scrollTop > this.$data.scrollTop) {
          "down" !== this.data.scrollDirect && this.setData({
            scrollDirect: "down"
          })
        } else {
          "up" != this.data.scrollDirect && this.setData({
            scrollDirect: "up"
          })
        }
      } else {
        "down" !== this.data.scrollDirect && this.setData({
          scrollDirect: "down"
        })
      }
      if (t.scrollTop > this.$data.stickyTop) {
        this.data.isSticky || (this.setData({
          isSticky: true
        }), this.$data.stickyFlag = true)
      } else {
        t.scrollTop < this.$data.stickyBackTop && this.data.isSticky && (this.setData({
          isSticky: false
        }), this.$data.stickyFlag = false)
      }
      this.$data.scrollTop = t.scrollTop
    }
  },

  onLoad: function(options) {
    console.log('options', options);
    wx.hideTabBar();
    var that = this;
    status.setNavBgColor();
    that.setData({ systemInfo: app.globalData.systemInfo });
    status.setGroupInfo().then((groupInfo) => { that.setData({ groupInfo }) });
    console.log('step1');
    if (options && Object.keys(options).length != 0) {
      console.log('step2');
      var scene = decodeURIComponent(options.scene);
      let community = wx.getStorageSync('community');
      let community_id = community.communityId;

      if (scene != 'undefined') {
        //$share_id.'_'.$member_id
        var opt_arr = scene.split("_");
        options.community_id = opt_arr[0];
        wcache.put('share_id', opt_arr[1]);
      }
      that.options = options;

      if (options.share_id != 'undefined' && options.share_id > 0) wcache.put('share_id', options.share_id);
      if (options.community_id != 'undefined' && options.community_id > 0) {
        console.log('step3');
        app.util.request({
          'url': 'entry/wxapp/index',
          'data': {
            controller: 'index.get_community_info',
            'community_id': options.community_id
          },
          dataType: 'json',
          success: function(res) {
            var token = wx.getStorageSync('token');
            if (res.data.code == 0) {
              console.log('step4');
              var community = res.data.data;
              if (options.community_id != community_id) {
                that.setData({
                  showChangeCommunity: true,
                  changeCommunity: community
                })
              }
              that.loadPage();
              that.setData({
                hidetip: false,
                token: token,
                showEmpty: false
              })
            } else {
              console.log('step5');
              that.loadPage();
              that.setData({
                hidetip: false,
                token: token,
                showEmpty: false
              })
            }
            token && that.addhistory();
          }
        })
      } else {
        console.log('step6');
        that.loadPage();
      }
    } else {
      console.log('step7');
      that.loadPage();
      var token = wx.getStorageSync('token');
      that.setData({
        hidetip: false,
        token: token,
        showEmpty: false
      })
    }
  },

  addhistory: function (id=0) {
    console.log('step13');
    let community_id = 0;
    if (id==0) {
      var community = wx.getStorageSync('community');
      community_id = community.communityId;
    } else {
      community_id = id;
    }
    console.log('history community_id=' + community_id);
    var token = wx.getStorageSync('token');
    let that = this;
    community_id !==void 0 && app.util.request({
      'url': 'entry/wxapp/index',
      'data': {
        controller: 'index.addhistory_community',
        community_id: community_id,
        'token': token
      },
      dataType: 'json',
      success: function(res) {
        if(id!=0) that.getHistoryCommunity(), console.log('addhistory+id', id);
      }
    })
  },

  loadPage: function() {
    wx.showLoading();
    console.log('step8');
    let that = this;
    that.get_index_info();
    that.getNavigat();
    status.loadStatus().then(function() {
      let appLoadStatus = app.globalData.appLoadStatus;
      console.log('appLoadStatus',appLoadStatus)
      if (appLoadStatus == 0) {
        wx.hideLoading();
        that.setData({ needAuth: true });
      } else if (appLoadStatus == 2) {
        console.log('step9');
        that.getHistoryCommunity();
      } else {
        console.log('step12');
        let community = wx.getStorageSync('community');
        community || (community=app.globalData.community);
        if (!community){
          util.getCommunityInfo().then((res) => {
            that.setData({
              community: that.fliterCommunity(res)
            })
          })
        } else {
          that.setData({
            community: that.fliterCommunity(community)
          })
        }
        console.log('step18');
        that.load_goods_data();
      }
    });
  },

  // 不显示社区省份
  fliterCommunity: function (community){
    let resArr = community && community.fullAddress && community.fullAddress.split('省');
    let newCommunity = Object.assign({}, community, { address: resArr[1] || resArr[0] });
    return newCommunity;
  },

  onShow: function() {
    // 页面显示
    let that = this;
    console.log('isFirst',that.isFirst)
    this.setData({ stopNotify: false, couponRefresh: true, tabbarRefresh: true })

    if (util.check_login()) {
      this.setData({ needAuth: false })
    } else {
      this.setData({ needAuth: true });
    }
    app.globalData.timer.start();
    (0, status.cartNum)('', true).then((res)=>{
      res.code == 0 && that.setData({ cartNum: res.data })
    });

    if (app.globalData.changedCommunity) {
      console.log('change')
      app.globalData.goodsListCarCount = [];
      let community = app.globalData.community;
      this.setData({
        community: that.fliterCommunity(community),
        newComerRefresh: false
      });
      this.getCommunityPos(community.communityId);
      this.hasRefeshin = false;
      this.setData({
        newComerRefresh: true,
        rushList: [],
        pageNum: 1,
        classificationId: null,
        "classification.activeIndex": -1
      }, () => {
        this.setData({
          "classification.activeIndex": 0
        })
      })
      this.$data = {
        ...this.$data, ...{
          overPageNum: 1,
          loadOver: false,
          hasOverGoods: false,
          countDownMap: {},
          actEndMap: {},
          timer: {},
          stickyFlag: false,
          hasCommingGoods: true
        }
      }
      app.globalData.changedCommunity = false, this.get_index_info(), this.addhistory();
      this.load_goods_data();
    } else {
      console.log('nochange')
      if (that.isFirst>=1){
        this.setData({ loadOver: true })
        let goodsListCarCount = app.globalData.goodsListCarCount; //[{ actId: 84, num: 2}]
        let rushList = this.data.rushList;
        if (goodsListCarCount.length > 0 && rushList.length>0){
          let newRushList = [];
          let changeCarCount = false;
          goodsListCarCount.forEach(function(item){
            let k = rushList.findIndex((n) => n.actId == item.actId);
            if (k != -1 && rushList[k].skuList.length === 0) {
              let newNum = item.num * 1;
              rushList[k].car_count = newNum >= 0 ? newNum : 0;
              changeCarCount = true;
            }
          })
          this.setData({ rushList, changeCarCount })
          // app.globalData.goodsListCarCount = [];
        }
      }
    }
    that.isFirst++;
  },

  onHide: function() {
    this.setData({ stopNotify: true, couponRefresh: false, tabbarRefresh: false, changeCarCount: false })
    console.log('详情页', this.data.stopNotify)
    app.globalData.timer.stop();
    console.log('onHide')
  },

  /**
   * 授权成功回调
   */
  authSuccess: function() {
    console.log('authSuccess');
    let that = this;
    this.tpage = 1;
    this.hasRefeshin = false;
    this.setData({
      rushList: [],
      pageNum: 1,
      needAuth: false
    })
    this.$data = {
      ...this.$data, ...{
        overPageNum: 1,
        loadOver: false,
        hasOverGoods: false,
        countDownMap: {},
        actEndMap: {},
        timer: {},
        hasCommingGoods: true
      }
    }
    status.getInNum().then((isCan) => {
      if (isCan) {
        that.setData({ isTipShow: true })
        timerOut = setTimeout(() => { that.setData({ isTipShow: false }) }, 7000);
      }
    })
    this.loadPage();
    this.data.isTipShow && (timerOut = setTimeout(() => { that.setData({ isTipShow: false }) }, 7000));
  },

  //获取历史社区
  getHistoryCommunity: function () {
    let that = this;
    var token = wx.getStorageSync('token');
    app.util.request({
      'url': 'entry/wxapp/index',
      'data': {
        controller: 'index.load_history_community',
        token: token
      },
      dataType: 'json',
      success: function (res) {
        console.log('step14');
        if (res.data.code == 0) {
          console.log('getHistoryCommunity');
          let history_communities = res.data.list;
          let isNotHistory = false;
          if (Object.keys(history_communities).length == 0 || history_communities.communityId == 0) isNotHistory = true;
          
          let resArr = history_communities && history_communities.fullAddress && history_communities.fullAddress.split('省');
          history_communities = Object.assign({}, history_communities, { address: resArr[1] })

          that.setData({
            community: history_communities
          })
          wcache.put('community', history_communities);
          app.globalData.community = history_communities;

          that.setData({
            community: app.globalData.community
          })
          that.load_goods_data();

        } else {
          let options = that.options;
          if (options !== void 0 && options.community_id) {
            console.log('新人加入分享进来的社区id:', that.options);
            that.addhistory(options.community_id);
          } else {
            wx.redirectTo({
              url: "/lionfish_comshop/pages/position/community"
            })
          }
        }
      }
    })
  },
  
  getScrollHeight: function () {
    wx.createSelectorQuery().select('.rush-list-box').boundingClientRect((rect) => {
      rect && rect.height && (this.$data.scrollHeight = rect.height || 1300);
      console.log(this.$data.scrollHeight)
    }).exec()
  },

  /**
   * 引导页切换
   */
  handleProxy: function(){
    clearTimeout(timerOut);
    this.setData({
      isTipShow: false,
      isShowGuide: true
    })
    wcache.put('inNum', 4);
  },

  handleHideProxy: function(){
    this.setData({
      isTipShow: false,
      isShowGuide: false
    })
  },

  /**
   * 获取首页信息
   */
  get_index_info: function() {
    let that = this;
    let community = wx.getStorageSync('community');
    let communityId = community && community.communityId || '';
    let token = wx.getStorageSync('token');
    app.util.request({
      'url': 'entry/wxapp/index',
      'data': {
        controller: 'index.index_info',
        communityId,
        token
      },
      dataType: 'json',
      success: function(res) {
        let rdata = res.data;
        if (rdata.code == 0) {
          if (!res.data.is_community && communityId && !that.data.needAuth) {
            wx.showModal({
              title: '提示',
              content: '该小区不在，请重新选择小区',
              showCancel: false,
              confirmColor: '#F75451',
              success(res) {
                if (res.confirm) {
                  wx.redirectTo({
                    url: '/lionfish_comshop/pages/position/community',
                  })
                }
              }
            })
          }
          let notice_list = rdata.notice_list;
          let slider_list = rdata.slider_list;
          let index_lead_image = rdata.index_lead_image;
          if(index_lead_image){
            status.getInNum().then((isCan)=>{
              if (isCan) {
                that.setData({ isTipShow: true },()=>{
                  timerOut = setTimeout(() => { that.setData({ isTipShow: false }) }, 9000);
                })
              }
            })
          } else {
            that.setData({ isTipShow: false })
          }

          let common_header_backgroundimage = rdata.common_header_backgroundimage;
          app.globalData.common_header_backgroundimage = common_header_backgroundimage;
          let order_notify_switch = rdata.order_notify_switch;
          let index_list_top_image_on = rdata.index_list_top_image_on || 1;
          let index_change_cate_btn = rdata.index_change_cate_btn || 0;
          let default_img = '../../images/rush-title.png';
          if (index_list_top_image_on == 1) default_img='';
          let index_list_top_image = rdata.index_list_top_image ? rdata.index_list_top_image : default_img;
          let shop_info = {
            shoname: rdata.shoname,
            shop_index_share_image: rdata.shop_index_share_image,
            index_list_top_image: index_list_top_image,
            title: rdata.title,
            common_header_backgroundimage,
            order_notify_switch,
            index_top_img_bg_open: rdata.index_top_img_bg_open || 0,
            index_top_font_color: rdata.index_top_font_color || '#fff'
          }
          app.globalData.placeholdeImg = rdata.index_loading_image || '';
          wcache.put('shopname', rdata.shoname);
          wx.setNavigationBarTitle({ title: rdata.shoname });

          let category_list = rdata.category_list || [];
          let index_type_first_name = rdata.index_type_first_name || '全部';
          if (category_list.length > 0) {
            category_list.unshift({
              name: index_type_first_name,
              id: 0
            })
            that.setData({
              isShowClassification: true,
              "classification.tabs": category_list
            })
          } else {
            that.setData({
              isShowClassification: false
            })
          }

          let theme = rdata.theme || 0;
          let rushEndTime = rdata.rushtime*1000 || 0;
          let isShowShareBtn = rdata.index_share_switch || 0;
          let isShowListCount = rdata.is_show_list_count || 0;
          let isShowListTimer = rdata.is_show_list_timer || 0;
          let isShowContactBtn = rdata.index_service_switch || 0; 
          let index_switch_search = rdata.index_switch_search || 0;

          if (rdata.is_comunity_rest == 1 && !that.data.needAuth) {
            wx.showModal({
              title: '温馨提示',
              content: '团长休息中，欢迎下次光临!',
              showCancel: false,
              confirmColor: '#F75451',
              confirmText: '好的',
              success(res) { }
            })
          }

          that.postion = rdata.postion;

          that.setData({
            notice_list,
            slider_list,
            index_lead_image,
            theme,
            indexBottomImage: rdata.index_bottom_image || '',
            shop_info: shop_info,
            loadOver: true,
            rushEndTime,
            commingNum: rdata.comming_goods_total,
            isShowShareBtn,
            isShowListCount,
            isShowListTimer,
            is_comunity_rest: rdata.is_comunity_rest,
            index_change_cate_btn,
            isShowContactBtn,
            index_switch_search,
            is_show_new_buy: rdata.is_show_new_buy || 0,
            qgtab: res.data.qgtab || {},
            notice_setting: rdata.notice_setting || {},
            index_hide_headdetail_address: rdata.index_hide_headdetail_address || 0,
            is_show_spike_buy: rdata.is_show_spike_buy || 0,
            hide_community_change_btn: rdata.hide_community_change_btn || 0,
            hide_top_community: rdata.hide_top_community || 0,
            index_qgtab_text: rdata.index_qgtab_text,
            ishow_index_copy_text: rdata.ishow_index_copy_text || 0
          })
        }
      }
    })
  },

  /**
   * 跳转地址选择
   */
  goSelectCommunity: function() {
    wx.redirectTo({
      url: '/lionfish_comshop/pages/position/community',
    })
  },

  /**
   * 确认切换社区
   */
  confrimChangeCommunity: function() {
    let community = this.data.changeCommunity;
    app.globalData.community = community;
    wcache.put('community', community);
    this.$data = {
      ...this.$data, ...{
        overPageNum: 1,
        loadOver: false,
        hasOverGoods: false,
        countDownMap: {},
        actEndMap: {},
        timer: {},
        stickyFlag: false
      }
    }
    this.hasRefeshin = false;
    this.setData({
      showChangeCommunity: false,
      community: community,
      rushList: [],
      pageNum: 1
    }, () => {
      this.loadPage();
      this.addhistory();
    })
  },

  /**
   * 关闭切换社区
   */
  closeChangeCommunity: function(){
    this.setData({
      showChangeCommunity: false
    })
  },

  /**
   * 获取商品列表
   */
  load_goods_data: function() {
    var token = wx.getStorageSync('token');
    var that = this;
    var cur_community = wx.getStorageSync('community');
    var gid = that.data.classificationId;
    this.$data.isLoadData = true;
    console.log('load_goods_begin ');

    if (!that.hasRefeshin && !that.$data.loadOver) {
      console.log('load_goods_in ');
      this.hasRefeshin = true;
      that.setData({
        loadMore: true
      });
      app.util.request({
        'url': 'entry/wxapp/index',
        'data': {
          controller: 'index.load_gps_goodslist',
          token: token,
          pageNum: that.data.pageNum,
          head_id: cur_community.communityId,
          gid
        },
        dataType: 'json',
        success: function(res) {
          if (res.data.code == 0) {
            let rushList = '';
            if (res.data.is_show_list_timer==1) {
              rushList = that.transTime(res.data.list);
              for (let s in that.$data.countDownMap) that.initCountDown(that.$data.countDownMap[s]);
            } else {
              let oldRushList = that.data.rushList;
              rushList = oldRushList.concat(res.data.list);
            }
            let rdata = res.data;
            let reduction = { full_money: rdata.full_money, full_reducemoney: rdata.full_reducemoney, is_open_fullreduction: rdata.is_open_fullreduction }
            if (that.data.pageNum==1) that.setData({ copy_text_arr: rdata.copy_text_arr || [] })
            that.hasRefeshin = false;
            that.setData({
              rushList: rushList,
              pageNum: that.data.pageNum + 1,
              loadMore: false,
              reduction,
              tip: ''
            }, ()=>{
              if (that.isFirst == 1) {
                that.isFirst++;
                if (rushList.length && !that.$data.stickyTop) {
                  wx.createSelectorQuery().select(".tab-nav").boundingClientRect(function (t) {
                    if (t && t.top){
                      wcache.put('tabPos', t);
                      that.$data.stickyTop = t.top + t.height, that.$data.stickyBackTop = t.top;
                    } else {
                      let tabpos = wcache.get('tabPos', false);
                      if (tabpos) that.$data.stickyTop = tabpos.top + tabpos.height, that.$data.stickyBackTop = tabpos.top;
                    }
                  }).exec();
                  that.$data.scrollTop > that.$data.stickyTop && wx.pageScrollTo({
                    duration: 0,
                    scrollTop: that.$data.stickyTop + 4
                  });
                }
              }
              that.getScrollHeight();
              if (that.data.pageNum == 2 && res.data.list.length < 10) {
                console.log('load_over_goods_list_begin')
                that.$data.loadOver = true;
                that.hasRefeshin = true;
                that.setData({
                  loadMore: true
                }, () => {
                  that.load_over_gps_goodslist();
                });
              }
            });
          } else if (res.data.code == 1) {
            that.$data.loadOver = true;
            that.load_over_gps_goodslist();
          } else if (res.data.code == 2) {
            //no login
            that.setData({ needAuth: true })
          }
        },
        complete: function() {
          that.$data.isLoadData = false;
          wx.hideLoading();
        }
      })
    } else {
      that.load_over_gps_goodslist();
    }
  },

  /**
   * 组合倒计时时间
   */
  transTime: function(list) {
    let that = this;
    e = arguments.length > 1 && void 0 !== arguments[1] ? arguments[1] : 0;
    e === 0 && list.map(function(t) {
      t.end_time *= 1000;
      that.$data.countDownMap[t.end_time] = t.end_time, that.$data.actEndMap[t.end_time] = t.end_time <= new Date().getTime() || t.spuCanBuyNum == 0;
    })
    return that.data.rushList.concat(list);
  },

  /**
   * 获取售罄商品
   */
  load_over_gps_goodslist: function() {
    var token = wx.getStorageSync('token');
    var that = this;
    var cur_community = wx.getStorageSync('community');
    var gid = that.data.classificationId;

    if (!that.$data.hasOverGoods && that.$data.loadOver) {
      that.$data.hasOverGoods = true;
      that.setData({
        loadMore: true
      });
      app.util.request({
        'url': 'entry/wxapp/index',
        'data': {
          controller: 'index.load_over_gps_goodslist',
          token: token,
          pageNum: that.$data.overPageNum,
          head_id: cur_community.communityId,
          gid
        },
        dataType: 'json',
        success: function(res) {
          if (res.data.code == 0) {
            let rushList = that.transTime(res.data.list);
            for (let s in that.$data.countDownMap) that.initCountDown(that.$data.countDownMap[s]);

            that.$data.hasOverGoods = false;
            that.$data.overPageNum += 1;
            that.setData({
              rushList: rushList,
              loadMore: false,
              tip: ''
            }, ()=>{
              if (that.isFirst == 1) {
                that.isFirst++;
                if (rushList.length && !that.$data.stickyTop) {
                  wx.createSelectorQuery().select(".tab-nav").boundingClientRect(function (t) {
                    if (t && t.top) {
                      wcache.put('tabPos', t);
                      that.$data.stickyTop = t.top + t.height, that.$data.stickyBackTop = t.top;
                    } else {
                      let tabpos = wcache.get('tabPos', false);
                      if (tabpos) that.$data.stickyTop = tabpos.top + tabpos.height, that.$data.stickyBackTop = tabpos.top;
                    }
                  }).exec();
                  that.$data.scrollTop > that.$data.stickyTop && wx.pageScrollTo({
                    duration: 0,
                    scrollTop: that.$data.stickyTop + 4
                  });
                }
              }
              that.getScrollHeight();
            });
          } else if (res.data.code == 1) {
            if (that.$data.overPageNum == 1 && that.data.rushList.length == 0) that.setData({
              showEmpty: true
            })
            that.setData({
              loadMore: false,
              tip: '^_^已经到底了'
            })
          } else if (res.data.code == 2) {
            that.setData({ needAuth: true })
          }
          that.$data.isLoadData = false;
        }
      })
    } else {
      that.$data.isLoadData = false;
    }
  },

  /**
   * 监控分类导航
   */
  classificationChange: function(t) {
    console.log(t.detail.e)
    wx.showLoading();
    var that = this;
    this.$data = {...this.$data, ...{
      overPageNum: 1,
      loadOver: false,
      hasOverGoods: false,
      countDownMap: {},
      actEndMap: {},
      timer: {}
    }
    }, this.hasRefeshin = false, this.setData({
      rushList: [],
      showEmpty: false,
      pageNum: 1,
      "classification.activeIndex": t.detail.e,
      classificationId: t.detail.a
    }, function() {
      if (this.$data.stickyFlag && (that.$data.scrollTop != that.$data.stickyTop+5)){
        wx.pageScrollTo({ scrollTop: that.$data.stickyTop + 5, duration: 0 })
      }
      that.load_goods_data();
    });
  },

  /**
  * 监控即将抢购分类导航
  */
  commingClassificationChange: function (t) {
    wx.showLoading();
    var that = this;
    that.tpage = 1;
    this.$data = {...this.$data, ...{hasCommingGoods: true} },
    this.setData({
      showCommingEmpty: false,
      commingList: [],
      "commingClassification.activeIndex": t.detail.e,
      commingClassificationId: t.detail.a
    }, function () {
      if (this.$data.stickyFlag && (that.$data.scrollTop != that.$data.stickyTop + 5)) {
        wx.pageScrollTo({ scrollTop: that.$data.stickyTop + 5, duration: 0 })
      }
      that.getCommingList();
    });
  },

  // 抢购切换
  tabSwitch: function (t) {
    var that = this;
    var tabIdx = 1 * t.currentTarget.dataset.idx;
    this.setData({ tabIdx: tabIdx }, ()=>{
      if (tabIdx == 1) {
        if (that.$data.stickyFlag && (that.$data.scrollTop != that.$data.stickyTop + 5)) {
          wx.pageScrollTo({ scrollTop: that.$data.stickyTop + 5, duration: 0 })
        }
        if (that.tpage == 1) {
          that.getCommingList();
        }
      }
    })
  },

  /**
   * 即将开抢列表
   */
  getCommingList: function(){
    this.data.commigLoadMore && wx.showLoading();
    var token = wx.getStorageSync('token');
    var that = this;
    var cur_community = wx.getStorageSync('community');
    var gid = this.data.commingClassificationId || 0;
    that.$data.isLoadData = true;

    if (that.$data.hasCommingGoods) {
      that.$data.hasCommingGoods = false;
      that.setData({ commigLoadMore: true });
      app.util.request({
        url: 'entry/wxapp/index',
        data: {
          controller: 'index.load_comming_goodslist',
          token: token,
          pageNum: that.tpage,
          head_id: cur_community.communityId,
          gid
        },
        dataType: 'json',
        success: function (res) {
          wx.hideLoading();
          if (res.data.code == 0) {
            let commingList = res.data.list;
            commingList = that.data.commingList.concat(commingList);
            that.$data.hasCommingGoods = true;
            that.tpage += 1;
            that.setData({
              commingList: commingList,
              commigLoadMore: false,
              commigTip: ''
            },()=>{
              that.getScrollHeight();
            });
          } else if (res.data.code == 1) {
            if (that.tpage == 1 && that.data.commingList.length == 0) that.setData({
              showCommingEmpty: true
            })
            that.setData({
              commigLoadMore: false,
              commigTip: '^_^已经到底了'
            })
          } else if (res.data.code == 2) {
            that.setData({ needAuth: true })
          }
          that.$data.isLoadData = false;
        }
      })
    } else{
      that.$data.isLoadData = false;
      !that.data.commigLoadMore && wx.hideLoading();
    }
  },

  openSku: function(t) {
    var that = this,
      e = t.detail;
    var goods_id = e.actId;
    var options = e.skuList;
    that.setData({
      addCar_goodsid: goods_id
    })

    let list = options.list || [];
    let arr = [];
    if (list.length > 0) {
      for (let i = 0; i < list.length; i++) {
        let sku = list[i]['option_value'][0];
        let temp = {
          name: sku['name'],
          id: sku['option_value_id'],
          index: i,
          idx: 0
        };
        arr.push(temp);
      }
      //把单价剔除出来begin

      var id = '';
      for (let i = 0; i < arr.length; i++) {
        if (i == arr.length - 1) {
          id = id + arr[i]['id'];
        } else {
          id = id + arr[i]['id'] + "_";
        }
      }

      var cur_sku_arr = options.sku_mu_list[id];

      that.setData({
        sku: arr,
        sku_val: 1,
        cur_sku_arr: cur_sku_arr,
        skuList: e.skuList,
        visible: true,
        showSku: true
      });
    } else {
      let goodsInfo = e.allData;
      that.setData({
        sku: [],
        sku_val: 1,
        skuList: [],
        cur_sku_arr: goodsInfo
      })
      let formIds = {
        detail: {
          formId: ""
        }
      };
      formIds.detail.formId = "the formId is a mock one";
      that.gocarfrom(formIds);
      //todo...addcart
    }

  },

  focus: function() {
    this.data.focusFlag = true;
  },

  canBuyFn: function(a, e) {
    var u = arguments.length > 2 && void 0 !== arguments[2] ? arguments[2] : {},
      i = this.data.skuList[e].canBuyNum - a,
      s = {
        value: a
      };
    i <= 10 && (s.canBuyMsg = "还可以购买 " + i + " 件"), this.data.canBuyMsg && i > 10 && (s.canBuyMsg = ""),
      this.setData(t({}, s, u));
  },

  changeNumber: function(t) {
    var a = t.detail;
    this.data.focusFlag = false, a && this.canBuyFn(a.value, this.data.current);
  },

  goOrder: function() {
    var that = this;
    if (that.data.can_car) {
      that.data.can_car = false;
    }
    var token = wx.getStorageSync('token');
    var community = wx.getStorageSync('community');

    var goods_id = that.data.addCar_goodsid;
    var community_id = community.communityId;
    var quantity = that.data.sku_val;

    var cur_sku_arr = that.data.cur_sku_arr;

    var sku_str = '';
    var is_just_addcar = 1;

    if (cur_sku_arr && cur_sku_arr.option_item_ids) {
      sku_str = cur_sku_arr.option_item_ids;
    }

    //addCar_goodsid: goods_id
    app.util.request({
      'url': 'entry/wxapp/user',
      'data': {
        controller: 'car.add',
        'token': token,
        "goods_id": goods_id,
        "community_id": community_id,
        "quantity": quantity,
        "sku_str": sku_str,
        "buy_type": 'dan',
        "pin_id": 0,
        "is_just_addcar": is_just_addcar
      },
      dataType: 'json',
      method: 'POST',
      success: function(res) {
        //console.log(res);
        if (res.data.code == 3) {
          wx.showToast({
            title: res.data.msg,
            icon: 'none',
            duration: 2000
          })
        } else if (res.data.code == 4) {
          wx.showToast({
            title: '您未登录',
            duration: 2000,
            success: () => {
              that.setData({ needAuth: true })
            }
          })
        } else if (res.data.code == 6) {
          let max_quantity = res.data.max_quantity || '';
          (max_quantity > 0) && that.setData({ sku_val: max_quantity })
          var msg = res.data.msg;
          wx.showToast({
            title: msg,
            icon: 'none',
            duration: 2000
          })
        } else {
          if (is_just_addcar == 1) {
            that.closeSku();
            (0, status.cartNum)(res.data.total);
            that.setData({ cartNum: res.data.total })
            wx.showToast({
              title: "已加入购物车",
              image: "../../images/addShopCart.png"
            })
          } else {
            var pages_all = getCurrentPages();
            if (pages_all.length > 3) {
              wx.redirectTo({
                url: '/lionfish_comshop/pages/buy/index?type=' + that.data.order.buy_type
              })
            } else {
              wx.navigateTo({
                url: '/lionfish_comshop/pages/buy/index?type=' + that.data.order.buy_type
              })
            }
          }

        }

      }
    })

  },

  /**
   * 确认加入购物车
   */
  gocarfrom: function(e) {
    var that = this;
    var is_just_addcar = 1;
    wx.showLoading();
    a.collectFormIds(e.detail.formId);
    that.goOrder();
  },

  /**
   * 关闭购物车选项卡
   */
  closeSku: function() {
    this.setData({
      visible: 0,
      stopClick: false,
    });
  },

  selectSku: function(event) {
    var that = this;
    let str = event.currentTarget.dataset.type;
    let obj = str.split("_");
    let arr = that.data.sku;
    let temp = {
      name: obj[3],
      id: obj[2],
      index: obj[0],
      idx: obj[1]
    };
    arr.splice(obj[0], 1, temp);
    that.setData({
      sku: arr
    })
    var id = '';
    for (let i = 0; i < arr.length; i++) {
      if (i == arr.length - 1) {
        id = id + arr[i]['id'];
      } else {
        id = id + arr[i]['id'] + "_";
      }
    }
    var options = this.data.skuList;
    var cur_sku_arr = options.sku_mu_list[id];

    that.setData({
      cur_sku_arr: cur_sku_arr
    });

    console.log(id);
  },

  /**
   * 数量加减
   */
  setNum: function(event) {
    let types = event.currentTarget.dataset.type;
    var that = this;
    var num = 1;
    let sku_val = this.data.sku_val * 1;
    if (types == 'add') {
      num = sku_val + 1;
    } else if (types == 'decrease') {
      if (sku_val > 1) {
        num = sku_val - 1;
      }
    }

    let arr = that.data.sku;
    var options = this.data.skuList;

    if (arr.length > 0) {
      var id = '';
      for (let i = 0; i < arr.length; i++) {
        if (i == arr.length - 1) {
          id = id + arr[i]['id'];
        } else {
          id = id + arr[i]['id'] + "_";
        }
      }
    }

    if (options.length > 0) {
      let cur_sku_arr = options.sku_mu_list[id];
      if (num > cur_sku_arr['canBuyNum']) {
        num = num - 1;
      }
    } else {
      let cur_sku_arr = this.data.cur_sku_arr;
      if (num > cur_sku_arr['canBuyNum']) {
        num = num - 1;
      }
    }

    this.setData({
      sku_val: num
    })
  },
  
  skuConfirm: function() {
    this.closeSku(), (0, status.cartNum)().then((res) => {
      res.code == 0 && that.setData({ cartNum: res.data })
    });
  },

  /**
   * 返回顶部
   */
  backTop: function() {
    this.stickyFlag = false, wx.pageScrollTo({
      scrollTop: 0
    });
  },

  goLink: function(event) {
    let url = event.currentTarget.dataset.link;
    wx.redirectTo({
      url: url
    })

  },

  goGoods: function(goods_id) {
    let id = goods_id;
    if (!util.check_login()) {
      util.login('/Snailfish_shop/pages/goods/index?id=' + id);
      return false;
    }
    var pages_all = getCurrentPages();

    if (pages_all.length > 3) {
      wx.redirectTo({
        url: '/Snailfish_shop/pages/goods/index?id=' + id
      })
    } else {
      wx.navigateTo({
        url: '/Snailfish_shop/pages/goods/index?id=' + id
      })
    }
  },

  /**
   * 导航小图标
   */
  getNavigat: function(){
    let that = this;
    app.util.request({
      'url': 'entry/wxapp/index',
      'data': {
        controller: 'index.get_navigat'
      },
      dataType: 'json',
      success: function (res) {
        if (res.data.code == 0) {
          let navigat = res.data.data || []
          that.setData({ navigat })
        }
      }
    })
  },
  
  /**
   * 导航图标跳转
   */
  goNavUrl: function(t) {
    let idx = t.currentTarget.dataset.idx;
    let navigat = this.data.navigat;
    if (navigat.length > 0) {
      let url = navigat[idx].link;
      let type = navigat[idx].type;
      if (type== 0){
        // 跳转webview
        wx.navigateTo({
          url: '/lionfish_comshop/pages/web-view?url=' + encodeURIComponent(url),
        })
      } else if (type==1) {
        if (url.indexOf('lionfish_comshop/pages/index/index') != -1 || url.indexOf('lionfish_comshop/pages/order/shopCart') != -1 || url.indexOf('lionfish_comshop/pages/user/me') != -1 || url.indexOf('lionfish_comshop/pages/type/index') != -1) {
          wx.switchTab({ url: url })
        } else {
          wx.navigateTo({ url: url })
        }
        
      } else if (type==2){
        // 跳转小程序
        let appid = navigat[idx].appid;
        appid && wx.navigateToMiniProgram({
          appId: navigat[idx].appid,
          path: url,
          extraData: {},
          envVersion: 'release',
          success(res) {
            // 打开成功
          },
          fail(error) {
            console.log(error)
          }
        })
      } else if (type == 3){
        //首页分类
        // t.detail.e 选中索引
        // t.detail.a 选中id
        let classification = this.data.classification;
        let tabs = classification && classification.tabs;
        let cid = url;
        let activeIdx = tabs.findIndex((p) => { return p.id == cid });
        if (activeIdx!=-1) {
          let cateInfo = {
            detail: { e: activeIdx, a: cid }
          };
          this.classificationChange(cateInfo);
        }
      } else if (type == 4) {
        //独立分类
        app.globalData.typeCateId = url;
        wx.switchTab({
          url: '/lionfish_comshop/pages/type/index'
        })
      }
    }
  },

  /**
   * 幻灯片跳转
   */
  goBannerUrl: function (t) {
    let idx = t.currentTarget.dataset.idx;
    let slider_list = this.data.slider_list;
    if (slider_list.length > 0) {
      let url = slider_list[idx].link;
      let type = slider_list[idx].linktype;
      if (type == 0) {
        // 跳转webview
        url && wx.navigateTo({ url: '/lionfish_comshop/pages/web-view?url=' + encodeURIComponent(url) })
      } else if (type == 1) {
        if (url.indexOf('lionfish_comshop/pages/index/index') != -1 || url.indexOf('lionfish_comshop/pages/order/shopCart') != -1 || url.indexOf('lionfish_comshop/pages/user/me') != -1 || url.indexOf('lionfish_comshop/pages/type/index') != -1) {
          url && wx.switchTab({ url: url })
        } else {
          url && wx.navigateTo({ url: url })
        }

      } else if (type == 2) {
        // 跳转小程序
        let appid = slider_list[idx].appid;
        appid && wx.navigateToMiniProgram({
          appId: slider_list[idx].appid,
          path: url,
          extraData: {},
          envVersion: 'release',
          success(res) {
            // 打开成功
          },
          fail(error) {
            console.log(error)
          }
        })
      }
    }
  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {
    this.setData({ couponRefresh: false, newComerRefresh: false });
    this.tpage = 1;
    this.$data = {
      ...this.$data, ...{
        overPageNum: 1,
        loadOver: false,
        hasOverGoods: false,
        countDownMap: {},
        actEndMap: {},
        timer: {},
        stickyFlag: false,
        hasCommingGoods: true
      }
    }
    this.hasRefeshin = false;
    this.setData({
      rushList: [],
      commingList: [],
      tabIdx: 0,
      pageNum: 1,
      couponRefresh: true,
      newComerRefresh: true
    }, ()=>{
      this.loadPage();
    })
    wx.stopPullDownRefresh();
    console.log(111)
  },

  onReachBottom: function(e) {
    if (this.data.tabIdx==0){
      this.load_goods_data();
    } else {
      this.getCommingList();
    }
  },

  /**
   * 获取团长位置
   */
  getCommunityPos: function (community_id){
    let that = this;
    app.util.request({
      'url': 'entry/wxapp/user',
      'data': {
        controller: 'index.get_community_position',
        communityId: community_id
      },
      dataType: 'json',
      method: 'POST',
      success: function (res) {
        if (res.data.code == 0) {
          that.postion = res.data.postion;
        }
      }
    })
  },

  /**
  * 查看地图
  */
  gotoMap: function () {
    let community = this.data.community;
    let postion = this.postion || {lat: 0, lon: 0};
    let longitude = parseFloat(postion.lon),
      latitude = parseFloat(postion.lat),
      name = community.disUserName,
      address = `${community.fullAddress}(${community.communityName})`;
    wx.openLocation({
      latitude: latitude,
      longitude: longitude,
      name: name,
      address: address,
      scale: 28
    })
  },

  share_handler: function () {
    this.setData({
      is_share_html: false
    })
  },

  hide_share_handler: function () {
    this.setData({
      is_share_html: true
    })
  },

  // 搜索
  goResult: function (e) {
    let keyword = e.detail.value.replace(/\s+/g, '');
    if (!keyword) {
      wx.showToast({
        title: '请输入关键词',
        icon: 'none'
      })
      return;
    }
    wx.navigateTo({
      url: '/lionfish_comshop/pages/type/result?keyword=' + keyword,
    })
  },

  /**
   * 新人优惠券显示开关
   */
  toggleCoupon: function(){
    this.setData({
      showNewCoupon: !this.data.showNewCoupon
    })
  },

  changeCartNum: function(t) {
    let that = this;
    let e = t.detail;
    (0, status.cartNum)(that.setData({ cartNum: e }));
  },

  /**
   * 一键复制文本
   */
  copyText: function (e) {
    let copy_text_arr = this.data.copy_text_arr;
    let community = this.data.community;
    let communityName = community.communityName;
    let disUserName = community.disUserName;
    let communityAddress = community.address || community.communityAddress || community.fullAddress;
    let data = '-团长信息-\r\n小区：' + communityName + '\r\n团长：' + disUserName + '\r\n自提点：' + communityAddress + '\r\n\r\n今日推荐\r\n';
    if (copy_text_arr.length) {
      copy_text_arr.forEach(function(item, index){
        data += (index + 1) + '.【' + item.goods_name + '】  团购价' + item.price + '\r\n';
        data += '~~~~~~~~~~~~~~~~~~~~\r\n';
      })
    }
    let that = this;
    wx.setClipboardData({
      data: data,
      success: function (res) {
        wx.getClipboardData({
          success: function (res) {
            that.setData({ showCopyText: false })
            wx.showToast({
              title: '复制成功'
            })
          }
        })
      }
    })
  },

  /**
   * 显示关闭复制文本
   */
  showCopyTextHandle: function(e){
    let showCopyText = e.currentTarget.dataset.status;
    this.setData({ showCopyText })
  },

  onShareAppMessage: function(res) {
    this.setData({ is_share_html: true });
    var community = wx.getStorageSync('community');
    var community_id = community.communityId;
    var member_id = wx.getStorageSync('member_id');
    console.log('首页分享地址：');
    console.log(community_id, member_id);
    return {
      title: this.data.shop_info.title,
      path: "lionfish_comshop/pages/index/index?community_id=" + community_id + '&share_id=' + member_id,
      imageUrl: this.data.shop_info.shop_index_share_image,
      success: function() {},
      fail: function() {}
    };
  }
}))