//webscoket
class newWebScoket {
    //初始化时自调用 构造函数
    constructor(url = "", time = 3000) {
        //连接地址
        this.url = url
        //连接器
        this.ws = null
        //避免重复连接
        this.is_open_scoket = false
        //心跳定时器
        this.heartbeatTimer = null
        //心跳时间
        this.heartbeatTime = time > 2000 ? time : 3000
        //检测心跳定时器
        this.heartbeatDetectionTimer = null
        //心跳回复
        this.heartbeatRecovery = 0
        //重连定时器
        this.reconnectionTimer = null
        //重连次数
        this.timesReconnection = 9
        //已连接次数
        this.connectedTimes = 0
        try {
            this.init()
        } catch (error) {

        }
    }
    //初始化创建连接器函数，（函数名自定义）
    init() {
        //创建连接器
        this.ws = new WebSocket(this.url)
        //连接成功时触发
        this.ws.onopen = (e) => {
            clearInterval(this.heartbeatTimer)
            clearTimeout(this.heartbeatDetectionTimer)
            clearInterval(this.reconnectionTimer)
            this.is_open_scoket = true
            this.onMessage()//连接成功确认心跳回复并赋值
            this.heartbeat()//开启心跳
        }
    }
    onMessage() {
        this.ws.onmessage = (e) => {
            if (this.isJSON(e.data)) {
                let { code, data } = JSON.parse(e.data)
                if (code === 1) {
                    this.heartbeatRecovery = 1
                }
            }
        }
    }
    //发送消息
    onSend(obj) {
        if (Object.prototype.toString.call(obj) !== '[object String]') {
            obj = JSON.stringify(obj)
        }
        this.ws.send(obj)
    }
    //心跳
    heartbeat() {
        this.heartbeatTimer = setInterval(() => {
            let data = {
                code: 1,
                msg: '心跳信息'
            }
            this.onSend(data)//发送心跳内容
            this.heartbeatDetection()//检测心跳
        }, this.heartbeatTime)
    }
    //检测心跳
    heartbeatDetection() {
        this.heartbeatDetectionTimer = setTimeout(() => {
            if (this.heartbeatRecovery === 0) {
                //开启重连机制
                this.is_open_scoket = false
                this.reconnection()//心跳信息等于0 就重连
            }
        }, 1000)
    }
    //重连
    reconnection() {
        if (!this.is_open_scoket) {
            //连接了9次以后就直接关闭
            if(this.connectedTimes === this.timesReconnection){
            this.onClose()
                return 
            }
            this.connectedTimes++
            this.onClose()
            this.init()
            this.reconnectionTimer = setInterval(() => {
                if (this.connectedTimes < this.timesReconnection) {
                    this.reconnection()
                }else{
                    this.onClose()
                }
            }, 3000)

        }
    }
    //关闭
    onClose() {
        clearInterval(this.heartbeatTimer)
        clearTimeout(this.heartbeatDetectionTimer)
        clearInterval(this.reconnectionTimer)
        this.is_open_scoket = false
        this.ws.close()
    }
    //判断是否是json
    isJSON(str) {
        if (typeof str === 'string') {
            try {
                let obj = JSON.parse(str)
                if (typeof obj === 'object' && obj) {
                    return true
                } else {
                    return false
                }
            } catch (e) {
                return false
            }
        } else {
            return false
        }
    }
}
export default newWebScoket