<template>
  <ul class="icons">
    <li
      v-for="item in icons"
      :key="item.icon"
      class="icon"
      @click="onSelected(item)"
    >
      <i :class="item.iconFamily">
        {{ item.icon }}
      </i>
    </li>
  </ul>
</template>
<script lang="ts" setup>
import { onMounted, reactive } from 'vue';

const { urls } = defineProps<{
  urls: string[];
}>();

const emit = defineEmits(['change']);

const icons = reactive([]);

onMounted(() => {
  urls.forEach(async (url) => {
    const iconList: any = await addIcons(url.replace('.css', '.json'));
    icons.push(...iconList.list);
  });
});

const onSelected = (item: any) => {
  emit('change', item);
};

const addIcons = (url: string) => {
  return new Promise((resolve, reject) => {
    const xhr = new XMLHttpRequest();
    xhr.open('GET', url, true);
    xhr.send();
    xhr.onreadystatechange = () => {
      if (xhr.readyState === 4 && xhr.status === 200) {
        try {
          const iconfont = JSON.parse(xhr.responseText);
          const iconGroup = {
            name: iconfont.name,
            loaded: true,
            show: true,
            list: [],
          };

          iconfont.glyphs.forEach((item: any) => {
            iconGroup.list.push({
              iconFamily: iconfont.font_family,
              icon: String.fromCharCode(item.unicode_decimal),
            });
          });
          resolve(iconGroup);
        } catch (error) {
          reject(error);
        }
      }
    };
  });
};
</script>
<style lang="postcss" scoped>
.icons {
  display: grid !important;
  grid-template-columns: 1fr 1fr 1fr 1fr;
  gap: 12px;
  padding-left: 6px;

  .icon {
    display: flex;
    align-items: center;
    justify-content: center;
    width: 50px;
    height: 50px;
    border: 1px solid transparent;
    border-radius: 2px;
    cursor: pointer;

    &:hover {
      border-color: var(--color-primary);
    }

    i {
      width: 21px;
      height: 21px;
      font-size: 20px;
      color: var(--color);
    }
  }
}
</style>
