// import { url } from '@src/utils/axios'
const DEFAULT_ADDRESS = process.env.NODE_ENV === 'production' ? 'ws://mall.huaml.com:8282' : 'ws://mall.huaml.com:8282'

const TYPE = {
	CART: 1
}
Object.freeze(TYPE)

const init = (address = DEFAULT_ADDRESS) => {
	let ws = new WebSocket(address)
	// 当socket连接打开时
	ws.onopen = function (e) {
		console.log('websocket握手成功')
		// onMessage(e)
	}
	// 当有消息时根据消息类型显示不同信息
	ws.onmessage = function (e) {
		let data
		try {
			data = JSON.parse(e.data)
		} catch (e) {
			data = e.data
		}
		let collection = Watcher.collection || {}
		Object.keys(collection).forEach(watcherId => {
			let watcher = collection[watcherId]
			if (watcher == null) return
			watcher.receive(data)
		})
	}

	ws.onclose = function () {
		console.log('连接关闭，定时重连')
		// init(address)
	}
	ws.onerror = function () {
		console.log('出现错误')
	}

	return ws
}

let watcherId = 1000

const isValidType = type => {
	// return type == null || type == '' || _.isString(type)
	if (type == null || type == '') return true
	let i = -1
	Object.keys(TYPE).forEach((key, index) => {
		if (TYPE[key] === type) return (i = index)
	})

	return i === -1 ? false : true
}

class Watcher {
	constructor(types, cb, filter) {
		this.cb = cb
		this.filter = filter
		this._id = watcherId++
		this.types = []

		this._register()
	}

	_register() {
		Watcher.collection[this._id] = this
	}

	// _destroy() {
	// 	let collection = Watcher.collection
	// 	collection[this._id] = null
	// }
	_isNeedReceiveMessage(type, data, source, target) {
		if (this.types.length == 0) return true
		let index = this.types.findIndex(_type => {
			return _type == type
		})
		if (index == -1) return false
		if (!_.isFunction(this.filter)) {
			return true
		}
		try {
			return this.filter.call(null, type, data, source, target)
		} catch (e) {
			throw new Error(e)
		}
	}
	receive({ type, data, source, target } = {}) {
		let _need = this._isNeedReceiveMessage(type, data, source, target)
		if (!_need) {
			return
		}
		this.cb.call(null, type, data, source, target)
	}
}

//收集器
Watcher.collection = {}

const handler = () => {
	let watcher
	let ws
	return {
		MESSAGE_TYPE: TYPE,
		watch(types, cb, filter) {
			ws = init()
			watcher = new Watcher(types, cb, filter)
			return watcher
		},
		destroy() {
			// watcher._destroy()
			ws.close()
			watcher = null
			ws = null
		}
	}
}

export default handler
