var netUtil = require('network.js')
var baseUrl = require('wxconstant.js').BaseUrl()
var getUrl = require('wxconstant.js').getUrl
var dateutil = require('DateTime.js')

//公用获取openid方法
function getComOpenid(){
  var openid
  wx.login({
    success: function (res) {
      var url = baseUrl + getUrl.getOpenid
      if (res.code) {
        var data = {
          code: res.code
        }
        netUtil.requestLoading(url, data, '正在请求...', 'GET', function (res) {
          if (res.data) {
            if (res.data.data.openid) {
              openid = res.data.data.openid
              wx.setStorageSync('openid', openid)
            }
          }
        }, function (res) {
          wx.showToast({
            title: '数据获取失败',
            icon: 'none',
            duration: 2000
          })
        })
      }
    }
  })
  return openid
}

/**
 * 公共获取用户信息的方法 
 */
function getPersonlEmp(){
  var data = { openid: wx.getStorageSync('openid') }
  var url = baseUrl + getUrl.getEmp
  netUtil.requestLoading(url, data, '正在加载数据...', 'GET', function (res) {
    if(res.data.success && res.data.data){
      wx.setStorageSync("myInfoData", res.data.data)
      // console.log('myInfoData', wx.getStorageSync('myInfoData'))
    }
  }, function (res) {
    wx.showToast({
      title: '加载数据失败',
      icon: 'none',
      duration: 2000
    })
  })
}

/**
 * 公共获取用户是否关联绑定公司信息
 */
function judgeisReg(){
  var data = {
    openid: wx.getStorageSync('openid'),
  }
  var url = baseUrl + getUrl.getRank
  netUtil.requestLoading(url, data, '正在加载数据...', 'GET', function (res) {
    if (res.data.success) {
      var isregistered = res.data.data.isregistered
      wx.setStorageSync('isregistered', isregistered)
      if (!isregistered){
        wx.showModal({
          title: '提示',
          content: '您当前尚未与企业关联绑定，是否立即去绑定?',
          success: function (res) {
            if (res.confirm) {
              wx.navigateTo({
                url: '../bindphone/bindphone',
              })
            } else if (res.cancel) {
              return
            }
          }
        })
      }
    }
  }, function (res) {
    wx.showToast({
      title: '加载数据失败',
      icon: 'none',
      duration: 2000
    })
  })
}
function getAccessToken(){
  var data = {  }
  var url = baseUrl + getUrl.getAccessToken
  netUtil.requestLoading(url, data, '正在加载数据...', 'GET', function (res) {
    if(res.data.success && res.data.data){
      var access_token = JSON.parse(res.data.data).access_token
      console.log('access_token=', access_token)
      wx.setStorageSync('access_token', access_token)
      // console.log('access_token=', wx.getStorageSync('access_token'))
    }
  }, function (res) {
    wx.showToast({
      title: '加载数据失败',
      icon: 'none',
      duration: 2000
    })
  })
}
module.exports = {
  judgeisReg: judgeisReg,
  getComOpenid: getComOpenid,
  getPersonlEmp: getPersonlEmp,
  getAccessToken: getAccessToken
}
