<template>
    <button class="input-tool-item" type="button" :disabled="isPending" @click="handleClick">
        <input ref="inputRef" class="input-tool-native-input" type="file" @change="handleChange" />
        <img :src="sendFileIcon" class="input-tool-icon" :alt="t('文件')" />
        <span class="input-tool-label">{{ t('文件') }}</span>
    </button>
</template>

<script setup lang="ts">
import { ref } from 'vue';
import { useI18n } from 'vue-i18n';
import AIDeskCoreInstance from '@tencentcloud/ai-desk-core';
import toast from '../../../../../../utils/toast';
import sendFileIcon from './sendFileIcon.svg';
import { parseUnknownError } from '../../../../../../utils/parseUnknownError';

const props = defineProps<{
    sessionId: string;
}>();

const emit = defineEmits<{
    (event: 'sent'): void;
}>();

const { t } = useI18n();
const inputRef = ref<HTMLInputElement | null>(null);
const isPending = ref(false);

const resetInputValue = () => {
    const input = inputRef.value;
    if (!input) {
        return;
    }

    input.value = '';
};

const handleClick = () => {
    if (!props.sessionId || isPending.value) {
        return;
    }

    inputRef.value?.click();
};

const handleChange = async (event: Event) => {
    const input = event.target as HTMLInputElement | null;
    const file = input?.files?.[0];

    if (!file) {
        resetInputValue();
        return;
    }

    try {
        isPending.value = true;
        await AIDeskCoreInstance.chatService.sendFileMessage({
            sessionId: props.sessionId,
            payload: {
                file,
            },
        });
        emit('sent');
    } catch (error) {
        console.error(error);
        toast.error(parseUnknownError(error))
    } finally {
        isPending.value = false;
        resetInputValue();
    }
};
</script>

<style scoped>
.input-tool-item {
    position: relative;
    display: inline-flex;
    flex: 0 0 70px;
    flex-direction: column;
    align-items: center;
    justify-content: center;
    width: 70px;
    height: 70px;
    padding: 0;
    border: 1px solid #E6E9F0;
    border-radius: 12px;
    background: #fff;
    box-sizing: border-box;
}

.input-tool-item:disabled {
    opacity: 0.4;
}

.input-tool-native-input {
    display: none;
}

.input-tool-icon {
    display: block;
    width: 28px;
    height: 28px;
}

.input-tool-label {
    margin-top: 10px;
    color: #222;
    font-size: 12px;
    line-height: 16px;
    text-align: center;
    white-space: nowrap;
}
</style>