import { Component, ViewChild, OnInit,Input,Output,EventEmitter} from '@angular/core';
import { EditorComponent } from './editor/editor.component';
import { SharedataService } from './service/sharedata.service';
import { FileUploader, FileItem, ParsedResponseHeaders } from "ng2-file-upload";
import { AppComponent } from '../../../../../app.component';
import { BsModalService } from "ngx-bootstrap/modal";
import { FlexModalComponent } from "../../../../../..../../shared/common/FlexModal.component";
import { FrameVariable } from "../../../../../shared/frame/frame-variable";

@Component({
  selector: 'photo-uploader',
  templateUrl: './photo-uploader.component.html',
  styleUrls: ['./photo-uploader.component.scss']
})
export class PhotoUploaderComponent extends FlexModalComponent implements OnInit {
	


  // 上传路径
  @Input()
  uploadUrl: string;

  @Input()
  addonParams: {};

  @Output() afterUpload = new EventEmitter();


  uploader: FileUploader ;

 

  constructor(
	public sharedata: SharedataService,
	public bsModalService: BsModalService,) {
	  super(bsModalService);
  }

  ngOnInit(): void {
	this. uploader= new FileUploader({
			url: FrameVariable.BASE_URL + this.uploadUrl, 
			itemAlias: "file",     
			isHTML5: true,
			autoUpload: false,
			removeAfterUpload: true,                                            
		});
  }
  onChangeLoader(value) {
    const that = this;
    // 图片载入
    that.sharedata.data = value;
    // 下载路径要更新
	this.sharedata.handledata({});
  }
  updateChange() {
    const that = this;
    // 下载路径要更新
    this.sharedata.handledata({});
    // 更新editor组件，主动更新视图
    this.sharedata.data.loaded = false;
    setTimeout(() => {
	  that.sharedata.data.loaded = true;
    }, 1);
  }

  navbarchange(action) {
	  
    switch (action) {
      case 'crop':
        this.crop();
        break;

      case 'clear':
        this.clear();
        break;

      case 'restore':
        this.restore();
        break;

      case 'remove':
        this.reset();
        break;

      default:
    }
  }
  stop() {
    if (this.sharedata.cropper) {
      this.sharedata.cropper.destroy();
      this.sharedata.cropper = null;
    }
  }
  crop() {
    if (this.sharedata.data.cropping) {
      this.sharedata.cropdata.croppedData = this.sharedata.cropper.getData();
      this.sharedata.cropdata.canvasData = this.sharedata.cropper.getCanvasData();
      this.sharedata.cropdata.cropBoxData = this.sharedata.cropper.getCropBoxData();


      this.sharedata.data.cropped = true;
      this.sharedata.data.cropping = false;
      this.sharedata.data.previousUrl = this.sharedata.data.url,
	  this.sharedata.data.url = this.sharedata.cropper.getCroppedCanvas(this.sharedata.data.type === 'image/png' ? {} : {
        fillColor: '#fff',
	  }).toDataURL(this.sharedata.data.type);
	  let that=this;
		this.compress(that.sharedata.data.url, 288,384,0.99).then(function (val) {
			that.sharedata.data.url = val;
			if(that.sharedata.data.type === 'image/png'){
				that.sharedata.data.name = that.sharedata.data.name.replace("png","jpeg");
			}
			that.sharedata.data.type = 'image/jpeg'
			
		});

	  this.stop();
	  this.updateChange();
    }
  }
  update(data) {
    Object.assign(this.sharedata.data, data);
  }
  clear() {
    if (this.sharedata.data.cropping) {
      this.sharedata.cropper.clear();
      this.update({
        cropping: false,
      });
    }
  }

  restore() {
    if (this.sharedata.data.cropped) {
      this.sharedata.data.cropped = false;
      this.sharedata.data.url = this.sharedata.data.previousUrl;
      this.sharedata.data.previousUrl = '';
	  this.updateChange();
    }
  }
  reset() {
    this.stop();
    this.sharedata.data = {
      cropped: false,
      cropping: false,
      loaded: false,
      name: '',
      previousUrl: '',
      type: '',
	  url: '',
	  file:File
    };
    this.sharedata.cropdata = {
      canvasData: null,
      cropBoxData: null,
      croppedData: null
    };
  }
   compress(base64String, w,h, quality) {
	var getMimeType = function (urlData) {
		var arr = urlData.split(',');
		var mime = arr[0].match(/:(.*?);/)[1];
		// return mime.replace("image/", "");
		return mime;
	};
	var newImage = new Image();
	var imgWidth, imgHeight;

	var promise = new Promise(resolve => newImage.onload = resolve);
	newImage.src = base64String;
	return promise.then(() => {
		imgWidth = newImage.width;
		imgHeight = newImage.height;
		var canvas = document.createElement("canvas");
		var ctx = canvas.getContext("2d");
		// if (Math.max(imgWidth, imgHeight) > w) {
		// 	if (imgWidth > imgHeight) {
		// 		canvas.width = w;
		// 		canvas.height = w * imgHeight / imgWidth;
		// 	} else {
		// 		canvas.height = w;
		// 		canvas.width = w * imgWidth / imgHeight;
		// 	}
		// } else {
		// 	canvas.width = imgWidth;
		// 	canvas.height = imgHeight;
		// }
		canvas.width = w;
		canvas.height = h;
		ctx.clearRect(0, 0, canvas.width, canvas.height);
		ctx.drawImage(newImage, 0, 0, canvas.width, canvas.height);
		var base64 = canvas.toDataURL("image/jpeg", quality);
		return base64;
	});
}


 async upload() {
	this.uploader.clearQueue();
	
	var file;
	if (!this.sharedata.data.cropped) {
		file=this.sharedata.data.file;
	} else {
		var arr=this.sharedata.data.url.split(','),
		mime=arr[0].match(/:(.*?);/)[1],
		bstr=atob(arr[1]),
		n=bstr.length,
		u8arr=new Uint8Array(n);
		while(n--){
			u8arr[n]=bstr.charCodeAt(n);
		}
		let blob=new Blob([u8arr],{type:mime});
		file=new File([blob],this.sharedata.data.name,{type:this.sharedata.data.type,lastModified: Date.now()});
	}
	this.uploader.addToQueue([file]);
	
	this.uploader.onBuildItemForm  = (fileItem: FileItem, form: any) =>{
		//Object.assign(form,this.param);
		if (this.addonParams !== undefined) {
			for (const v in this.addonParams) {
			  form.append(v, this.addonParams[v]);
			}
		  }
	}
   
	this.uploader.onSuccessItem  = (item: FileItem, response: string, status: number, headers: ParsedResponseHeaders) =>{
		let respObj = JSON.parse(response);
		this.afterUpload.emit(respObj);
		if(respObj.success){
		// 	AppComponent.GobalComponent.successMsg('图片上传成功');
		this.reset();
		if(this.bsModalWin)this.bsModalWin.hide();
		// //   let url = respObj.map.url;
		// //   let std = respObj.map.stdRegInfo;
		// //   this.item.photo_url = null;
		// //   std.photo_url_full = url + std.photo_url;
		//if(this.bsModalWin)this.bsModalWin.hide();
		// }else{
		//   AppComponent.alert({ 'title': '提示', 'text': respObj.errorMsg });
		 }
	  }
	  this.uploader.queue[0].upload();
  }

}
