import Md5 from './md52'
import Base64 from './base64'
import Cache from './cache'
import Global from './global'

//缓存 该缓存只在本文件调用
let _storage = {}
Cache.defineProperty(_storage, 'refreshPage')

//工具类
let util = {}

//md5加密
util.md5 = value => {
  return Md5(value)
}

//base64编码
util.base64Encode = value => {
  return Base64.encode(value)
}

//base64解码
util.base64Decode = value => {
  try {
    return Base64.decode(value)
  } catch (ex) {
    return value
  }
}

//是否为手机号码
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]
}

// 时间函数-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
}

//四舍五入保留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
}

// 活动倒计时  需要在外面调用 如：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 {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('&')
}

// 判定指定路由是否在刷新队列
util.isInRefreshList = (route = '') => {
  if (!route) return false
  let list = _storage.refreshPage || []
  return list.indexOf(route) != -1
}

// 添加指定页面到待刷新页面
util.refreshPage = (routes = []) => {
  let list = _storage.refreshPage || []

  for (var i in routes) {
    let route = routes[i]
    if (route.indexOf('/') === 0) {
      console.error('routes[' + i + "] 不应该以 '/' 开头")
    } else {
      if (!list.includes(route)) {
        list.push(route)
        console.log('refreshPage push', list)
      }
    }
  }
  _storage.refreshPage = list
}

// 判定是否刷新当前页面并执行刷新
util.doIsRefreshPage = route => {
  let isRefresh = false
  if (typeof route == 'string') {
    let page = route.indexOf('/') === 0 ? route.substring(1) : route
    let list = _storage.refreshPage || []
    let temp = []
    for (var i in list) {
      let item = list[i]
      if (item == page) {
        isRefresh = true
      } else {
        temp.push(item)
      }
    }
    _storage.refreshPage = temp
  }
  return isRefresh
}

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

/**
 * 生成日期对象
 * @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)
} 

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

//更新管理
util.updateManager = () => {
  if (
    [
      Global.platform.baidu,
      Global.platform.weixin,
      Global.platform.toutiao
    ].includes(process.env.VUE_APP_PLATFORM)
  ) {
    const updateManager = uni.getUpdateManager()
    updateManager.onCheckForUpdate(res => {
      // 请求完新版本信息的回调
      // console.log('updateManager', res.hasUpdate)
    })
    updateManager.onUpdateReady(() => {
      wx.showModal({
        title: '更新提示',
        content: '新版本已经准备好，是否重启应用？',
        success: res => {
          if (res.confirm) {
            // 新的版本已经下载好，调用 applyUpdate 应用新版本并重启
            updateManager.applyUpdate()
          }
        }
      })
    })
    updateManager.onUpdateFailed(() => {
      // 新版本下载失败
    })
  }
}

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.subscribe = (tmplIds) => {
	return new Promise((resolve, reject) => {
	  uni.requestSubscribeMessage({
		tmplIds,
		success(res) {
		  resolve(res)
		},
		fail(err) {
		  reject(err)
		}
	  })
	})
}

//回到上一页刷新页面
util.isReloadAndBack = () => {
    let prePage=util.getPageCtx(1)
	prePage.setData({
		"reload":true
	})
	uni.navigateBack({
		delta:1
	})
}

//onshow方法通过刷新mescroll数据
util.reload = (mescroll) => {
    let page= util.getPageCtx()
    if (page.data.reload) {
    	mescroll.resetUpScroll();
    	page.data.reload=false  
    }
}

util.showModal=(content,isShowCancel=true,title='提示',)=>{
    return new Promise((resolve,reject)=>{
        uni.showModal({
			title: title,
			content: content,
			showCancel:isShowCancel,
			success: (res)=>{
				if (res.confirm) {
					resolve(res)
				} 
			}
		});
	})
}

util.showLoading=(title='加载中...')=>{
	uni.showLoading({
		title
	})
}

export default util
