import { Component, ElementRef, OnDestroy, OnInit, ViewChild } from '@angular/core';
import { ActivatedRoute, NavigationEnd, Router, RouterStateSnapshot } from '@angular/router';
import { NzContentComponent } from 'ng-zorro-antd/layout';
import { NzMessageService } from 'ng-zorro-antd/message';
import { delay, filter, firstValueFrom, interval, repeatWhen, Subscription, switchMap, takeWhile, timer } from 'rxjs';
import { AuthService } from './auth/auth.service';
import { MsgService } from './pages/msg/msg.service';

@Component({
  selector: 'admin-layout',
  template: `


<nz-layout class="app-layout">
  <nz-sider class="menu-sidebar"
            [nzCollapsible]="true"
            nzTheme="dark"
            [nzCollapsedWidth]="64"
            nzWidth="216px"
            [nzCollapsed]="isCollapsed"
            [nzTrigger]="null">
    <div class="menu-sidebar-inner">
      <div class="sidebar-logo">
        <a href="https://ng.ant.design/" target="_blank">
          <img src="https://ng.ant.design/assets/img/logo.svg" alt="logo">
          <h1 i18n>创作平台</h1>
        </a>
      </div>
      <admin-menu class="menu" [isCollapsed]="isCollapsed"></admin-menu>
    </div>

  </nz-sider>
  <nz-layout >

    <nz-header class="header">
      <div class="app-header d-flex flex-row ">
        <span class="header-trigger" (click)="isCollapsed = !isCollapsed">
            <i class="trigger" nz-icon [nzType]="isCollapsed ? 'menu-unfold' : 'menu-fold'" ></i>
        </span>

        <ul nz-menu nzMode="horizontal">
          <li nz-submenu  nzIcon="user">
            <span title class="d-inline-block">
              {{profile?.username}}
              <i nz-icon nzType="down" style="font-size:12px;"  ></i>
            </span>
            <ul>
                <li nz-menu-item (click)="logout()" >
                  <i nz-icon nzType="logout"  ></i> 
                  <span class="d-inline-block pr-1" i18n>退出</span>
                </li>
            </ul>
          </li>
          <!-- <a (click)="open()">
            <nz-badge nzSize="small" [nzCount]="unreadMsgs?.length" [nzOffset]="[10, -3]" i18n-nzTitle nzTitle="系统消息">
              <i nz-icon nzType="bell" style="font-size:12px;"></i>
            </nz-badge>
          </a> -->
          <!-- <nz-drawer [nzClosable]="false" [nzVisible]="visible" nzPlacement="right" (nzOnClose)="close()" >
            <ng-container *nzDrawerContent>
              <ng-container *ngFor="let msg of unreadMsgs; let i=index">
                <div>
                <span style="color:#cd5c5c; font-size:12px" i18n>(未读)</span>
                  {{msg.from.name || msg.from.username}} {{msg.time | dateDist }}<ng-container i18n>前</ng-container> <strong>{{msg.content}}</strong>:
                  <div style="display: flex;">
                      <div style="display: inline-block; margin-right: 10px">
                        <a (click)="onDetail(msg.art._id); setRead([msg._id])">
                          <img [src]="msg.art.thumb" width="100px" loading="lazy" />
                        </a>
                      </div>
                      <div style="display: inline-block; font-size: 13px; color: #5f9ea0">
                        <ng-container i18n>作品</ng-container>: {{msg.art.name}} <br />
                        <ng-container i18n>作者</ng-container>: {{msg.art.user.name || msg.art.user.username}} <br />
                        <ng-container i18n>区块数</ng-container>: {{msg.art.areaCount}} <br />
                        <ng-container i18n>类型</ng-container>: {msg.art.hasSpecial ? 'true' : 'false', select,  true {彩绘}  false {普通}} <br />
                        <ng-container i18n>分类</ng-container>: {{msg.art.tags.join(', &nbsp;')}} 
                      </div>
                    </div>
                </div>
              </ng-container>
              <ng-container *ngFor="let msg of readedMsgs; let i=index">
                <div>
                  <span style="color:#5f9ea0; font-size:12px" i18n>(已读)</span>
                  {{msg.from.name || msg.from.username}} {{msg.time | dateDist }}<ng-container i18n>前</ng-container> <strong>{{msg.content}}</strong>:
                    <div style="display: flex;">
                      <div style="margin-right: 10px">
                        <a (click)="onDetail(msg.art._id)">
                          <img [src]="msg.art.thumb" width="100px" loading="lazy" />
                        </a>
                      </div>
                      <div style="font-size: 13px; color: #5f9ea0">
                        <ng-container i18n>作品</ng-container>: {{msg.art.name}} <br />
                        <ng-container i18n>作者</ng-container>: {{msg.art.user.name || msg.art.user.username}} <br />
                        <ng-container i18n>区块数</ng-container>: {{msg.art.areaCount}} <br />
                        <ng-container i18n>类型</ng-container>: {msg.art.hasSpecial ? 'true' : 'false', select,  true {彩绘}  false {普通}} <br />
                        <ng-container i18n>分类</ng-container>: {{msg.art.tags.join(', &nbsp;')}} 
                      </div>
                    </div>
                </div>
              </ng-container>
            </ng-container>
          </nz-drawer>  -->
        </ul>
      </div>
    </nz-header>
    <nz-content >
      <div class="inner-content" #content >
        <router-outlet></router-outlet>
      </div>
    </nz-content>
  </nz-layout>
</nz-layout>

  `,
  styles: [`

:host {
  display: flex;
  text-rendering: optimizeLegibility;
  -webkit-font-smoothing: antialiased;
  -moz-osx-font-smoothing: grayscale;
}

.app-layout {
  align-items:stretch;
}

.menu-sidebar {
  position: relative;
  z-index: 1001;
  min-height: 100vh;
  box-shadow: 2px 0 6px rgba(0,21,41,.35);
}

.menu-sidebar-inner{
  position:sticky;
  height:100vh;
  top:0;
  left:0;
  display:flex;
  flex-direction:column;
  background: #001529;
}

.menu {
  flex:1;
}

.sidebar-logo {
  height: 64px;
  padding-left: 14px;
  overflow: hidden;
  line-height: 64px;
}

.sidebar-logo img {
  display: inline-block;
  height: 32px;
  width: 32px;
  vertical-align: middle;
}

.sidebar-logo h1 {
  display: inline-block;
  margin: 0 0 0 20px;
  color: #fff;
  font-weight: 600;
  font-size: 14px;
  font-family: Avenir,Helvetica Neue,Arial,Helvetica,sans-serif;
  vertical-align: middle;
}

nz-header {
  padding: 0;
  width: 100%;
  z-index: 1000;
}

.app-header {
  position: relative;
  justify-content: space-between;
  height: 64px;
  padding: 0;
  background: #fff;
  box-shadow: 0 1px 4px rgba(0,21,41,.08);
}

.header-trigger {
  height: 64px;
  padding: 0px 24px;
  font-size: 20px;
  cursor: pointer;
  transition: all .3s,padding 0s;
}

.trigger:hover {
  color: #1890ff;
}

nz-content {
  margin: 0px;
  background-color:white;
}

.inner-content {
  padding: 10px;
  background: #fff;
  height: 100%;
}

nz-badge {
  margin-right: 40px;
}

    `]
})
export class AdminLayout implements OnInit, OnDestroy {


  @ViewChild('content') nzContent: ElementRef;

  isCollapsed = true;
  profile: any;
  currentUrl: string;
  // msgInterval: Subscription;  // 轮询查阅消息定时器
  // unreadMsgs: any[] = []; // 未读消息列表
  // readedMsgs: any[] = []; // 已读消息列表
  constructor(
    private auth: AuthService,
    private message: NzMessageService,
    private router: Router,
    private msg: MsgService,
  ) {
    firstValueFrom(this.auth.profile()).then(res => {
      this.profile = res;
      console.log('profile:', this.profile);
    }).catch(err => {
      this.message.warning(err.error?.message || err.message);
    })

    //获取当前的url, 用于logout return
    this.router.events
      .pipe(filter((event: any) => event instanceof NavigationEnd))
      .subscribe((event: any) => {
        this.currentUrl = event.url;
      });

    this.router.events.subscribe(e => {
      /*
      if (this.nzContent?.nativeElement) {
        let el = this.nzContent?.nativeElement as HTMLElement;
        console.log('navigation:', el.scrollTop, e);
      }else{
        console.log('navigation:', e);
      }
      */
    })

  }


  ngOnInit() {
    // 启动轮询
    // this.msgInterval = this.msg.msgPolling.subscribe((res: any) => {
    //   this.unreadMsgs = res.unread;
    //   this.readedMsgs = res.readed;
    // })
  }

  ngOnDestroy(): void {
    // this.msgInterval.unsubscribe();
  }

  logout() {
    firstValueFrom(this.auth.signOut()).then(res => {
      this.router.navigate(['/auth/login'], {
        queryParams: {
          return: this.currentUrl,
        }
      });
    }).catch(err => {
      this.message.warning(err.error?.message || err.message);
    })
  }

  onDetail(artId: string) {
    this.router.navigate(['/pages/detail', artId]); 
  }

  // setAllRead() {
  //   // 没处理好， 应注意ids可能过大
  //   if (this.unreadMsgs.length > 0) {
  //     let ids = this.unreadMsgs.map(m => m._id);
  //     firstValueFrom(this.msg.setRead(ids)).then(res => {
  //       this.unreadMsgs = [];
  //     }).catch(err => {
  //       this.message.warning(err.error?.message || err.message);
  //     })
  //   }
  // }

  // setRead(ids: string[]) {
  //   firstValueFrom(this.msg.setRead(ids)).then(res => {
  //     this.unreadMsgs = [];
  //   }).catch(err => {
  //     this.message.warning(err.error?.message || err.message);
  //   })
  // }

  ///////////////////////// right Drawer //////////////////////
  // visible = false;
  // open(): void {
  //   this.visible = true;
  // }

  // close(): void {
  //   this.visible = false;
  //   this.setAllRead();
  // }

}
