
/**
 * 提取文字颜色.
 *  @author pengliang
 */
export function extractColorByText(text) {
  const temp = []

  for (let index = 0; index < text.length; index++) {
    temp.push(parseInt(text[index].charCodeAt(0), 10).toString(16))
  }

  const color = temp.slice(0, 6).join('').slice(0, 6)
  return '#' + color
}

/**
 * 本月最后一天.
 */
export function getMonthLastDate() {
  var year = new Date().getFullYear()
  var month = new Date().getMonth() + 1
  var lastDate = new Date(year, month, 0).getDate()
  month = month < 10 ? '0' + month : month
  return new Date(`${year}/${month}/${lastDate} 23:59:59`)
}

/**
 * 字节格式化字符, 已千字节计算..
 *
 * @author pengliang
 */
export function bytesFomater(bytes) {
  if (!bytes) {
    return { value: 0, unit: 'B', fomater: '0 B' }
  }
  const k = 1000
  const sizes = ['B', 'KB', 'MB', 'GB', 'TB', 'PB', 'EB', 'ZB', 'YB']
  const i = Math.floor(Math.log(bytes) / Math.log(k))
  const value = (bytes / Math.pow(k, i)).toPrecision(3)
  const unit = sizes[i]
  return { value, unit, fomater: `${value} ${unit}` }
}

/**
 * list to map
 * @author pengliang
 */
export function toMap(list, filed) {
  const result = {}
  if (!list || list.length === 0 || !filed) {
    return result
  }
  list.forEach(item => {
    result[item[filed]] = item
  })
  return result
}

/**
 * 是否mock环境
 * @author pengliang
 */
export function isMock() {
  return process.env.VUE_APP_START_MOCK === 'true'
}

/**
 * 创建scrpt标签
 * @author pengliang
 * @param {*} text
 */
export function createScript(url) {
  return new Promise((resolve, reject) => {
    const script = document.createElement('script')
    script.type = 'text/javascript'
    script.src = url
    document.getElementsByTagName('head')[0].appendChild(script)
    // 引入成功
    script.onload = function() {
      resolve()
    }
    // 引入失败
    script.onerror = function() {
      reject()
    }
  })
}

/**
 * 复制文本
 * @author pengliang
 * @param {*} text
 */
export function copyText(text) {
  try {
    const input = document.createElement('input')
    document.body.appendChild(input)
    input.setAttribute('readonly', 'readonly')
    input.setAttribute('value', text)
    input.select()
    input.setSelectionRange(0, text.length)
    document.execCommand('copy')
    document.body.removeChild(input)
    return Promise.resolve()
  } catch (error) {
    return Promise.reject(error)
  }
}

/**
 * 获取element ui 的文件上传file
 * @param {*} filename
 * @returns
 */
export function getElementUiUploadFile(filename) {
  if (!filename) {
    return []
  }
  return [{
    name: filename.substring(filename.lastIndexOf('/')),
    url: filename
  }]
}

/**
 * 合并数组并且去除重复
 * @param {*} arr1
 * @param {*} arr2
 * @returns
 */
export function delArrays(souceArray, delArray) {
  for (var deIndex = 0; deIndex < delArray.length; deIndex++) {
    for (var souceIndex = 0; souceIndex < souceArray.length; souceIndex++) {
      if (souceArray[souceIndex] === delArray[deIndex]) {
        souceArray.splice(souceIndex, 1)
      }
    }
  }
  return souceArray
}

/**
 * 生成uuid
 */
export function uuid() {
  var s = []
  var hexDigits = '0123456789abcdef'
  for (var i = 0; i < 36; i++) {
    s[i] = hexDigits.substr(Math.floor(Math.random() * 0x10), 1)
  }
  s[14] = '4' // bits 12-15 of the time_hi_and_version field to 0010
  s[19] = hexDigits.substr((s[19] & 0x3) | 0x8, 1) // bits 6-7 of the clock_seq_hi_and_reserved to 01
  s[8] = s[13] = s[18] = s[23] = '-'

  var uuid = s.join('')
  return uuid
}

/**
 * 转换描述
 * @param {*} value 值
 * @param {*} descriptionMapping {name:'',value:''}描述映射
 */
export function convertDescription(value, descriptionMapping) {
  const unknownStr = '未知'
  if ((!value && value !== 0) || !descriptionMapping || descriptionMapping.length === 0) {
    return unknownStr
  }
  for (let index = 0; index < descriptionMapping.length; index++) {
    const data = descriptionMapping[index]
    if (!data || (!data.value && data.value !== 0)) {
      continue
    }
    if (data.value === value) {
      return data.name
    }
  }
  return unknownStr
}

/**
 * 是否是对象.
 */
export function isObject(target) {
  return target && typeof target === 'object' && !Array.isArray(target)
}

/**
 * 是否是数组.
 */
export function isArray(target) {
  return Array.isArray(target)
}

/**
 * 合并对象.
 */
export function mergeObject(source, target) {
  if (!source && !target) {
    return {}
  }

  if (!source) {
    return !!target && isObject(target) ? deepClone(target) : {}
  }

  if (!target) {
    return !!source && isObject(source) ? deepClone(source) : {}
  }

  const resultObj = deepClone(source)
  for (const key in target) {
    const sourceObj = resultObj[key]
    const targetObj = target[key]

    if (!isObject(sourceObj) || !isObject(targetObj)) {
      resultObj[key] = deepClone(target[key])
      continue
    }
    resultObj[key] = mergeObject(sourceObj, targetObj)
  }
  return resultObj
}

/**
 * 递归拷贝
 * @author pengliang
 * @param {*} target
 */
export function deepClone(target) {
  let result
  if (typeof target === 'object') {
    if (Array.isArray(target)) {
      result = []
      for (const i in target) {
        result.push(deepClone(target[i]))
      }
      return result
    }
    if (target === null) {
      return null
    }
    if (target.constructor === RegExp) {
      return target
    }
    result = {}
    for (const i in target) {
      result[i] = deepClone(target[i])
    }
    return result
  }
  result = target
  return result
}

/**
 * 获取年龄
 * @author pengliang
 * @since 2020/3/2
 */
export function getAge(strBirthday) {
  var returnAge
  var strBirthdayArr = strBirthday.split('-')
  var birthYear = Number(strBirthdayArr[0])
  var birthMonth = Number(strBirthdayArr[1])
  var birthDay = Number(strBirthdayArr[2])

  var d = new Date()
  var nowYear = d.getFullYear()
  var nowMonth = d.getMonth() + 1
  var nowDay = d.getDate()

  if (nowYear === birthYear) {
    // 同年 则为0岁
    return 0
  }
  var ageDiff = nowYear - birthYear // 年之差
  if (ageDiff > 0) {
    if (nowMonth === birthMonth) {
      var dayDiff = nowDay - birthDay// 日之差
      if (dayDiff < 0) {
        returnAge = ageDiff - 1
      } else {
        returnAge = ageDiff
      }
    } else {
      var monthDiff = nowMonth - birthMonth// 月之差
      if (monthDiff < 0) {
        returnAge = ageDiff - 1
      } else {
        returnAge = ageDiff
      }
    }
  } else {
    returnAge = -1// 返回0 表示出生日期输入错误 晚于今天
  }

  return returnAge// 返回周岁年龄
}

/**
 * 获取当前日期前 day 天date 对象
 * @param {*} day number
 */
export function beforeDateObject(day) {
  const dateTime = new Date()
  dateTime.setTime(dateTime.getTime() - 3600 * 1000 * 24 * day)
  return dateTime
}

/**
 * 获取最近的日期
 * @param {*} day number
 * @param delimiter 分割符号, 默认-
 */
export function recentDate(day, delimiter) {
  day = day || 0
  delimiter = delimiter || '-'
  const today = new Date()
  const targetday_milliseconds = today.getTime() + 1000 * 60 * 60 * 24 * day
  today.setTime(targetday_milliseconds)
  var tYear = today.getFullYear()
  var tMonth = today.getMonth()
  var tDate = today.getDate()
  tMonth = doHandleMonth(tMonth + 1)
  tDate = doHandleMonth(tDate)
  function doHandleMonth(month) {
    var m = month
    if (month.toString().length === 1) {
      m = '0' + month
    }
    return m
  }
  return tYear + delimiter + tMonth + delimiter + tDate
}

/**
 * 获取最近的日期集合
 * @param {*} day number
 */
export function recentDateArrays(day) {
  const resultArrays = []
  if (day === 0) {
    resultArrays.push(recentDate(0))
    return resultArrays
  }
  if (day < 0) {
    for (let index = day; index <= 0; index++) {
      resultArrays.push(recentDate(index))
    }
    return resultArrays
  }
  for (let index = 0; index < day + 1; index++) {
    resultArrays.push(recentDate(index))
  }
  return resultArrays
}

/**
 * 格式化日期
 * @param time 日期
 * @param format 格式默认 yyyy-MM-dd HH:mm:ss
 */
export function formatDate(time, format) {
  if (!time) {
    return ''
  }
  if (!format) {
    format = 'yyyy-MM-dd HH:mm:ss'
  }
  if (typeof time === 'string') {
    time = time.replace(/-/g, '/')
  }
  if (/^\d+$/.test(time)) {
    time = Number(time)
  }
  const date = new Date(time)
  var tf = function(i) {
    return (i < 10 ? '0' : '') + i
  }
  return format.replace(/yyyy|MM|dd|HH|mm|ss/g, function(a) {
    switch (a) {
      case 'yyyy':
        return tf(date.getFullYear())
      case 'MM':
        return tf(date.getMonth() + 1)
      case 'mm':
        return tf(date.getMinutes())
      case 'dd':
        return tf(date.getDate())
      case 'HH':
        return tf(date.getHours())
      case 'ss':
        return tf(date.getSeconds())
    }
  })
}

/**
 * 在指定日期上添加一天
 * @param {*} date
 * @param {*} day
 * @returns {date}
 */
export function datePlusDays(date, day) {
  if (typeof date === 'string') {
    date = date.replace(/-/g, '/')
  }
  const dateObj = new Date(date)
  dateObj.setDate(dateObj.getDate() + day)
  return dateObj
}

/**
 * Parse the time to string
 * @param {(Object|string|number)} time
 * @param {string} cFormat
 * @returns {string | null}
 */
export function parseTime(time, cFormat) {
  if (arguments.length === 0) {
    return null
  }
  const format = cFormat || '{y}-{m}-{d} {h}:{i}:{s}'
  let date
  if (typeof time === 'object') {
    date = time
  } else {
    if ((typeof time === 'string') && (/^[0-9]+$/.test(time))) {
      time = parseInt(time)
    }
    if ((typeof time === 'number') && (time.toString().length === 10)) {
      time = time * 1000
    }
    date = new Date(time)
  }
  const formatObj = {
    y: date.getFullYear(),
    m: date.getMonth() + 1,
    d: date.getDate(),
    h: date.getHours(),
    i: date.getMinutes(),
    s: date.getSeconds(),
    a: date.getDay()
  }
  const time_str = format.replace(/{([ymdhisa])+}/g, (result, key) => {
    const value = formatObj[key]
    // Note: getDay() returns 0 on Sunday
    if (key === 'a') { return ['日', '一', '二', '三', '四', '五', '六'][value ] }
    return value.toString().padStart(2, '0')
  })
  return time_str
}

/**
 * @param {number} time
 * @param {string} option
 * @returns {string}
 */
export function formatTime(time, option) {
  if (('' + time).length === 10) {
    time = parseInt(time) * 1000
  } else {
    time = +time
  }
  const d = new Date(time)
  const now = Date.now()

  const diff = (now - d) / 1000

  if (diff < 30) {
    return '刚刚'
  } else if (diff < 3600) {
    // less 1 hour
    return Math.ceil(diff / 60) + '分钟前'
  } else if (diff < 3600 * 24) {
    return Math.ceil(diff / 3600) + '小时前'
  } else if (diff < 3600 * 24 * 2) {
    return '1天前'
  }
  if (option) {
    return parseTime(time, option)
  } else {
    return (
      d.getMonth() +
      1 +
      '月' +
      d.getDate() +
      '日' +
      d.getHours() +
      '时' +
      d.getMinutes() +
      '分'
    )
  }
}

/**
 * @param {string} url
 * @returns {Object}
 */
export function param2Obj(url) {
  const search = url.split('?')[1]
  if (!search) {
    return {}
  }
  return JSON.parse(
    '{"' +
      decodeURIComponent(search)
        .replace(/"/g, '\\"')
        .replace(/&/g, '","')
        .replace(/=/g, '":"')
        .replace(/\+/g, ' ') +
      '"}'
  )
}

/**
 * Check if an element has a class
 * @param {HTMLElement} elm
 * @param {string} cls
 * @returns {boolean}
 */
export function hasClass(ele, cls) {
  return !!ele.className.match(new RegExp('(\\s|^)' + cls + '(\\s|$)'))
}

/**
 * Add class to element
 * @param {HTMLElement} elm
 * @param {string} cls
 */
export function addClass(ele, cls) {
  if (!hasClass(ele, cls)) ele.className += ' ' + cls
}

/**
 * Remove class from element
 * @param {HTMLElement} elm
 * @param {string} cls
 */
export function removeClass(ele, cls) {
  if (hasClass(ele, cls)) {
    const reg = new RegExp('(\\s|^)' + cls + '(\\s|$)')
    ele.className = ele.className.replace(reg, ' ')
  }
}
