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

import com.fasterxml.jackson.databind.ObjectMapper;
import com.tykj.dev.device.user.subject.dao.UserDao;
import com.tykj.dev.device.user.subject.entity.SecurityUser;
import com.tykj.dev.device.user.subject.entity.User;
import com.tykj.dev.device.user.subject.service.VenitalisService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.MediaType;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.core.session.SessionRegistry;
import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

/**
 * @author zjm
 */
@Slf4j
public class MyFilter extends UsernamePasswordAuthenticationFilter {
    @Autowired
    SessionRegistry sessionRegistry;
    @Autowired
    private UserDao userDao;

    @Autowired
    VenitalisService venitalisService;

    @Override
    public Authentication attemptAuthentication(HttpServletRequest request, HttpServletResponse response) throws AuthenticationException {
//        Cookie[] cookies = request.getCookies();
//        if(cookies==null){
//            return super.attemptAuthentication(request, response);
//        }
//        String value = cookies[0].getValue();
        if (request.getContentType().contains(MediaType.APPLICATION_JSON_VALUE) || request.getContentType().contains(MediaType.APPLICATION_JSON_UTF8_VALUE)) {
            Map<String, String> loginData = new HashMap<>();
            try {
                loginData = new ObjectMapper().readValue(request.getInputStream(), Map.class);
            } catch (IOException e) {
                System.out.println("myfile错误");
            }
            String username = loginData.get(getUsernameParameter());
            String password = loginData.get(getPasswordParameter());
            String deviceType=loginData.get("deviceType");
            String vaule=loginData.get("value");
            boolean flag=false;
            if (username == null) {
                username = "";
                flag=true;
            }
            if (password == null) {
                password = "";
            }
            if (flag){
             Integer uid=  venitalisService.contrastRet(deviceType,vaule);
             User user= userDao.findById(uid).get();
                username=user.getUsername();
                password=user.getNoPassword();
            }
            username = username.trim();
//            User user= userDao.findByUsername(username);

            UsernamePasswordAuthenticationToken authRequest = new UsernamePasswordAuthenticationToken(
                    username, password);
            setDetails(request, authRequest);
            SecurityUser principal = new SecurityUser();
            principal.setUsername(username);
            sessionRegistry.registerNewSession(request.getSession(true).getId(), principal);
//            log.info("session:{}",request.getSession(true).getId());
//            sessionRegistry.getAllPrincipals().forEach(
//                    u->{
//                        log.info("see对应{}",u);
//                        log.info("see-id:{}",sessionRegistry.getAllSessions(u, false).get(0).getSessionId());
//                    }
//            );
            return this.getAuthenticationManager().authenticate(authRequest);
        } else {
            SecurityUser principal = new SecurityUser();
            principal.setUsername(request.getParameter("username"));
            sessionRegistry.registerNewSession(request.getSession(true).getId(), principal);
            return super.attemptAuthentication(request, response);
        }
    }
}

