package com.xiaomai.utils;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.xiaomai.enums.ApiModule;
import org.springframework.jdbc.core.JdbcTemplate;

import java.io.File;
import java.io.FileReader;
import java.io.IOException;
import java.lang.reflect.Field;
import java.util.*;

/**
 * @Auther: pdd
 * @Date: 2020/12/30/17:46
 * @Description: 统计API数量总量
 */
public class CountApi {
    private static JsonAndFile fileHandle = new JsonAndFile();

    public static List<File> getFiles(String path) {
        File root = new File(path);
        List<File> files = new ArrayList<File>();
        if (!root.isDirectory()) {
            files.add(root);
        } else {
            File[] subFiles = root.listFiles();
            for (File f : subFiles) {
                files.addAll(getFiles(f.getAbsolutePath()));
            }
        }
        return files;
    }

    public static void writeApiInfo2DataBase() throws IOException {

        String business_model = "god";
        JdbcTemplate template = JDBCConnect.getTemplate();
        String filePath ="\\src\\main\\resources\\apicase\\"+business_model;
        List<File> files = getFiles( System.getProperty("user.dir")+filePath);
        String configPath = "\\src\\main\\resources\\config.properties";

        Properties versionProp = new Properties();
        versionProp.load(new FileReader(new File(System.getProperty("user.dir")+configPath)));

        for (File f : files) {
            if ("commonParam.json".equals(f.getName())) {
                continue;
            }
            String api_model = null;
            // 获取文件路径
            String absPath = f.getAbsolutePath();
            String relativePath = absPath.replace(System.getProperty("user.dir"),"").replace("\\", "/");
            Enumeration<?> names = versionProp.propertyNames();
            // 根据文件路径循环遍历获取路径对应的api_model名字
            while (names.hasMoreElements()){
                String name = names.nextElement().toString();
                String value = versionProp.getProperty(name);
                if(relativePath.equals(value)){
                    api_model = name;
                    // 根据api_model名字映射ApiModele类的静态属性名。没有用到
                    Field[] fields =ApiModule.class.getDeclaredFields();
                    for(Field field:fields){
                        field.setAccessible(true);
                        try {
                            String fieldValue = field.get(ApiModule.class).toString();
                            if(fieldValue.equals(name)){
                                String fieldName = field.getName();
//                                api_model = fieldName;
                            }
                        } catch (IllegalAccessException e) {
                            e.printStackTrace();
                        }
                    }
                }
            }
            if(api_model == null){
                continue;
            }
            String fileParam = JsonAndFile.readTxtFile(f);
            JSONObject apis =  JSON.parseObject(fileParam);
            org.json.JSONObject jsonObject_apis = new org.json.JSONObject(apis);
            Iterator iterator = jsonObject_apis.keys();

            // api信息插入数据库
            while(iterator.hasNext()){
                String api_name = (String) iterator.next();
                JSONObject apiInfo = apis.getJSONObject(api_name);
                String api_path = apiInfo.getString("apiPath");
                String api_contentType = apiInfo.getString("apiContentType");
                String api_describe = apiInfo.getString("desc");
                String api_name2 = apiInfo.getString("apiName");
                template.update("INSERT INTO api_info(api_name,business_model,api_model,api_path,api_contentType,api_describe,api_name2) VALUES (?,?,?,?,?,?,?)",api_name,business_model,api_model,api_path,api_contentType,api_describe,api_name2);
            }

        }

    }

    public static void countApi(){
        int total = 0;
        StringBuffer bf = new StringBuffer();
        List<File> files = getFiles( System.getProperty("user.dir")+"\\src\\main\\resources\\apicase\\god");
        for (File f : files) {
            if ("commonParam.json".equals(f.getName())) {
                continue;
            }
            String fileParam = fileHandle.readTxtFile(f);
            JSONObject apis =  JSON.parseObject(fileParam);
            total += apis.size();
            bf.append(f.getName() + ":" + apis.size() +"\r\n");
            System.out.println(f.getName() + ":" + apis.size());
        }
        System.out.println("总数：" + total);
        bf.append("总数：" + total +"\r\n");
        bf.append("统计日期：" + TimeUtils.getCurrentTimeString() +"\r\n");

        fileHandle.writeTxt(System.getProperty("user.dir")+ "\\src\\main\\resources\\api-count.txt",bf.toString());
    }

    public static void main(String[] args) throws IOException{
        writeApiInfo2DataBase();
    }
}
