import Vue from 'vue'
import Vuex from 'vuex'
import {
	socketurl
} from '@/api/socketurl.js'
Vue.use(Vuex)
const store = new Vuex.Store({
	state: {
		//公共的变量，这里的变量不能随便修改，只能通过触发mutations的方法才能改变
		timeoutObj: null,
		socketOpen: false,
		SOCKETURL: '',
	},
	mutations: {
		scoket(state) {
			uni.closeSocket();
			clearInterval(state.timeoutObj);
			state.SOCKETURL = socketurl + uni.getStorageSync('patientId')
			state.socketOpen = false
			try {
				uni.connectSocket({
					url: state.SOCKETURL
				})
				uni.onSocketOpen(res => {
					console.log('webScoket连接已打开', res);
					state.socketOpen = true
					clearInterval(state.timeoutObj);
					state.timeoutObj = setInterval(() => {
						uni.sendSocketMessage({
							data: 'ping',
							success(res) {
								console.log('正在发送心跳');
							},
							fail(err) {
								console.log('心跳发送失败，重新连接...');
								state.socketOpen = true
								uni.connectSocket({
									url: state.SOCKETURL
								})
							}
						})
					}, 3000)
				})
				uni.onSocketError(err => {
					console.log('webScoket连接打开失败', err);
					if (err && err.code != 1000) {
						setTimeout(() => {
							state.socketOpen = true
							uni.connectSocket({
								url: state.SOCKETURL
							})
						}, 3000)
					}
				})
				uni.onSocketClose(err => {
					console.log('webScoket连接关闭', err);
					if (err && err.code !== 1000) {
						setTimeout(() => {
							state.socketOpen = true
							uni.connectSocket({
								url: state.SOCKETURL
							})
						}, 3000)
					}
				})
			} catch (e) {
				console.log(e);
			}
		},
		socketOpenfalse(state) {
			state.socketOpen = false
		},
		//相当于同步的操作
		//点击确认
		integralsubscribesuccess(state) {
			wx.requestSubscribeMessage({
				tmplIds: [
					// 'S_c9bR4znSWpXg-6ACIMn7AkaR11dzo113XM8w4CKz0'
				],
				success(res) {},
				fail(err) {},
				complete(scc) {}
			})
		},
		subscribesuccess(state) {
			wx.requestSubscribeMessage({
				tmplIds: [
					'8InV9jXDT5sMj9OWfXEvlLQGlw2UaWfZ9OBMFxufmfk',
					'2wn1BssReKjZasxKKZRWxBN0VqSmGmkuhc3AhTr18I0',
					'MSSKCxOdtMUkY1ACu-u3itz8Vh_w5xDkO2llAOGwElU',
				],
				success(res) {},
				fail(err) {},
				complete(scc) {}
			})
		},
	},
	actions: {
		//相当于异步的操作,不能直接改变state的值，只能通过触发mutations的方法才能改变
		integralopenPopup(contxt) {
			// 获取用户的当前设置，判断是否点击了“总是保持以上，不在询问”
			wx.getSetting({
				withSubscriptions: true, // 是否获取用户订阅消息的订阅状态，默认false不返回
				success(res) {
					if (res.authSetting['scope.subscribeMessage']) {} else {
						//因为没有选择总是保持，所以需要调起授权弹窗再次授权
						contxt.commit('integralsubscribesuccess')
					}
				}
			})
		},
		// 是否设置过授权
		openPopup(contxt) {
			// 获取用户的当前设置，判断是否点击了“总是保持以上，不在询问”
			wx.getSetting({
				withSubscriptions: true, // 是否获取用户订阅消息的订阅状态，默认false不返回
				success(res) {
					if (res.authSetting['scope.subscribeMessage']) {} else {
						//因为没有选择总是保持，所以需要调起授权弹窗再次授权
						contxt.commit('subscribesuccess')
					}
				}
			})
		},
	}
})
export default store