<script setup lang="ts">
import { iconSelector } from "@/store/store.ts";
import { useRequest } from "vue-request";
import { myRequest } from "@/requests/request.ts";
import { ref, watch } from "vue";
import { Close } from "@element-plus/icons-vue";
const filter = ref("");
const { data: icons, loading } = useRequest(() => myRequest(`/api/sys/icon`), {
  ready: () => !Boolean(iconSelector.iconList.length),
});
watch(icons, () => {
  iconSelector.iconList = icons.value.data.map((e: { icon: string }) => e.icon);
});
defineEmits<{ (e: "update", value: string): void }>();
</script>

<template>
  <el-dialog
    v-model="iconSelector.visible"
    append-to-body
    :show-close="false"
    style="max-width: 60vw; max-height: 60vh; overflow-y: auto"
  >
    <template #header>
      <el-input
        placeholder="输入名称筛选,双击左键选择图标"
        clearable
        v-model="filter"
        style="
          position: sticky;
          top: 10px;
          background: #fff;
          width: calc(100% - 5rem);
        "
      />
      <el-icon><Close @click="iconSelector.visible = false" /></el-icon>
    </template>

    <div v-loading="loading">
      <el-icon
        v-for="item in iconSelector.iconList.filter(
          (e: string) => e.indexOf(filter) > -1,
        )"
        size="32"
        style="padding: 1rem"
        :class="{ selected: iconSelector.selected === item }"
        ><el-tooltip :content="item" placement="top"
          ><i
            :class="{ [item]: true }"
            @click="
              iconSelector.selected !== item
                ? (iconSelector.selected = item)
                : (iconSelector.selected = '')
            "
            @dblclick="
              () => {
                iconSelector.selected = item;
                $emit('update', iconSelector.selected);
                iconSelector.visible = false;
              }
            " /></el-tooltip
      ></el-icon>
    </div>
  </el-dialog>
</template>

<style scoped>
.selected {
  background-color: #409eff50;
}
:global(.el-icon:hover) {
  cursor: pointer;
}
:global(.el-dialog__header) {
  position: sticky;
  top: 0;
  z-index: 9;
  background: #fff;
  display: flex;
  align-items: center;
  justify-content: space-between;
}
</style>
