import { Component, ElementRef, Output, Input, OnInit, EventEmitter } from '@angular/core';
import WangEditor from 'wangeditor';
import { HttpHeaders, HttpRequest, HttpClient  } from "@angular/common/http";
import host from "../../../assets/js/http";
import { NzMessageService } from "ng-zorro-antd";
import { MainService } from 'src/app/services/main.service';

@Component({
  selector: 'app-wang-editor',
  templateUrl: './wang-editor.component.html',
  styleUrls: ['./wang-editor.component.less']
})
export class wangEditorComponent implements OnInit {

	@Output() changeContent = new EventEmitter();
	@Input() content: string;
	editor: any;
	isLoading:boolean=false;
	constructor(
		private http: HttpClient,
		private message: NzMessageService,
    private mainService: MainService,
	) { }

  ngOnInit() {
		// if(this.editor){
		// 	this.editors()
		// }
		this.editor = new WangEditor('#editorMenu', '#editor');
		this.setEditorConfig()
  }

	// 编辑器相关配置设置
	setEditorConfig () {
		// 使用 base64 保存图片
		this.editor.config.uploadImgShowBase64 = false;
		// 菜单展示项配置
		this.editor.config.menus = this.getMenuConfig();
		// 自定义配置颜色（字体颜色、背景色）
		this.editor.config.colors = this.getColorConfig();
		// 表情面板可以有多个 tab ，因此要配置成一个数组。数组每个元素代表一个 tab 的配置
		// this.editor.config.emotions = this.getEmotionsConfig();
		// 自定义字体
		this.editor.config.fontNames = this.getFontFamilyConfig();

		// 上传图片大小 20M
		this.editor.config.uploadImgMaxSize = 20 * 1024 * 1024
		// // 隐藏插入网络图片的功能
		this.editor.config.showLinkImg = false

		// 上传视频大小 50M
		this.editor.config.uploadVideoMaxSize = 50 * 1024 * 1024
		this.editor.config.showLinkVideo = false

		// // 配置触发 onchange 的时间频率，默认为 200ms
		this.editor.config.onchangeTimeout = 500 // 修改为 500ms
		this.editor.config.customUploadImg = (resultFiles, insertImgFn) =>{
			if(resultFiles[0].size > this.editor.config.uploadImgMaxSize){
				this.message.error('图片大小不能超过20M')
				return
			}
			let url = this.mainService.returnUploadUrl('solutionContent', 0);
			const formData = new FormData()
			formData.append('file', resultFiles[0]);
			formData.append('filename', resultFiles[0].name);
			const req = new HttpRequest('POST', url, formData, {
				reportProgress: false,
				withCredentials: false
			});
			this.isLoading = true
			this.http.request(req).subscribe((res:any) => {
				if(res.status==200 && res.body){
					this.isLoading = false
					let url = location.origin + '/file' + res.body.data.relativeFilePath
					insertImgFn(url,url,url)
				}else if(res.status==500 && res.body){
					this.message.error(res.body.error)
				}
			});
		}

		this.editor.config.customUploadVideo = (resultFiles, insertVideoFn) =>{
			if(resultFiles[0].size > this.editor.config.uploadVideoMaxSize){
				this.message.error('视频大小不能超过50M')
				return
			}
			let url = this.mainService.returnUploadUrl('solutionContent', 0);
			const formData = new FormData()
			formData.append('file', resultFiles[0]);
			formData.append('filename', resultFiles[0].name);
			const req = new HttpRequest('POST', url, formData, {
				reportProgress: false,
				withCredentials: false
			});
			this.isLoading = true
			this.http.request(req).subscribe((res:any) => {
				if(res.status==200 && res.body){
					this.isLoading = false
					let url = location.origin + '/file' + res.body.data.relativeFilePath
					insertVideoFn(url)
				}else if(res.status==500 && res.body){
					this.message.error(res.body.error)
				}
			});
		}

		// 配置编辑器内容改变触发方法
		this.editor.config.onchange = this.editorContentChange;
		// 编辑器获取到焦点触发方法
		this.editor.config.onfocus = this.editorOnFocus;
		// 编辑器失去焦点触发方法
		this.editor.config.onblur = this.editorOnBlur;

		this.editor.create();
		// 设置内容
		this.setContent()
	}

	  // 获取显示菜单项
	  getMenuConfig (): string[] {
	    return [
	      'bold',  // 粗体
	      'italic',  // 斜体
	      'underline',  // 下划线
	      'head',  // 标题
				'image',  // 插入图片
				'video',  // 插入视频
	      'fontName',  // 字体
	      'fontSize',  // 字号
	      'strikeThrough',  // 删除线
	      'foreColor',  // 文字颜色
	      'backColor',  // 背景颜色
	      // 'link',  // 插入链接
	      'list',  // 列表
	      'justify',  // 对齐方式
	      'quote',  // 引用
	      // 'emoticon',  // 表情
	      // 'table',  // 表格
	      // 'code',  // 插入代码
	      'undo',  // 撤销
	      'redo'  // 重复
	    ];
	  }

	  // 获取字体、背景颜色列表配置
	  getColorConfig(): string[] {
	    return [
	      '#000000',
	      '#eeece0',
	      '#1c487f',
	      '#4d80bf',
	      '#c24f4a',
	      '#8baa4a',
	      '#7b5ba1',
	      '#46acc8',
	      '#f9963b',
	      '#ffffff'
	    ];
	  }

	  // 获取表情配置
	  getEmotionsConfig() {
	    return [
	      {
	        // tab 的标题
	        title: '默认',
	        // type -> 'emoji' / 'image'
	        type: 'image',
	        // content -> 数组
	        content: [
	          {
	            alt: '[坏笑]',
	            src: 'http://img.t.sinajs.cn/t4/appstyle/expression/ext/normal/50/pcmoren_huaixiao_org.png'
	          },
	          {
	            alt: '[舔屏]',
	            src: 'http://img.t.sinajs.cn/t4/appstyle/expression/ext/normal/40/pcmoren_tian_org.png'
	          }
	        ]
	      },
	      {
	        // tab 的标题
	        title: 'emoji',
	        // type -> 'emoji' / 'image'
	        type: 'emoji',
	        // content -> 数组
	        content: ['?', '?', '?', '?', '?']
	      }
	    ];
	  }

	  // 获取字体列表配置
	  getFontFamilyConfig(): string[] {
	    return [
	      '宋体',
	      '微软雅黑',
	      'Arial',
	      'Tahoma',
	      'Verdana'
	    ];
	  }

	  // 富文本编辑器内容变化触发方法
	  editorContentChange = (html) => {
			this.changeContent.emit(html)
	    console.log(222,html);
	  }

	  // 编辑器获取到焦点触发事件
	  editorOnFocus = () => {
	    console.log('on focus');
	  }

	  // 编辑器失去焦点触发事件
	  editorOnBlur = (html) => {
			this.changeContent.emit(html)
	  }

	  // 设置编辑器显示内容
	  setContent() {
			console.log(7777,this.content)
	    this.editor.txt.html(this.content);
	  }

		editors(){
			this.editor.destroy()//销毁组件
			this.editor = null
		}
	//   // 获取编辑器内容，带html
	//   getContent() {
	//     this.showMessage = this.editor.txt.html();
	//   }

	//   // 获取编辑器文字内容
	//   getContentText() {
	//     this.showMessage = this.editor.txt.text();
	//   }
}

