<script setup lang="ts">
import icons from '@/components/SvgSelect/requireIcons'
import { ArrowDownBold, ArrowUpBold } from '@element-plus/icons-vue'

const props = withDefaults(
  defineProps<{
    modelValue?: string
    width?: string
  }>(),
  {
    width: '100%'
  }
)

const inputRef = ref()
const visible = ref(false)
const iconNames = ref<string[]>(icons)
const filterValue = ref('')

const emits = defineEmits(['update:modelValue'])

const computedModelValue = computed({
  get() {
    return props.modelValue
  },
  set(newValue) {
    emits('update:modelValue', newValue)
  }
})

/**
 * 筛选图标
 */
function filterIcons() {
  if (filterValue.value) {
    iconNames.value = icons.filter((iconName) => iconName.includes(filterValue.value))
  } else {
    iconNames.value = icons
  }
}

/**
 * 选择图标
 * @param iconName 选择的图标名称
 */
function selectedIcon(iconName: string) {
  computedModelValue.value = iconName
  visible.value = false
}
</script>

<template>
  <el-input
    ref="inputRef"
    v-model="computedModelValue"
    readonly
    placeholder="点击选择图标"
    :suffix-icon="visible ? ArrowUpBold : ArrowDownBold"
  >
    <template #prepend>
      <svg-icon v-if="computedModelValue" :icon-class="computedModelValue" />
    </template>
  </el-input>

  <el-popover
    v-model:visible="visible"
    :virtual-ref="inputRef"
    placement="bottom-start"
    trigger="click"
    virtual-triggering
    :width="450"
  >
    <el-input
      v-model="filterValue"
      placeholder="搜索图标"
      clearable
      @input="filterIcons"
      style="padding: 0 0 10px 10px"
    />

    <el-scrollbar>
      <ul class="icon-list">
        <el-tooltip
          v-for="(iconName, index) in iconNames"
          :key="index"
          :content="iconName"
          :enterable="false"
          :hide-after="0"
          placement="top"
        >
          <li
            :class="['icon-item', { active: computedModelValue == iconName }]"
            @click="selectedIcon(iconName)"
          >
            <svg-icon :icon-class="iconName" />
          </li>
        </el-tooltip>
      </ul>
    </el-scrollbar>
  </el-popover>
</template>

<style scoped lang="scss">
.el-scrollbar {
  max-height: calc(50vh - 100px) !important;
  overflow-y: auto;
}
.el-divider--horizontal {
  margin: 10px auto !important;
}
.icon-list {
  display: flex;
  flex-wrap: wrap;
  padding-left: 0;
  margin-top: 0;

  .icon-item {
    cursor: pointer;
    width: 10%;
    margin: 0 0 10px 10px;
    padding: 5px;
    display: flex;
    flex-direction: column;
    justify-items: center;
    align-items: center;
    border: 1px solid #ccc;
    &:hover {
      border-color: var(--el-color-primary);
      color: var(--el-color-primary);
      transition: all 0.2s;
      transform: scaleX(1.1);
    }
  }
  .active {
    border-color: var(--el-color-primary);
    color: var(--el-color-primary);
  }
}
</style>
