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 formatDate = (date, fmt) => {
  if (typeof date == 'string') {
    return date;
  }
  if (!fmt) fmt = "YYYY-MM-DD hh:mm:ss"
  if (!date || date == null) return null
  var o = {
    'M+': date.getMonth() + 1, // 月份
    'D+': date.getDate(), // 日
    'h+': date.getHours(), // 小时
    'm+': date.getMinutes(), // 分
    's+': date.getSeconds(), // 秒
    'q+': Math.floor((date.getMonth() + 3) / 3), // 季度
    'S': date.getMilliseconds() // 毫秒
  }
  if (/(Y+)/.test(fmt)) fmt = fmt.replace(RegExp.$1, (date.getFullYear() + '').substr(4 - RegExp.$1.length))
  for (var k in o) {
    if (new RegExp('(' + k + ')').test(fmt)) fmt = fmt.replace(RegExp.$1, (RegExp.$1.length === 1) ? (o[k]) : (('00' + o[k]).substr(('' + o[k]).length)))
  }
  return fmt
}

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

// 定义获取元素属性值
const $data = (event, key) => {
  let result = event.currentTarget.dataset
  if (key) {
    return result[key]
  } else {
    return result
  }
}

const auth = (auth, cb) => {
  // 获取用户设置信息
  wx.getSetting({
    withSubscriptions: true,
    success: res => {
      const {
        authSetting
      } = res
      if (!authSetting[auth]) {
        wx.authorize({
          scope: auth,
          fail: err => {
            wx.showModal({
              title: '注意',
              content: '该权限会影响功能正常使用，请再次授权！',
              showCancel: false,
              success: () => {
                wx.openSetting({
                  withSubscriptions: true,
                })
              }
            })
          }
        })
      } else {
        cb && cb()
      }
    },
    fail: err => {
      console.log(err)
      wx.showToast({
        title: '获取设置失败',
        icon: 'error'
      })
    }
  })
}

module.exports = {
  formatTime,
  formatDate,
  $data,
  auth
}