import { Component, EventEmitter, Input, OnInit, Output } from '@angular/core';
import { NzUploadModule } from 'ng-zorro-antd/upload';
import { CommonCompModule } from '../../services/common.modules';
import { NzMessageService } from 'ng-zorro-antd/message';
import { NzUploadChangeParam, NzUploadFile } from 'ng-zorro-antd/upload';
import { ProvierOssAli } from './provider-oss-aliyun';
import { NzImageService } from 'ng-zorro-antd/image';
import { NzImageModule } from 'ng-zorro-antd/image';

@Component({
  selector: 'app-comp-upload',
  standalone: true,
  imports: [NzUploadModule, CommonCompModule, NzImageModule],
  templateUrl: './comp-upload.component.html',
  styleUrls: ['./comp-upload.component.scss'],
})
export class CompUploadComponent implements OnInit {
  @Input('title') title: string = '上传文件';
  @Input('files') files: Array<any> = [];
  @Output() change: EventEmitter<any> = new EventEmitter<any>();
  @Input('width') width: number = 0;
  @Input('maxlenght') maxlenght: number = 1; //文件数量限制
  @Input('type') type: string = 'file';
  get accept() {
    let type;
    switch (this.type) {
      case 'image':
        type = 'image/*';
        break;
      case 'pdf':
        type = 'application/pdf';
        break;
      case 'audio':
        type = 'audio/*';
        break;
      case 'video':
        type = 'video/*';
        break;
      default:
        type = 'file';
        break;
    }
    return type;
  }

  fileList: any = [
    // {
    //   name: 'xxx.png',
    //   status: 'done',
    //   url: 'http://www.baidu.com/xxx.png'
    // },
  ];
  ossProvider: { upload: any } | undefined;
  constructor(
    private msg: NzMessageService,
    private nzImageService: NzImageService
  ) {
    this.ossProvider = new ProvierOssAli();
  }

  ngOnInit() {
    this.fileList = this.files.map((item: any) => {
      console.log(item);
      return {
        url: item?.url,
        name: item?.name,
        status: 'done',
      };
    });
    this.Previewfilelist = this.fileList;
  }
  ossFileList: any;
  Previewfilelist: any;
  async handleChange(info: NzUploadChangeParam) {
    console.log(info);
    let fileList = [...info.fileList];
    fileList = fileList.slice(-this.maxlenght);
    fileList = fileList.map((file) => {
      if (file.response) {
        file.url = file.response.url;
      }
      return file;
    });
    this.fileList = fileList;

    if (info.file.status !== 'uploading') {
      // 选择文件后，自动开始上传
      // console.log(info.file, info.fileList);
      this.Previewfilelist = info.fileList;
      let ossFileList = await this.uploadAllFileList(info?.fileList);
      this.ossFileList = ossFileList;
      this.change.emit(
        ossFileList?.map((item) => {
          // console.log(item);
          let f = {
            name: item.locaname,
            url: item?.url,
          };
          return f;
        })
      );
    }
    if (info.file.status === 'done') {
      // this.msg.success(`${info.file.name} file uploaded successfully`);
      // console.log(info);
    } else if (info.file.status === 'error') {
      // this.msg.error(`${info.file.name} file upload failed.`);
    }
    // this.change.emit(info.fileList)
  }

  async uploadAllFileList(fileList: Array<NzUploadFile>) {
    let ossFileList = [];
    for (let index = 0; index < fileList.length; index++) {
      let file = fileList[index];
      if (file) {
        let ossFile;
        try {
          ossFile = await this.ossProvider?.upload(file?.originFileObj);
        } catch (err) {}
        if (ossFile) {
          ossFile.locaname = file.name;
          ossFileList.push(ossFile);
        }
      }
    }
    return ossFileList;
  }
  /**预览图片 */
  preview = async (e: any): Promise<void> => {
    let index = this.Previewfilelist.findIndex(
      (item: any) => item.uid == e.uid
    );
    let file = this.ossFileList[index].url;
    if (!/\.(jpg|jpeg|png|GIF|JPG|PNG)$/.test(file)) {
      window.open(file);
    } else {
      this.nzImageService.preview([{ src: file }], { nzZoom: 1, nzRotate: 0 });
    }
  };
}
