// /pages/common.wxs

var formatDate = function (date, identity) {
  var date = getDate(date)
  var year = date.getFullYear()
  var month = date.getMonth() + 1
  var day = date.getDate()

  var ident = identity ? '.' : '-'
  return [year, month, day].map(formatNumber).join(identity)
}

var formatDateTime = function (date) {
  var date = getDate(date)
  var year = date.getFullYear()
  var month = date.getMonth() + 1
  var day = date.getDate()
  var hour = date.getHours()
  var minute = date.getMinutes()
  var second = date.getSeconds()

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

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

/**
 * 秒转分
 */
var secToMinu = function (second) {
  return Math.round(second / 60)
}

/**
 * 性别文字转换
 */
var formatSex = function (sex) {
  if (1 == sex) {
    return '男'
  } else if (2 == sex) {
    return '女'
  } else {
    return '未知'
  }
}

/**
 * 数值保留小数位
 */
var numFixed = function (num, fixed) {
  var fixed = typeof fixed === 'number' ? fixed : 0;
  return parseFloat(num).toFixed(fixed);
}

/**
 * 根据两点经纬度计算距离
 */
var getDistance = function (lat1, lng1, lat2, lng2) {
  lat1 = lat1 || 0;
  lng1 = lng1 || 0;
  lat2 = lat2 || 0;
  lng2 = lng2 || 0;

  var rad1 = lat1 * Math.PI / 180.0;
  var rad2 = lat2 * Math.PI / 180.0;
  var a = rad1 - rad2;
  var b = lng1 * Math.PI / 180.0 - lng2 * Math.PI / 180.0;

  var r = 6378137;
  var d = r * 2 * Math.asin(Math.sqrt(Math.pow(Math.sin(a / 2), 2) + Math.cos(rad1) * Math.cos(rad2) * Math.pow(Math.sin(b / 2), 2)));
  if (d >= 1000) {
    d = d / 1000;
    return d.toFixed(2) + 'km';
  } else {
    return d.toFixed(0) + 'm';
  }
}

var nextLevel = function (n) {
  return parseInt(n) + 1
}

/**
 * 判断item是否在数组arr中
 */
var inArray = function (arr, item) {
  return arr.indexOf(item) == -1 ? false : true;
}

module.exports = {
  formatDate: formatDate,
  formatDateTime: formatDateTime,
  formatSex: formatSex,
  numFixed: numFixed,
  getDistance: getDistance,
  nextLevel: nextLevel,
  secToMinu: secToMinu,
  inArray: inArray
};
