import { defineComponent, h } from 'vue';
import { useModel } from 'vue';
import { useUpload } from '/#/upload/hooks';
import { useDark } from '@vueuse/core';
import { module, useCool } from '/@/cool';
import { MdEditor, MdPreview } from 'md-editor-v3';
import 'md-editor-v3/lib/style.css';
import 'md-editor-v3/lib/preview.css';
import '../static/index.scss';
import { useI18n } from 'vue-i18n';

export default defineComponent({
	name: 'cl-editor-md',

	components: {
		MdEditor,
		MdPreview
	},

	props: {
		// 绑定值
		modelValue: String,

		// 是否预览模式
		preview: Boolean,

		// 编辑时预览
		enablePreview: {
			type: Boolean,
			default: true
		}
	},

	setup(props, { expose }) {
		const config = module.config('editor-md');

		const { refs, setRefs } = useCool();
		const { toUpload } = useUpload();
		const isDark = useDark();
		const { t } = useI18n();

		// 绑定值
		const value = useModel(props, 'modelValue');

		// 图片上传事件
		async function onUploadImg(files: File[], callback: (urls: string[]) => void) {
			const res = await Promise.all(
				files.map(file => {
					return toUpload(file);
				})
			);

			callback(res.map(e => e.url));
		}

		// 聚焦
		function focus() {
			refs.editor.focus();
		}

		expose({
			focus
		});

		return () => {
			return h(
				props.preview ? (
					<md-preview v-model={value.value} />
				) : (
					<md-editor v-model={value.value} ref={setRefs('editor')} />
				),
				{
					placeholder: t('请输入'),
					theme: isDark.value ? 'dark' : 'light',
					onUploadImg,
					...config,
					preview: props.enablePreview
				}
			);
		};
	}
});
