import {
	v4 as uuidv4
} from "uuid";
import IMSDK from "openim-uniapp-polyfill";
import {
	businessGetUserInfo
} from "@/api/login";
import {
	filterEmptyValue
} from "@/util/common";

const state = {
	selfInfo: {},
	authData: {},
	isSyncing: false,
	reinstall: false,
	progress: 0,
	token: ""
};

const mutations = {
	SET_TOKEN(state, info) {
		state.token = info;
	},
	SET_SELF_INFO(state, info) {
		state.selfInfo = {
			...info,
		};
	},
	SET_AUTH_DATA(state, data) {
		state.authData = {
			...data,
		};
	},
	SET_IS_SYNCING(state, data) {
		state.isSyncing = data;
	},
	SET_REINSTALL(state, data) {
		state.reinstall = data;
	},
	SET_PROGRESS(state, data) {
		state.progress = data;
	},
};

const actions = {
	async getSelfInfo({
		commit
	}) {
		try {
			const result = await IMSDK.asyncApi(IMSDK.IMMethods.GetSelfUserInfo,uuidv4(),);
			const res = await businessGetUserInfo(result.data.userID);
			
			const businessData = res.data[0] ?? {};
			filterEmptyValue(businessData);
			commit("SET_SELF_INFO", {
				...result.data,
				...businessData,
			});
		} catch (e) {
			console.log(e);
			uni.$u.toast("获取个人信息失败");
		}
	},
	async updateBusinessInfo({
		commit,
		state
	}) {
		try {
			const res = await businessGetUserInfo(state.selfInfo.userID);
			const businessData = res.data[0] ?? {};
			filterEmptyValue(businessData);
			commit("SET_SELF_INFO", {
				...state.selfInfo,
				...businessData,
			});
		} catch (e) {
			console.log(e);
		}
	},
};

export default {
	namespaced: true,
	state,
	mutations,
	actions,
};