package com.mortals.xhx.common.utils;

import cn.hutool.core.util.StrUtil;
import com.alibaba.fastjson.JSONObject;
import com.mortals.framework.annotation.UnAuth;
import com.mortals.xhx.base.system.resource.model.ResourceEntity;
import com.mortals.xhx.common.code.MethodNameEnum;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.util.ObjectUtils;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.io.File;
import java.io.FileFilter;
import java.io.IOException;
import java.lang.reflect.Method;
import java.net.JarURLConnection;
import java.net.URL;
import java.net.URLDecoder;
import java.util.ArrayList;
import java.util.Date;
import java.util.Enumeration;
import java.util.List;
import java.util.jar.JarEntry;
import java.util.jar.JarFile;

@Slf4j
public class ControllerScanUtil {

    public static final String[] WHITE_URL = {"login", "test", "file", "securitycode"};


    public static void main(String[] args) {
        List<Class<?>> classList = getAllClassByPackageName("com.mortals.xhx.base.system.menu");
        //System.out.println(classList); //获取到了所有的类
        List<ResourceEntity> list = getAnnotationInfo(classList);
        log.info(JSONObject.toJSONString(list));
    }

    public static List<ResourceEntity> getAnnotationInfo(List<Class<?>> clsList) {
        List<ResourceEntity> resourceArrayList = new ArrayList<>();
        if (clsList != null && clsList.size() > 0) {
            for (Class<?> cls : clsList) {
                boolean exits = cls.isAnnotationPresent(RestController.class);
                if (!exits) {
                    continue;
                }
                //获取controller类，
                Method substringMethod = null;
                String result = "";
                try {
                    substringMethod = cls.getMethod("getModuleDesc");
                    result = (String) substringMethod.invoke(cls.getDeclaredConstructor().newInstance());

                } catch (Exception e) {
                    log.error("反射获取controller类异常", e);
                }
                //获取基础路径
                RequestMapping requestMappingCls = cls.getAnnotation(RequestMapping.class);
                String prefix = "";
                if (requestMappingCls != null) {
                    prefix = "/" + requestMappingCls.value()[0];
                    boolean b = false;
                    for (String s : WHITE_URL) {
                        if (StrUtil.contains(requestMappingCls.value()[0].toLowerCase(), s)) {
                            b = true;
                            break;
                        }
                    }
                    if (b) {
                        continue;
                    }
                }

                if (ObjectUtils.isEmpty(result)) {
                    if (requestMappingCls != null) {
                        result = StrUtil.removeSuffix(StrUtil.removePrefix(requestMappingCls.value()[0].toUpperCase(), "/"), "/") + "接口模块";
                    }
                }

                //获取类中的所有的方法 并生成resourceEntity
                Method[] methods = cls.getDeclaredMethods();
                if (!ObjectUtils.isEmpty(methods)) {
                    for (Method method : methods) {
                        boolean unAuth = method.isAnnotationPresent(UnAuth.class);
                        if (unAuth) {
                            continue;
                        }
                        String name = "其它";
                        String url = "";
                        boolean mExits = method.isAnnotationPresent(RequestMapping.class);
                        if (mExits) {
                            RequestMapping requestMapping = method.getAnnotation(RequestMapping.class);
                            url = prefix + "/" + requestMapping.value()[0];

                        }

                        boolean mExits1 = method.isAnnotationPresent(GetMapping.class);
                        if (mExits1) {
                            GetMapping getMapping = method.getAnnotation(GetMapping.class);
                            url = prefix + "/" + getMapping.value()[0];
                        }

                        boolean mExits2 = method.isAnnotationPresent(PostMapping.class);
                        if (mExits2) {
                            PostMapping postMapping = method.getAnnotation(PostMapping.class);
                            url = prefix + "/" + postMapping.value()[0];

                        }
                        if (!ObjectUtils.isEmpty(url)){
                            ResourceEntity resourceEntity = buildResourceEntity( result, method, url, name);
                            resourceArrayList.add(resourceEntity);
                        }

                    }
                }


                //获取超类中的方法
                Method[] superMethods = cls.getSuperclass().getDeclaredMethods();
                if (!ObjectUtils.isEmpty(superMethods)) {
                    for (Method method : superMethods) {
                        boolean unAuth = method.isAnnotationPresent(UnAuth.class);
                        if (unAuth) {
                            continue;
                        }
                        String name = "其它";
                        String url = "";

                        boolean mExits = method.isAnnotationPresent(RequestMapping.class);
                        if (mExits) {
                            RequestMapping requestMapping = method.getAnnotation(RequestMapping.class);
                            url = prefix + "/" + requestMapping.value()[0];
                            //判断路径是否存在枚举类中
                            MethodNameEnum[] values = MethodNameEnum.values();
                            for (MethodNameEnum value : values) {
                                boolean contains = StrUtil.contains(requestMapping.value()[0], value.getValue());
                                if (contains) {
                                    name = value.getDesc();
                                    break;
                                }
                            }

                        }

                        boolean mExits1 = method.isAnnotationPresent(GetMapping.class);
                        if (mExits1) {
                            GetMapping getMapping = method.getAnnotation(GetMapping.class);
                            url = prefix + "/" + getMapping.value()[0];
                            //判断路径是否存在枚举类中
                            MethodNameEnum[] values = MethodNameEnum.values();
                            for (MethodNameEnum value : values) {
                                boolean contains = StrUtil.contains(getMapping.value()[0], value.getValue());
                                if (contains) {
                                    name = value.getDesc();
                                    break;
                                }
                            }
                        }

                        boolean mExits2 = method.isAnnotationPresent(PostMapping.class);
                        if (mExits2) {
                            PostMapping postMapping = method.getAnnotation(PostMapping.class);
                            url = prefix + "/" + postMapping.value()[0];
                            MethodNameEnum[] values = MethodNameEnum.values();
                            for (MethodNameEnum value : values) {
                                boolean contains = StrUtil.contains(postMapping.value()[0], value.getValue());
                                if (contains) {
                                    name = value.getDesc();
                                    break;
                                }
                            }
                        }

                        if (!ObjectUtils.isEmpty(url)){
                            ResourceEntity resourceEntity = buildResourceEntity( result, method, url, name);
                            resourceArrayList.add(resourceEntity);
                        }
                    }
                }
            }
        }

        return resourceArrayList;
    }

    private static ResourceEntity buildResourceEntity( String result, Method method, String url, String name) {
        url = url.replaceAll("/+", "/");
        //判断方法上是否有ApiOperation注解 有读取名称

        ApiOperation annotation = method.getAnnotation(ApiOperation.class);
        if (annotation != null) {
            name = annotation.value();
        }
        ResourceEntity resourceEntity = new ResourceEntity();
        resourceEntity.initAttrValue();
        resourceEntity.setName(name);
        resourceEntity.setGroupName(result);
        resourceEntity.setUrl(url);
        resourceEntity.setCreateTime(new Date());
        resourceEntity.setCreateUserId(1L);
        resourceEntity.setCreateUserName("admin");
        return resourceEntity;
    }

    public static List<Class<?>> getAllClassByPackageName(String packageName) {
        // 获取当前包下以及子包下所以的类
        List<Class<?>> returnClassList = getClasses(packageName);
        return returnClassList;
    }

    /**
     * 从包package中获取所有的Class
     *
     * @param packageName
     * @return
     */
    private static List<Class<?>> getClasses(String packageName) {
        // 第一个class类的集合
        List<Class<?>> classes = new ArrayList<Class<?>>();
        // 是否循环迭代
        boolean recursive = true;
        // 获取包的名字 并进行替换
        String packageDirName = packageName.replace('.', '/');
        // 定义一个枚举的集合 并进行循环来处理这个目录下的things
        Enumeration<URL> dirs;
        try {
            dirs = Thread.currentThread().getContextClassLoader().getResources(packageDirName);
            // 循环迭代下去
            while (dirs.hasMoreElements()) {
                // 获取下一个元素
                URL url = dirs.nextElement();
                // 得到协议的名称
                String protocol = url.getProtocol();
                //System.out.println(url.getFile());
                // 如果是以文件的形式保存在服务器上
                if ("file".equals(protocol)) {
                    // 获取包的物理路径
                    String filePath = URLDecoder.decode(url.getFile(), "UTF-8");
                    // 以文件的方式扫描整个包下的文件 并添加到集合中
                    findAndAddClassesInPackageByFile(packageName, filePath, recursive, classes);
                } else if ("jar".equals(protocol)) {
                    // 如果是jar包文件
                    // 定义一个JarFile
                    JarFile jar;
                    try {
                        // 获取jar
                        jar = ((JarURLConnection) url.openConnection()).getJarFile();
                        // 从此jar包 得到一个枚举类
                        Enumeration<JarEntry> entries = jar.entries();
                        // 同样的进行循环迭代
                        while (entries.hasMoreElements()) {
                            // 获取jar里的一个实体 可以是目录 和一些jar包里的其他文件 如META-INF等文件
                            JarEntry entry = entries.nextElement();
                            String name = entry.getName();
                            // 如果是以/开头的
                            if (name.charAt(0) == '/') {
                                // 获取后面的字符串
                                name = name.substring(1);
                            }
                            // 如果前半部分和定义的包名相同
                            if (name.startsWith(packageDirName)) {
                                int idx = name.lastIndexOf('/');
                                // 如果以"/"结尾 是一个包
                                if (idx != -1) {
                                    // 获取包名 把"/"替换成"."
                                    packageName = name.substring(0, idx).replace('/', '.');
                                }
                                // 如果可以迭代下去 并且是一个包
                                if ((idx != -1) || recursive) {
                                    // 如果是一个.class文件 而且不是目录
                                    if (name.endsWith(".class") && !entry.isDirectory()) {
                                        // 去掉后面的".class" 获取真正的类名
                                        String className = name.substring(packageName.length() + 1, name.length() - 6);
                                        try {
                                            // 添加到classes
                                            classes.add(Class.forName(packageName + '.' + className));
                                        } catch (ClassNotFoundException e) {
                                            e.printStackTrace();
                                        }
                                    }
                                }
                            }
                        }
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }
            }
        } catch (IOException e) {
            e.printStackTrace();
        }

        return classes;
    }

    /**
     * 以文件的形式来获取包下的所有Class
     *
     * @param packageName
     * @param packagePath
     * @param recursive
     * @param classes
     */
    private static void findAndAddClassesInPackageByFile(String packageName, String packagePath, final boolean recursive, List<Class<?>> classes) {
        // 获取此包的目录 建立一个File
        File dir = new File(packagePath);
        // 如果不存在或者 也不是目录就直接返回
        if (!dir.exists() || !dir.isDirectory()) {
            return;
        }
        // 如果存在 就获取包下的所有文件 包括目录
        File[] dirFiles = dir.listFiles(new FileFilter() {
            // 自定义过滤规则 如果可以循环(包含子目录) 或则是以.class结尾的文件(编译好的java类文件)
            public boolean accept(File file) {
                return (recursive && file.isDirectory()) || (file.getName().endsWith(".class"));
            }
        });

        assert dirFiles != null;
        // 循环所有文件
        for (File file : dirFiles) {
            // 如果是目录 则继续扫描
            if (file.isDirectory()) {
                findAndAddClassesInPackageByFile(packageName + "." + file.getName(), file.getAbsolutePath(), recursive, classes);
            } else {
                // 如果是java类文件 去掉后面的.class 只留下类名
                String className = file.getName().substring(0, file.getName().length() - 6);
                try {
                    // 添加到集合中去
                    classes.add(Class.forName(packageName + '.' + className));
                } catch (ClassNotFoundException e) {
                    e.printStackTrace();
                }
            }
        }
    }
}
