package com.yunfeiyun.agmp.common.framework.web.service;

import com.alibaba.fastjson2.JSON;
import com.yunfeiyun.agmp.common.constant.Constants;
import com.yunfeiyun.agmp.common.core.domain.AjaxResult;
import com.yunfeiyun.agmp.common.core.domain.model.LoginUser;
import com.yunfeiyun.agmp.common.core.domain.model.PortalInfo;
import com.yunfeiyun.agmp.common.framework.manager.AsyncFactory;
import com.yunfeiyun.agmp.common.framework.manager.AsyncManager;
import com.yunfeiyun.agmp.common.utils.ServletUtils;
import com.yunfeiyun.agmp.common.utils.StringUtils;
import com.yunfeiyun.agmp.common.utils.spring.SpringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.core.Authentication;
import org.springframework.security.web.authentication.logout.LogoutSuccessHandler;
import org.springframework.web.client.RestTemplate;

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

/**
 * 自定义退出处理类 返回成功
 * 
 * @author 杨晓辉
 */
@Configuration
public class LogoutSuccessHandlerImpl implements LogoutSuccessHandler
{

    @Autowired
    RestTemplate restTemplate;


    /**
     * 退出处理
     * 
     * @return
     */
    @Override
    public void onLogoutSuccess(HttpServletRequest request, HttpServletResponse response, Authentication authentication) throws IOException, ServletException
    {
        LoginUser loginUser = SpringUtils.getBean(TokenService.class).getLoginUser(request);
        if (StringUtils.isNotNull(loginUser))
        {
            String userName = loginUser.getUsername();
            //发消息给sso
            senSsoLogout(loginUser);
            // 删除用户缓存记录
            SpringUtils.getBean(TokenService.class).delLoginUser(loginUser.getToken());
            // 记录用户退出日志
            AsyncManager.me().execute(AsyncFactory.recordLogininfor(userName, Constants.LOGOUT, "退出成功"));
        }
        ServletUtils.renderString(response, JSON.toJSONString(AjaxResult.success("退出成功")));
    }

    public void senSsoLogout(LoginUser loginUser){
        PortalInfo portalInfo = SpringUtils.getBean(PortalService.class).getSsoInfo();
        HashMap<String, String> params = new HashMap<>();
        params.put("ptsToken", loginUser.getPtsToken());
        params.put("sysId", "FMS");
        AjaxResult response = null;
        try {

            response = restTemplate.postForObject(portalInfo.getSsoLogoutUrl(), params, AjaxResult.class );
        }catch (Exception e){
            e.printStackTrace();
        }
    }
}
