import App from './App'
import uviewPlus from 'uview-plus'

const TAB_BAR_STYLE_NOT_FOUND_ERROR = 'setTabBarStyle:fail not TabBar page'

const shouldIgnoreTabBarStyleError = (error) => {
  const message = typeof error === 'string'
    ? error
    : error?.errMsg || error?.message || ''
  return message.includes(TAB_BAR_STYLE_NOT_FOUND_ERROR)
}

const patchSafeSetTabBarStyle = () => {
  if (typeof uni === 'undefined' || typeof uni.setTabBarStyle !== 'function') {
    return
  }

  if (uni.setTabBarStyle.__upSafePatched) {
    return
  }

  const originalSetTabBarStyle = uni.setTabBarStyle.bind(uni)
  const safeSetTabBarStyle = (options = {}) => {
    try {
      const result = originalSetTabBarStyle(options)
      if (result && typeof result.catch === 'function') {
        return result.catch((error) => {
          if (shouldIgnoreTabBarStyleError(error)) {
            return undefined
          }
          return Promise.reject(error)
        })
      }
      return result
    } catch (error) {
      if (shouldIgnoreTabBarStyleError(error)) {
        return undefined
      }
      throw error
    }
  }

  safeSetTabBarStyle.__upSafePatched = true
  uni.setTabBarStyle = safeSetTabBarStyle
}

// #ifndef VUE3
import Vue from 'vue'
import './uni.promisify.adaptor'
Vue.config.productionTip = false
App.mpType = 'app'
patchSafeSetTabBarStyle()
const app = new Vue({
  ...App
})
app.$mount()
// #endif

// #ifdef VUE3
import { createSSRApp } from 'vue'
export function createApp() {
  patchSafeSetTabBarStyle()
  const app = createSSRApp(App)
  // 使用 uview-plus (版本 3.4.0+)
  app.use(uviewPlus, () => {
    return {
      options: {
        config: {
          // 默认单位 rpx
          unit: 'rpx'
        },
        props: {
          // 可以在这里配置组件默认属性
        }
      }
    }
  })
  return {
    app
  }
}
// #endif
