
import { wxlogin } from '@/api/index.js';
import { CHAT_TYPE } from '@/common/enum.js'

// #ifndef VUE3
import Vue from 'vue'
import Vuex from 'vuex'
import creatPersistedstate from 'vuex-persistedstate'
import { curVersion } from '@/common/config.js'

Vue.use(Vuex)
const store = new Vuex.Store({
// #endif

// #ifdef VUE3
import { createStore } from 'vuex'
const store = createStore({
// #endif
	state: {
		chatToken: '',
		chatSeq: 0,
		chatStatus: 0, // 聊天会话状态
		chatType: CHAT_TYPE.NORMAL,
		userId: '',
		userAvatar: '',
		nickname: '',
		leftTimes: '',
		leftCutTimes: 0,
		settings: {},
		version: '',
		shareId: '',
		invited: 0,
		isVIP: false,
		expireTime: '',
		finishPhone: false,
		imgList: {}
	},
	mutations: {
		setShareId(state, id) {
			console.log('setShareId', state.shareId, id);
			if(!state.shareId && id) {
				state.shareId = id
			}
		},
		setLoginInfo(state, res) {
			// "userId": 2, // 用户ID 接stomp时会用到
			// "chatToken": "2c81c5390c0c4befa92a218dfed963ec", // chat-token
			// "leftTimes": 47, // 剩余的可用次数
			// "nickname": "AK47", // 用户昵称
			// "userAvatar": "wxfile://asdfasdfasdfas.jpg", // 用户头像
			// "isVIP": false, // 是否是充值会员
			// "expireTime": null, // 会员到期时间戳
			// "leftCutTimes": 20 // 剩余插队次数
			// console.log('setLoginInfo', res);
			res.chatToken && (state.chatToken = res.chatToken)
			state.userId = res.userId
			state.nickname = res.nickname
			state.userAvatar = res.userAvatar
			state.leftTimes = res.leftTimes
			state.leftCutTimes = res.leftCutTimes
			state.settings = res.settings
			state.isVIP = res.isVIP  // 是否是充值会员
			state.expireTime = res.expireTime // 会员到期时间戳
			state.finishPhone = res.finishPhone
		},
		setLeftTimes(state, times) {
			state.leftTimes = times
		},
		setSessionId(state, sid) {
			state.chatToken = sid
		}, 
		setAvatar(state, url) {
			state.userAvatar = url
		},
		setNickname(state, name) {
			state.nickname = name
		},
		setFinishPhone(state, b) {
			state.finishPhone = b
		},
		resetChatSeq(state) {
			state.chatSeq = 0
		},
		setChatSeq(state) {
			state.chatSeq++
		},
		setChatType(state, type) {
			state.chatType = type
		},
		setChatStatus(state, value) {
			state.chatStatus = value
		},
		setVersion(state, value) {
			state.version = value
		},
		setInvited(state, value) {
			state.invited = value
		},
		setImageSrc(state, imgobj) {
			console.log('setImageSrc', imgobj);
			state.imgList[`${imgobj.name}`] = imgobj.src
		}
		// login(state, provider) {
		// 	state.hasLogin = true;
		// 	state.loginProvider = provider;
		// },
		// logout(state) {
		// 	state.hasLogin = false
		// 	state.openid = null
		// }
	},
	getters: {
		// currentColor(state) {
		// 	return state.colorList[state.colorIndex]
		// },
		getChatSeq(state) {
			return state.chatSeq
		}
	},
	actions: {
		login: async function({
			commit,
			state
		}, code) {
			return await new Promise((resolve, reject) => {
				uni.showLoading({
				  title: '登录中',
				  mask: true
				})
				// #ifdef MP-WEIXIN
				wx.login({
					success(res) {
						if (res.code) {
							wxlogin(res.code, state.shareId).then(rst => {
								wx.hideLoading()
								if (rst.code === 0) {
									commit('setLoginInfo', rst.data)
									commit('setVersion', curVersion)
									commit('resetChatSeq')
									resolve(rst.data)
								} else {
									uni.showToast({
										icon: 'error',
										title: '登录失败' + rst.code,
										duration: 2000
									})
									reject('登录失败')
								}
							})
						}
					},
					fail(err) {
						uni.hideLoading()
						uni.showToast({
							icon: 'error',
							title: '登录失败' + err.errMsg,
							duration: 2000
						})
						// console.log('登录失败fail！' + err.errMsg)
						reject(err.errMsg)
					},
					complete() {
						console.log('login complete');
						uni.hideLoading()
					}
				})	
				
				// #endif
				
				// #ifdef H5
					console.log('code:', code)
					wxlogin(code, state.shareId).then(rst => {
						wx.hideLoading()
						if (rst.code === 0) {
							commit('setLoginInfo', rst.data)
							commit('setVersion', curVersion)
							commit('resetChatSeq')
							resolve(rst.data)
						} else {
							uni.showToast({
								icon: 'error',
								title: '登录失败' + rst.code,
								duration: 2000
							})
							reject('登录失败')
						}
					})
				// #endif
			})
		},
		
		// lazy loading openid
		getUserOpenId: async function({
			commit,
			state
		}) {
			return await new Promise((resolve, reject) => {
				if (state.openid) {
					resolve(state.openid)
				} else {
					uni.login({
						success: (data) => {
							commit('login')
							setTimeout(function() { //模拟异步请求服务器获取 openid
								const openid = '123456789'
								console.log('uni.request mock openid[' + openid + ']');
								commit('setOpenid', openid)
								resolve(openid)
							}, 1000)
						},
						fail: (err) => {
							console.log('uni.login 接口调用失败，将无法正常使用开放接口等服务', err)
							reject(err)
						}
					})
				}
			})
		},
		getPhoneNumber: function({
			commit
		}, univerifyInfo) {
			return new Promise((resolve, reject) => {
				uni.request({
					url: 'https://97fca9f2-41f6-449f-a35e-3f135d4c3875.bspapp.com/http/univerify-login',
					method: 'POST',
					data: univerifyInfo,
					success: (res) => {
						const data = res.data
						if (data.success) {
							resolve(data.phoneNumber)
						} else {
							reject(res)
						}

					},
					fail: (err) => {
						reject(res)
					}
				})
			})
		}
	},
	plugins: [creatPersistedstate({
		storage: {
			getItem: (key) => uni.getStorageSync(key),
			setItem: (key, val) => uni.setStorageSync(key, val),
			removeItem: (key) => uni.removeStorageSync(key),
		}
	})],
})

export default store
