import { defineStore } from 'pinia';
import {Cookie, Session} from '/@/utils/storage';
import { getUserInfo } from "/@/api/login/user"

/**
 * @description 用户信息
 * @methods getUserInfos 获取用户信息
 * @methods setUserInfos 设置用户信息
 */
export const useUserInfo = defineStore('userInfo', {
	state: (): UserInfosStates => ({
		userInfos: {
			account: '', // 账号
			name: '',// 姓名
			phoneNo: '', //电话
			staffNo: '', // 工号
			id: '',
			photo: '', //头像
			authBtnList: [],  // 授权按钮数组
			defaultTelNo: '', // 默认分机号
			token: '',
			showTelControl: false, // 是否展示坐席操作电话面板
			orgName:'', // 组织名称
			roles: [], // 角色
		},
	}),
	actions: {
		async setUserInfos(buttons: string[]) {
			if (Session.get('userInfo')) { //有缓存 取缓存
				this.userInfos = Session.get('userInfo');
			} else {
				this.userInfos = await this.getApiUserInfo(buttons) as any;
			}
		},
		async getApiUserInfo(buttons: string[]) {
			try {
				// 个人信息
				let userInfo: any = await getUserInfo();
				this.userInfos.name = userInfo.result.name ?? '暂无名称';
				this.userInfos.account = userInfo.result.account ?? '';
				this.userInfos.phoneNo = userInfo.result.phoneNo ?? '';
				this.userInfos.staffNo = userInfo.result.staffNo ?? '';
				this.userInfos.defaultTelNo = userInfo.result.defaultTelNo ?? '';
				this.userInfos.id = userInfo.result.id ?? '';
				this.userInfos.roles = userInfo.result.roles ?? [];
				this.userInfos.token = Cookie.get('token') ?? '';
				this.userInfos.photo = "";
				this.userInfos.orgName = userInfo.result.organization?.orgName ?? '';
				//授权按钮
				this.userInfos.showTelControl = buttons.includes('public:seat:panel'); // 查询是否有展示面板权限
				this.userInfos.authBtnList = buttons;
				Session.set('userInfo', this.userInfos);
				return this.userInfos;
			} catch (error) {
				this.userInfos = {
					account: '暂无名称', // 账号
					name: '',// 姓名
					phoneNo: '', //电话
					staffNo: '', // 工号
					id: '',
					photo: '', //头像
					authBtnList: [],  // 授权按钮数组
					defaultTelNo: '', // 默认分机号
					token: '',
					showTelControl: false, // 是否展示坐席操作电话面板
					orgName:'', // 组织名称
					roles: [], // 角色
				}
				Session.set('userInfo', this.userInfos);
				return this.userInfos;
			}
		},
	},
});
