import { Component } from '@angular/core';
import { SplashScreen } from '@ionic-native/splash-screen/ngx';
import { StatusBar } from '@ionic-native/status-bar/ngx';
import { AppMinimize } from '@ionic-native/app-minimize/ngx';
import { Router, NavigationEnd } from '@angular/router';
import { Platform } from '@ionic/angular';

@Component({
  selector: 'app-root',
  templateUrl: 'app.component.html',
  styles: [],
  providers: [AppMinimize]
})
export class AppComponent {

  backBtnPressed = false; // 用于判断返回键是否触发
  url;
  dom;

  constructor(
    private platform: Platform,
    private splashScreen: SplashScreen,
    private statusBar: StatusBar,
    private appMinimize: AppMinimize,
    private router: Router
  ) {
    this.initializeApp();
    this.initEvent();
    this.initRouterListen();
  }

  initializeApp() {
    this.platform.ready().then(() => {
      this.statusBar.styleDefault();
      this.statusBar.backgroundColorByHexString('#ffffffff');
      this.splashScreen.hide();
      this.registerBackButtonAction(); // 注册返回按键事件
      this.platform.resume.subscribe(); // 弹出框
    });
  }

  initEvent() {
    window.addEventListener('orientationchange', function (e) {
      console.log(e);
      if (window.orientation === 180 || window.orientation === 0) {
        console.log('竖屏');
        window.location.reload();
      } else if (window.orientation === 90 || window.orientation === -90) {
        console.log('横屏');
        window.location.reload();
      }
    });
  }

  initRouterListen() {
    this.router.events.subscribe(event => { // 需要放到最后一个执行
      if (event instanceof NavigationEnd) {
        this.url = window.location.pathname;
      }
    });
  }

  registerBackButtonAction() {
    this.platform.backButton.subscribe((event) => {
      if (this.url === '/main' || this.url === '/extra') {
        if (this.backBtnPressed) {
          this.appMinimize.minimize();
          this.backBtnPressed = false;
          window.history.pushState('forward', null, this.url);
          // window.history.forward();
          return;
        } else {
          this.backBtnPressed = true;
          setTimeout(() => this.backBtnPressed = false, 2000);
          return;
        }
      } else {
        this.backBtnPressed = true;
        setTimeout(() => this.backBtnPressed = false, 2000);
        return;
      }
    });
  }
}
