import {ref} from 'vue';
import {ElMessage, ElMessageBox} from 'element-plus';
import {createFragments} from '@/api/reportFragments';

export const useStudyFragment = () => {
    const fragmentsDialogVisible = ref(false);
    const fragmentContent = ref('');

    const openFragmentDialog = () => {
        fragmentContent.value = '';
        fragmentsDialogVisible.value = true;
    };

    const closeFragmentDialog = () => {
        ElMessageBox.confirm('确定取消生成吗？', '提示', {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'warning',
        }).then(() => {
                fragmentsDialogVisible.value = false;
                ElMessage.info('已取消生成');
            })
            .catch(() => {
                // 用户取消了操作，无需处理
            });
    };

    const confirmGenerateFragment = async (sessionNum: string) => {
        if (!fragmentContent.value.trim()) {
            ElMessage.warning('请输入学习内容！');
            return;
        }

        ElMessageBox.confirm('确定要生成学习残片吗？', '提示', {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'info',
        })
            .then(async () => {
                try {
                    const res = await createFragments(sessionNum, fragmentContent.value);

                    if (res.code === 200) {
                        ElMessage.success('学习残片生成成功！');
                        fragmentsDialogVisible.value = false;
                    } else {
                        ElMessage.error(res.message || '生成学习残片失败');
                    }
                } catch (error: any) {
                    ElMessage.error(error.message || '请求失败');
                }
            })
            .catch(() => {
                ElMessage.info('已取消生成');
            });
    };

    return {
        fragmentsDialogVisible,
        fragmentContent,
        openFragmentDialog,
        closeFragmentDialog,
        confirmGenerateFragment,
    };
};
