package com.diagbot.filter;

import com.diagbot.client.DiagbotmanServiceClient;
import com.diagbot.client.UserServiceClient;
import com.diagbot.dto.RespDTO;
import com.diagbot.entity.ServiceToken;
import com.diagbot.util.GsonUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.cloud.context.config.annotation.RefreshScope;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.cloud.gateway.support.ServerWebExchangeUtils;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.io.buffer.DataBuffer;
import org.springframework.http.HttpStatus;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Flux;
import reactor.core.publisher.Mono;

import java.net.URI;
import java.nio.charset.StandardCharsets;
import java.util.HashMap;
import java.util.Iterator;
import java.util.LinkedHashSet;
import java.util.Map;

/**
 * @Description: 全局过滤器
 * @author: gaodm
 * @time: 2018/9/7 13:55
 */
@Configuration
@RefreshScope
@Slf4j
public class GlobalGatewayFilter implements GlobalFilter {

    private static final String GATE_WAY_PREFIX = "/api";
    private static Boolean IS_GENERATE = false;
    private static Map<String, Long> SERVICE_FILTER = new HashMap<>();

    @Value("${lantone.product}")
    private String lantonePrduct;

    @Autowired
    UserServiceClient userServiceClient;
    @Autowired
    DiagbotmanServiceClient diagbotmanServiceClient;


    @Override
    public Mono<Void> filter(ServerWebExchange serverWebExchange, GatewayFilterChain gatewayFilterChain) {
        log.info("check token and url permission....");
        LinkedHashSet requiredAttribute = serverWebExchange.getRequiredAttribute(ServerWebExchangeUtils.GATEWAY_ORIGINAL_REQUEST_URL_ATTR);
        ServerHttpRequest request = serverWebExchange.getRequest();
        String requestUri = request.getPath().pathWithinApplication().value();
        String serviceName = "";
        if (requiredAttribute != null) {
            Iterator<URI> iterator = requiredAttribute.iterator();
            while (iterator.hasNext()){
                URI next = iterator.next();
                if(next.getPath().startsWith(GATE_WAY_PREFIX)){
                    requestUri = next.getPath().substring(GATE_WAY_PREFIX.length());
                    serviceName = requestUri.substring(requestUri.indexOf('/') + 1, requestUri.indexOf('/', 2));
                }
            }
        }
        log.info("APIURL:{}", requestUri);
        log.info("SERVICENAME:{}", serviceName);

//        if(!IS_GENERATE) {
//            RespDTO<List<ServiceFilter>> filter = diagbotmanServiceClient.getAll();
//            if (filter != null){
//                List<ServiceFilter> list =  filter.data;
//                if (ListUtil.isNotEmpty(list)){
//                    for(ServiceFilter bean : list) {
//                        SERVICE_FILTER.put(bean.getName(), bean.getProductId());
//                    }
//                    IS_GENERATE = true;
//                }
//            }
//        }

        Map<String, Long> serviceFilters = this.dealServiceFilter();
        if(serviceFilters.get(serviceName) != null) {
            String appkey = request.getHeaders().getFirst("appkey");
            String secret = request.getHeaders().getFirst("secret");
            Long productId = SERVICE_FILTER.get(serviceName);
            //获取appkey，secret对应的权限信息
            ServiceToken st = new ServiceToken();
            st.setAppkey(appkey);
            st.setSecret(secret);
            st.setProductId(productId);
            RespDTO<Boolean> res = diagbotmanServiceClient.hasPermission(st);
            if(res == null || !RespDTO.TRUE_CODE.equals(res.code)) {
                return getVoidMono(serverWebExchange, res);
            }
        }

        ServerHttpRequest.Builder builder = serverWebExchange.getRequest().mutate();
        builder.header("Authorization","Authorization Bearer token");
        gatewayFilterChain.filter(serverWebExchange.mutate().request(builder.build()).build());
        return gatewayFilterChain.filter(serverWebExchange.mutate().request(builder.build()).build());
    }

    /**
     * 网关抛异常
     *
     */
    private Mono<Void> getVoidMono(ServerWebExchange serverWebExchange, RespDTO res) {
        RespDTO resp = new RespDTO();
        serverWebExchange.getResponse().setStatusCode(HttpStatus.OK);
        resp.msg = res.msg;
        resp.code = res.code;
        resp.data = "";
        byte[] bytes = GsonUtil.toJson(resp).getBytes(StandardCharsets.UTF_8);
        DataBuffer buffer = serverWebExchange.getResponse().bufferFactory().wrap(bytes);
        return serverWebExchange.getResponse().writeWith(Flux.just(buffer));
    }

    /**
     * 处理需要过滤的列表
     * @return 过滤的列表
     */
    private Map<String, Long> dealServiceFilter(){
        Map<String, Long> serviceFilters = new HashMap<>();
        String[] set = lantonePrduct.split(";");
        for (String s: set){
            String[] d = s.split(",");
            serviceFilters.put(d[0],Long.valueOf(d[1]));
        }
        return serviceFilters;
    }
}
