import {Component, ElementRef, EventEmitter, Input, OnInit, Output, ViewChild} from '@angular/core';
import {FileItem, FileUploader, ParsedResponseHeaders} from 'ng2-file-upload';
import {environment} from '../../../../../environments/environment';
import {MsgService} from '../../../service/msg.service';

@Component({
  selector: 'frame-upload-silence',
  templateUrl: './frame-upload-silence.html'
})
export class FrameUploadSilence implements OnInit {
  /******************
   * 上传地址
   */
  @Input()
  uploadUrl: string;
  /******************
   * 文件格式不正确
   */
  @Input()
  fileTypeErrorMsg: string;
  /*****************
   * 是否允许上传多个文件
   */
  multiple = false;
  /*************************
   * 上传前提示信息
   */
  @Input()
  confirmMsg: string;
  /************************
   * 上传后提示信息
   */
  @Input()
  successMsg: string;
  /************************
   * 上传后提示信息
   */
  @Input()
  showLoading = false;
  /************************
   * 允许的文件类型
   */
  @Input()
  allowedFileType: [string];
  /************************
   * 允许的文件类型
   */
  /***********************
   * 最大文件限制
   */
  @Input()
  maxFileSize: number;
  @Input()
  autoUpload = false;

  @Output()
  afterChooseFile = new EventEmitter<any>();
  @Output()
  afterItemComplete = new EventEmitter<any>();
  @Output()
  afterItemSuccess = new EventEmitter<any>();
  @Output()
  afterItemError = new EventEmitter<any>();
  @Output()
  afterAllComplete = new EventEmitter<any>();

  //选择文件时带的参数
  chooseFileParam: any;
  /**********************
   * 文件上传参数
   */
  uploadParams = {};
  // 线程id
  threadId: any;


  // 上传核心组件
  fileUploader: FileUploader;
  @ViewChild('elSimpleUpload', {static: false}) elSimpleUpload: ElementRef;


  constructor() {
  }

  ngOnInit() {
    this.fileUploader = new FileUploader({
      url: environment.uploadRoot + this.uploadUrl,
      // allowedFileType: this.allowedFileType,
      method: 'post',
      maxFileSize: this.maxFileSize * 1024,
      isHTML5: true,
      autoUpload: this.autoUpload, // 不自动上传
      // removeAfterUpload: true 不自动移除
      // headers: [{ name: 'Access-Control-Allow-Origin', value: '*'}]
    });
    this.fileUploader.onBuildItemForm = this.onBuildItemForm.bind(this);
    this.fileUploader.onCompleteItem = this.onCompleteItem.bind(this);
    this.fileUploader.onAfterAddingFile = this.onAfterAddingFile.bind(this);
    this.fileUploader.onCompleteAll = this.onCompleteAll.bind(this);
  }

  /***********************
   * 上传之前传递参数
   */
  private onBuildItemForm(fileItem: FileItem, form: any) {
    fileItem.withCredentials = false;
    const data = Object.assign({}, this.uploadParams, this.chooseFileParam);
    for (const v in data) {
      form.append(v, data[v]);
    }
    if (this.showLoading)
      MsgService.showLoading();
  }

  /***************************
   * 单个文件完成上传
   */
  private onCompleteItem(item: FileItem, response: string, status: number, headers: ParsedResponseHeaders) {
    if (status === 404) {
      MsgService.errorAlert(`无法访问上传地址，请联系系统管理员！`);
      return;
    }

    if (status !== 200) {
      // 非正常返回，直接提示错误信息、
      MsgService.errorAlert(`文件上传出现异常，请稍后再试！`);
      return;
    }
    if (response === undefined || response === '') {
      return;
    }
    const ajax = JSON.parse(response);
    if (ajax.success === undefined || ajax.success === false) {
      MsgService.errorAlert(ajax.errorMsg);
      this.afterItemError.emit(ajax);
    } else {
      this.afterItemSuccess.emit(ajax);
    }
    this.afterItemComplete.emit(ajax);


  }

  private onAfterAddingFile(item) {
    const file = item.file;
    let matchFlag = true
    if (this.allowedFileType!==undefined && this.allowedFileType.length != null && this.allowedFileType.length > 0) {
      // 需要判断文件是否是对应的格式
      const array = file.name.split('.');
      if (array.length == 1) {
        // 没有后缀名
        matchFlag = false;
      } else {
        const suffix = array[array.length - 1].toLowerCase();
        for (const s of this.allowedFileType) {
          if (s.toLowerCase() === suffix) {
            matchFlag = true;
            break;
          }
          matchFlag = false;
        }
      }
      if (!matchFlag) {
        let msg = '文件格式不符合要求';
        if (this.fileTypeErrorMsg !== undefined)
          msg = this.fileTypeErrorMsg;
        else {
          if (this.allowedFileType.length == 1) {
            msg = msg + '，请使用后缀名为【' + this.allowedFileType[0] + '】的数据文件！';
          }
        }
        this.fileUploader.removeFromQueue(item);
        this.afterChooseFile.emit(undefined);
        MsgService.errorToastr(msg);
        return false;
      }
      item.file.rawFile.localPath = this.elSimpleUpload.nativeElement.value;
      item.file.rawFile.chooseFileParam = this.chooseFileParam;
      this.afterChooseFile.emit(item.file.rawFile);
    }

  }

  onCompleteAll() {
    this.afterAllComplete.emit();
    if (this.showLoading)
      MsgService.hideLoading();
  }

  chooseFile(param?) {
    this.chooseFileParam = param;
    this.fileUploader.clearQueue();
    this.elSimpleUpload.nativeElement.click();
  }

  uploadFile(params?) {
    if (this.fileUploader.queue.length == 0) {
      MsgService.errorToastr('请先选取需要上传的文件！');
      return;
    }
    if (params)
      this.uploadParams = params;
    if (this.showLoading)
      MsgService.showLoading();
    this.fileUploader.uploadAll();

  }

}
