import { ref, computed, watch } from 'vue';
import { createComponent } from '../../_helper/create';
import { isDef } from '../../_helper/validate';
import { addUnit } from '../../_helper/tools';
import { props } from './props';
const { componentName, create, createName } = createComponent('image');
export default create({
    name: componentName,
    props,
    emits: ['load', 'error'],
    setup(props, context) {
        const error = ref(false);
        const loading = ref(true);
        const dom = ref();
        const style = computed(() => {
            const style = {
                width: addUnit(props.width),
                height: addUnit(props.height),
            };
            if (isDef(props.radius)) {
                style.overflow = 'hidden';
                style.borderRadius = addUnit(props.radius);
            }
            return style;
        });
        watch(() => props.src, () => {
            error.value = false;
            loading.value = true;
        });
        const onLoad = (event) => {
            loading.value = false;
            context.emit('load', event);
        };
        const onError = (event) => {
            error.value = true;
            loading.value = false;
            context.emit('error', event);
        };
        const renderImage = () => {
            if (error.value || !props.src) {
                return;
            }
            const attrs = {
                alt: props.alt,
                class: createName('img'),
                style: {
                    objectFit: props.fit,
                    objectPosition: props.position,
                },
            };
            if (props.lazyLoad) {
                return <img ref={dom} v-lazy={props.src} {...attrs}/>;
            }
            return (<img src={props.src} onLoad={onLoad} onError={onError} {...attrs}/>);
        };
        const renderPlaceholder = () => {
            if (loading.value && props.showLoading) {
                return (<div class={createName('loading')}>
            <i class="iconfont icon-loading"></i>
          </div>);
            }
            if (error.value && props.showError) {
                return (<div class={createName('error')}>
            <i class="iconfont icon-jiazaishibai"></i>
          </div>);
            }
        };
        return () => {
            var _a, _b;
            return (<div class={componentName} style={style.value}>
        {renderImage()}
        {renderPlaceholder()}
        {(_b = (_a = context.slots).default) === null || _b === void 0 ? void 0 : _b.call(_a)}
      </div>);
        };
    },
});
