<template>
  <div :class="classname" :style="{ width, height }">
    <template v-if="hasLoadError">
      <slot name="error" />
    </template>
    <template v-else>
      <img
        v-if="!IN_UNI_APP"
        :class="imageClassName"
        :src="src"
        :style="{ objectFit }"
        @error="handleError"
      />
      <image
        v-if="IN_UNI_APP"
        :class="imageClassName"
        :src="src"
        :mode="objectFit"
        @error="handleError"
      />
    </template>
  </div>
</template>

<script lang="ts">
export default {
  options: {
    virtualHost: true
  }
}
</script>

<script setup lang="ts">
import { ref, computed, watch } from '../../../../adapter-vue';
import { IN_UNI_APP, classNames } from '../util';
import { ImageProps, MiniProgramImageFitMap, imageEmits } from './TKImage';
import { PREFIX } from '../constants/index';

const props = defineProps(ImageProps);
const emit = defineEmits(imageEmits);
const hasLoadError = ref(false);


watch(() => props.src, () => {
  hasLoadError.value = false;
});

const classname = computed(() => classNames([`${PREFIX}-image`]));
const imageClassName = computed(() => classNames([
  `${PREFIX}-image_inner`,
]));
const objectFit = computed(() => {
  if (IN_UNI_APP) {
    return MiniProgramImageFitMap[props.fit] || MiniProgramImageFitMap.cover;
  } else {
    return props.fit;
  }
});

function handleError(e) {
  hasLoadError.value = true;
  emit('error', e);
}
</script>

<style lang="scss">
@import './style/TKImage.scss';
</style>