import { Toast, Dialog } from 'vant'
import { postMessage } from '@/helpers/native-message'
import { browser } from '@/helpers/utils'
import { state } from '@/state'

// share information
export const shareCall = (str: string, params?: any) => {
  const query = {
    url: str,
    action: params?.action || 'h5', // app, h5
    pageTag: params?.pageTag || 1 // 页面标识
    // params: {}
  }
  const iosStr = encodeURIComponent(JSON.stringify(query))
  console.log(iosStr, 'query')
  if (/(iPhone|iPad|iPod|iOS)/i.test(navigator.userAgent)) {
    // ColexiuStudent 唤起学生端
    window.location.href = `ColexiuStudent://linkUrl=${iosStr}`
  } else if (/(Android)/i.test(navigator.userAgent)) {
    window.location.href = `colexiustudent://html:8888/SplashActivity?url=${iosStr}`
  } else {
    Toast('请用手机或移动设备打开')
  }
}

export const appDownload = () => {
  function failed() {
    window.location.href = '应用商店的地址'
  }

  function transfer(cb) {
    window.location.href = 'app的scheme'
    const initialTime = +new Date()
    let counter = 0
    let waitTime = 0
    const checkOpen = setInterval(() => {
      counter++
      waitTime = +new Date() - initialTime
      if (waitTime > 3500) {
        clearInterval(checkOpen)
        cb()
      }
      if (counter < 1000) {
        return
      }
    }, 20)

    document.addEventListener('visibilitychange', () => {
      const isHidden = document.hidden
      if (isHidden) {
        clearInterval(checkOpen)
      }
    })
  }
  transfer(failed)
}

// 页面跳转原生页面
export const initJumpNativePage = (url: string) => {
  if (browser().isApp) {
    if (state.platformType === 'STUDENT') {
      // 自动跳转到学生端视频课详情购买页
      window.location.replace(url)
      // 为了处理andoird webview的跳转问题
      if (browser().ios) {
        window.location.replace(url)
      } else {
        postMessage({
          api: 'openWebView',
          content: {
            url,
            orientation: 1,
            isHideTitle: false
          }
        })

        postMessage({ api: 'back' })
      }
      return
    } else if (state.platformType === 'TEACHER') {
      Dialog.alert({
        title: '提示',
        message: '请使用酷乐秀学生端扫码打开',
        confirmButtonColor: '#2dc7aa'
      }).then(() => {
        postMessage({ api: 'back' })
      })
    }
  } else {
    // 如果不在app里面则不需要唤起操作
    shareCall(url)
  }
}
