import { Component, ElementRef, EventEmitter, Input, OnInit, Output, ViewChild } from '@angular/core';
import { NzMessageService } from 'ng-zorro-antd/message';
import { NzModalService } from 'ng-zorro-antd/modal';
import { PortalService } from './portal.service';
import { firstValueFrom } from 'rxjs';
import { NzI18nService } from 'ng-zorro-antd/i18n';
import { NzCarouselComponent } from 'ng-zorro-antd/carousel';

@Component({
  selector: 'app-portal-preview',
  template: `
    <div class="box">
      <h5 i18n>画廊</h5>
      <div class="banner">
        <nz-carousel nzAutoPlay (click)="onBannerClick($event)" #carouselComp>
          <ng-container *ngIf="!banner || banner.length <= 0">
            <div nz-carousel-content *ngFor="let index of testArray">
              <h4>{{ index }}</h4>
            </div>
          </ng-container>
          <div nz-carousel-content *ngFor="let ban of banner">
            <img class="banner-img" [src]='ban.cover' loading="lazy">
          </div>
        </nz-carousel>
      </div>

      <div #columnsDiv class="columns" (click)="onHeaderClick()">
        <span class="column" *ngIf="!header || header.length == 0">header区</span>
        <span class="column" *ngFor="let cat of header; let i=index" (click)="onColumnClick(cat)"
          [ngClass]="{'column-select': curTag == cat}">
          {{ cat.title }}
        </span>
      </div>

      <div class="content">
        <div nz-row [nzGutter]="[8, 8]" class="pt-2 pb-2 scroll ">
          <div nz-col [nzSpan]="12"
            *ngFor="let item of dataList; let i=index" class="rounded d-flex flex-column text-secondary ">
            <div class="img d-flex  flex-column align-items-center position-relative">
              <img [src]="item?.thumb" loading="lazy"/>
            </div>
          </div>
        </div>
      </div>

      <div class="footer pt-2">
        <div class="text-center">
          <i class="footer-icon fal fa-home"></i>
          <div class="footer-title">主页</div>
        </div>
        <div class="text-center">
          <i class="footer-icon fal fa-clock"></i>
          <div class="footer-title">每日一图</div>
        </div>
        <div class="text-center">
          <i class="footer-icon fal fa-image"></i>
          <div class="footer-title">我的作品</div>
        </div>
      </div>

    </div>
  `,
  styles: [`

  .box {
    height: 610px;
    width: 100%;
    padding: 50px 15px 10px 15px;
    background-image: url('../../../assets/images/phone.png');
    background-repeat: no-repeat;
    background-size:100% 100%;
  }

  .banner {
    height: 100px;
  }

  .banner-img {
    width:100%;
    /* aspect-ratio: 3 / 1; */
    overflow:hidden;
  }

  [nz-carousel-content] {
    text-align: center;
    height: 50px;
    background: #364d79;
    color: #fff;
    overflow: hidden;
    cursor : pointer;
  }

  h4 {
    color: #fff;
    margin-bottom: 0;
    user-select: none;
  }

  .columns {
    margin-left: -6px;
    text-align:left;
    white-space: nowrap;  /*控制不要换行*/
    overflow: auto;
    margin-top: 15px;
    font-size: 13px;
    line-height: 13px;
    font-weight: 600;
    /* Firefox hide scrollbar*/
    scrollbar-width: none; 
  }
  /*webkit browser hide scrollbar*/
  .columns::-webkit-scrollbar { 
    display: none;
  }

  .column {
    cursor: pointer;
    display:inline-block;
    position: relative;
    margin-left: 6px;
    padding: 3px 6px;
    background: transparent;
  }

  .column-select {
    color: #ff8c00;
    background: #ddd;
    border-style: solid;
    border-width: 1px;
    border-color: #fff8dc;
  }

  .column:hover {
    color: #ff8c00;
    background: #F2F2F2;
  }

  .content {
    /* background: #f5f5f5; */
    margin-top: 8px;
    height: 320px;
    overflow: auto;
    overflow-x: hidden;
  }
  .content::-webkit-scrollbar { 
    display: none;
  }
  .content-title {
    font-size: 16px;
    font-weight: 600;
  }

  .footer {
    height: 50px;
    display: flex;
    justify-content: space-around;
    align-items: flex-start;
  }
  .footer-icon {
    font-size: 20px;
  }
  .footer-title {
    font-size: 6px;
    line-height: 16px;
  }

  div.img{
    height:100%;
    aspect-ratio: 1 / 1;
    overflow:hidden;
    background-color:#fefefe;
  }

  img{
    height:100%;
    cursor : pointer;
  }

  `
  ]
})

export class PortalPreviewComponent implements OnInit {
  @ViewChild('columnsDiv') columnsDiv: ElementRef;
  @ViewChild('carouselComp') carouselComp: NzCarouselComponent;
  @Output() onFocus = new EventEmitter<any>();

  _productId: string;
  @Input() get productId() {
    return this._productId;
  }
  set productId(value: string) {
    this._productId = value;
    this.curTag = null;
    this.dataHash = {};
    this.loadData();
  }

  testArray = [1, 2, 3, 4];

  _curTag: any;  // 当前选中的栏目/分类/专辑
  @Input() set curTag(value: any) {
    this._curTag = value;
  }
  get curTag() {
    return this._curTag;
  }
  get curTagIdx(): number {
    let idx = this.header?.findIndex(e => e == this.curTag);
    if (idx < 0) idx = 0;
    return idx; 
  }

  banner: any[] = [];
  header: any[] = [];
  content: any[] = [];  // 暂时没用
  footer: any[] = [];   // 暂时没用

  dataHash: any = {};
  get dataList(): any[] {
    if (!this.curTag) return null;
    if (!this.curTag.link.startsWith('art://inapp')) return null;
    let link = this.curTag.link;
    let urlParams = new URLSearchParams(link.substring(link.indexOf('?')));
    let id = urlParams.get('id');
    let type = urlParams.get('type');
    let key = `${type}_${id}`;
    let list = this.dataHash[key];
    if (!list) {
      list = [];
      this.dataHash[key] = list;
      this.loadContentData(type, id, key);
    }
    return list;
  }

  constructor(
    private portalService: PortalService,
    private message: NzMessageService,
    private modal: NzModalService,
    public i18n: NzI18nService,
  ) { 
  }

  ngOnInit(): void {
    this.loadData();
  }

  ngAfterViewInit(): void {
    this.adjustScroll();
  }

  loadData() {
    
    let lang = this.i18n.getLocaleId() == 'en' ? 'en' : 'zh';

    firstValueFrom(this.portalService.apiGetPortal(this.productId, lang))
      .then((resp: any) => {
        this.banner = resp?.banner;
        this.header = resp?.header;
        if (!this.curTag && this.header) {
          this.curTag = this.header[0];
        }
      })
  }

  loadContentData(type, id, key) {
    if (type == 'column') {
      firstValueFrom(this.portalService.apiEpgContentList(this.productId, id))
      .then((resp: any) => {
        this.dataHash[key] = resp.data || [];
      });
    } else if (type == 'album') {
      let lang = this.i18n.getLocaleId() == 'en' ? 'en' : 'zh';
      firstValueFrom(this.portalService.apiAlbumDetail(id, lang))
      .then((resp: any) => {
        this.dataHash[key] = resp.contents || [];
      });
    } else if (type == 'collection') {
      let lang = this.i18n.getLocaleId() == 'en' ? 'en' : 'zh';
      firstValueFrom(this.portalService.apiCollectionDetail(id, lang))
      .then((resp: any) => {
        this.dataHash[key] = resp.contents || [];
      });
    }
  }

  // 调整栏目进度条
  adjustScroll() {
    let divElem = this.columnsDiv.nativeElement as HTMLDivElement;
    let viewWidth = divElem.clientWidth;  //视窗宽度
    let count = viewWidth / (divElem.scrollWidth / this.header.length); //视窗内显示了多少个元素
    let width = viewWidth / count; //每个元素占用的宽度
    let scrollPos = (divElem.scrollWidth / this.header.length) * this.curTagIdx - count * width / 2 + width /2 ;
    divElem.scroll({left: scrollPos, top: 0, behavior: 'smooth'});
  }


  onBannerClick(event) {
    console.log(event);
    this.carouselComp.next();
    this.onFocus.emit('banner');
  }

  onColumnClick(tag: any) {
    this.curTag = tag;
    this.adjustScroll();
  }

  onHeaderClick() {
    this.onFocus.emit('header');
  }

}
