import http from '../utils/http'
import baseUrl from '../utils/env'

const formatDate = (date, fmt = 'yyyy-MM-dd') => {

  var o = {
    "M+": date.getMonth() + 1, //月份
    "d+": date.getDate(), //日
    "h+": date.getHours() % 12 == 0 ? 12 : date.getHours() % 12, //小时
    "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 checkMobile = mobile => {
  return /^1[234578]\d{9}$/.test(mobile)
}

const error = msg => {
  wx.showToast({
    icon: 'none',
    title: msg,
  })
}

const success = msg => {
  wx.showToast({
    title: msg,
  })
}

const firstCase = str => {
  return str.charAt(0).toUpperCase() + str.slice(1)
}

const uploadFile = (path, cb = null) => {
  wx.uploadFile({
    filePath: path,
    name: 'file',
    url: baseUrl + 'uploadFile',
    success: function (res) {
      var data = JSON.parse(res.data)
      if (data.code == 0) {
        typeof cb === "function" && cb(data)
      } else {
        error('上传文件失败')
      }
    }
  })
}

const callLogin = (data, redirect, cb) => {
  http({
    url: 'loginByWechat',
    data: data,
    loadTitle: redirect ? '登录中' : '',
    success: function (res) {
      if (res.code == 0) {
        getApp().updateUserInfo(res.data)
        if (redirect) {
          wx.switchTab({
            url: '/pages/index/index',
          })
        }
        typeof cb === "function" && cb(res.data)
      }
    }
  })
}

const wechatLogin = (e, redirect = false, cb = null, bind = false) => {
  if (e.detail.errMsg == 'getUserInfo:ok') {
    // wx.checkSession({
    //   success () {
    //     that.wechatLogin(e.detail)
    //   },
    //   fail () {
    // session_key 已经失效，需要重新执行登录流程
    wx.login({
      success(res) {
        if (res.code) {
          callLogin(Object.assign({}, e.detail, {
            code: res.code,
            bind: bind
          }), redirect, cb)
        }
      }
    }) //重新登录
    // }
    // })
  }
}

const checkPass = (str) => {
  return /^(\d+[a-zA-Z]+|[a-zA-Z]+\d+)([0-9a-zA-Z]*)$/.test(str)
}

const beforeClose = (action) => {
  return false
};

module.exports = {
  formatDate,
  checkMobile: checkMobile,
  error,
  success,
  firstCase,
  uploadFile,
  wechatLogin,
  checkPass,
  beforeClose
}