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
}

const formatHtml = content => {
  content = content.replace(/\<img/gi, '<img style="width:100% !important;height:auto !important;margin:0;display:flex;" ');
  content = content.replace(/style="/gi, 'style="max-width:100% !important;table-layout:fixed;word-wrap:break-word;word-break;break-all;');
  content = content.replace(/\<table/gi, '<table style="table-layout:fixed;word-wrap:break-word;word-break;break-all;" ');
  content = content.replace(/\<td/gi, '<td  cellspacing="0" cellpadding="0" border="0" style="display:block;vertical-align:top;margin: 0px; padding: 0px; border: 0px;outline-width:0px;" ');
  content = content.replace(/width=/gi, 'sss=');
  content = content.replace(/height=/gi, 'sss=');
  content = content.replace(/ \/\>/gi, ' style="max-width:100% !important;height:auto !important;margin:0;display:block;" \/\>');
  return content;
}

const endOfStartTime = (startTime, endTime) => {
  let result = {
    day: '00',
    hou: '00',
    min: '00',
    sec: '00'
  }
  if (endTime - startTime > 0) {
    let time = (endTime - startTime) / 1000;
    // 获取天、时、分、秒
    let day = parseInt(time / (60 * 60 * 24));
    let hou = parseInt(time % (60 * 60 * 24) / 3600);
    let min = parseInt(time % (60 * 60 * 24) % 3600 / 60);
    let sec = parseInt(time % (60 * 60 * 24) % 3600 % 60);
    result = {
      day: `${timeFormat(day)}`,
      hou: `${timeFormat(hou)}`,
      min: `${timeFormat(min)}`,
      sec: `${timeFormat(sec)}`
    }
  }
  return result
}

// 小于10的格式化函数
const timeFormat = (times) => {
  return times < 10 ? '0' + times : times;
}

const dateToTimestamp = (dateStr) => {
  if (!dateStr) {
    return ''
  }
  let newDataStr = dateStr.replace(/\.|\-/g, '/')
  let date = new Date(newDataStr);
  let timestamp = date.getTime();
  return timestamp
}

// 检查是否授权
const checkAuthInfo = (fn, unNeedAuth) => {
  if (wx.getStorageSync('loginResult').userId) {
    fn()
  } else if (!unNeedAuth) {
    wx.hideLoading()
    wx.navigateTo({
      url: '/pages/login/login'
    })
  }
}

/**
 * 手机号正则校验
 */
const checkPhoneNumber = (phoneNumber) => {
  var regexp = /^[1]([3-9])[0-9]{9}$/
  return regexp.test(phoneNumber)
}

/**
 * 用户名正则校验
 */
const checkUserName = (userName) => {
  var regexp = /^([a-zA-Z0-9_]{4,16})$/
  return regexp.test(userName)
}
/**
 * 时间戳转化为年 月 日 时 分 秒
 * number: 传入时间戳
 * format：返回格式，支持自定义，但参数必须与formateArr里保持一致
 */
function timestampToDate(timestamp) {
  if (timestamp) {
    const date = new Date(timestamp * 1000); 
    const year = date.getFullYear();
    const month = (date.getMonth() + 1).toString().padStart(2, '0');
    const day = date.getDate().toString().padStart(2, '0');
    const hours = date.getHours().toString().padStart(2, '0');
    const minutes = date.getMinutes().toString().padStart(2, '0');
    const seconds = date.getSeconds().toString().padStart(2, '0');
    return `${year}-${month}-${day} ${hours}:${minutes}:${seconds}`;
  }
  return "";
}

//经纬度转距离
function getDistance(point1, point2) {
  let R = 6371000; // 地球平均半径，单位：米
  let lat1 = point1.latitude * Math.PI / 180;
  let lat2 = point2.latitude * Math.PI / 180;
  let lon1 = point1.longitude * Math.PI / 180;
  let lon2 = point2.longitude * Math.PI / 180;
  // Haversine公式
  let a = Math.sin((lat2 - lat1) / 2) * Math.sin((lat2 - lat1) / 2) +
          Math.cos(lat1) * Math.cos(lat2) * Math.sin((lon2 - lon1) / 2) * Math.sin((lon2 - lon1) / 2);
  let c = 2 * Math.atan2(Math.sqrt(a), Math.sqrt(1 - a));
  let d = R * c; // 初始计算得到的距离，单位：米
  if (d >= 1000) {
      return (d / 1000).toFixed(2) + "千米";
  } else {
      return d + "米";
  }
}
module.exports = {
  dateToTimestamp: dateToTimestamp,
  formatTime: formatTime,
  formatHtml: formatHtml,
  endOfStartTime: endOfStartTime,
  checkAuthInfo: checkAuthInfo,
  checkPhoneNumber: checkPhoneNumber,
  checkUserName: checkUserName,
  timestampToDate:timestampToDate,
  getDistance:getDistance
}