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
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
package com.vci.web.service.impl;
import com.vci.client.common.objects.UserObject;
import com.vci.corba.common.PLException;
import com.vci.corba.common.data.UserEntityInfo;
import com.vci.corba.framework.data.UserInfo;
import com.vci.corba.pllog.data.LogInfo;
import com.vci.corba.pllog.data.LogPeriodInfo;
import com.vci.corba.pllog.data.LogType;
import com.vci.dto.LogInfoDTO;
import com.vci.dto.LogPeriodInfoDTO;
import com.vci.dto.LogQueryCriteriaDTO;
import com.vci.starter.web.pagemodel.BaseResult;
import com.vci.web.service.*;
import com.vci.web.util.*;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
 
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.stream.Collectors;
 
/**
 * 业务类型服务
 * @author yuxc
 * @date 2024-9-11
 */
@Service
public class LogBasicServiceImpl implements LogBasicServiceI {
 
    /**
     * 日志
     */
    private Logger logger = LoggerFactory.getLogger(getClass());
 
    /**
     * 平台的调用工具类
     */
    @Autowired
    private PlatformClientUtil platformClientUtil;
    public static final String UTF8_BOM="\uFEFF";
    private final String LOG_SAVE_PERIOD = "logSavePeriod";//日志保存期限
 
    /**
     * 获取日期保存期限下拉列表框
     * @return 查询结果
     */
    @Override
    public BaseResult getPeroid() throws PLException {
        //获取当前期限设置
        int curPeriod = platformClientUtil.getLogService().getCurPeriod();
        LogPeriodInfo[] periods = platformClientUtil.getLogService().getPeriods();
        List<LogPeriodInfoDTO> logDTOs = new ArrayList<>();
        for (LogPeriodInfo period : periods) {
            LogPeriodInfoDTO dto = new LogPeriodInfoDTO();
            dto.setValue(period.value);
            if(period.code.startsWith(UTF8_BOM)) {
                period.code=period.code.substring(1);
            }
            if (Integer.valueOf(period.code) == curPeriod){
                dto.setChoose(true);
            }
            dto.setCode(period.code);
            logDTOs.add(dto);
        }
        return BaseResult.dataList(logDTOs);
    }
 
    /**
     * 保存期限设置
     * period 期限编码
     * @return 保存结果
     */
    @Override
    public BaseResult savePeriod(String period) throws PLException {
        UserEntityInfo userEntityInfo = new UserEntityInfo();
        userEntityInfo.setModules("com.vci.client.log.ui.LogBasicConfPanel");
        userEntityInfo.setUserName(WebUtil.getCurrentUserId());
        boolean b = platformClientUtil.getLogService().savePeriod(period, userEntityInfo);
        if(!b){
            return BaseResult.fail("保存失败!");
        }
        return BaseResult.success("保存成功!");
    }
 
    /**
     * 删除日志
     * @param deleteDate 删除的日期
     * @return 删除结果
     * @throws PLException
     */
    @Override
    public BaseResult deleteLog(String deleteDate) throws PLException {
        if(StringUtils.isBlank(deleteDate)){
            throw new PLException("500", new String[]{"日期不能为空!"});
        }
        //获取当前期限设置
        int curSavePeriod = platformClientUtil.getLogService().getCurPeriod();
        int monthSpan = 1;
        String monthLabel = "";
        LogPeriodInfo[] periods = platformClientUtil.getLogService().getPeriods();
        Map<String, String> periodMap = Arrays.stream(periods).collect(Collectors.toMap(e -> e.code, e -> e.value));
 
 
        if(curSavePeriod <= 0){
            // 未配置时,只能删除
            monthLabel = periods[0].value;
            monthSpan = Integer.valueOf(periods[0].code);
        } else {
            monthSpan = curSavePeriod;//期限code
            monthLabel = periodMap.get(String.valueOf(curSavePeriod));//期限显示值
        }
        //检查删除逻辑
        checkCanDelete(deleteDate, monthSpan, monthLabel);
        boolean res = false;
        res = platformClientUtil.getLogService().deleteLog(getDeleteDateString(deleteDate));//删除日志
        if(!res){
            return BaseResult.fail("删除失败!");
        }
        return BaseResult.success("删除成功!");
    }
 
    /**
     * 查询日志
     * @param queryDto 查询条件传输对象
     * @return 查询数据
     * @throws PLException
     */
    @Override
    public BaseResult getLogListByContion(LogQueryCriteriaDTO queryDto) throws PLException {
        String querySql = getSQL(queryDto);
        LogInfo[] logInfos = platformClientUtil.getLogService().getLogListByContion(queryDto.getPageNo(),queryDto.getPageSize(),querySql);
        List<LogInfoDTO> dtos = new ArrayList<>();
        for (LogInfo logInfo : logInfos) {
            LogInfoDTO dto = new LogInfoDTO();
            dto.setLogType(logInfo.logType);
            dto.setDate(logInfo.date);
            dto.setContent(logInfo.content);
            dto.setPuid(logInfo.puid);
            dto.setModuleName(logInfo.moduleName);
            dto.setEntityDesc(logInfo.entityDesc);
            dto.setResult(logInfo.result);
            dto.setType(logInfo.type);
            dto.setProperty(logInfo.property);
            dto.setTruename(logInfo.truename);
            dto.setNewVal(logInfo.newVal);
            dto.setUserIp(logInfo.userIp);
            dto.setUsername(logInfo.username);
            dto.setPreviousVal(logInfo.previousVal);
            dtos.add(dto);
        }
        long sumLogRows = platformClientUtil.getLogService().getSumLogRows(querySql);
        BaseResult result = new BaseResult();
        result.setSuccess(true);
        result.setCode(200);
        result.setData(dtos);
        result.setTotal(sumLogRows);
        return result;
    }
    /**
     * 操作用户获取
     */
    @Override
    public BaseResult getOperatingUsers() throws PLException {
        List<UserObject> users = new ArrayList<UserObject>();
        if("secAdmin".equals(WebUtil.getCurrentUserId())){
            users.addAll(getUsersByUserNames(Arrays.asList("auditAdmin")));
            users.addAll(getUsersByUserNames(getUserNameByUserType(2)));
        }
        else if("auditAdmin".equals(WebUtil.getCurrentUserId())){
            users.addAll(getUsersByUserNames(Arrays.asList("secAdmin", "sysAdmin")));
        } else if("sysAdmin".equals(WebUtil.getCurrentUserId())){
 
        }
        return BaseResult.dataList(users);
    }
 
    /**
     * 获取用户信息
     * @param userNames 用户名称
     * @return 用户信息
     * @throws PLException
     */
    private List<UserObject> getUsersByUserNames(List<String> userNames) throws PLException {
        List<UserObject> userList = new ArrayList<UserObject>();
        for(String userName : userNames){
            UserInfo userInfo = platformClientUtil.getFrameworkService().fetchUserInfoByName(userName);
            UserObject user = new UserObject();
            user.setId(userInfo.id);
            user.setUserName(userInfo.userName);
            user.setPwd(userInfo.pwd);
            user.setEmail(userInfo.email);
            user.setTrueName(userInfo.trueName);
            user.setSpecialties(userInfo.specialties);
            user.setDesc(userInfo.desc);
            user.setUserType(userInfo.userType);
            user.setStatus(userInfo.status);
            user.setCreateTime(userInfo.createTime);
            user.setCreateUser(userInfo.createUser);
            user.setUpdateTime(userInfo.updateTime);
            user.setUpdateUser(userInfo.updateUser);
            user.setPwdUpdateTime(userInfo.pwdUpdateTime);
            user.setGrantor(userInfo.grantor);
            user.setSecretGrade(userInfo.secretGrade);
            user.setIsDeptLeader(userInfo.isDeptLeader);
            userList.add(user);
        }
 
        Collections.sort(userList, new Comparator<UserObject>(){
            @Override
            public int compare(UserObject o1, UserObject o2) {
                return o1.getUserName().compareTo(o2.getUserName());
            }
        });
        return userList;
    }
 
    /**
     * 根据用户类型获取用户数据
     * @param userType 用户类型
     * @return 用户数据
     * @throws PLException
     */
    private List<String> getUserNameByUserType(int userType) throws PLException{
        List<String> userNames = new ArrayList<String>();
        String sql = "select plusername,pltruename from pluser u where u.plusertype = " + String.valueOf(userType);
        String[][] valss = platformClientUtil.getQueryService().queryBySqlWithoutKey(sql);
        for(String[] vals : valss){
            userNames.add(vals[0]);
        }
        return userNames;
    }
    /**
     * 获取查询条件并拼成SQL,只拼where子句后面的SQL
     * @return
     */
    public String getSQL(LogQueryCriteriaDTO dto) throws PLException {
        StringBuffer sql = new StringBuffer("");
//        int period = getPeriod(LOG_SAVE_PERIOD);//获取保存期限,以月为单位
        int period = platformClientUtil.getLogService().getCurPeriod();;//获取保存期限,以月为单位
        //下面是拼出SQL
        if(period != 0){
            sql.append(" to_date(PLDATE) >= add_months(to_date(sysdate),"+(-period)+")");
        }
        if(dto.getStartDate()!=null&&!dto.getStartDate().trim().equals("")&&!dto.getStartDate().equals("null")){//起始日期
            if(!sql.toString().equals("")){
                sql.append(" and ");
            }
            sql.append(" to_date(PLDATE) >= to_date('"+dto.getStartDate().trim()+"','yyyy-MM-dd') ");
        }
        if(dto.getEndDate()!=null&&!dto.getEndDate().trim().equals("")&&!dto.getEndDate().equals("null")){//结束日期
            if(!sql.toString().equals("")){
                sql.append(" and ");
            }
            sql.append(" trunc(PLDATE) <= to_date('"+dto.getEndDate().trim()+"','yyyy-MM-dd')");
        }
 
        if(dto.getLogType() == LogType.Login.value()) {//登入登出日志
            if(!sql.toString().equals("")){
                sql.append(" and ");
            }
            sql.append("PLLOGTYPE in ('" + getLogTypeString(LogType.Login) +"','" + getLogTypeString(LogType.Logout)+ "')");
        } else if(dto.getLogType() == LogType.Grant.value()) {//授权日志
            if(!sql.toString().equals("")){
                sql.append(" and ");
            }
            sql.append("PLLOGTYPE in('" + getLogTypeString(LogType.Grant) + "')");
        } else if(dto.getLogType() == LogType.General.value()) {//一般操作日志
            if(!sql.toString().equals("")){
                sql.append(" and ");
            }
            sql.append("PLLOGTYPE in('" + getLogTypeString(LogType.General) + "')");
        }
        if(StringUtils.isNotBlank(dto.getUserName())){//操作用户
            if(!dto.getUserName().trim().equals("")){//如果用户名为空格则不加用户条件
                if(!sql.toString().equals("")){
                    sql.append(" and ");
                }
                if(dto.getUserName().contains("*")){
                    dto.setUserName(dto.getUserName().trim().replaceAll("\\*", "%"));
                    sql.append(" PLUSER like '").append(dto.getUserName().trim()).append("'");
                }else{
                    sql.append(" PLUSER = '").append(dto.getUserName().trim()).append("'");
                }
            }
        }
        //按IP查询
        if(StringUtils.isNotBlank(dto.getIpText())){
            String ip = dto.getIpText().trim();
            if(!sql.toString().equals("")){
                sql.append(" and ");
            }
            if(ip.trim().contains("*")){//模糊查询
                ip = ip.trim().replaceAll("\\*", "%");
                sql.append(" PLIP like '").append(ip.trim()).append("'");
            }else{
                sql.append(" PLIP = '").append(ip.trim()).append("'");
            }
        }
        if(StringUtils.isNotBlank(dto.getTypeText())){
            String typeValue = dto.getTypeText();
            sql.append(" and pltype like '%").append(typeValue).append("%'");
        }
        //过滤掉admin和developer用户的日志记录
        sql.append(" and PLUSER !='admin' and  PLUSER !='developer' ");
 
        sql.append(" and pluser != '" + WebUtil.getCurrentUserId() + "' ");
 
 
        // 安全保密员不看系统管理员的日志
        if("secAdmin".equals(WebUtil.getCurrentUserId())){
            sql.append(" and pluser != 'sysAdmin' ");
        }
        // 审计管理员只看系统管理员和安全保密员的日志
        else if("auditAdmin".equals(WebUtil.getCurrentUserId())){
            sql.append(" and pluser in ('secAdmin', 'sysAdmin')");
        }
        return sql.toString();
    }
    protected String getLogTypeString(LogType logType){
        String res = "";
        if(logType == LogType.Login) {
            res = "登录";
        } else if(logType == LogType.Logout) {
            res = "登出";
        } else if(logType == LogType.Grant) {
            res = "授权";
        } else if(logType == LogType.General) {
            res = "一般操作";
        } else if(logType == LogType.Integration) {
            res = "集成应用";
        }
        return res;
    }
 
    /**
     * 日期字符串处理
     * @param deleteDate 日期字符串
     * @return 处理完成的日期字符串
     */
    protected String getDeleteDateString(String deleteDate){
        int s = Integer.parseInt(deleteDate.substring(8))+1;
        StringBuffer buff = new StringBuffer();
        buff.append(deleteDate.substring(0, 8));
        if(("0"+s).length()>2){
            buff.append(s+"");
        }else{
            buff.append("0"+s);
        }
        return buff.toString();
    }
 
    /**
     * 删除逻辑检查
     * @param deleteDate 日期字符串
     * @param monthSpan 期限code
     * @param monthLabel 期限显示值
     * @return
     * @throws PLException
     */
    private boolean checkCanDelete(String deleteDate, int monthSpan, String monthLabel) throws PLException {
        boolean res = false;
        try {
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
            sdf.parse(deleteDate);
        } catch (ParseException  e1) {
            throw new PLException("500", new String[]{"将" + deleteDate + "转换日期时发生错误!"});
        }
        String sql = "SELECT FLOOR(MONTHS_BETWEEN(SYSDATE, to_date('" + deleteDate + "','yyyy-mm-dd'))) from dual";
        String[][] vals;
        try {
            vals = platformClientUtil.getQueryService().queryBySqlWithoutKey(sql);
            if(vals != null && vals.length > 0 && vals[0].length > 0){
                int spval = Integer.valueOf(vals[0][0]);
                if(spval <= monthSpan){
                    throw new PLException("500", new String[]{"只能删除 " + monthLabel + " 之前的数据!"});
                }
            }
        } catch (PLException e) {
            e.printStackTrace();
            e.messages[0] += "计算是否可以删除指定日期之前的数据时发生错误!";
            throw new PLException("500", e.messages);
        }
        res = true;
        return res;
    }
}