import { createSSRApp } from 'vue'
import App from './App.vue'
import { createI18n } from 'vue-i18n'
 import { request, http } from '@/utils/request' // 引入封装的request
import en from './static/lang/enUS.json'
import zh from './static/lang/zh_CN.json'

export function createApp() {
  const app = createSSRApp(App)
  // 1. 获取系统语言
  const systemInfo = uni.getSystemInfoSync() || {}
  const systemLanguage = systemInfo.language || 'zh'
  let curLang = 'zh'
  
  switch (systemLanguage.toLowerCase()) {
    case 'en':
    case 'en-us':
      curLang = 'en'
      break
    case 'zh':
    case 'zh-cn':
    case 'zh-hans':
      curLang = 'zh'
      break
  }

  // 2. 配置i18n
  const i18n = createI18n({
    legacy: false,
    locale: curLang,
    fallbackLocale: 'en',
    messages: { en, zh },
    missing: (locale, key) => {
      console.error(`[i18n] 缺失: '${key}' 在 '${locale}' 语言包中不存在`)
      return process.env.NODE_ENV === 'development' ? `[缺失: ${key}]` : ''
    }
  })
  
  // 3. 挂载request到全局
  app.config.globalProperties.$request = request
  app.config.globalProperties.$http = http
  
  // 4. 使用i18n插件
  app.use(i18n)
  
  return {
    app,
    i18n
  }
}

// 非SSR模式下挂载应用
if (!globalThis.__IS_SSR__) {
  const { app } = createApp()
  
  // 全局错误处理
  app.config.errorHandler = (err) => {
    console.error('全局错误:', err)
    uni.showToast({
      title: '发生错误，请重试',
      icon: 'none'
    })
  }
  
  app.mount('#app')
}