// utils/util.js
// 获取全局的应用实例
const app = getApp();

/**
 +----------------------------------------------------------
 * 用户登录判断，主要用于页面中
 * mode 模式选项有：nomust可选性、must登录
 +----------------------------------------------------------
 */
const checkLoginState = function checkLoginState(reUrl) {
  var that = this
  
  wx.request({
    url: app.mp_url + 'user.php?rec=check_login_state',
    data: {
      'user_id': wx.getStorageSync('user_id'),
      'shell': wx.getStorageSync('shell')
    },
    method:'POST',
    header: {
      "Connect-Key" : wx.getStorageSync('connect_key'),
      'Content-Type': 'application/x-www-form-urlencoded'
    },
    success: function (res) {
      if (res.data.msg == 'fail') { // PHP中抛出的错误提示
        wx.reLaunch({
          url: '/pages/user/login_weixin'
        })
      } else if (res.data.phone == 'no' && res.data.login_phone) {
        // 验证是否获取过或者已经设置过手机号，该功能必须是认证的公众号，所以测试时先注释以下代码，正式使用时去掉注释
        wx.reLaunch({
          url: '/pages/user/login_weixin'
        })
      }
    },
    fail: function() {
      console.log('接口调用失败')
      wx.reLaunch({
        url: '/pages/user/login_weixin'
      })
    }
  })
}

// 用户登录判断，主要用于操作中，必须登录状态为真才可以执行
const checkActionPermission = function checkActionPermission(reUrl) {
  if (!wx.getStorageSync('loginEd')) {
    wx.reLaunch({
      url: reUrl ? reUrl : douGetCurrentPages()
    })
  }
}

// tabBar显示购物车数量
const showCartNumber = function showCartNumber() {
  wx.request({
    url: app.mp_url + 'databox.php?rec=cart_number',
    data: {
      'user_id': wx.getStorageSync('user_id'),
      'shell': wx.getStorageSync('shell')
    },
    header: {
      "Connect-Key" : wx.getStorageSync('connect_key')
    },
    success: function(res) {
      if (res.data.cart_number > 0) {
        wx.setTabBarBadge({
          index: 2,
          text: res.data.cart_number
        })
      } else {
        wx.hideTabBarRedDot({
          index: 2
        })
      }
    }
  })
}

// 重新生成通信标识时间
const reConnectKeyTime = function reConnectKeyTime() {
  if (wx.getStorageSync('connect_key')) {
    var nowTime = new Date().getTime()
    var connectKeyTime = wx.getStorageSync('connect_key_time')
    
    // 通信标识有效期为 1 小时，超过就重置 1 小时等于 1000 * 60 * 60
    if ((nowTime - connectKeyTime) / (1000 * 60 * 60) > 1) {
      wx.request({
        url: app.mp_url + 'user.php?rec=re_connect_key_time',
        data: {
          'user_id': wx.getStorageSync('user_id'),
          'shell': wx.getStorageSync('shell')
        },
        method:'POST',
        header: {
          "Connect-Key" : wx.getStorageSync('connect_key'),
          'Content-Type': 'application/x-www-form-urlencoded'
        },
        success: function (res) {
          if (res.data.user.connect_key) {
            // 通信标识
            wx.setStorageSync('connect_key', res.data.user.connect_key)
            wx.setStorageSync('connect_key_time', new Date().getTime()) // 通信标识生成时间

            wx.reLaunch({
              url: '/pages/index/index'
            })
          }
        }
      })
    }
  }
}

const formatTime = date => {
  const year = date.getFullYear()
  const month = date.getMonth() + 1
  const day = date.getDate()
  const hour = date.getHours()
  const minute = date.getMinutes()
  const second = date.getSeconds()

  return [year, month, day].map(formatNumber).join('/') + ' ' + [hour, minute, second].map(formatNumber).join(':')
}

const formatNumber = n => {
  n = n.toString()
  return n[1] ? n : '0' + n
}

// 获取当前页带参数的url
const douGetCurrentPages = function douGetCurrentPages() {
  var pages = getCurrentPages() // 获取加载的页面
  var currentPage = pages[pages.length-1] // 获取当前页面的对象
  var url = currentPage.route // 当前页面url
  var options = currentPage.options // 如果要获取url中所带的参数可以查看options

  //拼接url的参数
  var urlWithArgs = url + '?'
  for(var key in options){
    var value = options[key]
    urlWithArgs += key + '=' + value + '&'
  }
  
  return '/' + urlWithArgs.substring(0, urlWithArgs.length-1)
}

const showShareMenu = function showShareMenu() {
  wx.showShareMenu({
    withShareTicket: true
  })
}

// 弹窗提示
const douMsg = function douMsg(msg, url='') {
  wx.showToast({
    title: msg,
    icon: 'none',
    duration: 2000
  })
 
  if (url) {
    setTimeout(function () {
      wx.navigateTo({
        url: url
      })
    }, 2000)
  }
}

module.exports = {
  formatTime: formatTime,
  checkLoginState: checkLoginState,
  checkActionPermission: checkActionPermission,
  showCartNumber: showCartNumber,
  reConnectKeyTime: reConnectKeyTime,
  douGetCurrentPages: douGetCurrentPages,
  showShareMenu: showShareMenu,
  douMsg: douMsg
}


