import { Component, OnDestroy, OnInit } from '@angular/core';
import { AuthService } from "./auth/auth.service";
import { LifeCommonService } from "./common/life-common.service";
import { Subscription } from "rxjs/index";
declare var wx: any;
@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.scss']
})
export class AppComponent implements OnInit, OnDestroy {
  shareGuidePageEnable: boolean;
  subscription: Subscription;
  currentVersion: any;
  isNeedAlert: boolean;
  dialogInfo: any;

  constructor(private authService: AuthService, private lifeCommonService: LifeCommonService) {
    this.subscription = lifeCommonService.shareStatus$.subscribe(status => {
      this.shareGuidePageEnable = status == '1';
    });
  }

  ngOnInit() {
    this.authService.obtainToken().subscribe(res => {
      if (res['success']) {
        localStorage.setItem('lifeToken', res['data']['token']);
        this.ydWxConfig();
      }
    });

    this.getVersion();
  }

  ngOnDestroy() {
    this.subscription.unsubscribe();
  }


  // 微信JS-SDK注册
  ydWxConfig() {
    const url = encodeURIComponent(location.href.split('#')[0]);
    this.authService.ydWxConfig(url).subscribe(res => {
      const data = res['data'];
      wx.config({
        debug: false,
        appId: data.appId,
        timestamp: data.timestamp,
        nonceStr: data.nonceStr,
        signature: data.signature,
        jsApiList: data.jsApiList,
        beta: true
      });
    });
  }

  // 关闭弹窗
  getPopInfo() {
    this.isNeedAlert = false;
    let { search, href } = window.location;
    href = href.replace(/&?t_reload=(\d+)/g, '');
    window.location.href = href + (search ? '&' : '?') + 't_reload=' + new Date().getTime();
    localStorage.setItem('Version', this.currentVersion)
  }

  getVersion() {
    this.authService.currentVersionQuery().subscribe((res) => {
      if (res['data']['currentVersion']) {
        this.currentVersion = res['data']['currentVersion'];
      }
      //如果本地没有版本号刷新并设置缓存
      if (!localStorage.getItem('Version')) {
        this.isNeedAlert = true;
        this.dialogInfo = {
          title: null,
          content: { value: '检测到新版本', align: 'center' },
          footer: [{ value: '更新', routerLink: '', className: 'weui-dialog__btn_primary' }],
        };
      } else {

        const Version = localStorage.getItem('Version');
        //如果缓存有版本号对比本地和接口版本
        if (Version != this.currentVersion) {
          this.isNeedAlert = true;
          this.dialogInfo = {
            title: null,
            content: { value: '检测到新版本', align: 'center' },
            footer: [{ value: '更新', routerLink: '', className: 'weui-dialog__btn_primary' }],
          };
        }
      }
    })
  }
}
