package com.beagle.base.common.filter;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.alibaba.fastjson2.JSONObject;
import com.beagle.base.bean.vo.UserVo;
import com.beagle.base.common.component.ApplicationContextUtil;
import com.beagle.base.common.config.CommonConfig;
import com.beagle.base.common.contant.CodeEnum;
import com.beagle.base.common.contant.LoginConstants;
import com.beagle.base.common.util.ResponseUtil;
import lombok.Getter;
import lombok.Setter;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.http.*;
import org.springframework.web.client.RestTemplate;

import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;


/**
 * @author wuwanli
 */
@Slf4j
@Getter
@Setter
public class AuthenticationFilter implements Filter {
    public static final String USER_INFO_API_URL = "/xc/core/api/auth/userinfo";
    private static String[] whiteList ;
    public AuthenticationFilter(String consoleUrl) {
        whiteList =  new String[]{
                consoleUrl + "/doc.html","/swagger-resources","/api-docs",".html",".css",".js", consoleUrl + "/index"
        };
    }
    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) {
        HttpServletRequest request = (HttpServletRequest) servletRequest;
        HttpServletResponse response = (HttpServletResponse) servletResponse;
        try {

            // 设置白名单
            for (String whiteUrl : whiteList) {
                if (request.getRequestURI().startsWith(whiteUrl)
                    || request.getRequestURI().endsWith(whiteUrl)) {
                    filterChain.doFilter(request, response);
                    return;
                }
            }

            Cookie[] cookies = request.getCookies();
            if (cookies == null || cookies.length == 0) {
                ResponseUtil.returnBaseResponse(response, CodeEnum.NOT_LOGIN);
                return;
            }
            List<String> cookieList = Arrays.stream(cookies)
                    .map(obj -> obj.getName() + "=" + obj.getValue())
                    .collect(Collectors.toList());
            cookieList.forEach(item -> {
                log.info("Cookie:{}",item);
            });
            JSONObject userJson = getUserInfo(cookieList);
            UserVo userVo = new UserVo();
            userVo.setUserId(userJson.getString("user_id"));
            userVo.setUserType(userJson.getString("user_type"));
            userVo.setUserName(userJson.getString("user_name"));
            userVo.setPhone(userJson.getString("phone"));
            userVo.setEmail(userJson.getString("email"));
            String userId = userVo.getUserId();
            if (StringUtils.isBlank(userId)) {
                ResponseUtil.returnBaseResponse(response, CodeEnum.NOT_LOGIN);
                return;
            }
            String userName = userVo.getUserName();
            // 用户类型；1：超管
            String userType = userVo.getUserType();
            request.setAttribute(LoginConstants.COOKIE_NAME, cookieList);
            request.setAttribute(LoginConstants.USER_ID, userId);
            request.setAttribute(LoginConstants.USER_NAME, userName);
            request.setAttribute(LoginConstants.USER_TYPE, userType);
            log.info("----------------鉴权结束------------------------");
            filterChain.doFilter(request, response);
        } catch (Exception ex) {
            log.error("authenticationFilter Exception: ", ex);
            ResponseUtil.returnBaseResponse(response, CodeEnum.NOT_LOGIN);
        }
    }

    /**
     * 获取用户登录接口
     * @param cookieList cookie数据
     * @return 用户数据
     */
    private JSONObject getUserInfo(List<String> cookieList){
        JSONObject userJson = new JSONObject();
        HttpHeaders headers = new HttpHeaders();
        headers.put(HttpHeaders.COOKIE, cookieList);
        RestTemplate restTemplate = ApplicationContextUtil.getBean(RestTemplate.class);
        CommonConfig config = ApplicationContextUtil.getBean(CommonConfig.class);
        String url = config.getXcCoreHost() + USER_INFO_API_URL;
        log.info("调用xc-core用户登录接口地址：{}", url);
        ResponseEntity<JSONObject> responseEntity = restTemplate.exchange(url, HttpMethod.GET,new HttpEntity<>(headers),JSONObject.class);
        log.info("调用xc-core用户登录接口返回结果为：{},{}", responseEntity.getBody(), responseEntity.getStatusCodeValue());
        if(HttpStatus.OK.value() == responseEntity.getStatusCodeValue()){
            JSONObject resultJson = responseEntity.getBody();
            if (resultJson == null) {
                return userJson;
            }
            userJson = resultJson.getJSONObject("data");
            log.debug("----------- userJson -> {}", userJson);
        }
        return userJson;
    }
}
