<template>
    <div>
        <div :id="textId" class="ap-doc-text" v-html="docText">
        </div>
        <el-image v-if="imgSrc.length > 0" class="ap-doc-img" :id="imgId"
                  :src="imgSrc[0]" :preview-src-list="imgSrc">
        </el-image>
    </div>
</template>

<script>
import {highlightAll} from "ap-util/util/DocUtil";

export default {
    name: "ApDoc",
    model: {
        prop: 'modelValue',
        event: 'changeModelValue'
    },
    props: {
        modelValue: {
            required: false
        }
    },
    data() {
        let imgId = "DocImg" + parseInt(Math.random()*10000000);
        let textId = "DocImg" + parseInt(Math.random()*10000000);
        return {
            imgId: imgId,
            textId: textId,
            docText: "",
            imgSrc: [],
            clickTime: null,
        }
    },
    watch: {
        docText(value) {
            this.$emit('changeModelValue', this.docText);
            // 文本更新：添加图片监听、高亮代码
            this.addImgClick()
            highlightAll();
        },
        modelValue(value){
            this.docText = value
        }
    },
    created() {
        this.docText = this.modelValue;
    },
    methods: {
        addImgClick(){
            // 添加图片点击事件，双击查看大图
            this.$nextTick(()=>{
                let ctn = document.getElementById(this.textId);
                if (ctn == null) {
                    return
                }
                let items = ctn.getElementsByTagName("img");
                if (items == null) {
                    return;
                }
                for (let i = 0; i < items.length; i++) {
                    let img = items[i];
                    img.onclick = (e) => {
                        if(this.clickTime != null && ((new Date().getTime() - this.clickTime) < 500)){
                            this.imgSrc = [e.currentTarget.src];
                            // 解决第一次双击，加载未完成问题
                            setTimeout(() =>{
                                document.getElementById(this.imgId).click();
                            }, 200);
                        }
                        this.clickTime = new Date().getTime();
                    }
                }
            })
        }
    }
}
</script>

<style scoped>
.ap-doc-text h1,
.ap-doc-text h2,
.ap-doc-text h3 {
    margin: 10px 0;
}
.ap-doc-text {
    padding: 0px 20px;
}
.ap-doc-img {
    width: 0px;
    height: 0px;
}
</style>
