import { Toast } from 'vant'

let userAgent = navigator.userAgent
let isAndroid
let isIOS
if (userAgent.indexOf('Android') > -1 || userAgent.indexOf('Linux') > -1) {
  isAndroid = true
} else if (userAgent.indexOf('iPhone') > -1) {
  isIOS = true
}

const callNative = (method, data) => {
  if (isAndroid) {
    window.bridge && window.bridge.callNative(JSON.stringify({ method, data }))
  } else if (isIOS) {
    window.webkit && window.webkit.messageHandlers[method].postMessage({ data })
  } else {
    Toast('请在浏览器中打开')
  }
}

const callNativeAsync = (method, data) => {
  const cbName = 'CB_' + Date.now() + '_' + Math.ceil(Math.random() * 10)
  if (isIOS || isAndroid) {
    if (isAndroid) {
      window.bridge && window.bridge.callNative(JSON.stringify({ method, data, cb_name: cbName }))
    } else if (isIOS) {
      window.webkit && window.webkit.messageHandlers[method].postMessage({ data, cb_name: cbName })
    }
    return new Promise((resolve, reject) => {
      window[cbName] = (response) => {
        delete window[cbName]
        if (response.code === 0) {
          resolve(response)
        } else {
          const err = new Error(response.message)
          err.code = response.code
          reject(err)
        }
      }
    })
  } else {
    return Promise.reject(new Error('请在浏览器中打开'))
  }
}

const common = (fnName, str) => {
  if (isAndroid) {
    if (str == '') {
      window.AndroidWebView[fnName]()
    } else {
      window.AndroidWebView[fnName](str)
    }
  } else {
    window.webkit.messageHandlers[fnName].postMessage(str)
  }
}

export default {
  copyToCliborad (str) {
    callNative('copyToCliborad', { msg: str })
  },
  login () {
    return callNativeAsync('login')
  },
  // 通知APP关闭页面，新APP方法
  closeWindow() {
    callNative('closeWindow')
  },
  share(title, desc, img, url) {
    return callNativeAsync('share', { title, desc, img, url })
  },
  toast(str) {
    callNative('toast', { msg: str })
  },
  getLocation() {
    return callNativeAsync('getLocation')
  },
  openCamera(uploadUrl, token, param) {
    return callNativeAsync('openCamera', { uploadUrl, token, param })
  },
  openPhotoAlbum(uploadUrl, token, param) {
    return callNativeAsync('openPhotoAlbum', { uploadUrl, token, param })
  },

  copyContent(str) {
    common('copyContent', str)
  },
  callPhone(str) {
    common('callPhone', str)
  },
  sendSms(str) {
    common('sendSms', str)
  },
  // 通知APP关闭页面，兼容老APP
  closeWindow_c() {
    common('AppLogout', '')
  }
}
