import { ref,nextTick } from "vue";

export function useInitFroalaEditor() {
	let frolaEditorContentChange=ref(false)//富文本内容是否改变
	let lastFocusPosition=ref(null)//最后焦点位置
	let imgUploadFlag=ref(true)//图片是否上传完成

	const options = {
		toolbarButtons: [
			"insertImage",
			"insertVideo",
			"embedly",
			"insertFile",
			"textColor",
			"bold",
			"italic",
			"underline",
			"strikeThrough",
			"fontFamily",
			"fontSize",
			"color",
			"lineHeight",
			"align",
			"formatOL",
			"formatUL",
			"outdent",
			"indent",
			"quote",
			"insertTable",
			"insertHR",
			"undo",
			"redo",
		],
		height: 400,
		fontSize: ["6","8","10","12", "13", "14", "15", "16", "18", "20", "24", "28", "32", "36", "40"],
		
		fontSizeDefaultSelection: "16",
		theme: "dark", //主题
		placeholderText: "请输入内容",
		language: "zh_cn", //国际化
		imageUploadURL: import.meta.env.VITE_APP_API_URL + '/report/uploadImg', //上传url
		videoUploadURL: import.meta.env.VITE_APP_API_URL + '/report/uploadImg', //上传url
		fileUploadURL: import.meta.env.VITE_APP_API_URL + '/report/uploadImg', //上传url 更多上传介绍 请访问https://www.froala.com/wysiwyg-editor/docs/options
		imageDefaultWidth: false,
		quickInsertEnabled: false,
		// quickInsertButtons: ['image', 'ul', 'ol'], //快速插入项
		toolbarVisibleWithoutSelection: true, //是否开启 不选中模式
		toolbarSticky: false, //操作栏是否自动吸顶
		saveInterval: 0,
		charCounterCount: false,
		events:{
			// 内容变化事件
			contentChanged:function (){
				frolaEditorContentChange.value=true
				getSelection().rangeCount&&(lastFocusPosition.value=getSelection().getRangeAt(0))
			},
			keyup:function(e,editor){
				nextTick(()=>{
					getSelection().rangeCount&&(lastFocusPosition.value=getSelection().getRangeAt(0))
				})
			},
			click:function(e,editor){
				nextTick(()=>{
					getSelection().rangeCount&&(lastFocusPosition.value=getSelection().getRangeAt(0))
				})
			},
			'image.beforePasteUpload':function(){
				imgUploadFlag.value=false
			},
			'image.beforeUpload':function(){
				imgUploadFlag.value=false
			},
			'image.inserted':function(){
				imgUploadFlag.value=true
			},
			'image.error':function(){
				imgUploadFlag.value=true
			},
		}
	};

	/**
	 * 初始化编辑器
	 * @param  el domid
	 * @param  opts 配置项
	 * 由于要获取到富文本实例 要在new FroalaEditor(el,opt,callback)的callback中才能获取到
	 * 方案一返回一个promise
	 * 方案二直接返回富文本实例 无法在调用initFroalaEditor方法后立即执行实例上的一些方法或者读取属性
	 * 一般写个settimeout 可以解决
	 */
	const initFroalaEditor = (el,opts) => {
		// 方案一
		// let ins=null
		// return new Promise((resolve,reject)=>{
		// 	options.height=opts?.height??500
		// 	console.log(options);
		// 	ins=new FroalaEditor(el, options,()=>{
		// 		// console.log(ins);
		// 		resolve(ins)
		// 	})
		// })

		// 方案二
		options.height=opts?.height??500
		options.height=options.height<350?350:options.height
		console.log(options);
		return new FroalaEditor(el, options);
	};

	return {
		lastFocusPosition,
		frolaEditorContentChange,
		imgUploadFlag,
		initFroalaEditor,
	}
}
