// 手机型号
export function getMobileType() {
  return !!navigator.userAgent.match(/\(i[^;]+;( U;)? CPU.+Mac OS X/) == true ? 'ios' : 'android'
}

// 是否微信内
export function isWeixin() {
  return (window.navigator.userAgent.toLowerCase().match(/MicroMessenger/i) == 'micromessenger')
}

// 触发原生方法
export function callHandler(methodName, params = {}, callback) {
  if (window.location.href.indexOf('localhost') > -1) {
    return
  }
  console.log(`是否存在${methodName}方法`, window.webkit?.messageHandlers?.[methodName])
  console.log(`${methodName}方法的入参`, params)
  try {
    if (getMobileType() == 'ios') {
      window.webkit.messageHandlers[methodName].postMessage({ params: params })
    } else {
      // Android
      window.setupWebViewJavascriptBridge(bridge => {
        bridge.callHandler(methodName, params, result => {
          typeof callback === 'function' && callback(result)
        })
      })
    }
  } catch (e) {
    typeof callback == 'function' && callback({
      error: e,
      status: 0,
    })
  }
}

// 原生方法添加监听事件
export function registerHandler(methodName, callback) {
  try {
    if (getMobileType() == 'ios') {
      window.webkit.messageHandlers[methodName] = callback
      window[methodName] = callback
    } else {
      // Android
      window.setupWebViewJavascriptBridge(bridge => {
        bridge.registerHandler(methodName, result => {
          typeof callback === 'function' && callback(result)
        })
      })
    }
  } catch (e) {
    typeof callback == 'function' && callback()
    console.log(e)
  }
}

/**
 *  @description 拍照并返回结果
 *  1.H5调起移动端拍照OCR照片 
 *  2.监听OCR照片结果
 *  @return imgUrl 拍照返回结果
 */
export async function selectOCRFromCameraResult() {
  // 1.H5调起移动端拍照OCR照片
  callHandler('selectOCRFromCamera')
  return new Promise((resolve) => {
    // 2.监听OCR照片结果
    registerHandler('ocrSelectResult', async (res) => {
      console.log(res, '监听OCR照片结果ocrSelectResult')
      if (res) {
        res = JSON.parse(res)
      } else {
        res = {}
      }
      resolve(res)
    })
  })
}