<template>
    <div class="nus_imgae">
        <nu-aspect
            v-if="imgUrl"
            @click="_onClick"
            @tap="_onTap"
            :aspect="aspect"
            class="nu_img-wrap">
            <div class="nu_imgae" ref="hook_img"></div>
            <slot></slot>
        </nu-aspect>
    </div>
</template>

<script>
import { AeAnimation, aeZipPreset } from 'nimble-lib';
import ImgTmp from '../_comm/ImgTmp';
import NuAspect from '../../aspect';
AeAnimation.use(aeZipPreset); // zip文件解析器
export default {
    extends: ImgTmp,
    name: 'NuImgae',
    components: {
        NuAspect
    },
    props: {
        aeOptions: { // ae动画参数
            default: null
        }
    },
    watch: {
        imgUrl() {
            this.loadImg();
        }
    },
    mounted() {
        this.loadImg();
    },
    methods: {
        /**
         * 加载图片
         */
        loadImg() {
            let _that = this;
            if (_that.imgUrl) {
                if (!_that.ae) {
                    _that.ae = new AeAnimation();
                }
                _that.$nextTick(() => {
                    if (typeof _that._timeout !== 'undefined') {
                        clearTimeout(_that._timeout);
                    }
                    _that._timeout = setTimeout(() => { // 不加定时的时候在等比的缩放时显示不了
                        let hookImg = _that.$refs && _that.$refs.hook_img;
                        _that._lottie && _that._lottie.destroy();
                        _that._lottie = null;
                        hookImg.innerHTML = '';
                        hookImg && _that.ae.load(_that.imgUrl, Object.assign({
                            loop: true
                        }, _that.aeOptions || {}, {
                            container: hookImg,
                            renderer: 'canvas'
                        }), (ae) => {
                            _that._lottie = ae;
                            // console.log(ae);
                            _that.bindEvent(ae);
                        });
                    }, 20);
                });
            }
        },
        bindEvent(ae) {
            let _that = this;
            if (ae) {
                ['loopComplete', 'complete', 'enterFrame', 'segmentStart',
                    'config_ready', 'data_ready', 'data_failed', 'loaded_images', 'DOMLoaded', 'destroy'].forEach((evtType) => {
                    ae && ae.addEventListener(evtType, (evt) => {
                        _that.$emit(evtType, evt);
                    });
                });
            }
        }
    }
};
</script>

<style lang="scss">
.nus_imgae{
    display: block;
    .nus_aspect{
        .nu_imgae{
            height: 100%;
            width: 100%;
        }
    }
}
</style>
