<template>
    <div class="max-w-screen-md w-full flex flex-col space-y-4 p-6">
        <UCard :ui="{ body: { padding: 'p-4 sm:p-4' } }">
            <UTextarea
                name="createInput"
                v-model="query"
                autoresize
                placeholder="输入搜索内容..."
                :rows="5"
                variant="none"
                :padded="false"
            />
            <div class="flex justify-between">
                <USelectMenu
                    v-model="selectedRepo"
                    :options="repos"
                    placeholder="选择 GitHub 项目"
                    value-attribute="label"
                    option-attribute="label"
                    searchable
                >
                    <UButton color="gray" variant="ghost" trailing-icon="i-heroicons-chevron-down-20-solid" :label="selectedRepo || '选择 GitHub 项目'" />
                </USelectMenu>
                <UButton
                    trailing-icon="i-heroicons-chevron-right-20-solid"
                    @click="handleSearch"
                    :loading="loading"
                    :disabled="query === ''"
                >搜索</UButton>
            </div>
        </UCard>
    </div>
</template>
<script setup>
const { fetchRequest } = useFetchRequest()
const emits = defineEmits([ 'search' ])
const query = ref('')
const selectedRepo = ref('keycloak')
const repos = ref([
    // { url: 'https://github.com/allwefantasy/byzer-llm.git', label: 'byzer-llm', branch: 'master' },
    { url: 'https://github.com/keycloak/keycloak.git', label: 'keycloak', branch: 'master' }
])
const loading = ref(false)
const handleSearch = async () => {
    if (loading.value || query.value === '') return
    loading.value = true
    const result = await fetchRequest('/v1/chat/completion/create', {
        method: 'post',
        headers: {
            'Content-Type': 'application/x-www-form-urlencoded'
        }
    })
    if (result && result.data) {
        navigateTo(`/search/${result.data.c_id}?query=${query.value}&repo=${selectedRepo.value}`)
        emits('search')
        nextTick(() => {
            loading.value = false
        })
    }    
}
defineShortcuts({
    meta_enter: {
        usingInput: 'createInput',
        handler: () => {
            handleSearch()
        }
    }
})
</script>
