package com.xjrsoft.common.interceptor;

import cn.dev33.satoken.session.SaSession;
import cn.dev33.satoken.stp.StpUtil;
import cn.dev33.satoken.strategy.SaStrategy;
import com.xjrsoft.common.constant.GlobalConstant;
import com.xjrsoft.common.enums.ResponseCode;
import com.xjrsoft.common.model.result.R;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;
import org.ssssssss.magicapi.core.context.RequestEntity;
import org.ssssssss.magicapi.core.interceptor.RequestInterceptor;

import java.util.ArrayList;
import java.util.List;

/**
 * magic-api 接口鉴权
 *
 * @author tzx
 */
@Component
@Slf4j
public class MagicApiRequestInterceptor implements RequestInterceptor {

    /***
     * 接口请求之前
     * @param requestEntity
     * @return
     */
    @Override
    public Object preHandle(RequestEntity requestEntity) {

        if (!StpUtil.isLogin()) {
            return R.error(ResponseCode.UN_AUTHORIZED.getCode(), ResponseCode.UN_AUTHORIZED.getMessage());
        }
        SaSession tokenSession = StpUtil.getTokenSession();
        List<Long> roleIds = tokenSession.get(GlobalConstant.LOGIN_USER_ROLE_ID_KEY, new ArrayList<>());
        if (roleIds.size() == 0) {
            tokenSession = StpUtil.getSessionByLoginId(StpUtil.getLoginId());
            roleIds = tokenSession.get(GlobalConstant.LOGIN_USER_ROLE_ID_KEY, new ArrayList<>());
        }
        //非管理员需要进行权限验证
        if (!roleIds.contains(GlobalConstant.SUPER_ADMIN_ROLE_ID)) {
            if (!SaStrategy.me.hasElement.apply(tokenSession.get(GlobalConstant.LOGIN_USER_INTERFACE_AUTH_CODE_KEY, new ArrayList<>()), requestEntity.getApiInfo().getId())) {
                return R.error(ResponseCode.MAGIC_API_UN_AUTHORIZED.getCode(), ResponseCode.MAGIC_API_UN_AUTHORIZED.getMessage());
            }
        }
        return null;
    }


    /**
     * 接口执行之后
     *
     * @param requestEntity
     * @param returnValue
     * @return
     */
    @Override
    public Object postHandle(RequestEntity requestEntity, Object returnValue) {
        log.info("{} 执行完毕，返回结果:{}", requestEntity.getApiInfo().getName(), returnValue);
        return null;
    }


}
