import { defineStore } from 'pinia';
import Cookies from 'js-cookie';
import { UserInfosStates } from './interface';
import { Session } from '/@/utils/storage';
import { getBtns, getUserInfo } from "/@/api/login/user"

/**
 * 用户信息
 * @methods setUserInfos 设置用户信息
 */
export const useUserInfo = defineStore('userInfo', {
	state: (): UserInfosStates => ({
		userInfos: {
			name: '',// 姓名
			phoneNo: '', //电话
			staffNo: '', // 工号
			id: '',
			photo: '', //头像
			authBtnList: [],  // 授权按钮数组
			defaultTelNo: '', // 默认分机号
			token: '',
			showTelControl: false, // 是否展示坐席操作电话面板
		},
	}),
	actions: {
		async setUserInfos() {
			if (Session.get('userInfo')) { //有缓存 取缓存
				this.userInfos = Session.get('userInfo');
			} else {
				this.userInfos = this.getApiUserInfo() as any;
			}
		},
		async getApiUserInfo() {
			try {
				//授权按钮
				let btnInfo: any = await getBtns();
				this.userInfos.showTelControl = btnInfo.result.includes('999125'); // 查询是否有展示面板权限
				this.userInfos.authBtnList = btnInfo.result;
				// 个人信息
				let userInfo: any = await getUserInfo();
				this.userInfos.name = userInfo.result.name;
				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.token = Session.get('token');
				this.userInfos.photo = "";
				Session.set('userInfo', this.userInfos);
				return this.userInfos;
			} catch (error) {
				this.userInfos = {
					name: 'default name',// 姓名
					phoneNo: '', //电话
					staffNo: '', // 工号
					id: '',
					photo: '', //头像
					authBtnList: [],  // 授权按钮数组
					defaultTelNo: '', // 默认分机号
					token: '',
					showTelControl: false, // 是否展示坐席操作电话面板
				}
				Session.set('userInfo', this.userInfos);
				return this.userInfos;
			}
		},
	},
});
