import {Component, ElementRef, Input, OnInit, Output, ViewChild, EventEmitter} from '@angular/core';
import {FileItem, FileUploader, ParsedResponseHeaders} from "ng2-file-upload";
import {BsModalRef, BsModalService, ModalOptions} from "ngx-bootstrap/modal";
import {FrameDetailComponent} from "../../../../routes/frame/core/detail/frame.detail";
import {environment} from "../../../../../environments/environment";
import {VarService} from "../../../service/var.service";
import {MsgService} from "../../../service/msg.service";
import {AjaxService} from "../../../service/ajax.service";
import {ModalService} from "../../../service/modal.service";
import {FrameThreadRunningComponent} from "../../../../routes/frame/thread/frame-thread-running/frame-thread-running.component";

@Component({
  selector: 'frame-upload',
  templateUrl: './frame-upload.html'
})
export class FrameUpload extends FrameDetailComponent implements OnInit {
  /******************
   * 上传地址
   */
  uploadUrl: string;
  /******************
   * 标题
   */
  uploadTitle: string = '文件上传';
  /*****************
   * 是否允许上传多个文件
   */
  multiple = false;
  /*************************
   * 上传前提示信息
   */
  confirmMsg: string;
  /************************
   * 上传后提示信息
   */
  successMsg: string;
  /************************
   * 允许的文件类型
   */
  allowedFileType: [string];
  /***********************
   * 最大文件限制
   */
  maxFileSize: number;
  /**********************
   * 文件上传参数
   */
  uploadParams = {};
  /**********
   * 模版文件
   */
  templateFile: string;
  /**********
   * 成功回调
   */
  uploadCallback: Function;
  /******************
   * 是否自动关闭
   */
  autoClose = false;

  /*******************
   * 弹出主窗口
   */
  modalService:any;

  // 上传是否失败
  uploadFail = false;
  // 上传是否完成
  uploadComplete = false;
  // 线程id
  threadId: any;

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

  constructor(bsModalRef: BsModalRef) {
    super(bsModalRef);
  }

  ngOnInit() {
    this.fileUploader = new FileUploader({
      url: environment.uploadRoot + this.uploadUrl,
      allowedFileType: this.allowedFileType,
      method: 'post',
      maxFileSize: this.maxFileSize * 1024,
      isHTML5: true,
      autoUpload: false, // 不自动上传
      // 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.onCompleteAll = this.onCompleteAll.bind(this);
  }

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

  /***************************
   * 单个文件完成上传
   */
  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.uploadFail = true;
    } else {
      // 判断是否是后台线程
      if (ajax.threadId) {
        this.threadId = ajax.threadId;
        // 如果返回的json有threadId，表示是一个后台线程
        // ModalService.showThreadWindow(this.modalService,ajax.entity,{
        //   callback:this.uploadCallback
        // });
        const modal = Object.assign({}, {
          animated: true,
          keyboard: false,
          backdrop: true,
          ignoreBackdropClick: true,
          initialState:  {},
          class: 'modal-5p'
        }, {});
        modal.initialState['ResponseEntity'] = ajax.entity;
        modal.initialState['threadParam'] = {
          callback:this.uploadCallback
        };
        this.modalService.show(FrameThreadRunningComponent, modal);
        this.closeWindow();
      } else {
        if (this.uploadCallback)
          this.uploadCallback.call(undefined, ajax);
        if (this.autoClose)
          this.closeWindow();
      }
      this.uploadFail = false;
    }


  }

  private onCompleteAll() {
    if (this.multiple === true) {
      this.elMultipleUpload.nativeElement.value = '';
    } else {
      this.elSimpleUpload.nativeElement.value = '';
    }
    this.uploadComplete = true;

    // 只有非线程的时候弹出提示信息
    if (!this.uploadFail && this.successMsg !== undefined && this.threadId === undefined) {
      MsgService.successAlert(this.successMsg);
    }

  }

  chooseFile() {
    this.fileUploader.clearQueue();
    this.uploadComplete = false;
    if (this.multiple === true) {
      this.elMultipleUpload.nativeElement.click();
    } else {
      this.elSimpleUpload.nativeElement.click();
    }
  }

  /******************
   * 上传文件
   */
  uploadFiles(data?: any) {
    const fn = () => {
      this.uploadParams = data;
      if (this.multiple === true) {
        this.elMultipleUpload.nativeElement.click();
      } else {
        this.elSimpleUpload.nativeElement.click();
      }
    };
    if (this.confirmMsg !== undefined) {
      MsgService.confirmAlert(this.confirmMsg, fn);
    } else {
      fn.apply(undefined);
    }
  }


}
