import { Component, EventEmitter, Input, OnInit, Output } from '@angular/core';
import { NzMessageService } from 'ng-zorro-antd/message';
import { firstValueFrom } from 'rxjs';
import { PortalService } from './portal.service';
import { NzModalService } from 'ng-zorro-antd/modal';
import { FilterItem, FilterType } from 'src/app/lib/pager/pager-filter.component';
import { FormGroup } from '@angular/forms';
import { CdkDragDrop } from '@angular/cdk/drag-drop';

@Component({
  selector: 'app-portal-banner',
  template: `

<nz-page-header [nzGhost]="false">
  <nz-page-header-title>Banner</nz-page-header-title>
  <nz-page-header-extra>
  </nz-page-header-extra>
</nz-page-header>

<cg-pager 
    [userRouter]="false"
    [remoteUrl]="'/napi/coloring/web/banner/all'"
    [remoteHeaderUrl]="'/napi/coloring/web/banner/headers'"
    [listTemplate]="listTemplate"
    [pageSizeOptions]="[100]"
    [topPagination]="false"
    [bottomPagination]="false"
    [showOrder]="false"
    [showSearch]="false"
    [debug]="false"
    [refresh]="refreshTrigger"
    [defaultOrder]="'asc'"
    [defaultOrderBy]="'order'"
    [inputFilters]="inputFilters"
  >
</cg-pager>


<ng-template #listTemplate  let-list="list" let-headers="headers">
  <nz-radio-group class="ms-4" [(ngModel)]="enabled" >
    <label nz-radio [nzValue]="undefined" i18n>全部</label>
    <label nz-radio [nzValue]="true" i18n>启用</label>
    <label nz-radio [nzValue]="false" i18n>禁用</label>
</nz-radio-group>
<div nz-row [nzGutter]="[40, 20]" class="ms-2 mt-2">
  <div nz-col [nzSpan]="6">
      <nz-list nzBordered nzSize="small" cdkDropList (cdkDropListDropped)="dragdrop($event, list?.data)">
        <nz-list-item cdkDrag *ngFor="let item of list?.data" (click)="onFocus(item)"
          [ngClass]="{'nz-list-item-select': item == curBanner}">
          <img [src]="getNewIconUri(item.cover)" loading="lazy" class="banner-cover">
        </nz-list-item>
        <nz-list-item class="banner-plus" (click)="onNew()">
          <div class="banner-plus">
            <span><i class="fal fa-plus me-1" ></i><ng-container i18n>新增Banner</ng-container></span>
          </div>
        </nz-list-item>
    </nz-list>
  </div>
  <div nz-col [nzSpan]="18">
    <app-portal-banner-edit *ngIf="showEdit" [productId]="productId" [banner]="curBanner" 
      (onUpdateSuccess)="onBannerUpdate($event)" 
      (onAddSuccess)="onBannerAdd($event)"
      (onDeleteSuccess)="onBannerDelete($event)">
    </app-portal-banner-edit>
  </div>
</div>
</ng-template>

  `,
  styles: [`
  
  .banner-cover {
    width: 100%;
    /* aspect-ratio: 2 / 1; */
    overflow:hidden;
    cursor: pointer;
  }

  .nz-list-item-select {
    border: 2px dashed #ff00ff;
    transform: scale(1.04);
  }

  .banner-plus {
    box-sizing: border-box;
    background-color: #eee;
    width: 100%;
    text-align: center;
    aspect-ratio: 2 / 1;
    cursor : pointer;
    display: flex;
    justify-content: center;
    align-items: center;
  }

  nz-list-item:hover {
    transform: scale(1.04);
  }


  :host ::ng-deep .ant-list-bordered.ant-list-sm .ant-list-item {
    padding: 4px 2px 4px 2px;
  }


  ::ng-deep .cdk-drag-preview {
    display: table;
  }

  ::ng-deep .cdk-drag-placeholder {
    opacity: 0;
  }

  .cdk-drag-preview {
    box-sizing: border-box;
    border-radius: 4px;
    box-shadow: 0 5px 5px -3px rgba(0, 0, 0, 0.2),
                0 8px 10px 1px rgba(0, 0, 0, 0.14),
                0 3px 14px 2px rgba(0, 0, 0, 0.12);
  }

  .cdk-drag-placeholder {
    opacity: 0;
  }

  .cdk-drag-animating {
    transition: transform 250ms cubic-bezier(0, 0, 0.2, 1);
  }

  `
  ]
})
export class PortalBannerComponent implements OnInit {
  _productId: string;
  @Input() get productId() {
    return this._productId;
  }
  set productId(value: string) {
    this._productId = value;
    this.inputFilters = { pid: value, enabled: this.enabled };
    this.showEdit = false;
  }

  form: FormGroup;
  
  curBanner: any;

  refreshTrigger: number = 0;

  showEdit: boolean = false;
  
  @Output() onUpdate = new EventEmitter<any>();

  _enabled: boolean = true;
  get enabled() {
    return this._enabled;
  }
  set enabled(value) {
    this._enabled = value;
    this.inputFilters = { pid: this.productId, enabled: value };
  }
 
  inputFilters: any;

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

  ngOnInit(): void {
  }


  // 解决图片uri相同但图片实际已经变更而浏览器不刷新的问题
  getNewIconUri(uri: string) {
    return `${uri}?n=${this.refreshTrigger}`;
  }

  onBannerUpdate(value: any) {
    this.refreshTrigger++;
    this.onUpdate.emit();
  }

  onBannerAdd(value: any) {
    this.refreshTrigger++;
    this.curBanner = value;
    this.onUpdate.emit();
  }

  onBannerDelete(value: any) {
    this.refreshTrigger++;
    this.curBanner = null;
    this.onUpdate.emit();
  }

  onFocus(banner) {
    this.curBanner = Object.assign({}, banner);
    this.curBanner.cover = `${this.curBanner.cover}?n=${this.refreshTrigger}`;
    // this.curBanner = banner;
    this.showEdit = true;
  }

  
  onNew() {
    this.curBanner = null;
    this.showEdit = true;
  }

  onDelete(bannerId: string) {
    return () => {
      return this.portalService.bannerRemove(bannerId);
    }
  }

  dragdrop(event: CdkDragDrop<string[]>, list) {
    console.log(event);
    
    let data = [];
    let from = event.previousIndex, to = event.currentIndex;
    if (from == to) return;
    const target = list[from];
    const delta = to < from ? - 1: 1;
    for (let i = from; i != to; i += delta) {
      data.push({ _id: list[i + delta]._id, order: list[i].order });
      list[i] = list[i + delta];
    }
    data.push({ _id: target._id, order: list[to].order });
    list[to] = target;

    this.updateOrder(data);

    // moveItemInArray(list, event.previousIndex, event.currentIndex);
  }

  /**
   * 更新order
   * @param data : 形如：[{_id: xxx, order:xxx}] 
   */
  updateOrder(data) {
    console.log(data);
    firstValueFrom(this.portalService.batchBannerUpdate(this.productId, data))
      .then(res => {
        this.refreshTrigger++;
      })
      .catch(err => {
        this.message.error(err.error?.message || err.message);
        console.log(err);
      }).then(() => {
      })
  }



}
