import { Component, EventEmitter, Input, OnInit, Output } from '@angular/core';
import { FormBuilder, FormGroup, Validators } from '@angular/forms';
import { PortalService } from './portal.service';
import { NzMessageService } from 'ng-zorro-antd/message';
import { NzModalService } from 'ng-zorro-antd/modal';
import { firstValueFrom } from 'rxjs';
import { FormUtils } from 'src/app/lib/utils/form-utils';
import { NzUploadFile } from 'ng-zorro-antd/upload';
import Utils from 'src/app/lib/filler/common/utils';
import { PortalBannerContentSelectComponent } from './portal-banner-content-select.component';

@Component({
  selector: 'app-portal-banner-edit',
  template: `
<form [formGroup]="form" autocomplete="off" (ngSubmit)="onSubmit()" novalidate class="form-horizontal ">

<nz-form-item>
  <!-- <nz-form-label nzFor="icon" i18n>Banner图</nz-form-label> -->
  <div>
    <div *ngIf="coverFile && !iconRatioGood()" class="text-danger" i18n>
      尺寸错误: 要求等宽高
    </div>
    <div *ngIf="coverFile && !iconSizeGood()" class="text-danger" i18n>
      图片大小超过限制（最大允许2M）
    </div>
    <div class="upload-box" [ngClass]="{'good': coverFile && iconSizeGood() && iconSizeGood(), 'bad': (coverFile && (!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]="beforeUpload">
        <div *ngIf="!coverImage && !banner?.cover" class="text-secondary"><i nz-icon [nzType]="'plus'"></i><span>Banner图</span></div>
        <img class="preview" *ngIf="coverImage" [src]="coverImage.src"/>
        <img class="preview" *ngIf="!coverImage && banner?.cover" [src]="banner?.cover"/>
      </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="link" i18n>Link</nz-form-label>
  <nz-form-control i18n-nzErrorTip nzErrorTip="请输入Link">
    <input nz-input formControlName="link" id="link" i18n-placeHolder placeHolder="请选择内容或手动输入link">
    <a nz-button nzType="link" nz-tooltip [nzTooltipTitle]="linkTemplate" (click)="onSelectContent()">选择</a>
    <ng-template #linkTemplate>
      <div>link格式形如：</div>
      <div>链接到每日一图: art://inapp?type=daily</div>
      <div>链接到单个作品: art://inapp?type=single&id=xxx</div>
      <div>链接到某个栏目: art://inapp?type=column&id=xxx</div>
      <div>链接到某个专辑: art://inapp?type=album&id=xxx</div>
      <div>链接到某个收集: art://inapp?type=collection&id=xxx</div>
      <div>链接到所有专辑: art://inapp?type=allalbum</div>
      <div>链接到所有收集: art://inapp?type=allcollection</div>
      <div>外部链接: art://outapp?url=https://xxxx</div>
    </ng-template>
  </nz-form-control>
</nz-form-item>


<nz-form-item>
  <nz-form-label nzFor="enabled" i18n>启用</nz-form-label>
  <nz-form-control i18n-nzErrorTip nzErrorTip="">
    <nz-switch nzSize="small" formControlName="enabled" id="enabled"></nz-switch>
  </nz-form-control>
</nz-form-item>


<div class="text-start">
  <button nz-button nzType="primary" type="submit" [disabled]="!form.dirty" i18n>保存</button>
  <button *ngIf="banner && banner._id" nz-button nzType="primary" type="button" nzDanger class="ms-4"
    cgOpButton  i18n-confirmContent confirmContent="确定要删除么？" 
    [operation]="remove.bind(this)" (onSuccess)="onDeleteSuccess.emit(banner)" i18n>删除</button>
</div>

</form>
`,
styles: [`

input {
  width: 70%;
}

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

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

.preview {
  height: 100%;
  max-width: 100%;
  max-height: 100%; 
  aspect-ratio: 2 / 1;
}

:host ::ng-deep .thumb-uploader > .ant-upload {
  margin-right: 0;
  margin-bottom: 0;
  height:100%;
  aspect-ratio: 2 / 1;
}

:host ::ng-deep .ant-upload.ant-upload-select-picture-card {
  width: auto;
}

`]
})
export class PortalBannerEditComponent implements OnInit {
@Input() productId: string;
@Output() onAddSuccess = new EventEmitter<any>();
@Output() onUpdateSuccess = new EventEmitter<any>();
@Output() onDeleteSuccess = new EventEmitter<any>();
@Output() onError = new EventEmitter<any>();


_banner: any;
@Input('banner') set banner(value) {
  this._banner = value;
  if (value) {
    this.form.reset(value);
  } else {
    this.form.reset({enabled: false});
  }
  this.coverFile = null;
  this.coverImage = null;
}
get banner() {
  return this._banner;
}


form: FormGroup;
isLoading = false;


coverFile: File;
coverImage: HTMLImageElement;

constructor(
  private portalService: PortalService,
  private fb: FormBuilder,
  private message: NzMessageService,
  private nzModalService: NzModalService,
) {

  this.form = this.fb.group({
    link: [null, [Validators.required]],
    enabled: [false, [Validators.required]],
  })

}

ngOnInit() {

}

onSelectContent() {
  this.nzModalService.create({
    nzStyle: { top: '10px' },
    nzBodyStyle: { padding: '0px 24px 0px 24px' },
    nzTitle: $localize`选择内容`,
    nzWidth: "85vw",
    nzComponentParams: {
      productId: this.productId,
    },
    nzContent: PortalBannerContentSelectComponent,
    nzOnOk: (comp: PortalBannerContentSelectComponent) => {
      let link = comp.link;
      if (link) {
        this.form.controls['link'].setValue(link);
        this.form.controls['link'].markAsDirty();
      }
    }
  });
}

onSubmit() {
  if (!this.banner && (!this.coverFile || !this.iconRatioGood() || !this.iconSizeGood())) {
    this.message.error("请上传Banner图");
    return;
  }
  if (this.form.invalid) {
    FormUtils.markAsDirty(this.form);
    return;
  }
  this.isLoading = true;
  let formData = this.getFormData();
  if (this.banner) { // 编辑
    firstValueFrom(this.portalService.bannerUpdate(formData, this.banner._id))
    .then(res => {
      this.form.markAsPristine();
      this.onUpdateSuccess.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;
    }) 
  } else { // 新增
    firstValueFrom(this.portalService.bannerAdd(formData))
    .then(res => {
      let newBanner = Object.assign({}, this.form.value);
      newBanner.icon = this.coverImage.src;
      this.banner = newBanner;
      this.form.markAsPristine();
      this.onAddSuccess.emit(this.banner);
      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.productId);
  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.coverFile) {
    formData.append('cover', this.coverFile);
  }
  return formData;
}

remove() {
  return this.portalService.bannerRemove(this.banner._id);
}


//////////////////////////////// upload ///////////////////////////////

iconSizeGood() {
  if (this.coverFile && this.coverFile.size > 1024 * 1024 * 2) return false;
  return true;
}

iconRatioGood() {
  // if (this.coverImage && this.coverImage.width == this.coverImage.height) return true;
  if (this.coverImage) return true;
  return false;
}

beforeUpload = (file: NzUploadFile): boolean => {
  this.coverFile = file as unknown as File;
  Utils.blobToImage(this.coverFile).then(img => {
    this.coverImage = img;
    this.form.markAsDirty();
  })
  return false;
};


}
