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';
import { NzNotificationModule } from 'ng-zorro-antd/notification';
import { NzNotificationService } from 'ng-zorro-antd/notification';

@Component({
  selector: 'app-comp-upload',
  standalone: true,
  imports: [NzUploadModule, CommonCompModule, NzImageModule,NzNotificationModule],
  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';
  @Input('size') size: number = 2048; //上传文件限制大小单位KB

  @Input('acl') acl: "public-read-write" | "public-read" | "private" | "default" = "default"

  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'
    // },
  ];
  ossFileList: any;
  Previewfilelist: any;
  ossProvider: { upload: any, signatureUrl: any, download:any } | undefined;

  disabled: boolean = false

  constructor(
    private msg: NzMessageService,
    private nzImageService: NzImageService,
    private notification: NzNotificationService
  ) {
    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;
  }
  async handleChange(info: NzUploadChangeParam) {
    console.log(info);
    if (info.type == 'removed') {
      return
    }
    if(this.acl != 'private'){
      let isEncrypt = await this.isEncrypt(info)
    }
    // if (isEncrypt) {
    //   return
    // }
    this.disabled = true
    if (info.file.status !== 'uploading') {
      // 选择文件后，自动开始上传
      // console.log(info.file, info.fileList);
      let ossFileList = await this.uploadAllFileList(info?.fileList);
      let nowUploadFiles = ossFileList?.map((item) => {
        let f = {
          name: item.locaname,
          url: item?.url,
        };
        return f;
      })

      let fileList = [...this.fileList, ...nowUploadFiles];
      this.fileList = fileList.slice(-this.maxlenght);
      // fileList = fileList.map((file) => {
      //   if (file.response) {
      //     file.url = file.response.url;
      //   }
      //   return file;
      // });
      // this.fileList = fileList

      this.Previewfilelist = [...this.fileList];
      // this.ossFileList = ossFileList;
      this.change.emit(this.fileList);
      this.disabled = false
    }
    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,null,{acl:this.acl});
        } catch (err) { }
        if (ossFile) {
          ossFile.locaname = file.name;
          ossFileList.push(ossFile);
        }
      }
    }
    return ossFileList;
  }
  onRemove = (e: any): boolean => {
    console.log(e);
    let i = this.fileList.findIndex((item: any) => item.url == e?.url)
    this.fileList.splice(i, 1)
    this.change.emit(this.fileList);
    return false
  }
  /**预览图片 */
  preview = async (e: any): Promise<void> => {
    // let index = this.Previewfilelist.findIndex(
    //   (item: any) => item.url == e.url
    // );
    // let file = this.Previewfilelist[index]?.url;
    let url = e?.url
    if (!/\.(jpg|jpeg|png|GIF|JPG|PNG)$/.test(url)) {
      if(this.acl == 'private'){
        url = await this.ossProvider?.signatureUrl(url)
      }
      window.open(url);
    } else {
      this.nzImageService.preview([{ src: url }], { nzZoom: 1, nzRotate: 0 });
    }
  };
  timeOut: any
  /**判断pdf文件是否加密 */
  isEncrypt(info: NzUploadChangeParam): Promise<boolean> {//只查file，不查fileList
    return new Promise((resolve) => {
      let isEncrypt: boolean = false
      if (info.file.originFileObj) {
        let reader = new FileReader()
        let file = info.file.originFileObj
        reader.readAsArrayBuffer(file)
        reader.onload = () => {
          if (reader.result) {
            let files = new Blob([reader.result], { type: 'application/pdf' })
            files.text().then(x => {
              isEncrypt = x.substring(x.lastIndexOf("<<"), x.lastIndexOf(">>")).includes("/Encrypt")
              if (isEncrypt) {
                clearTimeout(this.timeOut)
                this.timeOut = setTimeout(() => {
                  this.notification.create(
                    'error',
                    '请勿上传加密文件',
                    `${file.name} 为加密文件，影响导出，请替换。`,
                    { nzDuration: 0 }
                  );

                }, 1000);
              }
              resolve(isEncrypt)
            })
          } else { resolve(false) }
        }
      } else { resolve(false) }
    })
  }
}
