<script setup lang="ts">
import AppConfig, { isTestEnv } from '@/common/config/AppCofig'
import { onError, onLaunch } from '@dcloudio/uni-app'
import { useAuthStore } from './store/auth'
import { configTheme } from './components/theme/ThemeDefine';
import { getCurrentPageUrl, navTo } from './components/utils/PageAction';
import { RequestApiConfig, RequestApiError } from '@imengyu/imengyu-utils';
import ApiCofig from './common/config/ApiCofig';
import { useAppInit } from './common/composeabe/AppInit';
import MemoryTimeOut from './common/composeabe/MemoryTimeOut';
import BugReporter, { type BugDetailDeviceInfo } from './common/BugReporter';
import { BugReporterAbstractionUniapp } from './common/BugReporter/impl/BugReporterAbstractionUniapp';
import { IconUtils } from './components/basic/IconUtils';

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


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

  //加载登录信息
  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,
});

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

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

//修改默认主题颜色
configTheme(false, (theme, defaultDarkTheme) => {
  theme.colorConfigs.default.primary = '#00b66a';
  theme.colorConfigs.pressed.primary = '#00814b';
  theme.colorConfigs.background.primary = '#dcfff0';

  theme.varOverrides['ImageDefaultImage'] = 'https://mncdn.wenlvti.net/app_static/xiangyuan/EmptyImage.png';
  return [theme, defaultDarkTheme];
});

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

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

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