<template>
    <div class="qg-image" @click="onClick" ref="qg_image">
        <img v-show="imgSrc && !isError && !loding" :src="imgSrc" :alt="$attrs.alt" @load="load" @error="error" :class="{ fit_contain: mode === 'fit' }" :style="{ ...$attrs }" />
        <img-loding v-bind="$attrs" v-if="loding" border="#ccc solid 1rem"></img-loding>
        <img-error v-bind="$attrs" v-if="isError"></img-error>
    </div>
</template>

<script>
import imgLoding from "./img-loding.vue";
import imgError from "./img-error.vue";
export default {
    inheritAttrs: false,
    name: "qg-image",
    components: { imgLoding, imgError },
    props: {
        src: {
            type: String,
            default: "",
        },
        lazy: {
            type: Boolean,
            default: false,
        },
        isAnalyse: {
            //倍数图
            type: Boolean,
            default: false,
        },
        mode: {
            type: String,
            default: "",
        },
    },
    data() {
        return {
            loding: true,
            isError: false,
            lazySrc: "",
            obver: {},
            y: 20,
        };
    },
    computed: {
        imgSrc() {
            let str = "";
            let src = this.lazy ? this.lazySrc : this.src;
            if (this.isAnalyse && this.lazy) console.error("isAnalyse 跟 lazy 不能同时使用");

            if (this.isAnalyse) {
                if (this.$screen.width >= 1920) {
                    str = "@2";
                } else {
                    str = "@1";
                }
                let a = src.split(".");
                let pop = a.pop();
                src = `${a.join(".")}${str}.${pop}`;
            }
            return src;
        },
    },
    mounted() {
        if (this.lazy) {
            var io = new IntersectionObserver((entries) => {
                // isIntersecting是一个Boolean值，判断目标元素当前是否可见
                if (entries[0].isIntersecting) {
                    this.loding = true;
                    this.isError = false;
                    // 图片出现在可视区域后停止监听该元素
                    this.lazySrc = this.src;
                    io.unobserve(entries[0].target);
                }
            });
            io.observe(this.$refs.qg_image);
        }
    },
    methods: {
        load(e) {
            this.loding = false;
            this.isError = false;
        },
        error(e) {
            this.loding = false;
            this.isError = true;
        },
        onClick(e) {
            if (this.isDisabled) return;
            this.$debounce(() => {
                this.$emit("click", e);
            });
        },
    },
};
</script>

<style scoped>
.qg-image {
    display: inline-block;
}
.fit_contain {
    object-fit: contain;
}
</style>
