package com.platform.aop;

import com.alibaba.nacos.api.annotation.NacosInjected;
import com.alibaba.nacos.api.exception.NacosException;
import com.alibaba.nacos.api.naming.NamingService;
import com.alibaba.nacos.api.naming.pojo.Instance;
import com.netflix.loadbalancer.ILoadBalancer;
import com.netflix.loadbalancer.LoadBalancerBuilder;
import com.netflix.loadbalancer.Server;
import org.apache.http.client.utils.URIBuilder;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import org.springframework.util.CollectionUtils;
import org.springframework.util.ObjectUtils;

import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Random;
import java.util.stream.Collectors;

/**
 * 系统日志，切面处理类
 *
 * @author lipengjun
 * @email 939961241@qq.com
 * @gitee https://gitee.com/fuyang_lipengjun/platform
 * @date 2017年3月8日 上午11:07:35
 */
@Aspect
@Component
public class RestTemplateAspect {

    @NacosInjected
    private NamingService namingService;

    @Value("${nacos.discovery.register.group-name}")
    private String groupName;

    private static Map<String, ILoadBalancer> loadBalancerMap = new HashMap<>();


    /**
     * 切点
     */
    @Pointcut("execution (public * org.springframework.web.client.RestTemplate.getForObject(..)) " +
            "|| execution (public * org.springframework.web.client.RestTemplate.postForEntity(..)) ")
    public void logPointCut() {

    }

    /**
     * 环绕通知
     */
    @Around("logPointCut()")
    public Object saveSysLog(ProceedingJoinPoint point) throws Throwable {
        Object[] args = point.getArgs();
        // 获取请求链接
        String url = args[0].toString();
        URIBuilder uriBuilder = new URIBuilder(url);
        if (uriBuilder.getPort() > 0) {
            return point.proceed();
        }
        String serviceName = uriBuilder.getHost();
        if (serviceName.contains(".")) {
            return point.proceed();
        }
        args[0] = url.replace(serviceName, getServer(serviceName).getHostPort());
        try {
            return point.proceed(args);
        } catch (Exception e) {
            e.printStackTrace();
            initLoadBalancerMap(serviceName);
            throw new RuntimeException("请求失败!");
        }
    }

    private Server getServer(String hostName) {
        if (!loadBalancerMap.containsKey(hostName)) {
            initLoadBalancerMap(hostName);
        }
        return loadBalancerMap.get(hostName).chooseServer(null);
    }

    private void initLoadBalancerMap(String hostName) {
        // 获取服务列表
        List<Instance> instances = null;
        try {
            instances = namingService.getAllInstances(hostName, groupName);
        } catch (NacosException e) {
            e.printStackTrace();
            throw new RuntimeException("获取服务实例失败,服务名称：" + hostName);
        }
        if (CollectionUtils.isEmpty(instances)) {
            throw new RuntimeException("未获取到服务实例,服务名称：" + hostName);
        }
        List<Server> servers = instances.stream().map(instance -> new Server(instance.getIp(), instance.getPort())).collect(Collectors.toList());
        ILoadBalancer loadBalancer = LoadBalancerBuilder.newBuilder().buildFixedServerListLoadBalancer(servers);
        loadBalancerMap.put(hostName, loadBalancer);
    }

}
