/**
 * 检查app版本是否需要升级
 */
const compareVersion = (v1: any, v2: any) => {
  //判断版本号大小是否最新
  const v1Arr = v1.split('.')
  const v2Arr = v2.split('.')
  const len = Math.max(v1Arr.length, v2Arr.length)
  for (let i = 0; i < len; i++) {
    const v1Seg = parseInt(v1Arr[i] || '0')
    const v2Seg = parseInt(v2Arr[i] || '0')
    if (v1Seg > v2Seg) {
      //	debugger
      return 1
    } else if (v1Seg < v2Seg) {
      //	debugger
      return -1
    }
  }
  return 0
}
const checkVersion = ({
  selfVersionCode, //线上版本
  name, //最新版本名称
  code, //最新版本号
  content, //更新内容
  url, //下载链接
  forceUpdate //是否强制升级
}) => {
  //debugger
  //const selfVersionCode = uni.getSystemInfoSync().appVersion; //当前App版本号
  //线上版本号高于当前，进行在线升级
  console.log('suhhdsahuduhdsahudhas', selfVersionCode, code)
  if (compareVersion(selfVersionCode, code) < 0) {
    let platform = uni.getSystemInfoSync().platform //手机平台
    //安卓手机弹窗升级
    if (platform === 'android') {
      //当前页面不是升级页面跳转防止多次打开
      if (getCurrentPageRoute() !== 'pages/lq-upgrade/upgrade') {
        uni.navigateTo({
          url: '/pages/lq-upgrade/upgrade',
          success() {
            uni.$emit('upgrade-app', {
              name,
              content,
              url,
              forceUpdate
            })
          }
        })
      }
    }
    //IOS无法在线升级提示到商店下载
    else {
      uni.showModal({
        // title: '发现新版本 ' + newVersionName,
        title: '发现新版本 ',
        content: '请到App store进行升级',
        showCancel: false
      })
    }
  }
}

//获取当前页面url
const getCurrentPageRoute = () => {
  let currentRoute = null
  let pages = getCurrentPages() // 获取栈实例
  if (pages && pages.length) {
    currentRoute = pages[pages.length - 1].route
  }
  return currentRoute
}

export default checkVersion
