package com.qmth.jkserver.controller.system;

import com.qmth.jkserver.common.Constants;
import com.qmth.jkserver.constant.SpringContextHolder;
import com.qmth.jkserver.constant.SystemConstant;
import com.qmth.jkserver.core.cache.JkCacheService;
import com.qmth.jkserver.core.exception.JkServerException;
import com.qmth.jkserver.model.User;
import org.apache.commons.lang3.StringUtils;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;

public class BaseSystemController {

    public User getCachedUser(HttpServletRequest request) {
        String token = request.getHeader(Constants.REQUEST_HEADER_TOKEN);
        if (StringUtils.isEmpty(token)) {
            token = request.getParameter(Constants.REQUEST_PARAM_TOKEN);
            if (StringUtils.isNotEmpty(token) && token.startsWith("$") && token.endsWith("~")) {
                // 去掉首尾的字符计
                token = new StringBuffer(token).deleteCharAt(0).toString();
                token = new StringBuffer(token).deleteCharAt(token.length() - 1).toString();
                // 倒序
                StringBuffer stringBuffer = new StringBuffer();
                for (int i = token.length() - 1; i >= 0; i--) {
                    stringBuffer.append(token.charAt(i));
                }
                token = stringBuffer.toString();
            }
        }
        if (StringUtils.isEmpty(token)) {
            throw JkServerException.withFieldValidateError("token is null");
        }
        return SystemConstant.tokenGetUser(token);
    }

    /**
     * 获取HttpServletRequest
     *
     * @return
     */
    public static HttpServletRequest getRequest() {
        ServletRequestAttributes servletRequestAttributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        return servletRequestAttributes.getRequest();
    }
}
