<template>
    <div class="pc-send-media-button">
        <BaseIconButton :icon="icon" :title="t('文件')" :disabled="!sessionId" @click="triggerPick" />
        <input ref="inputRef" class="pc-native-input" type="file" @change="handleChange" />
    </div>
</template>

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

const props = defineProps<{ sessionId: string }>();
const { t } = useI18n();
const icon = sendFileIcon;

const inputRef = ref<HTMLInputElement | null>(null);

const resetInput = () => {
    if (inputRef.value) {
        inputRef.value.value = '';
    }
};

const triggerPick = () => {
    inputRef.value?.click();
};

const handleChange = async (event: Event) => {
    const target = event.target as HTMLInputElement | null;
    const file = target?.files?.[0];
    if (!file || !props.sessionId) {
        resetInput();
        return;
    }

    try {
        await AIDeskCoreInstance.chatService.sendFileMessage({
            sessionId: props.sessionId,
            payload: { file },
        });
    } catch (error) {
        console.error(error);
        toast.error(t('发送文件失败'));
    } finally {
        resetInput();
    }
};
</script>

<style scoped>
.pc-send-media-button {
    display: inline-flex;
}

.pc-native-input {
    display: none;
}
</style>
