import { reactive } from 'vue';
import { uuid } from '/@/utils/random'
/*
 * @Description:: 请补充填写
 * @Version: 请配置版本号
 * @Author: 舟舟
 * @Date: 2022-08-02 18:28:30
 * @LastEditors: 舟舟
 * @LastEditTime: 2022-08-03 22:21:13
 * @FilePath: /ouicai_web_framework_vite_ep_nolang/src/utils/socketTools.ts
 */
interface socketConfig {
    ws: WebSocket | null
    lockReconnet: boolean
    timeout: number
    timeoutObj: any
    serverTimeoutObj: any
    timeoutNum: any
    isExit: boolean
    userId:number
    userName:string
}

interface socketMsg {
    id: string
    send: string
    sendUserId: number
    receiverUserId:number
    info: string
    type: number
}

export default class SocketTools {
    public _config: socketConfig = {
        ws: null,
        lockReconnet: false,
        timeout: 28 * 1000,
        timeoutObj: null,
        serverTimeoutObj: null,
        timeoutNum: null,
        isExit: false,
        userId:0,
        userName:""
    }


    public messageData=reactive({
        info:'',
        previewUrl:'',
        type:0
    })

    initSocket = () => {
        this._config.isExit = false
        this._config.ws = new WebSocket('ws:192.168.8.101:1070/ws')
        this._config.ws.onopen = this.onOpen
        this._config.ws.onmessage = this.onMessage
        this._config.ws.onerror = this.onError
        this._config.ws.onclose = this.onClose
    }

    reconnect = () => {
        if (this._config.isExit) {
            return
        }
        if (this._config.lockReconnet) {
            return
        }

        this._config.lockReconnet = true
        this._config.timeoutNum && clearTimeout(this._config.timeoutNum)
        this._config.timeoutNum = setTimeout(() => {
            this.initSocket()
            this._config.lockReconnet = false
        }, 5000)
    }

    reset = () => {
        clearTimeout(this._config.timeoutObj)
        clearTimeout(this._config.serverTimeoutObj)
        this.start()
    }

    start = () => {
        if (!this._config.isExit) {
            this._config.timeoutObj && clearTimeout(this._config.timeoutObj)
            this._config.serverTimeoutObj && clearTimeout(this._config.serverTimeoutObj)
            this._config.timeoutObj = setTimeout(() => {
                if (this._config.ws?.readyState == 1) {
                    this.onSend({
                        id: uuid(),
                        send: this._config.userName,
                        sendUserId:  this._config.userId,
                        info: 'heartCheck',
                        type: 3,
                        receiverUserId: 0
                    })
                } else {
                    this.reconnect()
                }
                this._config.serverTimeoutObj = setTimeout(() => {
                    this._config.ws?.close()
                }, this._config.timeout)
            }, this._config.timeout)
        }
    }

    onOpen = (res: any) => {
        this.onSend({
            id: uuid(),
            send: this._config.userName,
            sendUserId:  this._config.userId,
            info: '登录',
            type: 0,
            receiverUserId: 0
        })
        this.start()
        console.log('链接成功！')
    }

    // Websoket接收消息事件
    onMessage = (res: any) => {
         let data=JSON.parse(res.data)
         if(data.type==1){
            this.messageData.info=data.info
            this.messageData.type=1
            this.messageData.previewUrl=data.info
         }
         this.reset()
         console.log('消息回执',  data.info)

    }
    // Websoket连接错误事件
    onError = (res: any) => {
        let data=JSON.parse(res.data)
        console.log('连接错误', data.info)
    }
    // Websoket断开事件
    onClose = (res: any) => {
        let data=JSON.parse(res.data)
        console.log('断开连接', data.info)
        this.reconnect()
    }

    onSend = (msg: socketMsg) => {
        if (this._config.ws?.readyState == 1) {
            this._config.ws?.send(JSON.stringify(msg))
        }
    }

    closeSocket = () => {
        this._config.isExit = true
        this._config.ws?.close()
        this._config.ws = null
        clearTimeout(this._config.timeoutObj)
        clearTimeout(this._config.serverTimeoutObj)
        clearTimeout(this._config.timeoutNum)
        console.log('closeSocket')
    }
}
