import website from '~src/config/index'
import {isNullES} from 'js-fast-way'

// 长链接推送插件
export default class HcSocket {

    static socket = null

    static create(data, change) {
        const socket = new WebSocket(website.socket + data)
        socket.onopen = function () {
            console.log('link success')
        }
        socket.onclose = function () {
            console.log('link break')
        }
        socket.onmessage = function ({data}) {
            if (typeof change !== 'function') {
                return false
            } else {
                change(JSON.parse(data))
            }
            //console.log("收到消息：", data)
        }
        socket.onerror = function ({data}) {
            console.log('link error:', data)
        }
        this.socket = socket
    }

    //发送消息
    static async send(data) {
        const dataStr = data + ",business";
        const is_socket = await this.isSocket()
        if (!is_socket) return false
        this.socket.send(dataStr)
    }

    //链接是否存在
    static async isSocket(i = 0) {
        let _this = this
        return new Promise((resolve) => {
            if (isNullES(_this.socket)) {
                if (i <= 30) {
                    setTimeout(async () => {
                        i++
                        resolve(await _this.isSocket(i))
                    }, 1000)
                } else {
                    resolve(false)
                }
            } else {
                resolve(true)
            }
        })
    }

}
