import { Component, EventEmitter, Input, OnInit, Output } from '@angular/core';
import { PortalService } from './portal.service';
import { NzMessageService } from 'ng-zorro-antd/message';
import { NzModalService } from 'ng-zorro-antd/modal';
import { firstValueFrom } from 'rxjs';
import { CdkDragEnter, moveItemInArray } from '@angular/cdk/drag-drop';
import { FormControl } from '@angular/forms';
import { Router } from '@angular/router';
import { PortalHeaderContentSelectComponent } from './portal-header-content-select.component';
import { NzI18nService } from 'ng-zorro-antd/i18n';

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

<nz-page-header [nzGhost]="false">
  <nz-page-header-title>Header</nz-page-header-title>
  <nz-page-header-extra>
    <nz-badge nzDot [nzShowDot]="form?.dirty">
      <button class="btn" *can="['update', 'any', 'art-portal']" (click)="onSave()" [disabled]="!form?.dirty" i18n>保存</button>
    </nz-badge>
  </nz-page-header-extra>
</nz-page-header>

<nz-layout>

<nz-content>
<div nz-row [nzGutter]="[20, 20]" [nzAlign]="'top'" class="ms-2" 
  cdkDropListGroup>
  <div cdkDropList [cdkDropListData]="i" *ngFor="let item of form?.value; let i = index;" 
    nz-col  [nzSm]="6" [nzMd]="4" [nzLg]="4" [nzXl]="3" [nzXXl]="3"	>
    <div cdkDrag [cdkDragData]="i" (cdkDragEntered)="entered($event)" >
      <nz-card class="card-config"
        [nzHoverable]="true" [nzSize]="'small'" [nzBodyStyle]="{'padding': '0'}" 
        [ngClass]="{'card-select': item == curHeaderItem }" 
        (click)="onItemClick(item)">
        <div class="d-flex flex-column justify-content-center align-items-center">
        <div class="title">{{i18n.getLocaleId() == 'en' ? item.title.en : item.title.zh}}</div>
        <div class="subtitle">{{getItemType(item)}}</div>
        </div>
      </nz-card>
      <i class="box-delete fal fa-trash-alt" nz-popconfirm i18n-nzPopconfirmTitle nzPopconfirmTitle="确定移除该分类吗?" (nzOnConfirm)="onTrash(i)"></i>
    </div>
  </div>
  <div nz-col [nzSpan]="3"
    class="d-flex flex-column justify-content-center align-items-center flex-grow-1"
    (click)="onChooseContent()">
     <div class="blank-content d-flex flex-column justify-content-center align-items-center">
      <span><i class="fal fa-hand-point-up me-1" ></i><ng-container i18n>选择</ng-container></span>
    </div>
  </div>
  <div nz-col [nzSpan]="3"
    class="d-flex flex-column justify-content-center align-items-center flex-grow-1"
    (click)="onAddContent()">
     <div class="blank-content d-flex flex-column justify-content-center align-items-center">
      <span><i class="fal fa-plus me-1" ></i><ng-container i18n>添加</ng-container></span>
    </div>
  </div>
</div>

</nz-content>
<!-- *ngIf="form && !form.dirty" -->
<nz-footer class="d-flex flex-column justify-content-center align-items-start">
<header-item-edit class="item-edit" 
  [productId]="productId" [headerItem]="curHeaderItem"
  (onUpdate)="onHeaderUpdate($event)" >
</header-item-edit>
</nz-footer>

</nz-layout>
  `,
  styles: [`

  .card-config {
    display: flex;
    flex-direction: column;
    justify-content: center;
    align-items: center;
    border-radius: 4px;
    aspect-ratio: 2 / 1;
  }

  .card-select {
    background: dodgerblue;
    color: white;
  }

  .title {
    font-size: 20px;
    font-weight: 600;
  }

  .subtitle {
    font-size: 12px;
  }

  .blank-content {
    box-sizing: border-box;
    background-color: #eee;
    width: 100%;
    height: 100%;
    aspect-ratio: 2 / 1;
    cursor : pointer;
  }

  .box-delete {
    top:0px;
    right:0px;
    font-size: 8px !important;
    position: absolute;
    text-align: center;
    line-height: 16px;
    width:16px;
    height:16px;
    border-radius: 50%;
    background: #999;
    color:white;
    text-shadow: none;
    cursor: pointer;
  }

  .box-delete:hover {
    background: #ff0000;
  }


  .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);
  }

  nz-content {
    background: #fff;
    min-height: 320px;
  }

  nz-footer {
    background: #fff;
  }

  .item-edit {
    width: 70%;
  }

  `
  ]
})
export class PortalHeaderComponent implements OnInit {
  _productId: string;
  @Input() get productId() {
    return this._productId;
  }
  set productId(value: string) {
    this._productId = value;
    this.loadData();
  }

  curHeaderItem: any;  // 当前选中的header item
  
  form: FormControl;
  portal: any;

  @Output() onUpdate = new EventEmitter<any>();

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

  ngOnInit(): void {
  }

  loadData() {
    firstValueFrom(this.portalService.getPortal(this.productId))
      .then((resp: any) => {
        this.portal = resp;
        this.form = new FormControl(this.portal.header);
      })
      .catch(err => this.message.error(err.error?.message || err.message));
  }

  reset() {
    if (this.form && this.portal) {
      this.form.reset(this.portal.header);
    }
  }

  entered(event: CdkDragEnter) {
    console.log("preIndex=" + event.item.data + "  curIndex=" + event.container.data);
    let items = this.form.value;
    moveItemInArray(items, event.item.data, event.container.data);
    this.form.setValue(items);
    this.form.markAsDirty();
  }


  onChooseContent() {
    this.modal.create({
      nzStyle: { top: '10px' },
      nzBodyStyle: { padding: '0px 24px 0px 24px' },
      nzTitle: $localize`选择内容`,
      nzWidth: "85vw",
      nzComponentParams: {
        productId: this.productId,
      },
      nzContent: PortalHeaderContentSelectComponent,
      nzOnOk: (comp: PortalHeaderContentSelectComponent) => {
        let data = comp.data;
        if (data) {
          this.form.value.push(data);
          this.form.markAsDirty();
        }
      }
    });
  }

  onAddContent() {
    this.curHeaderItem = null;
  }


  onSave() {
    if (this.form.invalid) {
      console.log("form invalid!");
      return;
    }

    let header = Object.assign(this.form.value);
    header.forEach(e => {
      if (e.title) e.title = e.title._id;
    })
    let data = { header };
    
    firstValueFrom(this.portalService.updatePortal(this.productId, data))
      .then(res => {
        this.message.success($localize`保存成功`);
        this.form.markAsPristine(); 
        this.loadData();
        this.onUpdate.emit();
      })
      .catch(err => {
        this.message.error(err.error?.message || err.message);
      }).then(() => {
    })
  }


  
  onTrash(idx: any) {
    this.form.value.splice(idx, 1);
    this.form.markAsDirty();
    return null;
  }

  onItemClick(item: any) {
    this.curHeaderItem = item;
  }

  getItemType(item: any) {
    let link = item.link;
    let urlParams = new URLSearchParams(link.substring(link.indexOf('?')));
    let type = urlParams.get('type');
    return type;
  }

  // 来自header-item-edit的更新消息
  onHeaderUpdate(data) {
    let { oldHeaderItem, newHeaderItem } = data;
    if (!oldHeaderItem) { // 新增
      this.form.value.push(newHeaderItem);
      this.form.markAsDirty();
    } else { // 修改
      let index = this.form.value.findIndex(e => e == oldHeaderItem);
      if (index >= 0) {
        this.form.value[index] = newHeaderItem;
        this.form.markAsDirty();
      } 
    }
    this.onSave();
  }
}
