package com.xunhong.erp.turbo.satoken;

import cn.dev33.satoken.stp.StpInterface;
import cn.dev33.satoken.stp.StpUtil;
import com.alibaba.fastjson2.JSONArray;
import com.alibaba.fastjson2.JSONObject;
import com.xunhong.erp.turbo.base.dto.UserSession;
import lombok.RequiredArgsConstructor;
import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingClass;
import org.springframework.stereotype.Component;

import java.util.List;

/**
 * 自定义权限加载接口实现类
 *
 * @author shenyifei
 */
@Component
@ConditionalOnMissingClass
@RequiredArgsConstructor
public class StpInterfaceImpl implements StpInterface {

	/**
	 * 返回一个账号所拥有的权限码集合
	 */
	@Override
	public List<String> getPermissionList(Object loginId, String loginType) {
		Long platformId = UserSession.USER_THREAD_LOCAL.get().getPlatformId();

		return JSONArray.from(StpUtil.getSessionByLoginId(loginId).get("platformId:" + platformId)).stream()
			.map(permissionVO -> JSONObject.from(permissionVO).getString("slug"))
			.toList();
	}

	/**
	 * 返回一个账号所拥有的角色标识集合 (权限与角色可分开校验)
	 */
	@Override
	public List<String> getRoleList(Object loginId, String loginType) {
		Object userAuthVO = StpUtil.getSessionByLoginId(loginId).get("userAuth");

		return JSONObject.from(userAuthVO).getJSONArray("userRoleVOList").stream()
			.map(userRoleVO -> JSONObject.from(userRoleVO).getString("slug"))
			.toList();
	}
}
