package com.xiaomai.utils;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.InputStreamReader;
import java.text.NumberFormat;
import java.util.ArrayList;
import java.util.List;
import java.util.Set;

/**
 * @Auther: pdd
 * @Date: 2021/03/22/16:33
 * @Description: 统计计算当前API 覆盖率
 */
public class CountApiCover {

    public static void main(String[] args) {

        JsonAndFile fileHandle = new JsonAndFile();

        List<String> strList = new ArrayList();
        try {
            //(文件完整路径),编码格式
            BufferedReader reader = new BufferedReader(new InputStreamReader(new FileInputStream("C:\\Users\\pdd\\Desktop\\apis.csv"), "utf-8"));
            String line = null;
            while ((line = reader.readLine()) != null) {
                strList.add(line);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }


        List<String> coverApiList = new ArrayList<>();
        List<File> files = CountApi.getFiles(System.getProperty("user.dir") + "\\src\\main\\resources\\apicase\\god");
        int apitotal = 0;
        int coverTotal = 0;
        for (File f : files) {
            if ("commonParam.json".equals(f.getName())) {
                continue;
            }
            String fileParam = fileHandle.readTxtFile(f);
            JSONObject apis = JSON.parseObject(fileParam);
            apitotal += apis.size();
            Set<String> keys = apis.keySet();
            for (String key : keys) {
                JSONObject api = apis.getJSONObject(key);
                String apiPath = api.getString("apiPath");
                if (strList.contains(apiPath)) {
                    coverTotal++;
                    coverApiList.add(apiPath);
                }
            }
        }

        StringBuffer bf = new StringBuffer();
        bf.append("统计日期：" + TimeUtils.getCurrentTimeString() + "\r\n");
        bf.append("当前完成API数：" + apitotal + "\r\n");
        bf.append("当前覆盖完成数：" + coverTotal + "\r\n");
        bf.append("API总数:" + strList.size() + "\r\n");
        bf.append("覆盖占比:" + percentInstance(coverTotal, strList.size()) + "\r\n");
        bf.append("覆盖完成API:" + "\r\n");
        for (String a : strList) {
            bf.append(a + "\r\n");
        }

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


    }

    public static String percentInstance(Integer detailTotalNumber, Integer totalNumber) {
        Double bfTotalNumber = Double.valueOf(detailTotalNumber);
        Double zcTotalNumber = Double.valueOf(totalNumber);
        double percent = bfTotalNumber / zcTotalNumber;
        //获取格式化对象
        NumberFormat nt = NumberFormat.getPercentInstance();
        //设置百分数精确度2即保留两位小数
        nt.setMinimumFractionDigits(2);
        return nt.format(percent);
    }
}
