export function byteLength(val) {
  var byteLen = 0
  var len = val.length // 初始化字节数递加变量并获取字符串参数的字符个数
  if (len) { // 如果存在字符串，则执行计划
    for (var i = 0; i < len; i++) { // 遍历字符串，枚举每个字符
      if (val.charCodeAt(i) > 255) { // 字符编码大于255，说明是双字节字符
        byteLen += 2 // 则累加2个
      } else {
        byteLen++ // 否则递加一次
      }
    }
  }

  return byteLen // 返回字节数
}

export function isTypeof(option) {
  var value = Object.prototype.toString.call(option)

  if (value === '[object Undefined]') return 'undefined'
  else if (value === '[object String]') return 'string'
  else if (value === '[object Boolean]') return 'boolean'
  else if (value === '[object Number]') return 'number'
  else if (value === '[object Null]') return 'null'
  else if (value === '[object Object]') return 'object'
  else if (value === '[object Array]') return 'array'
  else if (value === '[object Date]') return 'date'
  else if (value === '[object RegExp]') return 'regexp'
  else if (value === '[object Function]') return 'function'
}

export function formateTData(date, fmt) { // 字符串
  if (date) {
    if (fmt == 'date') {
      return formatDate(date, 'yyyy-MM-dd')
    } else if (fmt == 'all') {
      return formatDate(date, 'yyyy-MM-dd hh:mm:ss')
    } else {
      return formatDate(date, 'yyyy-MM-dd hh:mm')
    }
  }

  return ''
}
export function formatDate(date, fmt) { // date对象
  if (!date) return '-'
  var padLeftZero = function (str) {
    return ('00' + str).substr(str.length)
  }
  if (isTypeof(date) === 'string') {
    let tmpDate = date.replace(/-/g, '/')
    tmpDate = tmpDate.replace(/T/g, ' ')

    date = new Date(tmpDate)
  } else if (isTypeof(date) == 'number') {
    date = new Date(date)
  }
  if (/(y+)/.test(fmt)) {
    fmt = fmt.replace(RegExp.$1, (date.getFullYear() + '').substr(4 - RegExp.$1.length))
  }
  const o = {
    'M+': date.getMonth() + 1,
    'd+': date.getDate(),
    'h+': date.getHours(),
    'm+': date.getMinutes(),
    's+': date.getSeconds()
  }
  for (var k in o) {
    if (new RegExp(`(${k})`).test(fmt)) {
      var str = o[k] + ''
      fmt = fmt.replace(RegExp.$1, RegExp.$1.length === 1 ? str : padLeftZero(str))
    }
  }

  return fmt
}

export function inArray(value, array) {
  if (Array.prototype.indexOf) {
    return array.indexOf(value)
  } else {
    for (var i = 0; i < array.length; i++) {
      if (array[i] === value) return i
    }
  }

  return -1
}

export function dateTimePickerRange(timeString, sign) {
  sign = sign || '#'
  const times = timeString.split(sign)
  var start = times[0].split('-')
  var end = times[1].split('-')

  return {
    start: formatDate(new Date(start[0], (parseInt(start[1]) - 1), start[2]), 'yyyy-MM-dd 00:00:00'),
    end: formatDate(new Date(end[0], (parseInt(end[1]) - 1), end[2]), 'yyyy-MM-dd 23:59:59')
  }
}
export function fillerTimePickerRange(timeString, sign) {
  sign = sign || '#'
  const times = timeString.split(sign)
  var startDate = times[0].split('-')
  var endDate = times[1].split('-')
  var startDay = startDate[2].split(' ')
  var endDay = endDate[2].split(' ')
  var startTime = startDay[1].split(':')
  var endTime = endDay[1].split(':')
  var start = [startDate[0], startDate[1], startDay[0], startTime[0], startTime[1]]
  var end = [endDate[0], endDate[1], endDay[0], endTime[0], endTime[1]]
  return {
    start: formatDate(new Date(start[0], (parseInt(start[1]) - 1), start[2], start[3], start[4]), 'yyyy-MM-dd hh:mm:00'),
    end: formatDate(new Date(end[0], (parseInt(end[1]) - 1), end[2], end[3], end[4]), 'yyyy-MM-dd hh:mm:59')
  }
}
export function monthTimeArea(now) {
  var nowYear = now.getFullYear()
  var nowMonth = now.getMonth()

  var monthStartDate = new Date(nowYear, nowMonth, 1)
  var monthEndDate = new Date(nowYear, nowMonth + 1, 1)

  return {
    start: formatDate(monthStartDate, 'yyyy-MM-dd 00:00:00'),
    end: formatDate(monthEndDate, 'yyyy-MM-dd 00:00:00')
  }
}
export function monthDay(now) {
  var nowYear = now.getFullYear()
  var nowMonth = now.getMonth()

  var monthStartDate = new Date(nowYear, nowMonth, 1)
  var monthEndDate = new Date(nowYear, nowMonth + 1, 1)

  return {
    start: formatDate(monthStartDate, 'yyyy-MM-dd'),
    end: formatDate(monthEndDate, 'yyyy-MM-dd')
  }
}
export function storeLogout(_this) {
  _this.$store.dispatch('logout').then(() => {
    location.reload()
  })
}

export function uploadImageDate(path, upload, auth, status) {
  return [{
    url: (location.href.split('#/')[0].includes('localhost') ? 'http://dwx.auyen.com/' : location.href.split('#/')[0]) + path,
    isUpload: upload,
    isAuth: auth,
    status: status
  }]
}
// 加气站名片图片
export function fillerIntroducePreview(path, id) {
  return {
    path: process.env.VUE_APP_FILE_URL + path,
    id: id
  }
}

/* 对象深度合并 */
export function objectMerge(target, source) {
  if (typeof target !== 'object') {
    target = {}
  }
  if (Array.isArray(source)) {
    return source.slice()
  }
  Object.keys(source).forEach((property) => {
    const sourceProperty = source[property]
    if (sourceProperty && typeof sourceProperty === 'object') {
      target[property] = objectMerge(target[property], sourceProperty)
    } else {
      target[property] = sourceProperty
    }
  })

  return target
}

// 对象深度赋值
export function objectDepthAssignment(source) {
  const sourceCopy = Object.prototype.toString.call(source) === '[object Array]' ? [] : {}

  for (const item in source) {
    sourceCopy[item] = typeof source[item] === 'object' ? objectDepthAssignment(source[item]) : source[item]
  }

  return sourceCopy
}

// 数组根据某个字段排序
export function arrayResetSort(sourceColumn, key = 'serial', order = 'asc') {
  const arrayList = objectDepthAssignment(sourceColumn)

  if (order == 'asc') {
    arrayList.sort((arr1, arr2) => {
      return Number(arr1[key]) - Number(arr2[key])
    })
  } else if (order == 'desc') {
    arrayList.sort((arr1, arr2) => {
      return Number(arr2[key]) - Number(arr1[key])
    })
  }

  return arrayList
}
// 加气站类型判断
export function gasstationCheckType(type) {
  if (type === 2001 || type === 2002 || type === 2003 || type === 2004) {
    return true
  }

  return false
}

// 校验URL地址是否是http://或https://开头的
export function isHttpHeaderURL(url) {
  if (url && isTypeof(url) === 'string' && (url.indexOf('http://') === 0 || url.indexOf('https://') === 0)) {
    return true
  }

  return false
}

// 站点类型
export function utilSelectGasstationType(type = '') {
  let result = [
    { value: 2001, text: '中海油' },
    { value: 2002, text: '中石油' },
    { value: 2003, text: '中石化' },
    { value: 2004, text: '社会' }
  ]
  if (type === 'inner') {
    result = [
      { value: 1001, text: '大象自营' },
      { value: 1002, text: '大象合作' },
      { value: 1003, text: '大象加盟' }
    ]
  }

  if (type === 'all') {
    result.unshift({ value: 1003, text: '大象加盟' })
    result.unshift({ value: 1002, text: '大象合作' })
    result.unshift({ value: 1001, text: '大象自营' })
    result.unshift({ value: 100, text: '大象站' })
    result.unshift({ value: null, text: '全部站点' })
  }

  return result
}

export function mapCenterToPointList() {
  return {
    鲁东: [120.7806, 36.8515],
    鲁西: [117.1551, 36.3753],
    '冀南&长治': [114.1888, 37.2461],
    豫北: [113.1671, 34.4776],
    冀北: [116.8036, 39.4642],
    豫南: [113.4747, 32.0621],
    '苏北&皖北': [118.05606, 33.5121]
  }
}

// 去掉前后空格
export function trim(str) {
  return typeof str === 'string' ? str.replace(/^\s+|\s+$/g, '') : str
}

export function treeEqualValue (nodes, key, value) {
  if (Array.isArray(nodes)) {
    for (var i = 0, l = nodes.length; i < l; i++) {
      if (nodes[i][key] == value) {
        return nodes[i]
      } else {
        if (Array.isArray(nodes[i].children) && nodes[i].children.length > 0) {
          return treeEqualValue(nodes[i].children, key, value)
        }
      }
    }
  } else {
    return false
  }
}
