<template>
    <el-popover popper-class="app-icon-select" trigger="click" :hide-after="0" :width="selectorWidth"
        :visible="visible">
        <template #reference>
            <el-input ref="selectorInput" v-model="iconName" placeholder="请输入" @focus="popoverShow" @blur="popoverHide" />
        </template>
        <el-scrollbar :height="250">
            <ul @mousedown.self="inputFocus = true" @mouseup.self="inputFocus = false">
                <li :class="[key === iconName ? 'active' : '']" v-for="key in Object.keys(ElementIcons)" :key="key"
                    @click="onIcon(key)">
                    <app-icon :icon="key" />
                </li>
            </ul>
        </el-scrollbar>
    </el-popover>
</template>

<script lang="ts" setup>
import { ref, computed, onMounted } from 'vue'
import * as ElementIcons from '@element-plus/icons-vue'
import AppIcon from '@pc/components/base/icon/index.vue'

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

const props = defineProps({
    modelValue: {
        type: String,
        default: ''
    },
})

const visible = ref(false)
const inputFocus = ref(false)
const selectorInput = ref()
const selectorWidth = ref(0)

const iconName = computed({
    get() {
        return props.modelValue
    },
    set(val) {
        emit('update:modelValue', val)
    }
})

const popoverShow = () => {
    visible.value = true
}

const popoverHide = () => {
    if (inputFocus.value) {
        selectorInput.value.focus()
    } else {
        visible.value = false
    }
}

const onIcon = (key: string) => {
    iconName.value = key
    popoverHide()
}

onMounted(() => {
    selectorWidth.value = selectorInput.value.$el.offsetWidth
})
</script>

<style lang="less">
@import './index.less';
</style>