import config from '@/config'
import storage from '@/utilsRc/storage'
import constant from '@/utilsRc/constant'
import {
	login,
	// logout,
	loginByUserId,
	getInfo,
	register,
	smsLogin,
	wechatLogin
} from '@/apiRc/login'
import {
	getToken,
	setToken,
	removeToken
} from '@/utilsRc/auth'

import {sm2} from 'sm-crypto'
// const sm2 = require('sm-crypto').sm2
const baseUrl = config.baseUrl

const user = {
	state: {
		token: getToken(),
		name: storage.get(constant.name),
		avatar: storage.get(constant.avatar),
		roles: storage.get(constant.roles),
		permissions: storage.get(constant.permissions),
		type: storage.get(constant.type),
		phonenumber: storage.get(constant.phonenumber),
		nick: storage.get(constant.nick),
		userId: storage.get(constant.userId),
		handlerData: storage.get(constant.handlerData),
		showExitPopup: false,
		publicKey: '04970A174A090FCCD2B2503DD978152ACB906919245E4C8F237BE290E6E72334DDD89B857177A11C609FAA62CC62AD75D4BB1395E2A22F2663357A5D3EF9B1C1B8',

	},


	mutations: {
		SET_TOKEN: (state, token) => {
			state.token = token
			// 同时更新存储中的token
			setToken(token)
		},
		SET_NAME: (state, name) => {
			state.name = name
			storage.set(constant.name, name)
		},
		SET_AVATAR: (state, avatar) => {
			state.avatar = avatar
			storage.set(constant.avatar, avatar)
		},
		SET_ROLES: (state, roles) => {
			state.roles = roles
			storage.set(constant.roles, roles)
		},
		SET_PERMISSIONS: (state, permissions) => {
			state.permissions = permissions
			storage.set(constant.permissions, permissions)
		},
		SET_TYPE: (state, type) => {
			state.type = type
			storage.set(constant.type, type)
		},
		SET_PHONENUMBER: (state, phonenumber) => {
			state.phonenumber = phonenumber
			storage.set(constant.phonenumber, phonenumber)
		},
		SET_NICK: (state, nick) => {
			state.nick = nick
			storage.set(constant.nick, nick)
		},
		SET_USER_ID: (state, userId) => {
			state.userId = userId
			storage.set(constant.userId, userId)
		},

		// 存储经办人信息
		SET_HAND_LER(state, data) {
			state.handlerData = data
			storage.set(constant.handlerData, data)
		},

		SET_SHOWEXITPOPUP(state, type) {
			state.showExitPopup = type
		}
	},

	actions: {
		// 登录
		LoginByUserInfo({
			commit,
			// state
		}, userInfo) {

			return new Promise((resolve, reject) => {
				// const info = JSON.parse(JSON.stringify(userInfo))
				// info.password = '04' + sm2.doEncrypt(info.password, state.publicKey, 0)
				// info.username = '04' + sm2.doEncrypt(info.username, state.publicKey, 0)
				login(userInfo).then(res => {
					setToken(res.data.token)
					commit('SET_TOKEN', res.data.token)
					resolve(res)
				}).catch(error => {
					reject(error)
				})
			})
		},
		// 网格员登录
		LoginByID({
			commit,
			// state
		}, userInfo) {

			return new Promise((resolve, reject) => {
				// const info = JSON.parse(JSON.stringify(userInfo))
				// info.password = '04' + sm2.doEncrypt(info.password, state.publicKey, 0)
				// info.username = '04' + sm2.doEncrypt(info.username, state.publicKey, 0)
				loginByUserId(userInfo).then(res => {
					setToken(res.token)
					commit('SET_TOKEN', res.token)
					resolve(res)
				}).catch(error => {
					reject(error)
				})
			})
		},
		// 登录
		Login({
			commit,
			state
		}, userInfo) {

			return new Promise((resolve, reject) => {
				const info = JSON.parse(JSON.stringify(userInfo))
				info.password = '04' + sm2.doEncrypt(info.password, state.publicKey, 0)
				info.username = '04' + sm2.doEncrypt(info.username, state.publicKey, 0)
				login(info).then(res => {
					console.log('登录接口返回:', res);
					setToken(res.data.token)
					commit('SET_TOKEN', res.data.token)
					resolve(res)
				}).catch(error => {
					reject(error)
				})
			})
		},
		// 登录
		SMSLogin({
			commit
		}, userInfo) {
			return new Promise((resolve, reject) => {
				smsLogin(userInfo).then(res => {
					setToken(res.data.token)
					commit('SET_TOKEN', res.data.token)
					resolve(res)
				}).catch(error => {
					reject(error)
				})
			})
		},
		// 登录
		WXLogin({
			commit
		}, userInfo) {
			return new Promise((resolve, reject) => {
				wechatLogin(userInfo).then(res => {
					setToken(res.data.token)
					commit('SET_TOKEN', res.data.token)
					resolve()
				}).catch(error => {
					reject(error)
				})
			})
		},
		// 注册
		Register({
			commit
		}, userInfo) {
			const username = userInfo.username
			const password = userInfo.password
			const code = userInfo.code
			const uuid = userInfo.uuid
			const userType = userInfo.userType
			const userNumber = userInfo.userNumber
			return new Promise((resolve, reject) => {
				register(username, password, code, uuid, userType, userNumber).then(res => {
					uni.showToast({
						title: `账号${username}注册成功`,
						icon: 'none'
					})
					resolve()
				}).catch(error => {
					reject(error)
				})
			})
		},

		// 获取用户信息
		GetInfo({
			commit,
			state
		}) {
			return new Promise((resolve, reject) => {
				getInfo().then(res => {
					const user = res.data.user
					const avatar = (user == null || user.avatar == "" || user.avatar == null) ?
						"https://rc.jinan.gov.cn/qcwjyH5/static/icon/my.png" : user.avatar
					const username = (user == null || user.userName == "" || user.userName ==
						null) ? "" : user.userName
					const usertype = (user == null || user.userType == "" || user.userType ==
						null) ? "" : user.userType
					const usernumber = (user == null || user.phonenumber == "" || user
						.phonenumber == null) ? "" : user.phonenumber
					const nick = (user == null || user.nickName == "" || user.nickName == null) ?
						"" : user.nickName
					const userId = (user == null || user.userId == "" || user.userId == null) ? "" :
						user.userId
					if (res.data.roles && res.data.roles.length > 0) {
						commit('SET_ROLES', res.data.roles)
						commit('SET_PERMISSIONS', res.data.permissions)
					} else {
						commit('SET_ROLES', ['ROLE_DEFAULT'])
					}
					commit('SET_NAME', username)
					commit('SET_AVATAR', avatar)
					commit('SET_TYPE', usertype)
					commit('SET_PHONENUMBER', usernumber)
					commit('SET_NICK', nick)
					commit('SET_USER_ID', userId)

					// commit('SET_HAND_LER', {
					// 	deptName: user.dept.deptName,
					// 	nickName: user.nickName
					// })

					resolve(res)
				}).catch(error => {
					reject(error)
				})
			})
		},

		// 退出系统
		LogOut({
			commit,
			state
		}) {
			return new Promise((resolve) => {
				// 直接清理本地数据，不调用后端接口
				commit('SET_TOKEN', '')
				commit('SET_ROLES', [])
				commit('SET_PERMISSIONS', [])
				commit('SET_TYPE', '')
				commit('SET_NICK', '')
				commit('SET_PHONENUMBER', '')
				commit('SET_USER_ID', '')
				commit('SET_SHOWEXITPOPUP', false)
				removeToken()
				storage.clean()
				resolve()
			})
		}
	}
}

export default user
