package com.zcxk.security;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.fasterxml.jackson.databind.ObjectMapper;

import com.zcxk.dto.ResponseUserLoginDto;
import com.zcxk.dto.UserDto;
import com.zcxk.model.LoginUser;
import com.zcxk.model.AjaxMessage;
import com.zcxk.model.ResultStatus;
import com.zcxk.service.UserService;
import com.zcxk.util.RedisUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;


import org.springframework.security.core.Authentication;
import org.springframework.security.oauth2.common.OAuth2AccessToken;
import org.springframework.security.oauth2.common.exceptions.UnapprovedClientAuthenticationException;
import org.springframework.security.oauth2.provider.*;
import org.springframework.security.oauth2.provider.token.AuthorizationServerTokenServices;
import org.springframework.security.web.authentication.SavedRequestAwareAuthenticationSuccessHandler;
import org.springframework.stereotype.Component;

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

@Component("myAuthenticationSuccessHandler")
@Slf4j
public class MyAuthenticationSuccessHandler extends SavedRequestAwareAuthenticationSuccessHandler {

    @Autowired
    private ObjectMapper objectMapper;

    @Autowired
    private ClientDetailsService clientDetailsService;

    @Autowired
    private AuthorizationServerTokenServices authorizationServerTokenServices;


    @Autowired
    private UserService userService;


    @Autowired
    private RedisUtil redisUtil;

    @SuppressWarnings("unchecked")
    @Override
    public void onAuthenticationSuccess(HttpServletRequest request, HttpServletResponse response,
                                        Authentication authentication) throws IOException, ServletException {

        log.info("登录成功");

        String clientId = "smart-city-v2";
        String clientSecret = "smart-city-v2-123";



        ClientDetails clientDetails = clientDetailsService.loadClientByClientId(clientId);

        if (clientDetails == null) {
            throw new UnapprovedClientAuthenticationException("clientId对应的配置信息不存在:" + clientId);
        } else if (!StringUtils.equals(clientDetails.getClientSecret(), clientSecret)) {
            throw new UnapprovedClientAuthenticationException("clientSecret不匹配:" + clientId);
        }

        TokenRequest tokenRequest = new TokenRequest(new HashMap<>(),clientId,clientDetails.getScope(),"custom");

        OAuth2Request oAuth2Request = tokenRequest.createOAuth2Request(clientDetails);

        OAuth2Authentication oAuth2Authentication = new OAuth2Authentication(oAuth2Request, authentication);


        LoginUser loginUser = (LoginUser) oAuth2Authentication.getPrincipal();

        //踢掉已经在线的token


        OAuth2AccessToken token = authorizationServerTokenServices.createAccessToken(oAuth2Authentication);

        response.setContentType("application/json;charset=UTF-8");
        ObjectMapper objectMapper = new ObjectMapper();
        ResponseUserLoginDto responseUserLoginDto=new ResponseUserLoginDto();
        responseUserLoginDto.setToken(token);
        responseUserLoginDto.setLoginInfo(JSONArray.parseArray(loginUser.getUserInfos(), UserDto.class));
        JSONObject result=new JSONObject();


        result.put("token",token);
        result.put("userInfos",loginUser.getUserInfos());

        AjaxMessage ajaxMessage = new AjaxMessage(ResultStatus.OK,responseUserLoginDto);



        response.getWriter().write(objectMapper.writeValueAsString(ajaxMessage));
    }



}
