<template>
    <div class="flex justify-between">
        <UButton
            class="flex-grow"
            leading-icon="i-heroicons-magnifying-glass"
            color="gray"
            variant="ghost"
            size="md"
            label="搜索记录"
            @click="handleOpen"
        />
        <UButton
            v-if="$isSignIn"
            label="清空"
            size="md"
            variant="link"
            @click="handleClear"
        />
    </div>
    <div v-if="$isSignIn" class="flex flex-col gap-2 border-l border-gray-200 dark:border-gray-800 pl-2 ml-5">
        <template v-for="(item, index) in searchHistory" :key="index">
            <UButton
                color="gray"
                variant="ghost"
                size="xs"
                :to="'/search/' + item.url"
                @click="handleClickItem"
            >
                <div class="truncate">{{ item.title }}</div>
            </UButton>
        </template>
    </div>
    <UModal v-model="isOpenHistory" :ui="{ width: 'w-full sm:max-w-screen-md' }">
        <div class="flex items-center p-2">
            <UInput
                class="w-full"
                v-model="query"
                :padded="false"
                variant="none"
                leading-icon="i-heroicons-magnifying-glass-20-solid"
                placeholder="输入关键字搜索..."
            />
            <UButton
                leading-icon="i-heroicons-x-mark-20-solid"
                color="gray"
                variant="ghost"
                @click="handleClose"
            />
        </div>
        <UDivider />
        <div class="flex flex-col p-2">
            <template v-for="(item, index) in searchHistory" :key="index">
                <UButton
                    color="gray"
                    variant="ghost"
                    long
                    leading-icon="i-heroicons-document-text"
                    :to="'/search/' + item.url"
                    @click="handleClose"
                >
                    <div class="truncate font-light">{{ item.title }}</div>
                </UButton>
            </template>
        </div>
    </UModal>
</template>
<script setup>
const emits = defineEmits(['sign', 'clear'])
const Layout = inject('Layout')
const { $isSignIn } = useUserStore()
const searchHistory = ref([])
function handleClear () {
    emits('clear')
}
const isOpenHistory = ref(false)
const query = ref('')
function handleOpen () {
    if (!$isSignIn) emits('sign')
    else {
        isOpenHistory.value = true
    }
}
function handleClose () {
    isOpenHistory.value = false
}
function handleClickItem () {
    Layout.handleCloseAside()
}
async function getUserHistory () {
    const { data } = await useRequest('/v1/chat/completion/list')
    searchHistory.value = data.value && data.value.data || []
}
onMounted(() => {
    nextTick(() => {
        getUserHistory()
    })
})
</script>
