import { Component, OnInit, Output, EventEmitter, Input } from '@angular/core';
import { FormBuilder, Form, FormGroup, Validators } from '@angular/forms';
import { NzMessageService } from 'ng-zorro-antd/message';
import { FormUtils } from 'src/app/lib/utils/form-utils';
import { firstValueFrom } from 'rxjs';
import { AlbumService } from './album.service';
import { NzModalRef } from 'ng-zorro-antd/modal';
import { NzUploadFile } from 'ng-zorro-antd/upload';
import Utils from 'src/app/lib/filler/common/utils';

@Component({
  selector: 'app-album-add',
  template: `

    <p *ngIf="debug">{{form.value|json}}</p>

<form [formGroup]="form" autocomplete="off" (ngSubmit)="onSubmit()" novalidate class="form-horizontal ">
  
  <nz-form-item>
    <nz-form-label nzFor="icon" nzRequired i18n>icon图</nz-form-label>
    <div>
      <div *ngIf="iconFile && !iconRatioGood()" class="text-danger" i18n>
        尺寸错误: 要求等宽高
      </div>
      <div *ngIf="iconFile && !iconSizeGood()" class="text-danger" i18n>
        图片大小超过限制（最大允许2M）
      </div>
      <div class="upload-box-icon" [ngClass]="{'good': iconFile && iconSizeGood() && iconSizeGood(), 'bad': (iconFile && (!iconSizeGood() || !iconRatioGood()))}">
        <nz-upload class="thumb-uploader" nzFileType="image/png,image/jpeg,image/jpg" nzAccept="image/png,image/jpeg,image/jpg"
          nzListType="picture-card" [nzShowUploadList]="false" [nzBeforeUpload]="beforeIconUpload">
          <div *ngIf="!iconImage" class="text-secondary"><i nz-icon [nzType]="'plus'"></i><span>上传icon</span></div>
          <img class="preview" *ngIf="iconImage" [src]="iconImage.src"/>
        </nz-upload>
      </div>
      <div *ngIf="iconFile && iconImage" class="text-secondary">
        <small>{{iconFile.size | dataSize}}, {{iconFile.type}}, {{iconImage.width + 'x' + iconImage.height}}</small>
      </div>
    </div>    
  </nz-form-item>

  <nz-form-item>
    <nz-form-label nzFor="cover" nzRequired i18n>Cover图</nz-form-label>
    <div>
      <div *ngIf="coverFile && !coverRatioGood()" class="text-danger" i18n>
        尺寸错误: 要求宽高比：2:1
      </div>
      <div *ngIf="coverFile && !coverSizeGood()" class="text-danger" i18n>
        图片大小超过限制（最大允许2M）
      </div>
      <div class="upload-box-cover" [ngClass]="{'good': coverFile && coverSizeGood() && coverSizeGood(), 'bad': (coverFile && (!coverSizeGood() || !coverRatioGood()))}">
        <nz-upload class="thumb-uploader" nzFileType="image/png,image/jpeg,image/jpg" nzAccept="image/png,image/jpeg,image/jpg"
          nzListType="picture-card" [nzShowUploadList]="false" [nzBeforeUpload]="beforeHeaderUpload">
          <div *ngIf="!coverImage" class="text-secondary"><i nz-icon [nzType]="'plus'"></i><span>上传头图</span></div>
          <img class="preview" *ngIf="coverImage" [src]="coverImage.src"/>
        </nz-upload>
      </div>
      <div *ngIf="coverFile && coverImage" class="text-secondary">
        <small>{{coverFile.size | dataSize}}, {{coverFile.type}}, {{coverImage.width + 'x' + coverImage.height}}</small>
      </div>
    </div>    
  </nz-form-item>

  <nz-form-item>
    <nz-form-label nzFor="tag" nzRequired i18n>TAG</nz-form-label>
    <nz-form-control i18n-nzErrorTip nzErrorTip="请输入绑定的标签">
      <input nz-input formControlName="tag" id="tag" i18n-placeHolder placeHolder="专辑唯一标识，如horse, baby等">
    </nz-form-control>
  </nz-form-item>

  <nz-form-item>
    <nz-form-label nzFor="title" nzRequired i18n>名称</nz-form-label>
    <nz-form-control i18n-nzErrorTip nzErrorTip="请选择多语翻译">
      <nz-select id="title" formControlName="title" i18n-nzPlaceHolder nzPlaceHolder="请选择多语言">
        <nz-option *ngFor="let item of translateOptions; let i=index" [nzValue]="item.value" [nzLabel]="item.label"></nz-option>
      </nz-select>
    </nz-form-control>
  </nz-form-item>

  <nz-form-item>
    <nz-form-label nzFor="slogon" i18n>口号</nz-form-label>
    <nz-form-control i18n-nzErrorTip nzErrorTip="请选择多语翻译">
      <nz-select id="slogon" formControlName="slogon" i18n-nzPlaceHolder nzPlaceHolder="slogon，支持多语言">
        <nz-option *ngFor="let item of translateOptions; let i=index" [nzValue]="item.value" [nzLabel]="item.label"></nz-option>
      </nz-select>
    </nz-form-control>
  </nz-form-item>

  <nz-form-item>
    <nz-form-label nzFor="order" nzRequired i18n>排序</nz-form-label>
    <nz-form-control i18n-nzErrorTip nzErrorTip="排序">
      <input nz-input formControlName="order" id="order" i18n-nzPlaceHolder nzPlaceHolder="排序">
    </nz-form-control>
  </nz-form-item>

  <div class="text-end">
    <button nz-button class="me-2" type="button" (click)="modalRef.close()" i18n>取消</button>
    <button nz-button nzType="primary" type="submit" [disabled]="isLoading" i18n>添加</button>
  </div>

</form>
  `,
  styles: [`

  .upload-box-icon {
    display: flex;
    width: 100px;
    height: 100px;
    border:2px dashed #ccc;
    border-radius:6px;
    padding: 8px;
  }

  .upload-box-cover {
    display: flex;
    width: 200px;
    height: 100px;
    border:2px dashed #ccc;
    border-radius:6px;
    padding: 8px;
  }

  .bad {
    border-color:#cc0000;
  }
  .good{
    border-color:#00cc00;
  }

  .preview {
    width: auto;
    height: auto;
    max-width: 100%;
    max-height: 100%;  
  }

  :host ::ng-deep .thumb-uploader > .ant-upload {
    width: 100%;
    height:100%;
    aspect-ratio: 1 / 1;
  }

  `]
})
export class AlbumAddComponent implements OnInit {

  @Input() pid: string;

  @Output() onSuccess = new EventEmitter<any>();
  @Output() onError = new EventEmitter<any>();
  @Input() debug: boolean = false;

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

  form: FormGroup;
  isLoading = false;

  translateOptions: any[] = [];

  iconFile: File;
  iconImage: HTMLImageElement;
  coverFile: File;
  coverImage: HTMLImageElement;

  constructor(
    private albumService: AlbumService,
    private fb: FormBuilder,
    private message: NzMessageService,
    public modalRef: NzModalRef,
  ) {

    firstValueFrom(this.albumService.translateOptions()).then((resp: any[]) => {
      this.translateOptions = resp;
    }) 
  }

  ngOnInit() {
    this.form = this.fb.group({
      tag: [null, [Validators.required]],
      order: [1000, [Validators.required]],
      title: [null, [Validators.required]],
      slogon: [null],
    })
  }

  onSubmit() {
    if (!this.coverFile || !this.coverRatioGood() || !this.coverSizeGood()) {
      this.message.error("请上传头图");
      return;
    }
    if (this.form.invalid) {
      FormUtils.markAsDirty(this.form);
      return;
    }
    this.isLoading = true;
    let formData = this.getFormData();
    firstValueFrom(this.albumService.add(formData))
      .then(res => {
        this.onSuccess.emit(this.form.value);
        this.message.success($localize`添加成功`);
      })
      .catch(err => {
        this.message.error(err.error?.message || err.message);
        this.onError.emit(err);
      }).then(() => {
        this.isLoading = false;
      })
  }

  getFormData() {
    let formData = new FormData();

    formData.append('pid', this.pid);

    for (let key in this.form.controls) {
      if (this.form.controls[key].dirty && this.form.controls[key].valid) {
        formData.append(key, this.form.controls[key].value);
      }
    }

    if (this.iconFile) {
      formData.append('icon', this.iconFile);
    }
    if (this.coverFile) {
      formData.append('cover', this.coverFile);
    }

    return formData;
  }

    //////////////////////////////// upload ///////////////////////////////
    iconSizeGood() {
      if (this.iconFile && this.iconFile.size > 1024 * 1024 * 2) return false;
      return true;
    }
  
    iconRatioGood() {
      if (this.iconImage && this.iconImage.width == this.iconImage.height) return true;
      return false;
    }
  
    beforeIconUpload = (file: NzUploadFile): boolean => {
      this.iconFile = file as unknown as File;
      Utils.blobToImage(this.iconFile).then(img => {
        this.iconImage = img;
      })
      return false;
    };

    coverSizeGood() {
      if (this.coverFile && this.coverFile.size > 1024 * 1024 * 2) return false;
      return true;
    }
  
    coverRatioGood() {
      if (this.coverImage && this.coverImage.width == this.coverImage.height * 2) return true;
      return false;
    }
  
    beforeHeaderUpload = (file: NzUploadFile): boolean => {
      this.coverFile = file as unknown as File;
      Utils.blobToImage(this.coverFile).then(img => {
        this.coverImage = img;
      })
      return false;
    };

}
