import Taro from '@tarojs/taro'

const SystemInfo = Taro.getSystemInfoSync()
export const screenK = SystemInfo.screenWidth / 750

export function isValidUrl(url: string) {
  return /(ht|f)tp(s?):\/\/([^ \\/]*\.)+[^ \\/]*(:[0-9]+)?\/?/.test(url)
}

/**
 * 深度对比两个对象是否一致
 * from: https://github.com/epoberezkin/fast-deep-equal
 * @param  {Object} a 对象a
 * @param  {Object} b 对象b
 * @return {Boolean}   是否相同
 */
export function equal(a, b) {
  if (a === b) { return true }

  if (a && b && typeof a == 'object' && typeof b == 'object') {
    const arrA = Array.isArray(a)
    const arrB = Array.isArray(b)
    let i
    let length
    let key

    if (arrA && arrB) {
      length = a.length
      if (length != b.length) { return false }
      for (i = length; i-- !== 0;) { if (!equal(a[i], b[i])) { return false } }
      return true
    }

    if (arrA != arrB) { return false }

    const dateA = a instanceof Date
    const dateB = b instanceof Date
    if (dateA != dateB) { return false }
    if (dateA && dateB) { return a.getTime() == b.getTime() }

    const regexpA = a instanceof RegExp
    const regexpB = b instanceof RegExp
    if (regexpA != regexpB) { return false }
    if (regexpA && regexpB) { return a.toString() == b.toString() }

    const keys = Object.keys(a)
    length = keys.length

    if (length !== Object.keys(b).length) { return false }

    for (i = length; i-- !== 0;) { if (!Object.prototype.hasOwnProperty.call(b, keys[i])) { return false } }

    for (i = length; i-- !== 0;) {
      key = keys[i]
      if (!equal(a[key], b[key])) { return false }
    }

    return true
  }

  // eslint-disable-next-line no-self-compare
  return a !== a && b !== b
}
export /**
   * 是否支持负数
   * @param {Boolean} minus 是否支持负数
   */
const toPx = (num: string, minus = false) => {
  let reg
  if (minus) {
    reg = /^-?[0-9]+([.]{1}[0-9]+){0,1}(rpx|px)$/g
  }
  else {
    reg = /^[0-9]+([.]{1}[0-9]+){0,1}(rpx|px)$/g
  }
  const results = reg.exec(num)
  console.log('results', results)
  if (!num || !results) {
    console.log(`The size: ${num} is illegal`)
    return 0
  }
  const unit = results[2]
  const value = parseFloat(num)

  let res = 0
  if (unit === 'rpx') {
    res = Math.round(value * screenK)
  }
  else if (unit === 'px') {
    res = value
  }
  console.log('res', res)
  return res
}
