import { customAlphabet } from 'nanoid'

export default {
  generateId() {
    // 生成随机id
    const nanoid = customAlphabet(
      'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz',
      11
    )
    return nanoid()
  },
  hex2rgb(color) {
    var r = parseInt(color.substr(1, 2), 16)
    var g = parseInt(color.substr(3, 2), 16)
    var b = parseInt(color.substr(5, 2), 16)
    return new Array(r, g, b)
  },
  rgb2hex(rgb) {
    var s = '#'
    for (var i = 0; i < 3; i++) {
      var c = Math.round(rgb[i]).toString(16)
      if (c.length == 1) c = '0' + c
      s += c
    }
    return s
  },
  parseUrl(url) {
    var parser = document.createElement('a')
    parser.href = url
    var paramPart = parser.search.substr(1).split('&')
    parser.query = paramPart.reduce(function(res, item) {
      var parts = item.split('=')
      res[parts[0]] = parts[1]
      return res
    }, {})
    var {
      protocol,
      hostname,
      port,
      pathname,
      search,
      hash,
      host,
      query
    } = parser
    return { protocol, hostname, port, pathname, search, hash, host, query }
  },
  extend(dest, ...sources) {
    for (const src of sources) {
      for (const k in src) {
        dest[k] = src[k]
      }
    }
    return dest
  },
  endsWith(string, suffix) {
    return string.indexOf(suffix, string.length - suffix.length) !== -1
  },
  isIdExist(id, layers) {
    for (let i = 0; i < layers.length; i++) {
      if (layers[i].id === id) {
        return true
      }
    }
    return false
  },
  mergeObjs(def, obj) {
    if (!obj) {
      return def
    } else if (!def) {
      return obj
    }

    for (var i in obj) {
      // 是一个对象
      if (
        def[i] &&
        typeof def[i] === typeof obj[i] &&
        obj[i] != null &&
        obj[i].constructor == Object
      ) {
        def[i] = this.mergeObjs(def[i], obj[i])
      } else {
        def[i] = obj[i]
      }
    }
    return def
  },
  // 给定 admin code，返回 admin 级别
  // 省市县的 admin code 是6位格式，乡镇为8位格式
  // 返回值：1 -- 省；2 -- 市；3 -- 县；4 -- 乡镇; 0 -- 无效 codeName
  getAdminType(codeName) {
    if (codeName.length == 8) {
      return 4
    }
    if (codeName === '156') {
      return 0
    }
    // check valid
    if (codeName.length != 6) {
      return -1
    }
    // 省级行政区的后四位为0
    if (/0000$/.test(codeName)) {
      return 1
    }
    // 市级行政的后两位为0
    if (/00$/.test(codeName)) {
      return 2
    }
    return 3
  }
}
