import Vue from 'vue'
import Vuex from 'vuex'
Vue.use(Vuex)

const store = new Vuex.Store({
	state: {
		socketTask: null,
		websocketData: {}, // 存放从后端接收到的websocket数据
	},
	mutations: {
		setWebsocketData(state, data) {
			state.websocketData = data
		}
	},
	actions: {
		websocketInit({
			state,
			dispatch
		}, url) {
			state.socketTask = uni.connectSocket({
				url, // url是websocket连接ip
				success: () => {
					// console.log('WebSocket连接成功！')
				},
				fail: e => {
					setTimeout(() => {
						dispatch('websocketInit', url)
					}, 3000)
					// console.log('连接失败' + e)
				}
			})
			state.socketTask.onOpen(() => dispatch('websocketOnOpen'))
			state.socketTask.onMessage(res => dispatch('websocketOnMessage', res))
			state.socketTask.onClose(e => dispatch('websocketOnClose', url));
			state.socketTask.onError(e => dispatch('websocketOnError'));
		},
		websocketOnOpen({
			commit
		}) {
			// console.log('WebSocket连接正常打开中...！')
		},
		// 收到数据
		websocketOnMessage({
			commit
		}, res) {
			let data;
			try {
				data = JSON.parse(res.data)
			} catch {
				data = {
					content: res.data
				}
			}
			commit('setWebsocketData', data);

		},
		websocketOnClose({
			commit,
			dispatch
		}, url) {
			setTimeout(() => {
				dispatch('websocketInit', url)
			}, 3000)
			// console.log('WebSocket连接关闭')
		},
		websocketOnError({
			commit,
			dispatch
		}) {
			// console.log('WebSocket连接错误')
		},
		websocketClose({
			state
		}) {
			if (!state.socketTask) return
			state.socketTast.close({
				success(res) {
					// console.log('关闭成功', res)
				},
				fail(err) {
					// console.log('关闭失败', err)
				}
			})
		},
		// 发送数据
		websocketSend({
			state
		}, data) {
			uni.sendSocketMessage({
				data,
				success: res => {
					// console.log('发送成功', res)
				},
				fail: e => {
					// console.log('发送失败', e)
				}
			})
		}
	}

})

export default store
