var api = require('../../../config/api.js');
var util = require('../../../utils/util.js');
var user = require('../../../utils/user.js');

var app = getApp();
Page({
  data: {
    username: '',
    mobile: '',
    code: ""
  },
  onLoad: function (options) {
    // 页面初始化 options为页面跳转所带来的参数
    // 页面渲染完成
    if (options.reg != null) {
      wx.showModal({
        title: '提示',
        content: '授权过期，请重新授权',
        showCancel: false
      });
    }

  },
  onReady: function () {

  },
  onShow: function () {
    // 页面显示
    let that = this;
    user.login().then(res => {
      console.info(res)
      that.setData({
        code: res.code
      })
    })
  },
  onHide: function () {
    // 页面隐藏

  },
  onUnload: function () {
    // 页面关闭

  },
  getdefalutUserAddress() {
    //登陆拿用户默认地址，如果没有就拿系统默认地址 
    //如果有默认地址，但是不在门店服务区域里
    util.request(api.OrderBookDefaultAddress, {}, 'get').then(res => {
      if (res.errno === 0) {
        let address = res.data;
        var city = address.city.indexOf("市辖") != -1 ? address.province : address.city;
        //通过jz_shop的shop_no关联服务力分配的门店id，拿实际的jz_shop的门店id 
        var addresInfo = {
          city: city,
          lng: address.lng,
          lat: address.lat,
          shopId: address.shopId,
          address: address.addressDetail
        }
        // that.setData({
        //   addressInfo: res.data
        // })
        wx.setStorageSync('addressInfo', addresInfo);
        // that.getIndexData(); //加载商品
      } else {
        //无默认地址时 拿系统的
        this.getdefaultCityShop();
      }
    })
  },
  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);
      // }
    })

  },

  getPhoneNumber: function (e) {
    var ivObj = e.detail.iv
    var telObj = e.detail.encryptedData
    var that = this;
    let r_userid = wx.getStorageSync('r_userid');
    if (r_userid == null || r_userid == "") r_userid = 0;
   
    console.log("请求授权登录：code:"+that.data.code+"encryptedData,"+telObj+"iv,"+ivObj+'r_userid,'+r_userid);
    //------执行Login--------- 
    util.request(api.AuthRegister, {
      code: that.data.code,
      encryptedData: telObj,
      iv: ivObj,
      r_userid: r_userid
    }).then(function (res) {
      if (res.errno === 0) {
        //存储用户信息  
        app.globalData.hasLogin = true;
        wx.setStorageSync('userInfo', res.data.userInfo);
        wx.setStorageSync('token', res.data.token);
        that.getdefalutUserAddress();
        wx.showToast({
          title: '授权注册成功',
          icon: 'success',
          duration: 2000,
          complete: function () {
            setTimeout(function () {
              wx.navigateBack({
                delta: 1
              })
            }, 2000);
          }
        })
      } else {
        console.info(res);
        wx.showToast({
          title: '授权失败请重试',
          icon: 'error',
          duration: 3000
        });
      }
    });

    //-----------------是否授权，授权通过进入主页面，授权拒绝则停留在登陆界面
    if (e.detail.errMsg == 'getPhoneNumber:fail user deny') { //用户点击拒绝 
      wx.showModal({
        title: '警告',
        content: '您点击了拒绝授权，部分功能无法使用!!!',
        showCancel: false,
        confirmText: '确定',
        success: function (res) {
          // 用户没有授权成功，不需要改变 isHide 的值
          if (res.confirm) {
            wx.switchTab({
              url: '/pages/index/index',
            })
          };
        }
      })
    }

  },
  wxLogin: function (e) {
    //console.log(e);
    if (e.detail.userInfo == null) {
      app.globalData.hasLogin = false;
      return;
    }

    app.globalData.hasLogin = false;
    wx.setStorageSync('userInfo', null);

    user.checkLogin().catch(() => {
      user.loginByWeixin(e.detail.userInfo).then(res => {
        console.log(res);
        app.globalData.hasLogin = true;
        wx.navigateBack({
          delta: 1
        })
      }).catch((err) => {
        app.globalData.hasLogin = false;
        console.log(err);
        wx.switchTab({
          url: '/pages/index/index',
        })
      });
    });
  }
})