package com.chenyang.nse.bussiness.performance_monitor;

import com.chenyang.nse.bussiness.performance_monitor.entity.DSApiResponseMsg;
import com.chenyang.nse.bussiness.performance_monitor.entity.PerformanceDashBoardLineChartVO;
import com.chenyang.nse.bussiness.performance_monitor.entity.PerformanceDashBoardPieChart;
import com.chenyang.nse.bussiness.performance_monitor.entity.PerformanceDashBoardResVO;
import com.chenyang.nse.bussiness.performance_monitor.entity.PerformanceMonitorBase;
import com.chenyang.nse.bussiness.performance_monitor.entity.PerformanceMonitorDashBoardDetailEntity;
import com.chenyang.nse.bussiness.performance_monitor.entity.PerformanceMonitorDetailEntity;
import com.chenyang.nse.bussiness.performance_monitor.entity.PerformanceMonitorProcess;
import com.chenyang.nse.bussiness.performance_monitor.entity.PerformanceMonitorRecord;
import com.chenyang.nse.bussiness.performance_monitor.entity.PerformanceMonitorResVO;
import com.chenyang.nse.bussiness.performance_monitor.exception.AppException;
import com.chenyang.nse.bussiness.performance_monitor.service.PerformanceMonitorService;
import com.chenyang.nse.bussiness.performance_monitor.utils.SpringUtils;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.UUID;
import java.util.stream.Collectors;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

@RestController
@RequestMapping({"performance-monitor-controller"})
public class PerformanceMonitorController {
   public static Calendar calendar = Calendar.getInstance();
   public static SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.SSS");
   public static Map<String, List<PerformanceMonitorProcess>> processesInExecute = new HashMap();
   public static Map<String, Long> processesTimes = new HashMap();
   public static Boolean isSavingProcesses = false;
   public static Integer PROCESS_MONITOR__SIZE = 6;
   public static Map<String, PerformanceMonitorBase> bases = new HashMap();
   @Autowired
   PerformanceMonitorService performanceMonitorService;
   SimpleDateFormat sdf_Date = new SimpleDateFormat("yyyy-MM-dd");
   SimpleDateFormat sdf_Minute = new SimpleDateFormat("HH:mm");
   private static Map<String, Map<String, List<PerformanceMonitorBase>>> recordsInSegMap = new HashMap();
   private static Map<String, Integer> sqlAvgTimeMap = new HashMap();

   public static String base(String msg) {
      PerformanceMonitorBase base = buildPerformanceMonitorBaseVOByMap(msg);
      if (!processesTimes.containsKey(base.getTid())) {
         processesTimes.put(base.getTid(), System.currentTimeMillis());
      }

      bases.put(base.getTid(), base);
      return "数据网关保存主过程成功！\n";
   }

   public static String process(String processStr) {
      PerformanceMonitorController bean = (PerformanceMonitorController)SpringUtils.getBean(PerformanceMonitorController.class);
      PerformanceMonitorProcess process = buildPerformanceMonitorProcessVOByMap(processStr);
      String uuid = process.getUuid();
      if (!processesTimes.containsKey(uuid)) {
         processesTimes.put(uuid, System.currentTimeMillis());
      }

      synchronized(processesInExecute) {
         if (!processesInExecute.containsKey(uuid)) {
            processesInExecute.put(uuid, new ArrayList());
         }

         ((List)processesInExecute.get(uuid)).add(process);
      }

      if (((List)processesInExecute.get(uuid)).size() == PROCESS_MONITOR__SIZE) {
         bean.savePerformanceMonitorProcess(uuid);
      }

      return "数据网关保存子过程成功！\n";
   }

   private void savePerformanceMonitorProcess(String uuid) {
      List<PerformanceMonitorProcess> performanceMonitorProcesses = (List)processesInExecute.get(uuid);
      this.performanceMonitorService.savePerformanceProcesses(performanceMonitorProcesses);
      PerformanceMonitorController bean = (PerformanceMonitorController)SpringUtils.getBean(PerformanceMonitorController.class);
      bean.performanceMonitorService.savePerformanceBase((PerformanceMonitorBase)bases.get(uuid));
      removeProcess(uuid);
   }

   public static void removeProcess(String uuid) {
      processesInExecute.remove(uuid);
   }

   public static Map<String, String> mapstrToMap(String mapStr) {
      Map<String, String> resultMap = new HashMap();
      mapStr = mapStr.substring(1, mapStr.length() - 1);
      String[] split = mapStr.split(",");

      for(String s : split) {
         String[] kv = s.split("=");
         resultMap.put(kv[0].trim(), kv.length > 1 ? kv[1] : "");
      }

      return resultMap;
   }

   private static PerformanceMonitorBase buildPerformanceMonitorBaseVOByMap(String baseMapStr) {
      Map<String, String> baseMap = mapstrToMap(baseMapStr);
      PerformanceMonitorBase base = new PerformanceMonitorBase();
      base.setAppName((String)baseMap.get("appName"));
      base.setAppUser((String)baseMap.get("appUser"));
      base.setDbUser((String)baseMap.get("dbUser"));
      base.setConschema((String)baseMap.get("conschema"));
      base.setTid((String)baseMap.get("uuid"));
      base.setDatasystemAddr((String)baseMap.get("datasystemAddr"));
      base.setDatasystemName((String)baseMap.get("datasystemName"));
      base.setProxyServerName((String)baseMap.get("proxyServerName"));
      base.setProxyAddr((String)baseMap.get("proxyAddr"));
      base.setExeSql(((String)baseMap.get("sql")).replaceAll("///", ",").replaceAll("DENGHAO", "=").trim());
      return base;
   }

   private static PerformanceMonitorProcess buildPerformanceMonitorProcessVOByMap(String baseMapStr) {
      Map<String, String> processMap = mapstrToMap(baseMapStr);
      PerformanceMonitorProcess process = new PerformanceMonitorProcess();
      process.setUuid((String)processMap.get("uuid"));
      process.setProcessName((String)processMap.get("processName"));
      process.setActType((String)processMap.get("actType"));
      process.setSenderName((String)processMap.get("senderName"));
      process.setSenderAddr((String)processMap.get("senderAddr"));
      process.setAppName((String)processMap.get("appName"));
      process.setAppType((String)processMap.get("appType"));
      process.setReceiverAddr((String)processMap.get("receiverAddr"));
      process.setReceiverName((String)processMap.get("receiverName"));
      process.setExeTime((String)processMap.get("exeTime"));
      process.setExeTimeMillis(getTimeMillis(process.getExeTime()));
      process.setHidden((String)processMap.get("hidden"));
      process.setProcessOrder(Integer.parseInt((String)processMap.get("order")));
      process.setRemark(((String)processMap.get("remark")).replaceAll("///", ",").replaceAll("DENGHAO", "=").trim());
      return process;
   }

   public static int getRandomNum(int num1, int num2) {
      int result = (int)((double)num1 + Math.random() * (double)(num2 - num1 + 1));
      return result;
   }

   @RequestMapping({"getQueryParams"})
   public DSApiResponseMsg getQueryParams() {
      DSApiResponseMsg responseMsg = new DSApiResponseMsg();
      new HashMap();

      try {
         Map<String, List<String>> queryParams = this.performanceMonitorService.queryParams();
         responseMsg.setData(queryParams);
         responseMsg.setFlag(true);
      } catch (Exception e) {
         e.printStackTrace();
         responseMsg.setFlag(false);
         responseMsg.setMsg(e.getMessage());
      }

      return responseMsg;
   }

   @RequestMapping({"getRecordsByPage"})
   public DSApiResponseMsg getRecordsByPage(@RequestBody Map<String, Object> params) {
      DSApiResponseMsg responseMsg = new DSApiResponseMsg();

      try {
         Integer currentPage = (Integer)params.get("currentPage");
         Integer pageSize = (Integer)params.get("pageSize");
         int start = (currentPage - 1) * pageSize;
         String appName = params.get("appName") == null ? "" : (String)params.get("appName");
         String sql = params.get("sql") == null ? "" : (String)params.get("sql");
         String startTime = params.get("startTime") == null ? "" : (String)params.get("startTime");
         String endTime = params.get("endTime") == null ? "" : (String)params.get("endTime");
         String datasystemName = params.get("datasystemName") == null ? "" : (String)params.get("datasystemName");
         String proxyName = params.get("proxyName") == null ? "" : (String)params.get("proxyName");
         String appUser = params.get("appUser") == null ? "" : (String)params.get("appUser");
         String dbUser = params.get("dbUser") == null ? "" : (String)params.get("dbUser");
         List<PerformanceMonitorRecord> recordsByPage = this.performanceMonitorService.getRecordsByPage(start, pageSize, appName, sql, proxyName, datasystemName, startTime, endTime, appUser, dbUser);
         Integer total = this.performanceMonitorService.getTotal(start, pageSize, appName, sql, proxyName, datasystemName, startTime, endTime, appUser, dbUser);
         List<PerformanceMonitorResVO> performanceMonitorResVOS = this.buildPerformanceMonitorRecordsRes(recordsByPage);
         responseMsg.setFlag(true);
         responseMsg.setTotal(total);
         responseMsg.setData(performanceMonitorResVOS);
      } catch (AppException e) {
         e.printStackTrace();
         responseMsg.setFlag(false);
         responseMsg.setCode(e.getErrorCode());
         responseMsg.setMsg(e.getMessage());
      } catch (Exception e) {
         e.printStackTrace();
         responseMsg.setFlag(false);
         responseMsg.setCode("SE000001");
         responseMsg.setMsg("系统异常，请与系统管理员联系");
      }

      return responseMsg;
   }

   @GetMapping({"testadd"})
   public void testAdd(@RequestParam int count, @RequestParam int coefficient, @RequestParam String appName, @RequestParam String appUser, @RequestParam String date) throws ParseException {
      new SimpleDateFormat("yyyy-MM-dd");
      SimpleDateFormat test_sdf_millis = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.SSS");
      PerformanceMonitorController controllerBean = (PerformanceMonitorController)SpringUtils.getBean(PerformanceMonitorController.class);

      for(int c = 0; c < count; ++c) {
         List<PerformanceMonitorProcess> processes = new ArrayList();
         String uuid = UUID.randomUUID().toString().replaceAll("-", "");
         Calendar calendarTest = Calendar.getInstance();
         calendarTest.setTime(test_sdf_millis.parse(date + " 00:00:00.000"));
         long zero_millis = calendarTest.getTimeInMillis();
         long exeMillis = zero_millis + (long)getRandomNum(1, 86400000);
         int timediff = 0;

         for(int i = 1; i <= 6; ++i) {
            int timediffProcess = getRandomNum(1, coefficient);
            PerformanceMonitorProcess process = new PerformanceMonitorProcess();
            process.setUuid(uuid);
            process.setProcessName("过程名" + i);
            process.setActType("1");
            process.setSenderName(appName);
            process.setSenderAddr("senderAddr" + c % 50);
            process.setAppName("若依系统");
            process.setAppType("1");
            process.setReceiverAddr("receiverAddr" + c % 50);
            process.setReceiverName("receiverName" + c % 50);
            timediff += timediffProcess * timediffProcess;
            calendarTest.setTimeInMillis(exeMillis + (long)timediff);
            process.setExeTime(String.valueOf(test_sdf_millis.format(calendarTest.getTime())));
            process.setExeTimeMillis(exeMillis + (long)timediff);
            process.setHidden("0");
            process.setProcessOrder(i);
            process.setRemark(appName + "," + appUser + "的sql" + c % 50);
            processes.add(process);
         }

         PerformanceMonitorBase base = new PerformanceMonitorBase();
         base.setAppName(appName);
         base.setAppUser(appUser);
         base.setTid(uuid);
         base.setDatasystemAddr("若依系统资产库地址" + c % 50);
         base.setDatasystemName("若依系统资产库名称" + c % 50);
         base.setProxyServerName("若依系统代理服务器名称" + c % 50);
         base.setProxyAddr("若依系统代理服务器地址" + c % 50);
         base.setExeSql(appName + "," + appUser + "的sql" + c % 50);
         controllerBean.performanceMonitorService.savePerformanceProcesses(processes);
         controllerBean.performanceMonitorService.savePerformanceBase(base);
      }

   }

   @PostMapping({"getRecordListInSegTime"})
   public DSApiResponseMsg getRecordListInSegTime(@RequestBody Map<String, String> params) {
      DSApiResponseMsg responseMsg = new DSApiResponseMsg();

      try {
         String date = (String)params.get("date");
         String segTime = (String)params.get("segTime");
         responseMsg.setFlag(true);
         List<PerformanceMonitorBase> performanceMonitorBases = (List)((Map)recordsInSegMap.get(date)).get(segTime);
         List<PerformanceMonitorBase> sortedList = (List)performanceMonitorBases.stream().sorted((x, y) -> (int)(x.getStartTimeMillis() - y.getStartTimeMillis())).collect(Collectors.toList());
         sortedList.forEach((base) -> base.setAvgTimeBySql((Integer)sqlAvgTimeMap.get(base.getExeSql())));

         for(PerformanceMonitorBase performanceMonitorBase : sortedList) {
            int totalDiff = 0;

            for(PerformanceMonitorDashBoardDetailEntity entity : performanceMonitorBase.getDetailsDashBoard()) {
               totalDiff = (int)((long)totalDiff + entity.getTimeDiff());
            }

            performanceMonitorBase.setTimeDiff((long)totalDiff);
         }

         responseMsg.setData(sortedList);
      } catch (Exception e) {
         e.printStackTrace();
         responseMsg.setFlag(false);
      }

      return responseMsg;
   }

   @RequestMapping({"getRecordsDashBoard"})
   public DSApiResponseMsg getRecordsDashBoard(@RequestBody Map<String, Object> params) {
      PerformanceDashBoardResVO res = new PerformanceDashBoardResVO();
      DSApiResponseMsg responseMsg = new DSApiResponseMsg();

      try {
         String appName = params.get("appName") == null ? "" : (String)params.get("appName");
         String appUser = params.get("appUser") == null ? "" : (String)params.get("appUser");
         String date = params.get("date") == null ? "" : (String)params.get("date");
         String startTime = date + " 00:00:00.000";
         calendar.setTime(this.sdf_Date.parse(date));
         calendar.set(6, calendar.get(6) + 1);
         String endTime = sdf.format(calendar.getTime());
         List<PerformanceMonitorBase> recordsInDB = this.performanceMonitorService.getRecordsForDashBoard(appName, appUser, startTime, endTime);
         sqlAvgTimeMap = this.buildSqlAvgTimeMap(appUser, appName, startTime, endTime);
         Map<String, List<PerformanceMonitorBase>> segRecordsMap = this.buildSeg(startTime, recordsInDB);
         res.setRecords(this.buildAbnormalIndex(date, segRecordsMap, sqlAvgTimeMap, res));
         res.setAvgTime(recordsInDB != null && recordsInDB.size() != 0 ? res.getAvgTime() / (long)recordsInDB.size() : 0L);
         res.setAppUser(this.buildAppUsersPie(recordsInDB));
         res.setSlowProcess(this.buildSlowProcessPie(recordsInDB));
         res.setSlowSql(this.buildSlowSql(recordsInDB));
         responseMsg.setFlag(true);
         responseMsg.setData(res);
      } catch (AppException e) {
         e.printStackTrace();
         responseMsg.setFlag(false);
         responseMsg.setCode(e.getErrorCode());
         responseMsg.setMsg(e.getMessage());
      } catch (Exception e) {
         e.printStackTrace();
         responseMsg.setFlag(false);
         responseMsg.setCode("SE000001");
         responseMsg.setMsg("系统异常，请与系统管理员联系");
      }

      return responseMsg;
   }

   private Map<String, Integer> buildSqlAvgTimeMap(String appUser, String appName, String startTime, String endTime) {
      new HashMap();
      Map<String, Integer> avgTimeBySql = this.performanceMonitorService.getAvgTimeBySql(appUser, appName, startTime, endTime);
      return avgTimeBySql;
   }

   public Map<String, List<PerformanceMonitorBase>> buildSeg(String startTime, List<PerformanceMonitorBase> records) throws ParseException {
      Map<String, List<PerformanceMonitorBase>> segRecordsMap = new LinkedHashMap();
      calendar.setTime(sdf.parse(startTime));
      long zero_time_millis = calendar.getTimeInMillis();
      int segMillis = 300000;
      int segCount = 288;

      for(int i = 0; i < segCount; ++i) {
         calendar.setTimeInMillis(zero_time_millis + (long)(i * segMillis));
         segRecordsMap.put(this.sdf_Minute.format(calendar.getTime()), new ArrayList());
      }

      records.forEach((record) -> {
         long startTimeMillis = record.getStartTimeMillis();
         long millisBySeg = startTimeMillis - (startTimeMillis - zero_time_millis) % (long)segMillis;
         calendar.setTimeInMillis(millisBySeg);
         String segTime = this.sdf_Minute.format(calendar.getTime());
         ((List)segRecordsMap.get(segTime)).add(record);
      });
      return segRecordsMap;
   }

   private Map<String, PerformanceDashBoardLineChartVO> buildAbnormalIndex(String date, Map<String, List<PerformanceMonitorBase>> segRecordsMap, Map<String, Integer> sqlAvgTimeMap, PerformanceDashBoardResVO res) {
      Map<String, PerformanceDashBoardLineChartVO> recordsForDashBoard = new LinkedHashMap();
      segRecordsMap.forEach((segTime, recordList) -> {
         double maxIndex = (double)0.0F;
         if (recordList != null && !recordList.isEmpty()) {
            int timeDiffSum = 0;
            int avgTimeSum = 0;

            for(PerformanceMonitorBase record : recordList) {
               try {
                  Integer avgTime = (Integer)sqlAvgTimeMap.get(record.getExeSql());
                  long timeDiff = record.getTimeDiff();
                  res.setAvgTime(res.getAvgTime() + timeDiff);
                  if (timeDiff > res.getMaxTime()) {
                     res.setMaxTime(timeDiff);
                  }

                  timeDiffSum = (int)((long)timeDiffSum + timeDiff);
                  if (avgTime == null) {
                     avgTimeSum = (int)((long)avgTimeSum + timeDiff);
                  } else {
                     avgTimeSum += avgTime;
                  }
               } catch (Exception e) {
                  e.printStackTrace();
               }
            }

            if (avgTimeSum > 0) {
               maxIndex = (double)(timeDiffSum - avgTimeSum) / (double)avgTimeSum;
            } else {
               maxIndex = (double)0.0F;
            }
         }

         this.buildDetailsForDashBoard(recordList);
         PerformanceDashBoardLineChartVO lineChartVO = new PerformanceDashBoardLineChartVO();
         lineChartVO.setSegTime(segTime);
         lineChartVO.setMaxIndex(maxIndex);
         recordsForDashBoard.put(segTime, lineChartVO);
         if (!recordsInSegMap.containsKey(date)) {
            recordsInSegMap.put(date, new HashMap());
         }

         ((Map)recordsInSegMap.get(date)).put(segTime, recordList);
      });
      return recordsForDashBoard;
   }

   private List<PerformanceDashBoardPieChart> buildAppUsersPie(List<PerformanceMonitorBase> records) {
      List<PerformanceDashBoardPieChart> pies = new ArrayList();
      Map<String, Integer> usersMap = new HashMap();

      for(PerformanceMonitorBase record : records) {
         String appUser = record.getAppUser();
         if (!usersMap.containsKey(appUser)) {
            usersMap.put(appUser, 0);
         }

         usersMap.put(appUser, (Integer)usersMap.get(appUser) + 1);
      }

      usersMap.forEach((username, count) -> {
         PerformanceDashBoardPieChart pie = new PerformanceDashBoardPieChart();
         pie.setName(username);
         pie.setCount(count);
         pie.setDesc("用户：" + username + "，访问次数：" + count);
         pies.add(pie);
      });
      if (pies.size() >= 6) {
         List<PerformanceDashBoardPieChart> collect = (List)pies.stream().sorted((x, y) -> (Integer)x.getCount() - (Integer)y.getCount()).collect(Collectors.toList());
         return collect.subList(0, 6);
      } else {
         return pies;
      }
   }

   private List<PerformanceDashBoardPieChart> buildSlowSql(List<PerformanceMonitorBase> records) {
      List<PerformanceDashBoardPieChart> pies = new ArrayList();
      Map<String, Integer> slowSqlMap = new HashMap();
      slowSqlMap.put("ms≤10", 0);
      slowSqlMap.put("10<ms≤100", 0);
      slowSqlMap.put("100<ms≤200", 0);
      slowSqlMap.put("200<ms", 0);

      for(PerformanceMonitorBase record : records) {
         Long timeDiff = record.getDbTime();
         if (timeDiff <= 10L) {
            slowSqlMap.put("ms≤10", (Integer)slowSqlMap.get("ms≤10") + 1);
         } else if (10L < timeDiff && timeDiff <= 100L) {
            slowSqlMap.put("10<ms≤100", (Integer)slowSqlMap.get("10<ms≤100") + 1);
         } else if (100L < timeDiff && timeDiff <= 200L) {
            slowSqlMap.put("100<ms≤200", (Integer)slowSqlMap.get("100<ms≤200") + 1);
         } else {
            slowSqlMap.put("200<ms", (Integer)slowSqlMap.get("200<ms") + 1);
         }
      }

      slowSqlMap.forEach((k, v) -> {
         PerformanceDashBoardPieChart pie = new PerformanceDashBoardPieChart();
         pie.setDesc("执行时间" + k.replaceAll("<", "&lt;").replaceAll("≤", "&le;") + " :  " + v + "次");
         pie.setName(k);
         pie.setCount(v);
         pies.add(pie);
      });
      return pies;
   }

   private List<PerformanceDashBoardPieChart> buildSlowProcessPie(List<PerformanceMonitorBase> records) throws ParseException {
      List<PerformanceDashBoardPieChart> pies = new ArrayList();
      Map<String, Long> processesMap = new HashMap();
      processesMap.put("p3", 0L);
      processesMap.put("p2", 0L);
      processesMap.put("p1", 0L);

      for(PerformanceMonitorBase record : records) {
         processesMap.put("p1", (Long)processesMap.get("p1") + record.getBetweenTime1());
         processesMap.put("p2", (Long)processesMap.get("p2") + record.getDbTime());
         processesMap.put("p3", (Long)processesMap.get("p3") + record.getBetweenTime2());
      }

      processesMap.forEach((k, v) -> {
         PerformanceDashBoardPieChart pie = new PerformanceDashBoardPieChart();
         int size = records.size();
         if (size != 0) {
            if (k.equals("p1")) {
               pie.setName("应用->数据库");
               pie.setCount(v / (long)size);
               pie.setDesc("应用请求网络耗时：" + pie.getCount() + "ms");
            } else if (k.equals("p2")) {
               pie.setName("数据库引擎分析");
               pie.setCount(v / (long)size);
               pie.setDesc("数据库引擎分析耗时：" + pie.getCount() + "ms");
            } else if (k.equals("p3")) {
               pie.setName("数据库->应用");
               pie.setCount(v / (long)size);
               pie.setDesc("返回数据网络耗时：" + pie.getCount() + "ms");
            }

            pies.add(pie);
         }
      });
      return pies;
   }

   private List<PerformanceMonitorResVO> buildPerformanceMonitorRecordsRes(List<PerformanceMonitorRecord> recordsByPage) {
      List<PerformanceMonitorResVO> res = new ArrayList();
      recordsByPage.forEach((record) -> {
         PerformanceMonitorResVO resVO = new PerformanceMonitorResVO();
         if (record.getProcesses() != null && !record.getProcesses().isEmpty()) {
            Map<Integer, PerformanceMonitorProcess> processesMap = new HashMap();

            for(PerformanceMonitorProcess process : record.getProcesses()) {
               processesMap.put(process.getProcessOrder(), process);
            }

            buildBase(resVO, record.getBase(), processesMap);
            buildProcess_reqFromApp(resVO, processesMap);
            buildProcess_resFromDB(resVO, processesMap);
            buildProcess_resFromDBLoss(resVO, processesMap);
            buildProcess_resForApp(resVO, processesMap);
            res.add(resVO);
         }
      });
      return res;
   }

   private void buildDetailsForDashBoard(List<PerformanceMonitorBase> recordsByPage) {
      recordsByPage.forEach((record) -> {
         record.setReqTime(record.getReqTime().substring(11));
         record.setResTime(record.getResTime().substring(11));
         buildDashBoardProcess_reqFromApp(record);
         buildDashBoardProcess_BetweenAppAndDB(record);
         buildDashBoardProcess_exeInDB(record);
         buildDashBoardProcess_BetweenDBAndApp(record);
         buildDashBoardProcess_resFromDB(record);
      });
   }

   public static void buildDashBoardProcess_reqFromApp(PerformanceMonitorBase base) {
      PerformanceMonitorDashBoardDetailEntity entity = new PerformanceMonitorDashBoardDetailEntity();
      entity.setDesc(base.getReqTime() + "  " + base.getAppName() + "向数据库发送请求");
      if (base.getDetailsDashBoard() == null) {
         base.setDetailsDashBoard(new ArrayList());
      }

      base.getDetailsDashBoard().add(entity);
   }

   public static void buildDashBoardProcess_BetweenAppAndDB(PerformanceMonitorBase base) {
      PerformanceMonitorDashBoardDetailEntity entity = new PerformanceMonitorDashBoardDetailEntity();
      entity.setTimeDiff(base.getBetweenTime1());
      base.getDetailsDashBoard().add(entity);
   }

   public static void buildDashBoardProcess_exeInDB(PerformanceMonitorBase base) {
      PerformanceMonitorDashBoardDetailEntity entity = new PerformanceMonitorDashBoardDetailEntity();
      entity.setTimeDiff(base.getDbTime());
      entity.setSql(base.getExeSql());
      entity.setDatasystemName(base.getDatasystemName());
      entity.setDatasystemAddr(base.getDatasystemAddr());
      base.getDetailsDashBoard().add(entity);
   }

   public static void buildDashBoardProcess_BetweenDBAndApp(PerformanceMonitorBase base) {
      PerformanceMonitorDashBoardDetailEntity entity = new PerformanceMonitorDashBoardDetailEntity();
      entity.setTimeDiff(base.getBetweenTime2());
      base.getDetailsDashBoard().add(entity);
   }

   public static void buildDashBoardProcess_resFromDB(PerformanceMonitorBase base) {
      PerformanceMonitorDashBoardDetailEntity entity = new PerformanceMonitorDashBoardDetailEntity();
      entity.setDesc(base.getResTime() + "   " + base.getAppName() + "收到数据库返回的请求");
      base.getDetailsDashBoard().add(entity);
   }

   public static void buildBase(PerformanceMonitorResVO resVO, PerformanceMonitorBase base, Map<Integer, PerformanceMonitorProcess> processesMap) {
      resVO.setReqTime(((PerformanceMonitorProcess)processesMap.get(1)).getExeTime());
      resVO.setResTime(((PerformanceMonitorProcess)processesMap.get(6)).getExeTime());
      resVO.setTimeDiff(getTimeMillis(((PerformanceMonitorProcess)processesMap.get(6)).getExeTime()) - getTimeMillis(((PerformanceMonitorProcess)processesMap.get(1)).getExeTime()));
      resVO.setTid(base.getTid());
      resVO.setConschema(base.getConschema());
      resVO.setAppName(base.getAppName());
      resVO.setDatasystemAddr(base.getDatasystemAddr());
      resVO.setDatasystemName(base.getDatasystemName());
      resVO.setAppUser(base.getAppUser());
      resVO.setDbUser(base.getDbUser());
      resVO.setProxyServerName(base.getProxyServerName());
      resVO.setProxyAddr(base.getProxyAddr());
      resVO.setSql(base.getExeSql());
   }

   public static void buildProcess_reqFromApp(PerformanceMonitorResVO resVO, Map<Integer, PerformanceMonitorProcess> processesMap) {
      PerformanceMonitorDetailEntity reqFromApp = new PerformanceMonitorDetailEntity();
      reqFromApp.setProcessName(((PerformanceMonitorProcess)processesMap.get(1)).getProcessName());
      reqFromApp.setSenderName(((PerformanceMonitorProcess)processesMap.get(1)).getSenderName());
      reqFromApp.setSenderAddr(((PerformanceMonitorProcess)processesMap.get(1)).getSenderAddr());
      reqFromApp.setSenderTime(((PerformanceMonitorProcess)processesMap.get(1)).getExeTime());
      reqFromApp.setReceiverName(resVO.getDatasystemName());
      reqFromApp.setReceiverAddr(resVO.getDatasystemAddr());
      reqFromApp.setReceiverTime(((PerformanceMonitorProcess)processesMap.get(2)).getExeTime());
      reqFromApp.setTimeDiff(getTimeMillis(((PerformanceMonitorProcess)processesMap.get(2)).getExeTime()) - getTimeMillis(((PerformanceMonitorProcess)processesMap.get(1)).getExeTime()));
      reqFromApp.setRemark(resVO.getProxyServerName() + "(" + resVO.getProxyAddr() + ")");
      reqFromApp.setHidden(false);
      if (resVO.getDetails() == null) {
         resVO.setDetails(new ArrayList());
      }

      resVO.getDetails().add(reqFromApp);
   }

   public static void buildProcess_resFromDB(PerformanceMonitorResVO resVO, Map<Integer, PerformanceMonitorProcess> processesMap) {
      PerformanceMonitorDetailEntity dbDealTime = new PerformanceMonitorDetailEntity();
      dbDealTime.setProcessName("数据库服务处理时间");
      dbDealTime.setSenderName(resVO.getDatasystemName());
      dbDealTime.setSenderAddr(resVO.getDatasystemAddr());
      dbDealTime.setSenderTime(((PerformanceMonitorProcess)processesMap.get(2)).getExeTime());
      dbDealTime.setReceiverName(resVO.getDatasystemName());
      dbDealTime.setReceiverAddr(resVO.getDatasystemAddr());
      dbDealTime.setReceiverTime(((PerformanceMonitorProcess)processesMap.get(5)).getExeTime());
      dbDealTime.setTimeDiff(getTimeMillis(((PerformanceMonitorProcess)processesMap.get(4)).getExeTime()) - getTimeMillis(((PerformanceMonitorProcess)processesMap.get(2)).getExeTime()));
      dbDealTime.setRemark(((PerformanceMonitorProcess)processesMap.get(3)).getRemark());
      dbDealTime.setHidden(false);
      resVO.getDetails().add(dbDealTime);
   }

   public static void buildProcess_resFromDBLoss(PerformanceMonitorResVO resVO, Map<Integer, PerformanceMonitorProcess> processesMap) {
      PerformanceMonitorDetailEntity resFromDBLoss = new PerformanceMonitorDetailEntity();
      resFromDBLoss.setProcessName("数据返回时间损耗");
      resFromDBLoss.setSenderName(resVO.getDatasystemName());
      resFromDBLoss.setSenderAddr(resVO.getDatasystemAddr());
      resFromDBLoss.setSenderTime(((PerformanceMonitorProcess)processesMap.get(2)).getExeTime());
      resFromDBLoss.setReceiverName(resVO.getDatasystemName());
      resFromDBLoss.setReceiverAddr(resVO.getDatasystemAddr());
      resFromDBLoss.setReceiverTime(((PerformanceMonitorProcess)processesMap.get(5)).getExeTime());
      resFromDBLoss.setTimeDiff(getTimeMillis(((PerformanceMonitorProcess)processesMap.get(5)).getExeTime()) - getTimeMillis(((PerformanceMonitorProcess)processesMap.get(4)).getExeTime()));
      resFromDBLoss.setRemark(resVO.getDatasystemAddr() + " -> " + resVO.getProxyAddr());
      resFromDBLoss.setHidden(false);
      resVO.getDetails().add(resFromDBLoss);
   }

   public static void buildProcess_resForApp(PerformanceMonitorResVO resVO, Map<Integer, PerformanceMonitorProcess> processesMap) {
      PerformanceMonitorDetailEntity resForApp = new PerformanceMonitorDetailEntity();
      resForApp.setProcessName(((PerformanceMonitorProcess)processesMap.get(5)).getProcessName());
      resForApp.setSenderName(resVO.getDatasystemName());
      resForApp.setSenderAddr(resVO.getDatasystemAddr());
      resForApp.setSenderTime(((PerformanceMonitorProcess)processesMap.get(5)).getExeTime());
      resForApp.setReceiverName(((PerformanceMonitorProcess)processesMap.get(6)).getReceiverName());
      resForApp.setReceiverAddr(((PerformanceMonitorProcess)processesMap.get(6)).getReceiverAddr());
      resForApp.setReceiverTime(((PerformanceMonitorProcess)processesMap.get(6)).getExeTime());
      resForApp.setTimeDiff(getTimeMillis(((PerformanceMonitorProcess)processesMap.get(6)).getExeTime()) - getTimeMillis(((PerformanceMonitorProcess)processesMap.get(5)).getExeTime()));
      resForApp.setRemark("sender:" + resVO.getProxyServerName() + "(" + resVO.getProxyAddr() + ")");
      resForApp.setHidden(false);
      resVO.getDetails().add(resForApp);
   }

   private static long getTimeMillis(String timeStr) {
      try {
         calendar.setTime(sdf.parse(timeStr));
         return calendar.getTimeInMillis();
      } catch (ParseException e) {
         e.printStackTrace();
         return 0L;
      }
   }
}
