//工具类
let util = {}


//复制
util.copy=content=>{
	uni.setClipboardData({ data: content });
}

util.preview=async (src)=> {
	const urls = typeof src === 'string' ? [src] : src
	const filePath = async src => src.match(/^http/) ? src : (await uni.compressImage({ src, quality: 100 }))[1].tempFilePath
	for (let i = 0; i < urls.length; i++) {
		urls[i] = await filePath(urls[i])
	}
	uni.previewImage({ urls })
},


// 图片缓存


//拨打电话
util.call=phone=>{
	uni.showModal({
	    title: '提示',
	    content: `确定要拨打电话：${phone}吗?`,
	    success: function (res) {
	        if (res.confirm) {
				uni.makePhoneCall({
				    phoneNumber: phone //仅为示例
				});
	        } 
	    }
	});
}
util.showModal=(content,title='提示')=>{
    return new Promise((resolve,reject)=>{
        uni.showModal({
            title: title,
            content: content,
            success: (res)=>{
                resolve(res)
            }
        });
    })
}
//是否为手机号码
util.isPhone = phone => {
  let pat = /^(13[0-9]|14[579]|15[0-3,5-9]|16[6]|17[0135678]|18[0-9]|19[89])\d{8}$/
  return pat.test(phone)
}

//去除两边空格
util.trim = value => {
  if (value) {
    return value.replace(/^\s+|\s+$/gm, '')
  }
  return ''
}

//根据QueryString参数名称获取值
util.getQueryStringByName = (url, name) => {
  var result = url.match(new RegExp('[?&]' + name + '=([^&]+)', 'i'))
  if (result == null || result.length < 1) {
    return ''
  }
  return result[1]
}

//四舍五入保留2位小数（不够位数，则用0替补）
util.keepTwoDecimalFull = num => {
  var result = parseFloat(num)
  if (isNaN(result)) {
    return false
  }
  result = Math.round(num * 100) / 100
  var s_x = result.toString()
  var pos_decimal = s_x.indexOf('.')
  if (pos_decimal < 0) {
    pos_decimal = s_x.length
    s_x += '.'
  }
  while (s_x.length <= pos_decimal + 2) {
    s_x += '0'
  }
  return s_x
}

/**
 * 数组去重
 * @param {Array} arr 源数组
 * 
 * @return {Array} newArr 去重后的数组
 */
util.uniqueArray = (arr)=>{
  let newArr = []
  arr.forEach(item => {
    return newArr.includes(item) ? '' : newArr.push(item)
  })
  return newArr
}

util.checkMobile = phoneStr => {
  if (phoneStr.length < 11) {
    return false
  } else if (!/^1[3|4|5|6|7|8][0-9]\d{4,8}$/.test(phoneStr)) {
    return false
  } else {
    return true
  }
}

/**
 * 序列化对象
 * @param {Object} data 标准JS对象 { key:value,... }
 */
util.serialize = (data, isEncode = false) => {
  if (!data) return ''
  var pairs = []
  for (var name in data) {
    if (!data.hasOwnProperty(name)) continue
    if (typeof data[name] === 'function') continue
    var value =
      data[name] != null && typeof data[name] != 'undefined'
        ? data[name].toString()
        : ''
    if (isEncode) {
      name = encodeURIComponent(name)
      value = encodeURIComponent(value)
    }
    pairs.push(name + '=' + value)
  }
  return pairs.join('&')
}



//获取某一个页面上下文 context
util.getPageCtx = (idx = 0) => {
  let pages = getCurrentPages()
  if (pages.length > 0) {
    return pages[pages.length - 1 - idx] || {}
  }
  return {}
}

//获取当前页面路由
util.getCurrentRoute = () => {
  let page = util.getPageCtx()
  if (page.route) {
    return page.route
  }
  return ''
}


/* ======================== 时间日期 begin ========================== */


//日期转字符串
util.dateToString = (date)=>{
	var year = date.getFullYear();
	var month =(date.getMonth() + 1).toString(); 
	var day = (date.getDate()).toString();  
	if (month.length == 1) { 
	    month = "0" + month; 
	} 
	if (day.length == 1) { 
	    day = "0" + day; 
	}
	var dateTime = year + "-" + month + "-" + day;
	return dateTime; 
}
//字符串转日期
util.stringToDate = (dateStr,separator)=>{
	if(!separator){
	       separator="-";
	}
	var dateArr = dateStr.split(separator);
	var year = parseInt(dateArr[0]);
	var month;                     
	if(dateArr[1].indexOf("0") == 0){
	    month = parseInt(dateArr[1].substring(1));
	}else{
	     month = parseInt(dateArr[1]);
	}
	var day = parseInt(dateArr[2]);
	var date = new Date(year,month -1,day);
	return date;
}

/**
 * 天数加减
 * date传入你需要的日期，格式"xxxx-xx-xx"。addDays传要加减的日期数，往前传正数，往后传负数
 */
util.addDay=(date,addDays)=>{
	var Dates = new Date(date);
	Dates.setDate(Dates.getDate() + addDays);
	var mon = Dates.getMonth() + 1,
	    day = Dates.getDate();
	if(mon < 10){
	    mon = "0" + mon;//月份小于10，在前面补充0
	}
	if(day < 10){
	    day = "0" + day;//日小于10，在前面补充0
	}
	return Dates.getFullYear() + "-" + mon + "-" +day;
}


// 时间函数-tian=0(获取当前时间)-accuracy=1（获取年月日）
util.getTime = (tian, accuracy) => {
  //获取当前时间戳
  var timestamp = Date.parse(new Date())

  timestamp = timestamp / 1000
  var tomorrow_timetamp = timestamp - tian * 24 * 60 * 60

  var date = new Date(tomorrow_timetamp * 1000)
  //年
  var Y = date.getFullYear()
  //月
  var M =
    date.getMonth() + 1 < 10 ? '0' + (date.getMonth() + 1) : date.getMonth() + 1
  //日
  var D = date.getDate() < 10 ? '0' + date.getDate() : date.getDate()
  //时
  var h = date.getHours() < 10 ? '0' + date.getHours() : date.getHours()

  //分
  var m = date.getMinutes() < 10 ? '0' + date.getMinutes() : date.getMinutes()

  //秒
  var s = date.getSeconds() < 10 ? '0' + date.getSeconds() : date.getSeconds()

  var Time = Y + '-' + M + '-' + D
  var Time2 = Y + '-' + M + '-' + D + ' ' + h + ':' + m + ':' + s
  if (accuracy == '1') {
    return Time
  } else {
    return Time2
  }
}

// 格式化日期 2019-01-01 TT(WW)
util.dateFormat = (
  value = new Date(),
  format = 'yyyy-MM-dd',
  isInit = false
) => {
  if (value) {
    var date = typeof value == 'string' ? value.replace(/\-/g, '/') : value
    var d = new Date(date)
    var week = ''
    var label = ''
    if (isInit) {
      var cdt = new Date()
      var cur = new Date(
        cdt.getFullYear() + '/' + (cdt.getMonth() + 1) + '/' + cdt.getDate()
      )
      var diffTime = d.getTime() - cur.getTime()
      var oneDayTime = 24 * 60 * 60 * 1000
      var twoDayTime = 48 * 60 * 60 * 1000
      var threeDayTime = 72 * 60 * 60 * 1000
      let weeks = ['周日', '周一', '周二', '周三', '周四', '周五', '周六']
      if (diffTime > 0) {
        if (diffTime <= oneDayTime) {
          label = '今天'
        } else if (diffTime <= twoDayTime) {
          label = '明天'
        } else if (diffTime <= threeDayTime) {
          label = '后天'
        }
      }
      week = weeks[d.getDay()]
    }

    var o = {
      'T+': label,
      'W+': week,
      'M+': d.getMonth() + 1, //month
      'd+': d.getDate(), //day
      'h+': d.getHours(), //hour
      'm+': d.getMinutes(), //minute
      's+': d.getSeconds(), //second
      'q+': Math.floor((d.getMonth() + 3) / 3), //quarter
      S: d.getMilliseconds() //millisecond
    }

    if (/(y+)/.test(format)) {
      format = format.replace(
        RegExp.$1,
        (d.getFullYear() + '').substr(4 - RegExp.$1.length)
      )
    }
    for (var k in o) {
      if (k == 'T+' && !label) continue

      if (new RegExp('(' + k + ')').test(format)) {
        format = format.replace(
          RegExp.$1,
          RegExp.$1.length == 1
            ? o[k]
            : ('00' + o[k]).substr(('' + o[k]).length)
        )
      }
    }
    return format
  }
  return value
}

// 活动倒计时  需要在外面调用 如：setInterval("countDown()",1000);
util.countDown = (day, hour, minute, second) => {
  var flag = false
  second -= 1
  if (second == 0) {
    minute = minute - 1
    second = 60
    if (minute < 0) {
      hour = hour - 1
      minute = 59
      if (hour < 0) {
        day -= 1
        hour = 23
        if (day < 0) {
          flag = true
        }
      }
    }
  }
  if (flag) {
    return '活动结束'
  } else {
    return day + '天' + hour + '小时' + minute + '分' + second + '秒'
  }
}
// 两个时间相差 天 小时 分钟 秒 date1、date2格式：'2019-06-29 14:36:10'或'2019/06/29 14:36:10'
util.timeComparison = (date1, date2) => {
  // var date1 = '2019-06-29 14:36:10';  //开始时间
  // var date2 = new Date();    //结束时间
  var date3 = date2.getTime() - date1.getTime() //时间差的毫秒数

  //------------------------------

  //计算出相差天数
  var days = Math.floor(date3 / (24 * 3600 * 1000))

  //计算出小时数
  var leave1 = date3 % (24 * 3600 * 1000) //计算天数后剩余的毫秒数
  var hours = Math.floor(leave1 / (3600 * 1000))
  //计算相差分钟数
  var leave2 = leave1 % (3600 * 1000) //计算小时数后剩余的毫秒数
  var minutes = Math.floor(leave2 / (60 * 1000))
  //计算相差秒数
  var leave3 = leave2 % (60 * 1000) //计算分钟数后剩余的毫秒数
  var seconds = (leave3 / 1000).toFixed(1)

  return (
    ' 相差 ' +
    days +
    '天 ' +
    hours +
    '小时 ' +
    minutes +
    ' 分钟' +
    seconds +
    ' 秒'
  )
}
util.timeComparisonActive = (date1, date2, isNeedMillSecond = true) => {
  // var date1 = '2019-06-29 14:36:10';  //开始时间
  // var date2 = new Date();    //结束时间
  var date3 = date2.getTime() - date1.getTime() //时间差的毫秒数
  if (parseInt(date3) <= 0) {
    date3 = 0
  }
  //------------------------------

  //计算出相差天数
  var days = Math.floor(date3 / (24 * 3600 * 1000))

  //计算出小时数
  var leave1 = date3 % (24 * 3600 * 1000) //计算天数后剩余的毫秒数
  var hours = Math.floor(leave1 / (3600 * 1000))
  //计算相差分钟数
  var leave2 = leave1 % (3600 * 1000) //计算小时数后剩余的毫秒数
  var minutes = Math.floor(leave2 / (60 * 1000))
  //计算相差秒数
  var leave3 = leave2 % (60 * 1000) //计算分钟数后剩余的毫秒数
  if (isNeedMillSecond) {
    var seconds = (leave3 / 1000).toFixed(1)
  } else {
    var seconds = Math.floor(leave3 / 1000)
  }
  var allSeconds =
    days * 24 * 60 * 60 + hours * 60 * 60 + minutes * 60 + seconds
  hours = days * 24 + hours < 10 ? '0' + (days * 24 + hours) : days * 24 + hours
  minutes = minutes < 10 ? '0' + minutes : minutes
  seconds = seconds < 10 ? '0' + seconds : seconds
  days = days < 10 ? '0' + days : days

  var isEnd = allSeconds > 0 ? false : true

  return { days, hours, minutes, seconds, isEnd }
}


/**
 * 生成日期对象
 * @param {String,Number} value 日期 字符串 或者 毫秒数字
 * @return {Date} [date = new Date()] 日期对象
 */ 
util.createDate = (value)=>{
  let date = typeof (value) == 'string' ? value.replace(/\-/g, '/') : value
  return new Date(date)
} 
/* ======================== 时间日期 end ========================== */




export default util
