const util = require('../../utils/util.js');
const api = require('../../config/api.js');
const user = require('../../utils/user.js');
const map = require('../../utils/map.js');
const area = require('../../utils/area.js');

//获取应用实例
const app = getApp();

Page({
  data: {
    newGoods: [],
    hotGoods: [],
    topics: [],
    brands: [],
    groupons: [],
    floorGoods: [],
    banner: [],
    channel: [],
    coupon: [],
    goodsCount: 0,
    hasLogin: true,
    city: '', //当前业务城市
    citys: [],
    cityIndex: 0,
    addressInfo: {
      city: '上海市',
      shopId: 0,
      lng: 121.4737,
      lat: 31.23037,
      address: "上海市浦东新区祖冲之路1505弄100号3栋"
    },
    showModalStatus: false,
    couponsData: []
  },
  onShareAppMessage: function () {
    return {
      title: '鲸致生活商城',
      desc: '鲸致生活，为美好生活',
      path: '/pages/index/index'
    }
  },

  onPullDownRefresh() {
    wx.showNavigationBarLoading() //在标题栏中显示加载
    this.getIndexData();
    wx.hideNavigationBarLoading() //完成停止加载
    wx.stopPullDownRefresh() //停止下拉刷新
  },

  getIndexData: function () {
    wx.showLoading({
      title: '加载中',
    });
    let that = this;
    console.info(that.data.addressInfo.shopId)
    util.request(api.IndexUrl, {
      city: that.data.addressInfo.city,
      shopId: that.data.addressInfo.shopId
    }).then(function (res) {
      if (res.errno === 0) {
        that.setData({
          newGoods: res.data.newGoodsList,
          hotGoods: res.data.hotGoodsList,
          topics: res.data.topicList,
          //brands: res.data.brandList,
          //floorGoods: res.data.floorGoodsList,
          banner: res.data.banner,
          //groupons: res.data.grouponList,
          channel: res.data.channel,
          //coupon: res.data.couponList
        });
        //console.info(res.data.banner);
      }
      wx.hideLoading();
    });
    util.request(api.GoodsCount).then(function (res) {
      that.setData({
        goodsCount: res.data
      });
    });
  },
  youhuiquan() {
    //进入小程序优惠券展示
    let that = this;
    util.request(api.CouponRegister, {}).then(function (res) {
      console.info(res.data);
      if (res.errno === 0 && res.data.length > 0&&wx.getStorageSync('userInfo').nickName == null) {
        that.setData({
          showModalStatus: true,
          couponsData: res.data
        })
      }
    })
  },
  onLoad: function (options) {
    let that = this;

    //新人登陆优惠券发放判断 !app.globalData.hasLogin ||
    if (wx.getStorageSync('userInfo').id == null) {
      console.log('未登陆进入' + app.globalData.hasLogin + "----" + wx.getStorageSync('userInfo').id);
      that.youhuiquan();
    }

    // 页面初始化 options为页面跳转所带来的参数  

    //邀好友60现金券走这里，然后要注册登陆
    console.log("options.rId" + options.rId);
    if (options.rId) {
      wx.setStorageSync('r_userid', options.rId);
    }
    var shareId;
    if (options.scene) {
      //这个scene的值存在则证明首页的开启来源于朋友圈分享的图,同时可以通过获取到的goodId的值跳转导航到对应的详情页
      var scene = decodeURIComponent(options.scene);
      console.log(scene);
      //console.info(scene); sId:分享id
      //goods,1181009;rId,10;sId:0

      //三种格式(1) rId,2   (2)goods,3;rId,2 (3)goods,3;rId,sId:10（阿姨开单分享）

      if (scene.indexOf("rId") >= 0||scene.indexOf("r_userid") >= 0) {//兼容之前的r_userid
        let value = null;
        if (scene.indexOf(";") > 0) { //包含分号 表示是good和user两种
          value = scene.split(";")[1];
          //console.info(value);
          wx.setStorageSync('r_userid', value.split(",")[1]); //获取r_userid
          if (scene.indexOf("sId") >= 0||scene.indexOf("shareId") >= 0) { //阿姨开单分享id  ||兼容之前的shareId
            shareId = scene.split(";")[2].split(",")[1];
          }
          scene = scene.split(";")[0];
          //console.info(scene);

        } else {
          value = scene;
          wx.setStorageSync('r_userid', value.split(",")[1]);

          // 引荐人分享
          console.log('只有rid,进入引荐人');
          let rId=value.split(",")[1];
          wx.navigateTo({
            url: '../ucenter/parter/recommend/recommend?rId=' + rId 
          });

          // return; //结束逻辑 不在往下进行;   
        }
      }


      let info_arr = [];
      info_arr = scene.split(',');
      let _type = info_arr[0];
      let id = info_arr[1];
      console.info(_type);

      if (_type == 'goods') {
        if (shareId) {
          wx.navigateTo({
            url: '../goods/goods?id=' + id + '&shareId=' + shareId
          });
        } else {
          wx.navigateTo({
            url: '../goods/goods?id=' + id
          });
        }
      } else if (_type == 'groupon') {
        wx.navigateTo({
          url: '../goods/goods?grouponId=' + id
        });
      } else {
        wx.navigateTo({
          url: '../index/index'
        });
      }
    }

    // 页面初始化 options为页面跳转所带来的参数
    if (options.grouponId) {
      //这个pageId的值存在则证明首页的开启来源于用户点击来首页,同时可以通过获取到的pageId的值跳转导航到对应的详情页
      wx.navigateTo({
        url: '../goods/goods?grouponId=' + options.grouponId
      });
    }

    // 页面初始化 options为页面跳转所带来的参数
    if (options.goodId) {
      //这个goodId的值存在则证明首页的开启来源于分享,同时可以通过获取到的goodId的值跳转导航到对应的详情页
      if (options.share_id)
        wx.navigateTo({
          url: '../goods/goods?id=' + options.goodId + '&share_id=' + options.share_id
        });
      else
        wx.navigateTo({
          url: '../goods/goods?id=' + options.goodId
        });
    }

    // 页面初始化 options为页面跳转所带来的参数
    if (options.orderId) {
      //这个orderId的值存在则证明首页的开启来源于订单模版通知,同时可以通过获取到的pageId的值跳转导航到对应的详情页
      wx.navigateTo({
        url: '../ucenter/orderDetail/orderDetail?id=' + options.orderId
      });
    }
  },
  getLocation() {
    let that = this
    //获取地理位置 缓存中是否有地址
    /**
     * 分2重判断 
     * 1：缓存中是否有地址 
     * 2：未登录 取当前地理位置判断
     */
    var addressInfo = wx.getStorageSync("addressInfo");
    if (addressInfo) {
      console.info(addressInfo)
      that.setData({
        addressInfo: addressInfo
      })
      this.getIndexData();
    } else {
      if (!app.globalData.hasLogin) { //未登陆
        map.getCity().then(res => {
          console.log("getcity啊啊啊啊啊啊啊啊啊啊" + res);
          that.setData({
            addressInfo: res
          })
          console.info(res)
          this.getIndexData();
        }).catch(res => { //reject内容 1：未授权 2：不在服务范围 3：异常解析
          console.log(res);
          wx.showModal({
            title: '提醒',
            showCancel: false,
            content: '您未授权或非业务城市，已切换成默认【上海市】'
          })
          // if (res == 1 || res == 2) {
            this.getdefaultCityShop();
          // }
          //路由到上海市 latitude: 31.23037 longitude: 121.4737   

        });
      }
    }
  }, 
  getdefaultCityShop() {
    let that = this;
    util.request(api.getDefaultCityShop, {}, 'get').then(res => {
      if (res.errno === 0) {
        that.setData({
          addressInfo: res.data
        })
        wx.setStorageSync('addressInfo',  res.data);
        that.getIndexData();
      } else {
        util.showErrorToast(res.errmsg);
      }
    })

  },
  goCheckAddress() {
    user.checkLogin().then(res => {
      wx.navigateTo({
        url: '/pages/ucenter/address/address',
      })
    }).catch(res => {
      wx.navigateTo({
        url: '/pages/auth/login/login',
      })
    })

  },
  onReady: function () {
    // 页面渲染完成
  },
  onShow: function () {
    this.getLocation();
  },
  goLogin: function (e) {
    if (e.detail.userInfo == null) {
      app.globalData.hasLogin = false;
      util.showErrorToast('微信授权失败');
      return;
    }
    app.globalData.hasLogin = false;
    wx.setStorageSync('userInfo', null);

    user.loginByWeixin(e.detail.userInfo).then(res => {
      //跳转注册页
      if (user.checkRegisted() == false) {
        wx.navigateTo({
          url: "/pages/auth/register/register"
        });
      } else {
        this.setData({
          hasLogin: true
        })
      }
    }).catch((err) => {
      app.globalData.hasLogin = false;
    });
  },
  onHide: function () {
    // 页面隐藏
  },
  onUnload: function () {
    // 页面关闭
  },
  getCoupon(e) {
    if (!app.globalData.hasLogin) {
      wx.navigateTo({
        url: "/pages/auth/login/login"
      });
    }

    let couponId = e.currentTarget.dataset.index
    util.request(api.CouponReceive, {
      couponId: couponId
    }, 'POST').then(res => {
      if (res.errno === 0) {
        wx.showToast({
          title: "领取成功"
        })
      } else {
        util.showErrorToast(res.errmsg);
      }
    })
  },
  goinviteFriends(e) {
    console.log(app.globalData.hasLogin);
    //跳转到邀请页面
    if (app.globalData.hasLogin) {
      wx.navigateTo({
        url: '/pages/activity/invitefriends/inviteFriends'
      })
    } else {
      wx.navigateTo({
        url: "/pages/auth/login/login"
      });
    };
  },
  guanbicoupon() {
    this.setData({
      showModalStatus: false
    })
  },
  gocoupon(e) {
    this.setData({
      showModalStatus: false
    })
    if (!app.globalData.hasLogin) {
      wx.navigateTo({
        url: "/pages/auth/login/login"
      });
    };
  },
  myshowtost: function (v) {
    wx.showToast({
      title: v,
      icon: 'none',
      duration: 3000
    })
  },
  goCatalog(){
    wx.navigateTo({
      url: '/pages/tabBar/catalog/catalog',
    })
  },
  goHotGoods(){
    wx.navigateTo({
      url: '/pages/goods/hotGoods/hotGoods',
    })
  }

})