# 比较版本号

import isjs from 'is_js'

const userAgent = String(window.navigator.userAgent).toLowerCase()

/**
 * 判断客户端是否匹配
 *
 * @param {string} text
 * @returns
 */
export const isDeivceMatch = text => {
  return userAgent.indexOf(text) !== -1
}

export const device = {
  isXiaobangguihua: isDeivceMatch('xiaobangguihua'),
  isWeixin: isDeivceMatch('micromessenger'),
  isIOS: isjs.ios(),
  isAndroid: isjs.android(),
}

/**
 * 比较版本号,大于等于返回 true,只支持*.*.*的格式,例如4.3.0
 * @param {string} v1  版本1
 * @param {string} v2  版本2
 */
const compareVersion = (v1 = '', v2 = '') => {
  if (Array.isArray(v1)) v1 = v1.join('.')
  if (Array.isArray(v2)) v2 = v2.join('.')
  let preVersion1 = parseFloat(v1)
  let preVersion2 = parseFloat(v2)
  let nextVersion1 = v1.replace(preVersion1 + '.', '')
  let nextVersion2 = v2.replace(preVersion2 + '.', '')

  if (preVersion1 > preVersion2) {
    return true
  } else if (preVersion1 < preVersion2) {
    return false
  } else {
    return nextVersion1 >= nextVersion2
  }
}

// 根据正则获取版本号
const getVersion = regx => {
  const query = userAgent.match(regx)
  if (!query) {
    return [0, 0, 0]
  }
  const version = query[0].match(/\d+/g)
  if (typeof version[0] === 'undefined' || typeof version[1] === 'undefined' || typeof version[2] === 'undefined') {
    return [0, 0, 0]
  }
  return [parseInt(version[0], 10), parseInt(version[1], 10), parseInt(version[2], 10)]
}

/* eslint-disable */
const xiaobangguihuaRegx = /xiaobangguihua\/[\d\.]+/i
/* eslint-enable */

export const gtVersion = v2 => {
  const v1 = getVersion(xiaobangguihuaRegx)
  return compareVersion(v1, v2)
}


gtVersion('2.3.1')
// 当前版本大于等于2.3.1 返回true