// mixins.js
import { ref } from 'vue';
import {WebSocketManager} from '@/utils/webscoket'
import { getFileType } from '@/utils/ruoyi'

export function useWebSockets() {
        //定义初始值为0的变量，要使用ref方法赋值，直接赋值的话变量改变不会更新 UI
        let count = ref(0);
        const uploadData=ref({})//上传成功后返回的数据
        const id=ref(null)
        const client=ref(null)
        const resultStr=ref('')
        const outFilePath=ref('')//算法处理后的图片
        const route = useRoute()
        const { roleId } =route.params
        const { proxy } = getCurrentInstance();
        // 定义点击事件 myFn
        function handeUpload(e){
            uploadData.value = e
            client.value = new WebSocketManager('ws://192.168.3.82:8111/ai/sf',websocketMessage)
            client.value.connect();
        }
        function websocketMessage(e) {
            const result = e && JSON.parse(e)
            console.log("🚀 ~ websocketMessage ~ result:", result)
            if (result.type == 0) {  //获取sessionId
                proxy.$modal.loading("正在检测中请稍后");
                client.value.sendMessage({
                    sessionId: e,
                    algorithmType: roleId,
                    algorithmId: roleId,
                    fileType:uploadData.value.fileType,
                    type: getFileType(uploadData.value.fileName), //0 图片 1视频
                    filePath:uploadData.value.url,
                    fileName:uploadData.value.fileName
                })
            } else if (result.type == 2) {
                const queue = result.data.queue.indexOf('[') == -1 ? result.data.queue : JSON.parse(result.data.queue);
                outFilePath.value =  result.data.outFilePath;
                proxy.$modal.closeLoading();
                if (!queue.length) {
                    proxy.$modal.msgWarning("未检测到预警");
                    resultStr.value = '未检测到预警';
                    // outFilePath.value=''
                }else {
                    outFilePath.value =  result.data.outFilePath;
                    proxy.$modal.msgSuccess("算法处理成功");
                }
            
                client.value.disconnect();
            }
        }
       // 组件被挂载时，我们用 onMounted 钩子记录一些消息
        onMounted(() => {
            console.log('component mounted!')
        });

        // 外部使用组合API中定义的变量或方法，在模板中可用。
        return {handeUpload,outFilePath,resultStr} // 返回的函数与方法的行为相同
}