package com.thinkunion.smart.park.core.gateway.filter;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.thinkunion.park.service.common.cache.CacheNames;
import com.thinkunion.smart.park.core.gateway.props.AuthProperties;
import com.thinkunion.smart.park.core.gateway.provider.AuthProvider;
import com.thinkunion.smart.park.core.gateway.provider.RequestProvider;
import com.thinkunion.smart.park.core.gateway.provider.ResponseProvider;
import io.jsonwebtoken.Claims;
import jodd.util.StringPool;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.nest.springwrap.core.jwt.JwtUtil;
import org.nest.springwrap.core.jwt.props.JwtProperties;
import org.nest.springwrap.core.launch.constant.TokenConstant;
import org.nest.springwrap.core.redis.cache.NestRedis;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.Ordered;
import org.springframework.core.io.buffer.DataBuffer;
import org.springframework.http.HttpStatus;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.stereotype.Component;
import org.springframework.util.AntPathMatcher;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Flux;
import reactor.core.publisher.Mono;

import javax.annotation.Resource;
import java.nio.charset.StandardCharsets;


@Slf4j
@Component
@AllArgsConstructor
public class AuthFilter implements GlobalFilter, Ordered {
    private final AuthProperties authProperties;
    private final ObjectMapper objectMapper;
    private final JwtProperties jwtProperties;
    private final AntPathMatcher antPathMatcher = new AntPathMatcher();
    @Resource
    private NestRedis nestRedis;

    /**
     * 应用id
     */
    public static final String APPLY_ID = "Apply-Id";

    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        //校验 Token 合法性
        ServerHttpResponse resp = exchange.getResponse();

        //校验 Token 放行
        String originalRequestUrl = RequestProvider.getOriginalRequestUrl(exchange);
        String path = exchange.getRequest().getURI().getPath();
        if (isSkip(path) || isSkip(originalRequestUrl)) {
            return chain.filter(exchange);
        }
        //校验应用是否存在
        String headerApplyId = exchange.getRequest().getHeaders().getFirst(APPLY_ID);
        String paramApplyId = exchange.getRequest().getQueryParams().getFirst(APPLY_ID);
        if(StringUtils.isNotBlank(headerApplyId) || StringUtils.isNotBlank(paramApplyId)){
            String applyId = StringUtils.isBlank(headerApplyId) ? paramApplyId : headerApplyId;
            if(!nestRedis.exists(String.format(CacheNames.APPLY_ID, applyId))){
                //不存在则不能访问
                log.info("当前应用服务已停用,请联系管理员!");
                return unAuth(resp, "当前应用服务已停用,请联系管理员!",HttpStatus.FORBIDDEN);
            }
        }else{
            log.info("没有找到应用id信息!");
            return unAuth(resp, "没有找到应用信息，请联系管理员",HttpStatus.FORBIDDEN);
        }
        if(originalRequestUrl.contains(StringPool.QUESTION_MARK)){
            String[] split = originalRequestUrl.split(StringPool.BACK_SLASH+StringPool.QUESTION_MARK);
            originalRequestUrl=split[0];
        }

        String headerToken = exchange.getRequest().getHeaders().getFirst(AuthProvider.AUTH_KEY);
        String paramToken = exchange.getRequest().getQueryParams().getFirst(AuthProvider.AUTH_KEY);
        if (StringUtils.isBlank(headerToken) && StringUtils.isBlank(paramToken)) {
            return unAuth(resp, "缺失令牌,鉴权失败",HttpStatus.UNAUTHORIZED);
        }
        String auth = StringUtils.isBlank(headerToken) ? paramToken : headerToken;
        String token = JwtUtil.getToken(auth);
        Claims claims = JwtUtil.parseJWT(token);
        if (token == null || claims == null) {
            return unAuth(resp, "请求未授权",HttpStatus.UNAUTHORIZED);
        }
        //判断 Token 状态
        if (jwtProperties.getState()) {
            String tenantId = String.valueOf(claims.get(TokenConstant.TENANT_ID));
            String userId = String.valueOf(claims.get(TokenConstant.USER_ID));
            String accessToken = JwtUtil.getAccessToken(tenantId, userId, token);
            log.info("accessToken:{}",accessToken);
            log.info("token:{}",token);
            if (!token.equalsIgnoreCase(accessToken)) {
                return unAuth(resp, "令牌已失效",HttpStatus.UNAUTHORIZED);
            }
            log.info("************");
            //rebuild1.0版本 dept有值得话orgUserId必须要有值,否则说明是旧的token让用户重新登录
            String deptId = String.valueOf(claims.get(TokenConstant.DEPT_ID));
            if(StringUtils.isNotBlank(deptId)){
                if(Long.valueOf(deptId)>0){
                    String str=String.valueOf(claims.get(TokenConstant.ORG_USER_ID));
                    if (str == null) {
                        return unAuth(resp, "令牌已失效",HttpStatus.UNAUTHORIZED);
                    }
                    try {
                       Long orgUserId= Long.valueOf(str);
                       if(orgUserId<=0){
                           return unAuth(resp, "令牌已失效",HttpStatus.UNAUTHORIZED);
                       }
                    } catch (final NumberFormatException nfe) {
                        return unAuth(resp, "令牌已失效",HttpStatus.UNAUTHORIZED);
                    }
                }
            }

            //获取用户登录后缓存的接口权限集合,
//            String menuRootStr = JwtUtil.getMenuRoot(tenantId, token);
//            MenuRoot menuRoot = JSONObject.parseObject(menuRootStr, MenuRoot.class);
//            String pathUrl = menuRoot.hasPermission(originalRequestUrl);
//            if(pathUrl==null){
//                return unAuth(resp, "请求模块未开通授权",HttpStatus.METHOD_NOT_ALLOWED);
//            }
//            if(menuRoot.isExpiration(pathUrl)){
//                return unAuth(resp, "服务已到期",HttpStatus.PAYMENT_REQUIRED);
//            }
        }


        return chain.filter(exchange);
    }

    private boolean isSkip(String path) {
        return AuthProvider.getDefaultSkipUrl().stream().anyMatch(pattern -> antPathMatcher.match(pattern, path))
                || authProperties.getSkipUrl().stream().anyMatch(pattern -> antPathMatcher.match(pattern, path));
    }

    private Mono<Void> unAuth(ServerHttpResponse resp, String msg,HttpStatus status) {
        resp.setStatusCode(status);
        resp.getHeaders().add("Content-Type", "application/json;charset=UTF-8");
        String result = "";
        try {
            result = objectMapper.writeValueAsString(ResponseProvider.response(status.value(),msg));
        } catch (JsonProcessingException e) {
            log.error(e.getMessage(), e);
        }
        DataBuffer buffer = resp.bufferFactory().wrap(result.getBytes(StandardCharsets.UTF_8));
        return resp.writeWith(Flux.just(buffer));
    }


    @Override
    public int getOrder() {
        return -100;
    }

}
