许鹏程
2023-05-25 213cc37cbf0b2515a4de56cc1e01813211bad183
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
package com.product.admin.service;
 
import cn.hutool.core.util.NumberUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
import com.product.admin.config.CmnCode;
import com.product.admin.config.CmnConst;
import com.product.admin.util.MonitorInfoUtil;
import com.product.common.lang.StringUtils;
import com.product.core.dao.BaseDao;
import com.product.core.entity.DataTableEntity;
import com.product.core.entity.FieldSetEntity;
import com.product.core.exception.BaseException;
import com.product.core.service.support.AbstractBaseService;
import com.product.core.spring.context.SpringMVCContextHolder;
import com.product.core.websocket.service.server.WebSocketServer;
import com.product.module.sys.entity.SystemUser;
import com.product.util.BaseUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
 
import java.io.File;
import java.io.IOException;
import java.lang.management.ManagementFactory;
import java.lang.management.OperatingSystemMXBean;
import java.math.BigDecimal;
import java.math.RoundingMode;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;
 
/**
 * Copyright © 6c
 *
 * @Date 2022年08月22日 15:06
 * @Author 6c
 * @Description
 */
@Service
public class MonitorService extends AbstractBaseService {
    @Autowired
    private BaseDao baseDao;
 
    @Autowired
    OrganizationCacheService organizationCacheService;
 
    /**
     * 首页监控信息-超级管理员
     *
     * @return
     */
    public JSONObject getAdminIndexPageMonitorInfo() {
        JSONObject resultObj = new JSONObject();
 
        // 系统监控
        JSONObject sysObj = systemMonitor();
        resultObj.putAll(sysObj);
 
        // 单位在职员工
//        resultObj.put("serving_staff", getUnitServingStaff(null));
 
        // 单位在线员工
        resultObj.put("online_staff", WebSocketServer.getOnLineStaffs(null).stream().filter(item -> item.getUserType() == 0).map(user -> {
            Map<String, Object> map = new HashMap<>();
            map.put("user_name", user.getUser_name());
            map.put("user_id", user.getUser_id());
            map.put("org_level_uuid", user.getOrg_level_uuid());
            map.put("org_level_name", user.getOrg_level_name());
            return map;
        }).collect(Collectors.toList()));
 
        return resultObj;
    }
 
    public Object getUnitPortalStaffInfo() {
        SystemUser currentUser = SpringMVCContextHolder.getCurrentUser();
        if (!currentUser.isManager()) {
            return null;
        }
        if (currentUser.getUserType() == 1) {
            //admin
            DataTableEntity unitEmployees = this.getUnitEmployees(null);
            if (DataTableEntity.isEmpty(unitEmployees)) {
                return null;
            }
            List<String> unitName = new ArrayList<>();
            List<Object> unitOnlineNumber = new ArrayList<>();
            List<Object> unitUseNumber = new ArrayList<>();
            for (int i = 0; i < unitEmployees.getRows(); i++) {
                unitName.add(unitEmployees.getString(i, "org_level_name"));
                String org_level_uuid = unitEmployees.getString(i, "org_level_uuid");
                Map<String, Object> unitOnlinePersonnel = this.getUnitOnlinePersonnel(org_level_uuid);
                unitOnlineNumber.add(unitOnlinePersonnel != null ? unitOnlinePersonnel.get("online_staff_number") : 0);
                unitUseNumber.add(unitEmployees.getObject(i, "staff_number"));
            }
 
            return new Object[]{unitName, unitOnlineNumber, unitUseNumber};
        } else if (currentUser.getUserType() == 2) {
            DataTableEntity unitEmployees = this.getUnitEmployees(currentUser.getOrg_level_uuid());
            if (DataTableEntity.isEmpty(unitEmployees)) {
                return null;
            }
            FieldSetEntity fse = unitEmployees.getFieldSetEntity(0);
            String org_level_uuid = fse.getString("org_level_uuid");
            Map<String, Object> unitOnlinePersonnel = this.getUnitOnlinePersonnel(org_level_uuid);
            fse.setValue("online_staff_number", unitOnlinePersonnel != null ? unitOnlinePersonnel.get("online_staff_number") : 0);
            return fse;
        }
        return null;
    }
 
    /**
     * 获取单位在职人员
     *
     * @param orgLevelUuid
     * @return
     */
    public DataTableEntity getUnitEmployees(String orgLevelUuid) {
        StringBuilder sql = new StringBuilder();
        sql.append("\n select org_level_name,levels.uuid org_level_uuid,staff_number from product_sys_org_levels levels join (SELECT ");
        sql.append("\n org_level_uuid, ");
        sql.append("\n count( 1 )  staff_number ");
        sql.append("\n FROM ");
        sql.append("\n product_sys_staffs staff ");
        sql.append("\n JOIN product_sys_users users ON staff.user_id = users.user_id ");
        Object[] objects = null;
        if (!StringUtils.isEmpty(orgLevelUuid)) {
            sql.append(" AND staff.org_level_uuid=? ");
            objects = new Object[]{orgLevelUuid};
        }
        sql.append("\n WHERE staff.staff_status!=0 and users.status=1 ");
        sql.append("\n GROUP BY ");
        sql.append("\n org_level_uuid) b on levels.uuid=b.org_level_uuid ");
        return baseDao.listTable(sql.toString(), objects);
    }
 
    public Map<String, Object> getUnitOnlinePersonnel(String orgLevelUuid) {
        Map<String, Object> orgCacheByUuid = organizationCacheService.getOrgCacheByUuid(orgLevelUuid);
        if (orgCacheByUuid == null) {
            return null;
        }
        List<SystemUser> onLineStaffs = WebSocketServer.getOnLineStaffs(orgLevelUuid);
        Map<String, Object> map = new HashMap<>();
        map.put("org_level_uuid", orgLevelUuid);
        map.put(CmnConst.ORG_LEVEL_NAME, orgCacheByUuid.get(CmnConst.ORG_LEVEL_NAME));
        map.put("online_staff_number", onLineStaffs != null ? onLineStaffs.size() : 0);
        return map;
    }
 
 
    /**
     * 首页监控信息-单位管理员
     *
     * @return
     */
    public JSONObject getUnitAdminIndexPageMonitorInfo() {
        JSONObject resultObj = new JSONObject();
 
        SystemUser curUser = SpringMVCContextHolder.getCurrentUser();
        FieldSetEntity managerFse = curUser.getCurrentManager();
        String manageCompany = managerFse.getString(CmnConst.ORG_LEVEL_UUID);
        if (!StringUtils.isEmpty(manageCompany)) {
            String[] manageCompanyArr = manageCompany.split(",");
            String singleFilter = BaseUtil.buildQuestionMarkFilter("o.uuid", manageCompanyArr, true);
            // 单位在职员工
            resultObj.put("serving_staff", getUnitServingStaff(singleFilter));
 
            // 单位在线员工
            DataTableEntity paramDte = baseDao.listTable(CmnConst.PRODUCT_SYS_ORG_LEVELS, singleFilter, new Object[]{});
            Map<JSONObject, Object> paramMap = Maps.newHashMap();
            FieldSetEntity paramFse;
            for (int i = 0; i < paramDte.getRows(); i++) {
                paramFse = paramDte.getFieldSetEntity(i);
                JSONObject paramObj = new JSONObject();
                paramObj.put(CmnConst.UUID, paramFse.getUUID());
                paramObj.put(CmnConst.NAME, paramFse.getString(CmnConst.ORG_LEVEL_NAME));
                paramMap.put(paramObj, WebSocketServer.getOnLineStaffs(paramFse.getUUID()));
            }
            resultObj.put("online_staff", paramMap);
        }
 
        return resultObj;
    }
 
    /**
     * 获取单位在职员工
     *
     * @param filter
     * @return
     */
    private Map<JSONObject, Object> getUnitServingStaff(String filter) {
        StringBuilder sql = new StringBuilder(128);
        sql.append("select o.uuid o_uuid,o.org_level_name,s.* from product_sys_staffs s");
        sql.append("\nleft join product_sys_org_levels o on s.tricode like concat(o.org_level_code,'%') and org_level_type=0");
        if (!StringUtils.isEmpty(filter)) {
            sql.append("\nwhere ").append(filter);
        }
        sql.append("\nhaving o.uuid is not null");
        sql.append("\norder by o.uuid");
        DataTableEntity dte = baseDao.listTable(sql.toString(), new Object[]{});
        Map<JSONObject, Object> resultMap = Maps.newHashMap();
        FieldSetEntity fse;
        String preOrgUUID = "";
        String curOrgUUID = "";
        DataTableEntity tempDte = null;
        JSONObject tempObj = null;
        for (int i = 0; i < dte.getRows(); i++) {
            fse = dte.getFieldSetEntity(i);
            curOrgUUID = fse.getString("o_uuid");
            if (!preOrgUUID.equals(curOrgUUID)) {
                if (tempObj != null) {
                    resultMap.put(tempObj, BaseUtil.dataTableEntityToJson(tempDte));
                }
                tempDte = new DataTableEntity();
                tempObj = new JSONObject();
                tempObj.put(CmnConst.UUID, curOrgUUID);
                tempObj.put(CmnConst.NAME, fse.getString(CmnConst.ORG_LEVEL_NAME));
            }
            if (tempDte != null) {
                tempDte.addFieldSetEntity(fse);
            }
            preOrgUUID = curOrgUUID;
            if (i == dte.getRows() - 1) {
                resultMap.put(tempObj, BaseUtil.dataTableEntityToJson(tempDte));
            }
        }
 
        return resultMap;
    }
 
    /**
     * 系统监控
     *
     * @return
     * @throws IOException
     */
    public static JSONObject systemMonitor() {
        JSONObject resultObj = new JSONObject();
 
        final long GB = 1024 * 1024 * 1024;
        OperatingSystemMXBean operatingSystemMXBean = ManagementFactory.getOperatingSystemMXBean();
        String osJson = JSON.toJSONString(operatingSystemMXBean);
        JSONObject jsonObject = JSON.parseObject(osJson);
        // 系统CPU占用率
        double systemCpuLoad = jsonObject.getDouble("systemCpuLoad") * 100;
        resultObj.put("cpu_occupancy_rate", twoDecimal(systemCpuLoad) + "%");
        // 内存使用占比
        Long totalPhysicalMemorySize = jsonObject.getLong("totalPhysicalMemorySize");
        Long freePhysicalMemorySize = jsonObject.getLong("freePhysicalMemorySize");
        double memoryUseRatio = 1.0 * (totalPhysicalMemorySize - freePhysicalMemorySize) / totalPhysicalMemorySize * 100;
        resultObj.put("memory_occupancy_rate", twoDecimal(memoryUseRatio) + "%");
        // 所在磁盘剩余空间
        try {
            File file = new File("");
            String filePath = file.getCanonicalPath();
            String disk = filePath.substring(0, 1);
            file = new File(disk + ":");
            long freeSpace = file.getFreeSpace() / GB;
            resultObj.put("free_disk_space", freeSpace + "GB");
        } catch (Exception e) {
            throw new BaseException(CmnCode.GET_DISK_FREE_SPACE_FAIL);
        }
 
        return resultObj;
    }
 
 
    @Autowired
    MonitorInfoUtil monitorInfoUtil;
 
    public Object getSystemInfo(boolean newRecord) {
        List<MonitorInfoUtil.MonitorInfoBean> monitorInfoBeanList = monitorInfoUtil.getMonitorInfoBeanList();
        if (monitorInfoBeanList.size() > 0) {
            if (newRecord) {
                return monitorInfoBeanList.get(monitorInfoBeanList.size() - 1);
            } else {
                monitorInfoBeanList = Lists.newArrayList(monitorInfoBeanList);
                return monitorInfoBeanList;
            }
        }
 
        return null;
    }
 
 
    /**
     * 获取内存使用情况
     */
    public static Map<String, Object> getMemoryInfo() {
        com.sun.management.OperatingSystemMXBean mem = (com.sun.management.OperatingSystemMXBean) java.lang.management.ManagementFactory.getOperatingSystemMXBean();
        // 获取内存总容量
        double maxMemorySize = transformation(mem.getTotalPhysicalMemorySize());
        // 获取可用内存容量
        double freeMemorySize = transformation(mem.getFreePhysicalMemorySize());
 
        System.out.println("内存总容量:" + maxMemorySize);
        System.out.println("可用容量:" + freeMemorySize);
        System.out.println("使用率:" + ((maxMemorySize - freeMemorySize) / maxMemorySize) * 100);
        Map<String, Object> result = new HashMap<>();
        result.put("totalMemory", maxMemorySize);
        result.put("usableMemory", freeMemorySize);
        result.put("useRate", NumberUtil.round(((maxMemorySize - freeMemorySize) / maxMemorySize) * 100, 2));
        System.out.println(result);
        return result;
    }
 
    /**
     * 将字节容量转化为GB
     */
    public static double transformation(long size) {
        return NumberUtil.round(size / 1024.00 / 1024.00 / 1024.00, 2).doubleValue();
    }
 
    private static double twoDecimal(double doubleValue) {
        BigDecimal bigDecimal = new BigDecimal(doubleValue).setScale(2, RoundingMode.HALF_UP);
        return bigDecimal.doubleValue();
    }
}