/**
 * Created by PanJiaChen on 16/11/18.
 */

/**
 * 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 || !time) {
    return null
  }
  const format = cFormat || '{y}-{m}-{d} {h}:{i}:{s}'
  let date
  if (typeof time === 'object') {
    date = time
  } else {
    if (typeof time === 'string') {
      if (/^[0-9]+$/.test(time)) {
        // support "1548221490638"
        time = parseInt(time)
      } else {
        // support safari
        // https://stackoverflow.com/questions/4310953/invalid-date-in-safari
        time = time.replace(new RegExp(/-/gm), '/')
      }
    }

    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 = decodeURIComponent(url.split('?')[1]).replace(/\+/g, ' ')
  if (!search) {
    return {}
  }
  const obj = {}
  const searchArr = search.split('&')
  searchArr.forEach((v) => {
    const index = v.indexOf('=')
    if (index !== -1) {
      const name = v.substring(0, index)
      const val = v.substring(index + 1, v.length)
      obj[name] = val
    }
  })
  return obj
}

// 下载文件
export function downloadFile(obj, name) {
  var buffer = Buffer.from(obj.fileContents, 'base64')
  var blob = new Blob([buffer], {
    type: obj.contentType,
  })
  const url = window.URL.createObjectURL(blob)
  const link = document.createElement('a')
  link.style.display = 'none'
  link.href = url
  const fileName = name ? name : obj.fileDownloadName
  link.setAttribute('download', fileName)
  document.body.appendChild(link)
  link.click()
  document.body.removeChild(link)
}
export function downloadFile2(obj, name, suffix) {
  const url = window.URL.createObjectURL(new Blob([obj]))
  const link = document.createElement('a')
  link.style.display = 'none'
  link.href = url
  const fileName = parseTime(new Date()) + '-' + name + '.' + suffix
  link.setAttribute('download', fileName)
  document.body.appendChild(link)
  link.click()
  document.body.removeChild(link)
}
/**
 * 处理json字符串的key值
 * @param {Object} json
 * @param {Object} type： 默认不传 ==>全部小写;传1 ==>全部大写;传2 ==>首字母大写
 * 将json的key值进行大小写转换
 */
export function jsonKeysToCase(json, type) {
  if (typeof json == 'object') {
    var tempJson = JSON.parse(JSON.stringify(json))
    toCase(tempJson)
    return tempJson
  } else {
    return json
  }

  function toCase(json) {
    if (typeof json == 'object') {
      if (Array.isArray(json)) {
        json.forEach(function (item) {
          toCase(item)
        })
      } else {
        for (var key in json) {
          var item = json[key]
          if (typeof item == 'object') {
            toCase(item)
          }
          delete json[key]
          switch (type) {
            case 1:
              //key值全部大写
              json[key.toLocaleUpperCase()] = item
              break
            case 2:
              //key值首字母大写，其余小写
              json[key.substring(0, 1).toLocaleUpperCase() + key.substring(1).toLocaleLowerCase()] =
                item
              break
            default:
              //默认key值全部小写
              json[key.toLocaleLowerCase()] = item
              break
          }
        }
      }
    }
  }
}
/**
 * 处理地址字符串中被转义的字符
 * @param {string} n
 * @returns {string} 返回标准格式的地址
 */
export function escape2Html(n) {
  var t = {
    lt: '<',
    gt: '>',
    nbsp: ' ',
    amp: '&',
    quot: '"',
  }
  return n.replace(/&(lt|gt|nbsp|amp|quot);/gi, function (n, i) {
    return t[i]
  })
}

/**
 * 将相对坐标转换为经纬度
 * @param {*} c 为参考起始点的坐标，从后台json配置文件中来
 * @param {*} xDist 要转换点的x
 * @param {*} yDist 要转换点的y
 * @returns
 */
export function _locate(xDist, yDist, c = { x: 116.522816340649, y: 40.23528138525907 }) {
  // console.log(c, xDist, yDist);
  const radius = 6378137 //坐标系球的半径  WGS84是6378137
  // debugger;
  if (!c) {
    return null
  }
  if (!xDist) {
    xDist = 0
  }
  if (!yDist) {
    yDist = 0
  }
  if (!xDist && !yDist) {
    return c
  }
  let newXDist = xDist / 1000
  let newYDist = -(yDist / 1000)
  let x, y
  let ry = toRadian(c.y)
  if (newYDist !== 0) {
    const dy = Math.abs(newYDist)
    const sy = Math.sin(dy / (2 * radius)) * 2
    ry = ry + sy * (newYDist > 0 ? 1 : -1)
    y = wrap((ry * 180) / Math.PI, -90, 90)
  } else {
    y = c.y
  }
  if (newXDist !== 0) {
    // distance per degree
    const dx = Math.abs(newXDist)
    let rx = toRadian(c.x)
    const sx = 2 * Math.sqrt(Math.pow(Math.sin(dx / (2 * radius)), 2) / Math.pow(Math.cos(ry), 2))
    rx = rx + sx * (newXDist > 0 ? 1 : -1)
    x = wrap((rx * 180) / Math.PI, -180, 180)
  } else {
    x = c.x
  }
  c.x = x
  c.y = y
  // console.log(c);
  return c
}

export function toRadian(d) {
  return d * (Math.PI / 180)
}

export function wrap(n, min, max) {
  if (n === max || n === min) {
    return n
  }
  const d = max - min
  const w = ((((n - min) % d) + d) % d) + min
  return w
}

// 解析url参数
export function queryURLparamsByReg(url) {
  let obj = {}
  let reg = /([^?=&]+)=([^?=&]+)/g
  url.replace(reg, (...arg) => {
    obj[arg[1]] = arg[2]
  })
  return obj
}

/**
* 文件大小转换/单位换算
* @param size 文件大小（转换，必填）
* @param pointLength 转换完，保留几位小数（选填，默认保存2位）
* @param units 指定单位类型（选填）
* @returns {*}
*/
export function formatSize(size, pointLength, units) {
   var unit;
   units = units || [ 'B', 'K', 'M', 'G' ];
   while ( (unit = units.shift()) && size >= 1024 ) {
       size = size / 1024;
   }
   return (unit === 'B' ? size : size.toFixed( pointLength === undefined ? 2 : pointLength)) + unit;
}
/**
 * 获取类型字符串
 * @param {*} data 
 * @returns 
 * console.log(typeOf(1)); // Number
 * console.log(typeOf("1")); // String
 * console.log(typeOf(true)); // Boolean
 * console.log(typeOf(null)); // Null
 * console.log(typeOf(undefined)); // Undefined
 * console.log(typeOf(Symbol(1))); // Symbol
 * console.log(typeOf({})); // Object
 * console.log(typeOf([])); // Array
 * console.log(typeOf(function () {})); // Function
 * console.log(typeOf(new Date())); // Date
 * console.log(typeOf(new RegExp())); // RegExp
 */
export function typeOf(data) {
  return Object.prototype.toString.call(data).slice(8, -1);
}

/**
 * 获取选项标签值
 */
export function getElementItemLabel(options, data) {
  if (options){
    const item = options.find(a => a.value == data)
    if (item) return item.label
    else return null
  } else return null
}

/**
 * 获取树形选项标签值
 */
export function getElementTreeLabel(tree, data) {
  if (tree && data){
    for(let i in tree){
      if (tree[i].value && (tree[i].value == data)) return tree[i].label
      else if (tree[i].children) {
        const label = getElementTreeLabel(tree[i].children, data)
        if (label) return label
      }
      else null
    }
  } else return null
}