<template>
  <SvgIcon
    v-if="isSvgIcon"
    :size="size"
    :name="getSvgIcon"
    :class="[$attrs.class, 'anticon']"
    :spin="spin"
  />
  <svg
    v-else-if="isIconFont"
    :class="[$attrs.class, 'icon']"
    aria-hidden="true"
    :style="getWrapStyle"
  >
    <use :xlink:href="`#${getIconFontIcon}`"></use>
  </svg>

  <span
    v-else
    ref="elRef"
    :class="[$attrs.class, 'bz-app-iconify anticon', spin && 'app-iconify-spin']"
    :style="getWrapStyle"
  ></span>
</template>

<script lang="ts">
  import type { PropType } from 'vue';
  import {
    defineComponent,
    computed,
    ref,
    watch,
    onMounted,
    unref,
    nextTick,
    CSSProperties,
  } from 'vue';

  import SvgIcon from './SvgIcon.vue';
  import Iconify from '@purge-icons/generated';
  import { isString } from '/@/utils/is';
  import { propTypes } from '/@/utils/propTypes';

  const SVG_END_WITH_FLAG = '|svg';
  const ICON_FONT_END_WITH_FLAG = '|font';

  export default defineComponent({
    name: 'BzIcon',
    components: {
      SvgIcon,
    },
    props: {
      // name
      icon: propTypes.string,
      // color
      color: propTypes.string,
      // size
      size: {
        type: [String, Number] as PropType<string | number>,
        default: 16,
      },
      spin: propTypes.bool.def(false),
      prefix: propTypes.string.def(''),
    },
    setup(props) {
      const elRef = ref<ElRef>(null);
      const isSvgIcon = computed(() => props.icon?.endsWith(SVG_END_WITH_FLAG));
      const getSvgIcon = computed(() => props.icon.replace(SVG_END_WITH_FLAG, ''));
      const getIconRef = computed(() => `${props.prefix ? props.prefix + ':' : ''}${props.icon}`);

      const isIconFont = computed(() => props.icon?.endsWith(ICON_FONT_END_WITH_FLAG));
      const getIconFontIcon = computed(() => props.icon.replace(ICON_FONT_END_WITH_FLAG, ''));

      const update = async () => {
        if (unref(isSvgIcon)) return;

        const el = unref(elRef);
        if (!el) return;

        await nextTick();
        const icon = unref(getIconRef);
        if (!icon) return;

        const svg = Iconify.renderSVG(icon, {});
        if (svg) {
          el.textContent = '';
          el.appendChild(svg);
        } else {
          const span = document.createElement('span');
          span.className = 'iconify';
          span.dataset.icon = icon;
          el.textContent = '';
          el.appendChild(span);
        }
      };

      const getWrapStyle = computed((): CSSProperties => {
        const { size, color } = props;
        let fs = size;
        if (isString(size)) {
          fs = parseInt(size, 10);
        }

        return {
          fontSize: `${fs}px`,
          color: color,
          display: 'inline-flex',
        };
      });

      watch(() => props.icon, update, { flush: 'post' });

      onMounted(update);

      return { elRef, getWrapStyle, isSvgIcon, getSvgIcon, isIconFont, getIconFontIcon };
    },
  });
</script>
