package com.skr.mdm.authentication.admin;

import com.skr.mdm.dao.LogAdminDao;
import com.skr.mdm.dto.LoginAdminDTO;
import com.skr.mdm.dto.TokenDTO;
import com.skr.mdm.enums.LogAdminTypeEnum;
import com.skr.mdm.result.ResponseResult;
import com.skr.mdm.entity.LogAdminDO;
import com.skr.mdm.service.AdminTokenService;
import com.skr.mdm.util.ResponseUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.security.core.Authentication;
import org.springframework.security.web.authentication.AuthenticationSuccessHandler;
import org.springframework.stereotype.Component;

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

/**
 * @author nfq
 * @date 2020/7/17 10:56
 */
@Component
public class AdminAuthenticationSuccessHandler implements AuthenticationSuccessHandler {

    @Autowired
    private AdminTokenService tokenService;
    @Autowired
    private LogAdminDao logAdminDao;

    @Override
    public void onAuthenticationSuccess(HttpServletRequest request, HttpServletResponse response, Authentication authentication) throws IOException, ServletException {
        LoginAdminDTO loginAdminDTO = (LoginAdminDTO) authentication.getPrincipal();
        String password = request.getParameter("password");
        loginAdminDTO.setPassword(password);
        TokenDTO token = tokenService.saveToken(loginAdminDTO);
        log(loginAdminDTO, LogAdminTypeEnum.LOGIN_TYPE.getLogType(), "登录成功");
        ResponseResult result = ResponseResult.success(token);
        ResponseUtil.responseJson(response, HttpStatus.OK.value(), result);
    }

    public void log(LoginAdminDTO loginAdminDTO, Integer logType, String content) {
        LogAdminDO logAdminDO = new LogAdminDO();
        logAdminDO.setCompanyId(loginAdminDTO.getCompanyId());
        logAdminDO.setAdminId(loginAdminDTO.getId());
        logAdminDO.setOperator(loginAdminDTO.getAdminName());
        logAdminDO.setLogType(logType);
        logAdminDO.setContent(content);
        logAdminDao.insert(logAdminDO);
    }
}
