import eventBus from '../eventBus';
import { hostname, apiPrefix } from '@/common/hostname'
import EXEC from '@/common/utils/exec'
import Storage from '../storage';

let socket_url = `wss://${hostname}${apiPrefix}/sec_ws/webSocket/user?exec_comp_id=${EXEC.comp_id||'IA'}&user_token=${Storage.get('userToken')}`

var _socket:any = '';

export const Socket:any = {
    create: () => {
        uni.connectSocket({
            url: socket_url,
            header: {
                'content-type': 'application/json'
            },
            success: (res)=>{ 
                uni.onSocketOpen(function (res) {
                    // console.log('WebSocket连接已打开！', res);
                    uni.onSocketMessage(function (res) {
                        // console.log('SOCKET收到服务器内容：' + res.data);
                        returnData(res)
                    });
                });
            },
            fail: ()=>{
                console.log("webSocket is error.");
            }
        })
    },
    emit: (eventName:string, data:any) => {
        Object.assign(data, { _operte_type: eventName })
        _socket.send(data)
    },
    on: eventBus.on,
    off: eventBus.off,
}

const returnData = (result:any) => {
    let res = result['data']
    let data = JSON.parse(res)
    if(data.success){
        let eventName = data['_operte_type']
        eventBus.emit(eventName, data)
    }else{
        uni.showToast({
            title: '长连接返回被拦截',
            duration: 2000,
            icon: 'error',
        });
    }
}


export default Socket