function wss(wsSocketUrl) {
    return wsSocketUrl

    // const isHttps = document.location.protocol === 'https:'
    // if (isHttps) {
    //   return wsSocketUrl.replace('ws:', 'wss:')
    // } else {
    //   return wsSocketUrl.replace('wss:', 'ws:')
    // }
}

/**
 * @constructor
 */
const Socket = function (eventList) {
    const userId = localStorage.getItem('userId')
    this.apiBaseURL = `ws://10.48.36.43:18810/websocket/${userId}`
    this.eventList = eventList

    this.linkStatus = 0 // 连接状态 0未连接/连接失败 1连接中 2连接成功 99连接断开 该流程状态不可逆，如果想重来，请重新建立连接,这里状态不准许回退,该状态使用不准许使用!== 必须强制 ===
    this.linkErrorNum = 0 // 尝试连接错误次数，超过一定次数报异常
    this.reconnectTimer = '' // 多次连接定时任务
    this.pingTimer = '' // 心跳定时任务
    this.closeStatus = false // 主动关闭webSocket
}

Socket.prototype = {
    /**
     * 设置vue实例
     * @param vm
     */
    setVm(vm) {
        this.vm = vm
    },
    onInit() {
        this.onLink()
        this.onRequest()
    },
    /**
     * 进行登录
     */
    sendLogin() {
        const token = this.vm.$store.state.token
        if (!token) return false
        this.send({
            type: 'LOGIN',
            token
        })
    },
    /**
     * 发送消息
     * @param data
     */
    send(data) {
        data.t = new Date().getTime()
        // data.sign = new MD5().update(`${this.aId},${this.objectId},${this.vm.$store.state.token}`).digest('hex') // md5

        console.log('发送信息', JSON.stringify(data))
        return this.ws && this.ws.send(JSON.stringify(data))
    },
    /**
     * 开始请求
     */
    onRequest() {
        const _this = this
        // 10秒后检查连接状态
        this.reconnectTimer = setTimeout(function () {
            if (this.closeStatus === true) return false

            console.log('重新调起1', _this.apiBaseURL, _this.linkStatus, _this.linkErrorNum)

            if (_this.linkStatus === 1 && _this.linkErrorNum < 6) {
                // 如果没有连接成功,10秒后再次连接

                if (_this.ws) _this.ws.onclose() // 将上一次的进行关闭

                // 再次重启请求
                _this.onLink()
                _this.onRequest()
                _this.linkErrorNum++
            } else if (_this.linkStatus === 1 && _this.linkErrorNum >= 6) {
                console.log('连接超过6次')
            }
        }, 10 * 1000)
    },
    /**
     * [生命周期]连接
     */
    onLink() {
        if (this.ws) {
            console.log('异常链接,请调整代码')
            return false
        }

        console.log('建立链接', this.apiBaseURL, this.aId)

        // 进行连接
        this.ws = new WebSocket(wss(this.apiBaseURL))
        if (this.ws) {
            this.ws.onopen = this.onOpen.bind(this)
            this.ws.onerror = this.onError.bind(this)
            this.ws.onmessage = this.onMessage.bind(this)
            this.ws.onclose = this.onClose.bind(this)

            this.linkStatus = 1
        } else {
            console.log('ws不存在')
        }
    },
    /**
     * [生命周期]建立连接成功后
     */
    onOpen() {
        console.log('ws open')

        this.linkStatus = 2
        this.linkErrorNum = 0

        this.onPing()
        this.eventList['socket-open'](this)
    },
    /**
     * [生命周期]自定义生命周期，心跳任务
     */
    onPing() {
        const that = this
        this.pingTimer = setInterval(function () {
            that.send({
                type: 'PING'
            })
        }, 10000)
    },
    /**
     * [监听事件]后端n发送消息过来
     */
    onMessage(res) {
        const request = JSON.parse(res.data)
        console.log('onMessage', request)
        const msg = request.msg
        const code = request.code
        const data = request.data //  ? JSON.parse(request.data) : {}

        if (code === 1) {
            console.log('普通错误')
            this.vm.$message.error(msg)
        } else if (code === 2) {
            // 用户登录过期
            console.log('错误，将强制断线')
            this.vm.$message.error(msg)
            this.vm.$store.commit('userLogOut')
        } else if (code === 3) {
            // 用户登录过期
            console.log('登录过期，将强制断线')
            this.vm.$message.error(msg)
            this.vm.$store.commit('userLogOut')
        } else {
            this.eventList['socket-message']({
                code,
                msg,
                data
            })
        }
    },
    /**
     * 主动关闭连接,调用关闭后，请清除外部socket
     */
    close() {
        console.log('主动关闭')

        clearInterval(this.pingTimer)
        clearTimeout(this.reconnectTimer)
        this.send({
            type: 'OFFLINE'
        }) // 主动断链接 close有时候断不掉
        this.ws && this.ws.close()
        this.ws = null
        this.linkStatus = 99
        this.closeStatus = true
    },
    /**
     * [监听事件]后端断连
     */
    onClose() {
        console.log('onClose', '关闭监听程序')

        if (this.linkStatus === 2) {
            console.log('连接中断')
        } else if (this.linkStatus === 1 && this.linkErrorNum <= 6) {
            console.log('连接失败,马上重连')
        } else if (this.linkStatus === 1 && this.linkErrorNum >= 6) {
            console.log('多次连接失败,请刷新重试或者联系客服')
        }

        clearInterval(this.pingTimer)
        clearTimeout(this.reconnectTimer)
        this.ws = null
        this.linkStatus = 99
        this.eventList['socket-close']()
    },
    /**
     * [监听事件]异常错误
     */
    onError(e) {
        console.log('onError', '出错')
        this.ws = null
        this.linkStatus = 99
        this.eventList['socket-error'](e)
    }
}

Socket.prototype.constructor = Socket

export default Socket