import { Component, HostListener, OnInit } from '@angular/core';
import { IonApp, IonRouterOutlet } from '@ionic/angular/standalone';
import Parse from 'parse';
import { StatusBar, Style, StatusBarStyle } from '@capacitor/status-bar';
import { BackgroundColorService } from '../services/background-color.service';
import { Router } from '@angular/router';
// 添加IonIcons
import { addIcons } from 'ionicons';
import * as icons from 'ionicons/icons';
addIcons(icons)
import { SafariViewController } from '@ionic-native/safari-view-controller/ngx';
@Component({
  selector: 'app-root',
  standalone: true,
  imports: [IonApp, IonRouterOutlet],
  templateUrl: './app.component.html',
  styleUrl: './app.component.scss',
  providers: [SafariViewController],
})
export class AppComponent implements OnInit {
  title = 'live-app';
  // @HostListener("document:visibilitychange", ["$event"])
  // onvisibilitychange(event) {
  //   let isExits = event.target.visibilityState
  //     if (isExits == 'visible') {
  //       console.log('进入该页面')
  //     } else {
  //       console.log('离开该页面')
  //     }
  // }
  constructor(
    private router: Router,
    private backgroundColorService: BackgroundColorService
  ) {
    this.initParseService();
    this.initStatusBar();
  }
  ngOnInit() {
    // 初始化状态栏背景色
    this.setStatusBarColor();

    // 监听路由变化
    this.router.events.subscribe((event) => {
      if (event.constructor.name === 'NavigationEnd') {
        this.setStatusBarColor();
      }
    });
  }
  initParseService() {
    Parse.initialize('ncloudmaster');
    (Parse as any).serverURL = 'https://server.fmode.cn/parse';
    localStorage.setItem('company', 'Qje9D4bqol');
    this.saveParamsInvite();
  }
  saveParamsInvite() {
    let searchParams = this.searchParse();
    let invite = searchParams?.get('invite');
    invite && localStorage.setItem('invite', invite);
  }
  searchParse(url?: string): URLSearchParams {
    url = url || location.href;
    let u = new URL(url);
    return u.searchParams;
  }

  async initStatusBar() {
    try {
      // 设置状态栏为沉浸式模式
      // await StatusBar.setOverlaysWebView({ overlay: true });

      // 设置状态栏样式（可选）
      await StatusBar.setStyle({ style: StatusBarStyle.Light });

      // 设置状态栏背景颜色（可选）
      // await StatusBar.setBackgroundColor({ color: '#000000' });
    } catch (error) {
      console.warn('设置状态栏时出错:', error);
    }
  }

  async setStatusBarColor() {
    try {
      // 获取当前页面的背景色
      const backgroundColor = this.backgroundColorService.getBackgroundColor();

      // 设置状态栏背景色
      await StatusBar.setBackgroundColor({ color: backgroundColor });
    } catch (error) {
      console.warn('设置状态栏背景色时出错:', error);
    }
  }
}
