// mixins.js
import { ref } from 'vue';
import { WebSocketManager } from '@/utils/webscoket'
import { getFileType } from '@/utils/ruoyi'
import { el } from 'element-plus/es/locales.mjs';

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 identify= ref(false)
        const { roleId } =route.params
        const { proxy } = getCurrentInstance();
        const timerout = ref(null)

        // 定义点击事件 myFn
        function handeUpload(e){
            timerout.value = setTimeout(() => {
                identify.value = false;
                proxy.$modal.msgWarning("图片或视频格式不正确，请尝试更换照片重试");
                client.value.disconnect();
            }, 30000);
            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)
            
            if (result.type == 0) {  //获取sessionId
                identify.value = true;
                client.value.sendMessage({
                    sessionId: e,
                    algorithmType: roleId,
                    algorithmId: roleId,
                    fileType:uploadData.value.fileType?uploadData.value.fileType:'',
                    type: getFileType(uploadData.value.fileName), //0 图片 1视频
                    filePath:uploadData.value.url?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);
                identify.value = false;
                if(getFileType(result.data.outFilePath)=='1'){
                    outFilePath.value =  result.data.outFilePath;
                    proxy.$modal.msgSuccess("算法处理成功");
                }else{
                    if (!queue.length) {
                        proxy.$modal.msgWarning("未检测到预警");
                        resultStr.value = '未检测到预警';
                        outFilePath.value=''
                    }else {
                        outFilePath.value =  result.data.outFilePath;
                        proxy.$modal.msgSuccess("算法处理成功");
                    }
                }
                clearTimeout( timerout.value );
                client.value.disconnect();
            }
        }
       // 组件被挂载时，我们用 onMounted 钩子记录一些消息
        onMounted(() => {
            console.log('component mounted!')
        });

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