package com.tykj.dev.device.user.config.handler;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.tykj.dev.device.user.subject.dao.RoleDao;
import com.tykj.dev.device.user.subject.entity.*;
import com.tykj.dev.device.user.subject.service.PermissionsService;
import com.tykj.dev.device.user.subject.service.RolePermissionsService;
import com.tykj.dev.device.user.subject.service.UserRoleService;
import com.tykj.dev.device.user.subject.service.UserService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.session.SessionRegistry;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.web.authentication.AuthenticationSuccessHandler;
import org.springframework.stereotype.Component;

import javax.servlet.ServletException;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Optional;

/**
 * @author zjm
 */
@Component
@Slf4j
public class MySuccessHandler implements AuthenticationSuccessHandler {
    @Autowired
    PermissionsService permissionsService;
    @Autowired
    RoleDao roleDao;
    @Autowired
    private SessionRegistry sessionRegistry;
    private BCryptPasswordEncoder bCryptPasswordEncoder = new BCryptPasswordEncoder();
    @Autowired
    private UserService userService;
    @Autowired
    private UserRoleService userRoleService;
    @Autowired
    private RolePermissionsService rolePermissionsService;

    @Override
    public void onAuthenticationSuccess(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Authentication authentication) throws IOException, ServletException {
        Cookie[] cookies = httpServletRequest.getCookies();
//        if(cookies==null){
//            return;
//        }
//        String value = cookies[0].getValue();
//        List<Object> o = sessionRegistry.getAllPrincipals();
        SecurityUser user = (SecurityUser) authentication.getPrincipal();
//        String encode = bCryptPasswordEncoder.encode(user.getPassword());
//        user.setPassword(encode);
//        for (Object principal : o) {
//
//            SecurityUser cacheUser = (SecurityUser) principal;
//            log.info("principal---{}",cacheUser.getUsername());
//            if (cacheUser.getUsername().equals(user.getUsername())) {
//                log.info("当前用户已经在线上.现顶替:{}",user.getUsername());
//                List<SessionInformation> sessions = sessionRegistry.getAllSessions(cacheUser, false);
//                log.info("剔除前{}",sessionRegistry.getAllSessions(cacheUser,false).size());
//                for (SessionInformation sessionInformation : sessions) {
////                  String sessionId = sessionInformation.getSessionId();
//                    sessionInformation.expireNow();
//
//                }
//                log.info("剔除后{}",sessionRegistry.getAllSessions(cacheUser,false).size());
//            }
//        }


//        redisTemplate.opsForValue().set(user.getUsername(),0);
        List<UserRole> userRoles = userRoleService.findByUserId(user.getCurrentUserInfo().getUserId());
        List<Role> roles = new ArrayList<>();
        for (UserRole userRole : userRoles) {
            Integer roleId = userRole.getRoleId();
            Optional<Role> op = roleDao.findById(userRole.getRoleId());
            if (op.isPresent()) {
                Role role = op.get();
                List<RolePermissions> roleAuthorities = rolePermissionsService.findAllByRoleId(roleId);
                List<Integer> permissionsIds = new ArrayList<>();
                for (RolePermissions rolePermissions : roleAuthorities) {
                    permissionsIds.add(rolePermissions.getPermissionsId());
                }
                List<Permissions> authorities = permissionsService.findAllByPerissionsIds(permissionsIds);
                role.setPermissions(authorities);
                roles.add(role);
            }
        }

        user.setRoleList(roles);
        httpServletResponse.setStatus(200);
        httpServletResponse.setContentType("application/json; charset=utf-8");
        httpServletResponse.getWriter().println(new ObjectMapper().writeValueAsString(user));
    }

}

