import { Component, OnInit,Input,Output,EventEmitter } from '@angular/core';
import { HwobsProvider } from '../../app/hwobs.service';
import { CommonModule } from '@angular/common';
import { IonButton, IonContent, IonHeader, IonTitle, IonToolbar } from '@ionic/angular/standalone';
import { Router } from '@angular/router';

@Component({
  selector: 'comp-uploader-hwobs',
  templateUrl: './comp-uploader-hwobs.component.html',
  styleUrls: ['./comp-uploader-hwobs.component.scss'],
  standalone: true,
  imports:[
    CommonModule,
    IonHeader,
    IonToolbar,
    IonButton,
    IonTitle,
    IonContent
  ]
})
export class CompUploaderHwobsComponent  implements OnInit {

  @Input() url:string = "";
  @Output() onUrlChange:EventEmitter<string> = new EventEmitter<string>()

  uploader:HwobsProvider|undefined
  constructor(
    private router: Router
  ) { }

  ngOnInit() {
    this.uploader = new HwobsProvider({
      bucketName:"nova-cloud",
      prefix:"dev/jxnu/storage/",
      host:"https://app.fmode.cn/",
      access_key_id:"XSUWJSVMZNHLWFAINRZ1",
      secret_access_key:"P4TyfwfDovVNqz08tI1IXoLWXyEOSTKJRVlsGcV6"
    });
  }

  file:File|undefined
  fileData:any = ""
  fileList:File[] = []

  async upload(){
    let filename = this.file?.name;
    let dateStr = `${new Date().getFullYear()}${new Date().getMonth()+1}${new Date().getDate()}`;
    let hourStr = `${new Date().getHours()}${new Date().getMinutes()+1}${new Date().getSeconds()}`;
    let key = `${dateStr}/${hourStr}-${filename}`;
    // let key = `storage/${filename}`
    if(this.file){
      let attachment = await this.uploader?.uploadFile(this.file,key);
      console.log(attachment);
      this.url = attachment?.get("url");
      this.onUrlChange.emit(this.url);
    }
  }
  /**
   * 文件选择器 选择文件触发事件
   * @param event 
   */
  async onFileChange(event:any){
    console.log(event)
    // 将选择的文件列表，赋值给fileList
    this.fileList = event?.target?.files;
    // 默认将第一个文件，显示在展示区域
    this.setFile(event?.target?.files?.[0]);
  }

  /**
   * 设置展示区域文件
   * @param file 
   */
  async setFile(file:any){
    // 将文件设置为展示区域文件
    this.file = file
  }

  backHome(){
    this.router.navigate(['/tabs/tab4']);
  }
}