<script setup lang="ts">
import AppConfig, { isProd, isTestEnv } from '@/common/config/AppCofig'
import { useAuthStore } from './store/auth'
import { useAppConfiguration } from './api/system/useAppConfiguration';
import { useAppInit } from './common/composeabe/AppInit';
import { BugReporterAbstractionUniapp } from './common/BugReporter/impl/BugReporterAbstractionUniapp';
import { IconUtils } from './components/basic/IconUtils';
import { configAppTheme } from './common/config/Theme';
import { getCurrentPageUrl, navTo } from './components/utils/PageAction';
import { onError, onLaunch } from '@dcloudio/uni-app'
import { RequestApiConfig, RequestApiError } from '@imengyu/imengyu-utils';
import ApiCofig from './common/config/ApiCofig';
import MemoryTimeOut from './components/composeabe/MemoryTimeOut';
import BugReporter from './common/BugReporter';
import '@/common/style/icons';

const authStore = useAuthStore();
const { init } = useAppInit();
const { loadAppConfiguration } = useAppConfiguration();
const redirectThrottle = new MemoryTimeOut('RedirectThrottle', 50000);

onLaunch(async () => {
  console.log('App Launch');

  loadFontFace();
  await loadAppConfiguration();

  //加载登录信息
  const loginState = await authStore.loadLoginState();
  if (AppConfig.requireLogin) {
    //如果未登录，跳转登录页
    if (!loginState && redirectThrottle.isTimeout()) {
      redirectThrottle.recordTime();
      setTimeout(() => {   
        const pageUrl = getCurrentPageUrl() || '';
        const noLoginPages = AppConfig.noLoginPages;
        if (noLoginPages.indexOf('/' + pageUrl) == -1 && noLoginPages.indexOf(pageUrl) == -1)
          navTo('/pages/user/login');
      }, 500);
    }
  }
    
  await BugReporter.checkAndReportBug();
  await init();
});

//配置BugReporter
BugReporter.config({
  abstractionLayer: new BugReporterAbstractionUniapp(),
  serverUrl: ApiCofig.bugReport.server,
  appId: ApiCofig.bugReport.appId,
  appKey: ApiCofig.bugReport.appKey,
});

if (isProd) {
  onError((err) => {
    if (!((err as any) instanceof RequestApiError)) {
      BugReporter.reportError(err);
    }
  });
}

//设置请求基础地址
RequestApiConfig.setConfig({
  ...RequestApiConfig.getConfig(),
  BaseUrl: ApiCofig.server.Prod,
  EnableApiRequestLog: false, // isTestEnv,
  EnableApiDataLog: false,
})

function loadFontFace() {
  uni.loadFontFace({
    global: true,
    family: "SongtiSCBlack",
    source: 'url("https://mncdn.wenlvti.net/assets/fonts/STSongti-SC-Black.woff")',
  });
  uni.loadFontFace({
    global: true,
    family: "HUNdin1451",
    source: 'url("https://mncdn.wenlvti.net/app_static/minnan/fonts/HUN-din1451.woff")',
  });
}


configAppTheme();

IconUtils.loadDefaultIcons('https://mncdn.wenlvti.net/app_static/xiangyuan/data/DefaultIcon.json');
</script>

<style lang="scss">
	/*每个页面公共css */
  @import "@/components/index.scss";
  @import "@/common/style/leagicy.scss";

  page {
    background: #fef2e8;
  }
</style>
