package com.liquidnet.support.zuul.filter;

import com.liquidnet.commons.lang.util.JsonUtils;
import com.liquidnet.service.base.ResponseDto;
import com.liquidnet.service.adam.dto.AdamThirdPartParam;
import com.liquidnet.service.adam.dto.vo.AdamLoginInfoVo;
import com.liquidnet.service.feign.adam.api.FeignAdamLoginClient;
import com.netflix.zuul.ZuulFilter;
import com.netflix.zuul.context.RequestContext;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import javax.servlet.http.HttpServletRequest;
import java.io.IOException;
import java.util.List;
import java.util.stream.Collectors;

@Slf4j
@Component
public class GlobalLoginFilter extends ZuulFilter {
    @Value("#{'${global.login.url}'.split(', ')}")
    private List<String> loginUrl;

    @Autowired
    FeignAdamLoginClient feignAdamLoginClient;

    @Override
    public String filterType() {
        return "pre";
    }

    @Override
    public int filterOrder() {
        return 1;
    }

    @Override
    public boolean shouldFilter() {
        RequestContext ctx = RequestContext.getCurrentContext();
        return loginUrl.contains(ctx.getRequest().getRequestURI());
    }

    @Override
    public Object run() {
        RequestContext requestContext = RequestContext.getCurrentContext();
        HttpServletRequest servletRequest = requestContext.getRequest();

//        String token = servletRequest.getHeader("authorization");
//        if (StringUtils.isNotBlank(token)) {
//            requestContext.addZuulResponseHeader("authorization", token);
//        }

        ResponseDto<AdamLoginInfoVo> responseDto = null;
        switch (servletRequest.getRequestURI()) {
            case "/adam/login/sms":
                responseDto = feignAdamLoginClient.loginBySms(servletRequest.getParameter("mobile"), servletRequest.getParameter("code"));
                break;
            case "/adam/login/mobile":
                responseDto = feignAdamLoginClient.loginByMobile(servletRequest.getParameter("accessToken"));
                break;
            case "/adam/login/tpa":
                String body = null;
                try {
                    body = servletRequest.getReader().lines().collect(Collectors.joining(System.lineSeparator()));
                } catch (IOException e) {
                    log.error("reader request body exception", e);
                }
                responseDto = feignAdamLoginClient.loginByTpa(JsonUtils.fromJson(body, AdamThirdPartParam.class));
                break;
            default:
                log.warn("###无效的登录链接:{}", servletRequest.getRequestURI());
                break;
        }
        log.debug("login request result:{}", JsonUtils.toJson(responseDto));
        return null;
    }
}
