import { IPSSysImage } from '@ibiz-template/model';
import { useNamespace } from '@ibiz-template/vue-util';
import { defineComponent, PropType, VNode, computed } from 'vue';
import '@ibiz-template/theme/style/components/common/app-icon/app-icon.scss';
import { renderCompatibleIE } from '../../../ie-util';

export const AppIcon = defineComponent({
  name: 'AppIcon',
  props: {
    icon: {
      type: Object as PropType<IPSSysImage>,
    },
    size: {
      type: String as PropType<'small' | 'medium' | 'large'>,
    },
  },
  setup(props) {
    const ns = useNamespace('icon');
    const BaseUrl = `${ibiz.env.assetsUrl}/img/`;

    function getContent(icon?: IPSSysImage): VNode | null {
      if (icon) {
        if (icon.cssClass) {
          if (icon.cssClass.indexOf('fa-') !== -1) {
            return <i class={[ns.b(), icon.cssClass]} />;
          }
          return renderCompatibleIE(() => {
            <ion-icon class={ns.b()} name={icon.cssClass}></ion-icon>;
          });
        }
        if (icon.imagePath) {
          const prefixUrl =
            icon.imagePath.startsWith('./') || icon.imagePath.startsWith('/')
              ? ''
              : BaseUrl;
          if (icon.imagePath.endsWith('svg')) {
            if (icon.imagePath.startsWith('http')) {
              return renderCompatibleIE(() => {
                <ion-icon class={ns.b()} src={icon.imagePath}></ion-icon>;
              });
            }

            return renderCompatibleIE(() => (
              <ion-icon
                src={prefixUrl + icon.imagePath}
                class={ns.b()}
              ></ion-icon>
            ));
          }
          if (icon.imagePath.startsWith('http')) {
            return <img class={ns.b()} src={icon.imagePath} />;
          }
          return <img class={ns.b()} src={prefixUrl + icon.imagePath} />;
        }
      }
      return null;
    }

    const content = computed<VNode | null>(() => {
      return getContent(props.icon);
    });

    return () => content.value;
  },
});
export default AppIcon;
