<script setup>
import {nextTick, ref, useTemplateRef, watch} from "vue";
import {Message} from "@arco-design/web-vue";
import {debounce} from "lodash";

const {limit} = defineProps({
    limit: {
        type: Number,
        default: 5,
    }
});
const inputTagRef = useTemplateRef('inputTagRef');
const modelValue = defineModel();
const input = ref('');

watch(
    () => modelValue.value,
    (val) => {
        if (val) {
            if (val.length > limit) {
                val.length = limit;
                Message.warning(`最多可设置${limit}个话题`)
            }
        }
    },
    {deep: true}
)

const changeInput = debounce((value) => {
    const temp = value.split('#').filter(Boolean).map(item => `#${item}`);
    if (temp.length > 0) {
        input.value = null;
        nextTick(() => {
            inputTagRef.value.blur();
            nextTick(() => {
                inputTagRef.value.focus();
            });
        });
        modelValue.value.push(...temp);
    }
}, 2000);

const pressEnter = (_input, e) => {
    const temp = input.value.split('#').filter(Boolean).map(item => `#${item}`);
    nextTick(() => {
        modelValue.value.pop();
        modelValue.value.push(...temp);
    })
}
</script>

<template>
    <a-input-tag
        ref="inputTagRef"
        :retain-input-value="false"
        @press-enter="pressEnter"
        @input-value-change="changeInput"
        v-model:model-value="modelValue"
        v-model:input-value="input"
        placeholder="请输入话题"
        unique-value>
    </a-input-tag>
</template>

<style scoped lang="scss">

</style>
