import { ConfigManager } from '../../manager/UserConfigManager';
import { RouterUrls } from '../../common/RouterUrls';
import { PrivacyPolicyDialog } from '../../dialog/PrivacyPolicyDialog';
import { common } from '@kit.AbilityKit';
import { LevelMode, router } from '@kit.ArkUI';
import { LoginManager } from '../../manager/LoginGlobalManager';
import { LoadingDialog } from '../../dialog/LoadingDialog';
import { AppUtil, StrUtil } from '@pura/harmony-utils';
import { EventReportGlobalManager } from '../../manager/EventReportGlobalManager';
import { EventConstants } from '../../common/EventConstants';
import { GyConfig, GyManager } from '@getui/gysdk';
import { hilog } from '@kit.PerformanceAnalysisKit';

@Entry
@ComponentV2
struct SplashPage {
  privacyDialogController?: CustomDialogController | null;

  UIContext = this.getUIContext();
  uiAbilityContext = this.UIContext.getHostContext() as common.UIAbilityContext;
  private windowClass = this.uiAbilityContext.windowStage.getMainWindowSync();

  aboutToAppear(): void {
    this.registerFont()
    this.windowClass.setWindowLayoutFullScreen(true)
    if (ConfigManager.isAgreePrivacy()) {
      LoadingDialog.show(this.getUIContext());
      ConfigManager.getOaid()
        .then(() => {
          ConfigManager.getUserConfig()
            .then(() => {
              LoadingDialog.dismiss();
              // this.initGY();
              this.toNextPage();
            });
        })
        .catch((error: Error) => {
          LoadingDialog.dismiss();
          console.error(error.message)
        })
    } else {
      this.showPrivacyDialog();
    }
  }

  aboutToDisappear() {
    this.privacyDialogController = null;
  }

  showPrivacyDialog() {
    this.privacyDialogController = new CustomDialogController({
      builder: PrivacyPolicyDialog({
        confirm: () => {
          EventReportGlobalManager.eventReport(EventConstants.APP_LAUNCH, '', '')
          LoadingDialog.show(this.getUIContext());
          ConfigManager.saveIsAgreePrivacy(true);
          ConfigManager.getOaid()
            .then(() => {
              ConfigManager.getUserConfig()
                .then(() => {
                  LoadingDialog.dismiss();
                  // this.initGY();
                  this.toNextPage();
                });
            })
            .catch((error: Error) => {
              LoadingDialog.dismiss();
              console.error(error.message)
            })
        },
        cancel: () => {
          (this.getUIContext().getHostContext() as common.UIAbilityContext)?.terminateSelf()
        }
      }),
      onWillDismiss: () => {
        return false
      },
      width: '80%',
      cornerRadius: 20,
      maskColor: '#CC000000',
      levelMode: LevelMode.EMBEDDED,
      backgroundBlurStyle: BlurStyle.NONE
    })
    this.privacyDialogController.open();
  }

  async initGY() {
    const response = await GyManager.getInstance().init(new GyConfig(AppUtil.getContext())
      .setDebug(false)
      .setPreLoginUseCache(true)
      .setChannel("scmf_hmos"))
    if (response.isSuccess()) {
      hilog.debug(0x0000, "GY", `init success ==>${response}`)
    } else {
      hilog.debug(0x0000, "GY", `init failed==>${response}`)
    }
  }

  toNextPage() {
    if (LoginManager.isLogin()) {
      this.getUIContext().getRouter().replaceUrl({ url: RouterUrls.MAIN_PAGE }, router.RouterMode.Single)
    } else {
      if (ConfigManager.isFirstUse()) {
        ConfigManager.saveFirstUse(false);
        this.getUIContext().getRouter().replaceUrl({ url: RouterUrls.GUIDE_PAGE }, router.RouterMode.Single)
      } else {
        if (StrUtil.isNotEmpty(LoginManager.getLastLoginType())) {
          this.getUIContext().getRouter().replaceUrl({ url: RouterUrls.LOGIN_PAGE }, router.RouterMode.Single)
        } else {
          this.getUIContext().getRouter().replaceUrl({ url: RouterUrls.MAIN_PAGE }, router.RouterMode.Single)
        }
      }
    }
  }

  registerFont() {
    this.getUIContext().getFont().registerFont({
      familyName: "almmsht",
      familySrc: $rawfile('font/almmShuHeiTi.ttf')
    })
    this.getUIContext().getFont().registerFont({
      familyName: "ddp500m",
      familySrc: $rawfile('font/ddp500m.otf')
    })
    this.getUIContext().getFont().registerFont({
      familyName: "ysbth",
      familySrc: $rawfile('font/youSheBiaoTiHei.ttf')
    })
  }

  build() {
    Stack({alignContent: Alignment.Top}) {
      Image($r('app.media.ic_splash_bg'))
        .width('100%')
        .height('100%')

      Image($r('app.media.ic_splash_logo'))
        .width(288)
        .height(288)
        .margin({top: 50})
    }
    .width('100%')
    .height('100%')
  }

  onBackPress(): boolean | void {
    return true;
  }
}