// pages/microShop_home/microShop_home.js
var app = getApp();
Page({

  /**
	 * 页面的初始数据
	 */
  data: {
    Height: '',
    tempshare: null,
    username: "用户昵称",
    signName: "个性签名",
    category: [],
    carousel: [],
    goodsListData: [],
    ads: [],
    bannerData: [],
    userImg: "",
    shop_logo: "",
    shop_name: "",
    shop_id: "",
    bgImg: "",
    isCategory: false,
    amout: true,
    index2: 1,
    other: "",
    content: "",
    show: true,
    tempData: [{
      id: "M1491471961972",
      temp: "showsearch",
      params: {
        placeholder: "",
        style: "style2",
        color: "#000",
        bgcolor: "#FFF",
        bordercolor: "#fa1f24",
        searchurl: "",
        uniacid: "6"
      },
      data: "",
      other: "",
      content: ""
    }],
    oftemp: false,
    dftempData: false,
    follow: false,
    isfollow: true,
    havaShop: false, //是否已有商品
    shopData: {}, //微店信息
    shop_idKey: '',
    iPnoneBottomBol: false,
    // more
    isLoadMore: true,
    page: 1,
    total_page: 0,
  },
  /**
	 * 生命周期函数--监听页面加载
	 */
  onLoad: function(options) {
    this.getiPnoneBottom();
    var query = wx.createSelectorQuery();
    query.select('.li').boundingClientRect(function(rect) {
      console.log(rect);

    }).exec();
    if (options.mid) {
      app._setMid(options.mid);
    }
    if (options.shop_id) {
      this.setData({
        shop_idKey: options.shop_id,
        shop_id: options.shop_id
      });
    }
    this.getMicroShop();
  },
  getiPnoneBottom() {
    let that = this;
    try {
      var value = wx.getStorageSync('iPhoneBottom');
      if (value) {
        that.setData({
          iPnoneBottomBol: true
        });
        // Do something with return value
      }
    } catch (e) {
      // Do something when catch error
    }
  },
  /**
	 * 生命周期函数--监听页面初次渲染完成
	 */
  onReady: function() {

  },

  /**
	 * 生命周期函数--监听页面显示
	 */
  onShow: function() {

  },

  /**
	 * 生命周期函数--监听页面隐藏
	 */
  onHide: function() {

  },

  /**
	 * 生命周期函数--监听页面卸载
	 */
  onUnload: function() {

  },

  /**
	 * 页面相关事件处理函数--监听用户下拉动作
	 */
  onPullDownRefresh: function() {

  },

  /**
	 * 页面上拉触底事件的处理函数
	 */
  onReachBottom: function() {
    if (this.data.isLoadMore) {
      this.getMoreData();
    } else {
      console.log('没有更多了');
    }
  },
  // 获取更多数据
  getMoreData() {
    this.setData({
      isLoadMore: false
    });
    // 防止多次请求分页数据
    if (this.data.page >= this.data.total_page) {
      return;
    } else {
      let page = this.data.page + 1;
      this.setData({
        page
      });
      let urlStr = app.getNetAddresss('plugin.micro.frontend.controllers.MicroShop.MicroShopByShare.get-goods');
      urlStr += '&page=' + this.data.page;
      urlStr += '&shop_id=' + this.data.shop_id;
      app._getNetWork({
        url: urlStr,
        success: (resdata) => {
          var response = resdata.data;
          if (response.result == 1) {
            var myData = response.data.goods_list.data;
            this.data.isLoadMore = true;
            this.setData({
              goodsListData: this.data.goodsListData.concat(myData)
            });
          } else {
            this.data.page = this.data.page - 1;
            this.data.isLoadMore = false;
          }
        },
        fail: function(res) {
          console.log(res);
        }
      });
    }
  },

  /**
	 * 用户点击右上角分享
	 */
  onShareTimeline: function () {
    if (this.data.shop_id) {
      var value = wx.getStorageSync('yz_uid');
      var mid = '';
      if (value) {
        mid = value;
      }
      return {
        query: 'shop_id=' + this.data.shop_id + '&mid=' +
					mid
      };
    } else {
      wx.showToast({
        title: '分享信息正在加载',
        icon: 'none',
        duration: 1500
      });
    }
  },



  /**
	 * 用户点击右上角分享
	 */
  onShareAppMessage: function(res) {
    if (res && res.from === 'menu') {
      // 来自右上角转发按钮
      if (this.data.shop_id) {
        var value = wx.getStorageSync('yz_uid');
        var mid = '';
        if (value) {
          mid = value;
        }
        console.log('/packageC/microshop/micro_shop_share_home/micro_shop_share_home?shop_id=' + this.data.shop_id + '&mid=' +mid);
        return {
          path: '/packageC/microshop/micro_shop_share_home/micro_shop_share_home?shop_id=' + this.data.shop_id + '&mid=' +
            mid
        };
      }else {
        wx.showToast({
          title: '分享信息正在加载',
          icon: 'none',
          duration: 1500
        });
      }
    }
  },
  imgHeight: function(e) {
    var winWid = wx.getSystemInfoSync().windowWidth; //获取当前屏幕的宽度
    var imgh = e.detail.height; //图片高度
    var imgw = e.detail.width; //图片宽度
    var swiperH = winWid * imgh / imgw + "px"; //等比设置swiper的高度。 即 屏幕宽度 / swiper高度 = 图片宽度 / 图片高度  ==》swiper高度 = 屏幕宽度 * 图片高度 / 图片宽度
    this.setData({
      Height: swiperH //设置高度
    });
  },
  //获取微店信息
  getMicroShop() {
    let that = this;
    that.data.isLoadMore = false;
    let urlStr = app.getNetAddresss('plugin.micro.frontend.controllers.MicroShop.default');
    app._getNetWork({
      url: urlStr,
      success: function(resdata) {
        var res = resdata.data;
        if (res.result == 1) {
          that.setData({
            isLoadMore:true,
            shopData: res.data //微店数据
          });
          that.setMicroShopUserInfo(res.data); //设置微店用户基础信息
          that.setBannerData(res.data); //设置广告
          that.setCategoryData(res.data); //设置分类
          // that.setGoodsData(res.data); //设置商品
          that.setData({
            shop_id: res.data.shop_id //设置商店id
          });
          that.getGoodList();
          that.storeShopId(res.data.shop_id);
          app._setshopid(res.data.shop_id);
          // that.initShare(); //分享设置
          // that.replaceShopId(res.data.shop_id);
        } else {
          wx.showModal({
            title: '提示',
            content: '您暂时无微店,点击确定申请？',
            success(res) {
              if (res.confirm) {
                wx.navigateTo({
                  url: '/packageC/microshop/microShop_apply/microShop_apply'
                });
              } else if (res.cancel) {
                wx.navigateBack({
                  delta: 1
                });
              }
            }
          });
        }
      },
      fail: function(res) {
        console.log(res);
      }
    });
  },
  getGoodList(){
    let urlStr = app.getNetAddresss("plugin.micro.frontend.controllers.MicroShop.MicroShopByShare.get-goods");
    app._postNetWork({
      url: urlStr,
      data: {
        shop_id:this.data.shop_id,
        mid:wx.getStorageSync('yz_uid')
      },
      success: (resdata) => {
        let res = resdata.data;
        if (res.result == 1) {
          this.setGoodsData(res);
        }else {
          wx.showToast({
            icon: "none",
            title: res.msg,
            duration: 1000,
          });
        }
      },
      fail: (res) => {
        console.log(res);
      },
    });
  },
  //设置微店用户基础信息
  setMicroShopUserInfo(data) {
    let that = this;
    that.setData({
      username: data.nickname,
      signName: data.signature,
      shop_logo: data.shop_logo,
      shop_name: data.shop_name,
      bgImg: data.shop_background == 0 ? false : data.shop_background,
      userImg: data.shop_avatar
    });
  },
  //设置广告
  setBannerData(data) {
    let that = this;
    that.setData({
      bannerData: data.carousel
    });
  },
  //设置分类
  setCategoryData(data) {
    if (app._isTextEmpty(data.category) || data.category.length == 0) {
      this.setData({
        isCategory: false
      });
      return;
    }
    this.setData({
      isCategory: true
    });
    let that = this;
    that.setData({
      category: that.chunk(data.category, 8)
    });
    console.log(this.data.category);
  },
  chunk(arr, n) {
    var result = [];
    for (var i = 0, len = arr.length; i < len; i += n) {
      result.push(arr.slice(i, i + n));
    }
    return result;
  },
  //设置商品
  setGoodsData(data) {
    this.setData({
      goodsListData: data.data.goods_list.data
    });
    this.data.total_page = data.data.goods_list.last_page;
    this.data.page = data.data.goods_list.current_page;
  },
  //存储shop_id
  storeShopId(shop_id) {
    wx.setStorage({
      key: 'setShopId',
      data: shop_id
    });
  },
  //替换shop_id
  replaceShopId(shop_id) {
    let that = this;
    //判断是否相等
    if (app._isTextEmpty(that.data.shop_idKey)) {
      wx.redirectTo({
        url: '/packageC/microshop/microShop_home/microShop_home?shop_id=' + shop_id
      });
    } else {
      if (that.data.shop_idKey != shop_id) {
        wx.redirectTo({
          url: '/packageC/microshop/microShop_home/microShop_home?shop_id=' + shop_id
        });
      }
    }
  },
  //轮播图跳转
  goimgurl(e) {
    let url = e.currentTarget.dataset.link;
    try {
      wx.navigateTo({
        url: url
      });
    } catch (e) {
      wx.showToast({
        title: '链接设置错误',
        icon: 'none',
        duration: 2000
      });
      //TODO handle the exception
    }
  },
  gohome() {
    wx.reLaunch({
      url: '/packageG/index/index'
    });
  },
  gocart() {
    wx.reLaunch({
      url: '/packageG/pages/buy/cart_v2/cart_v2'
    });
  },
  gomember() {
    wx.reLaunch({
      url: '/packageG/member_v2/member_v2'
    });
  },
  gomicroShopShareCategory() {
    //micro_shop_share_category
    wx.navigateTo({
      url: '/packageC/microshop/micro_shop_share_category/micro_shop_share_category?shop_id=' + this.data.shop_id
    });
  },
  gomicroShopShopKeeperCenter() {
    wx.navigateTo({
      url: '/packageC/microshop/microShop_ShopKeeperCenter/microShop_ShopKeeperCenter?shop_id=' + this.data.shop_id
    });
  }
});
