package cn.com.qmth.stmms.ms.accesscontrol;

import cn.com.qmth.stmms.ms.accesscontrol.config.LoginConfig;
import cn.com.qmth.stmms.ms.core.domain.user.AbstractUser;
import cn.com.qmth.stmms.ms.core.domain.user.MarkUser;
import cn.com.qmth.stmms.ms.core.domain.user.Role;
import cn.com.qmth.stmms.ms.core.repository.MarkUserRepo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Objects;

public class LoginInterceptor extends HandlerInterceptorAdapter {

    @Autowired
    private MarkUserRepo markUserRepo;

    @Autowired
    private LoginConfig loginConfig;

    @Override
    public boolean preHandle(HttpServletRequest request,
                             HttpServletResponse response, Object handler) throws Exception {
        String token = (String) request.getSession().getAttribute("token");
        if (token != null) {
            String[] strs = token.split("#");
            String loginName = strs[1];
            if (loginConfig.adminLoginConfig().getLoginName().equals(loginName)
//                    || loginConfig.inspectionLoginConfig().getLoginName().equals(loginName)
            ) {
                return true;
            }
//            else if (loginConfig.clientLoginConfig().getLoginName().equals(loginName)) {
//                response.sendError(HttpStatus.UNAUTHORIZED.value(), "该账户只能在采集端登录");
//                return false;
//            }
//            else if (loginConfig.uploadLoginConfig().getLoginName().equals(loginName)) {
//                response.sendError(HttpStatus.UNAUTHORIZED.value(), "该账户只能在图片客户端登录");
//                return false;
//            }
            AbstractUser user = markUserRepo.findByLoginName(loginName);
            if (Objects.equals(Role.COLLECTOR, ((MarkUser) user).getRole())) {
                response.sendError(HttpStatus.UNAUTHORIZED.value(), "该账户只能在采集端登录");
                return false;
            }
            String sessionId = request.getSession().getId();
            if (user.getSessionId().equalsIgnoreCase(sessionId)) {
                return true;
            }
        }
        response.sendError(HttpStatus.UNAUTHORIZED.value(), "没有登录或会话超时");
        return false;
    }

    public void postHandle(HttpServletRequest request,
                           HttpServletResponse response) throws Exception {

    }

    @Override
    public void afterCompletion(HttpServletRequest request,
                                HttpServletResponse response, Object handler, Exception ex)
            throws Exception {

    }
}
