zm
2024-11-04 9d22bf2b596d8f5627f671f009b3f42d71d73bf4
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
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
package com.product.administration.service;
 
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.product.administration.config.CmnConst;
import com.product.administration.config.SystemCode;
import com.product.administration.service.ide.IIndicatorsEarlyWarningService;
import com.product.common.exception.job.TaskException;
import com.product.common.lang.DateUtils;
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.transfer.Transactional;
import com.product.core.websocket.service.WebsocketMesssageServiceThread;
import com.product.quartz.service.impl.SysJobService;
import com.product.util.BaseUtil;
import com.product.util.SystemParamReplace;
import org.quartz.SchedulerException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
 
import java.text.DecimalFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
 
/**
 * Copyright lx
 *
 * @Title: ClaimExpenseController
 * @Project: lx-SERVER
 * @Date: 2020-11-18 11:30:48
 * @Author: luoxin
 * @Description: 指标预警配置service
 */
@Service
public class IndicatorsEarlyWarningService extends AbstractBaseService implements IIndicatorsEarlyWarningService {
    @Autowired
    BaseDao baseDao;
 
    @Autowired
    SysJobService sysJobService;
 
    @Autowired
    TargetManagerService targetManagerService;
 
    @Autowired
    EarlyWarningServer earlyWarningServer;
 
    @Autowired
    EarlyWarningManagerService earlyWarningManagerService;
 
 
    public DataTableEntity getCurrentUserWarningInfo() throws BaseException {
        StringBuffer sql = new StringBuffer();
        sql.append(" SELECT ");
        sql.append(" wi.uuid, ");
        sql.append(" wi.warning_content, ");
        sql.append(" wi.early_warning_datetime, ");
        sql.append(" wc.config_name warning_name, ");
        sql.append(" ts.target_task_name, ");
        sql.append(" wft.look_time, ");
        sql.append(" ( ");
        sql.append(" SELECT ");
        sql.append(" CASE ");
        sql.append(" WHEN ");
        sql.append(" max( createDate ) > look_time THEN ");
        sql.append(" 1 ELSE 0 ");
        sql.append(" END ");
        sql.append(" FROM ");
        sql.append("product_sys_early_warning_info_feedback ");
        sql.append(" WHERE ");
        sql.append(" puuid IN ( SELECT uuid FROM product_sys_early_warning_info_feedback WHERE user_id = wft.look_people AND parent_uuid = wi.uuid ) ");
        sql.append(" ) AS new_reply, ");
        sql.append(" ( SELECT 1 FROM product_sys_early_warning_info_feedback WHERE parent_uuid = wi.uuid LIMIT 1 ) is_reply ");
        sql.append(" FROM ");
        sql.append("product_sys_early_warning_info wi ");
        sql.append(" JOIN product_oa_target_warning_configuration wc ON length( wi.configuration_uuid )> 0 ");
        sql.append(" AND concat( '%,', wi.receiver, ',%' ) LIKE concat( '%,', ?, ',%' ) ");
        sql.append(" AND wi.configuration_uuid = wc.uuid ");
        sql.append(" JOIN product_oa_target_task ts ON wc.related_indicator = ts.uuid ");
        sql.append(" LEFT JOIN product_oa_target_warning_feedback_time wft ON wi.uuid = wft.warning_uuid ");
        sql.append(" AND wft.look_people = ? ");
        sql.append(" ORDER BY ");
        sql.append(" new_reply DESC, ");
        sql.append("  wft.look_time IS NULL DESC, ");
        sql.append(" early_warning_datetime DESC ");
        int user_id = SpringMVCContextHolder.getCurrentUser().getUser_id();
        DataTableEntity dt = baseDao.listTable(sql.toString(),
                new Object[]{user_id, user_id}, 30, 1);
 
        return dt;
    }
 
 
    /**
     * 保存指标预警配置
     *
     * @param
     * @return
     * @throws BaseException
     */
    @Override
    @Transactional
    public String addTargetEarlyWarning(FieldSetEntity fieldSetEntity) throws BaseException, TaskException, SchedulerException {
 
        fieldSetEntity.setValue(CmnConst.CREATED_BY, SpringMVCContextHolder.getCurrentUser().getUser_id());
        fieldSetEntity.setValue(CmnConst.ORG_LEVEL_UUID, SpringMVCContextHolder.getCurrentUser().getOrg_level_uuid());
        fieldSetEntity.setValue(CmnConst.CREATED_UTC_DATETIME, new Date());
        String uuid = baseDao.add(fieldSetEntity);
        FieldSetEntity fseJob = new FieldSetEntity();
        fseJob.setTableName("product_sys_timed_task");
        fseJob.setValue("concurrent", 1);
        fseJob.setValue("job_name", fieldSetEntity.getString("config_name"));
        fseJob.setValue("cron_expression", fieldSetEntity.getString("execution_frequency"));
        fseJob.setValue("invoke_target", "indicatorsEarlyWarningService.obtainingIndicatorData('" + uuid + "')");
        fseJob.setValue("job_group", "system");
        fseJob.setValue("misfire_policy", 2);
        fseJob.setValue("remark", "");
        if (fieldSetEntity.getInteger("config_status") == 0) {
            fseJob.setValue("status", 0);
        } else {
            fseJob.setValue("status", 1);
        }
        fseJob.setValue("is_conceal", 1);
        sysJobService.insertJob(fseJob);
        return uuid;
    }
 
 
    public Boolean updateTargetEarlyWarning(FieldSetEntity fieldSetEntity) throws BaseException, TaskException, SchedulerException {
        String uuid = fieldSetEntity.getUUID();
        String key = "indicatorsEarlyWarningService.obtainingIndicatorData('" + uuid + "')";
        FieldSetEntity fseJob = baseDao.getFieldSetEntityBySQL(" select * FROM product_sys_timed_task where invoke_target = ? ", new String[]{key}, false);
        fseJob.setValue("job_name", fieldSetEntity.getString("config_name"));
        fseJob.setValue("cron_expression", fieldSetEntity.getString("execution_frequency"));
        if (fieldSetEntity.getInteger("config_status") == 0) {
            fseJob.setValue("status", 0);
        } else {
            fseJob.setValue("status", 1);
        }
        sysJobService.updateJob(fseJob);
        fieldSetEntity.setValue(CmnConst.UPDATED_BY, SpringMVCContextHolder.getCurrentUser().getUser_id());
        fieldSetEntity.setValue(CmnConst.UPDATED_UTC_DATETIME, new Date());
        return baseDao.update(fieldSetEntity);
    }
 
    /**
     * 获取指标预警配置详情
     *
     * @param
     * @return
     * @throws BaseException
     */
    public String getTargetEarlyWarning(String uuid) throws BaseException {
        FieldSetEntity fs = baseDao.getFieldSetEntity(CmnConst.PRODUCT_OA_TARGET_WARNING_CONFIGURATION, uuid, false);
        JSONObject result = new JSONObject();
        Map<String, Object> values = (Map) fs.getValues();
        result.putAll(values);
        //预警方式转换为String[]
        if (result.get(CmnConst.WARNING_METHOD) != null) {
            result.put(CmnConst.WARNING_METHOD, result.getString(CmnConst.WARNING_METHOD).split(","));
        }
        //业务相关人转换为数组
        if (result.get("recipient") != null) {
            result.put("recipient", result.getString("recipient").split(","));
        }
        String conditon_config = result.getString(CmnConst.CONDITON_CONFIG);
        if (!JSON.isValidArray(conditon_config)) {
            conditon_config = null;
        }
        result.put(CmnConst.CONDITON_CONFIG, earlyWarningManagerService.configDataTransition(conditon_config));
        String warning_content_config = result.getString(CmnConst.WARNING_CONTENT_CONFIG);
        if (!JSON.isValidArray(warning_content_config)) {
            warning_content_config = null;
        }
        result.put(CmnConst.WARNING_CONTENT_CONFIG, earlyWarningManagerService.configDataTransition(warning_content_config));
        return BaseUtil.success(result, null);
    }
 
    /**
     * 获取指标预警配置列表
     *
     * @param
     * @return
     * @throws BaseException
     */
    public DataTableEntity listTargetEarlyWarning(FieldSetEntity fieldSet) throws BaseException {
        //获取当前人
        String userId = String.valueOf(SpringMVCContextHolder.getCurrentUser().getUser_id());
        //每页条数
        Integer pagesize = fieldSet.getInteger("pagesize");
        //当前页
        Integer cpage = fieldSet.getInteger("cpage");
//        DataTableEntity dataTable = baseDao.listTable(" select * from product_oa_target_warning_configuration where created_by = ? ", new String[]{userId}, pagesize, cpage);
        DataTableEntity dataTable = baseDao.listTable(" select * from product_oa_target_warning_configuration ", new String[]{}, pagesize, cpage);
        baseDao.loadPromptData(dataTable);
        return dataTable;
    }
 
    /**
     * 删除指标预警配置
     *
     * @param
     * @return
     * @throws BaseException
     */
    @Override
    @Transactional
    public Boolean deleteTargetEarlyWarning(String uuid) throws BaseException, SchedulerException {
        String[] uuidArr = uuid.split(",");
        String[] jobUuid = new String[uuidArr.length];
        for (int i = 0; i < uuidArr.length; i++) {
            String key = "indicatorsEarlyWarningService.obtainingIndicatorData('" + uuidArr[i] + "')";
            FieldSetEntity fseJob = baseDao.getFieldSetEntityBySQL(" select * FROM product_sys_timed_task where invoke_target = ? ", new String[]{key}, false);
            jobUuid[i] = fseJob.getUUID();
        }
        sysJobService.deleteJobByIds(jobUuid);
        return baseDao.delete(CmnConst.PRODUCT_OA_TARGET_WARNING_CONFIGURATION, uuidArr);
    }
 
    /**
     * 通过指标uuid获取关联指标详情
     *
     * @param
     * @return
     * @throws BaseException
     */
    public FieldSetEntity getIndicatorsInfo(String uuid) throws BaseException {
        return baseDao.getFieldSetEntity(CmnConst.PRODUCT_OA_TARGET_TASK, uuid, false);
    }
 
    /**
     * 解析条件表达式
     *
     * @param end_value     结果值
     * @param target_value  目标值
     * @param starting_time 起始时间
     * @param deadline      结束时间
     * @param expression    表达式
     * @return
     * @throws BaseException
     */
    public Boolean analyticConditionalExpression(Double end_value, Double target_value, String starting_time, String deadline, String expression) throws BaseException {
        //结果值
        expression = expression.replace("{#end_value#}", String.valueOf(end_value));
        //目标值
        expression = expression.replace("{#target_value#}", String.valueOf(target_value));
        //起始日期
        expression = expression.replace("{#starting_time#}", "to_days('" + starting_time + "')");
        //截止日期
        expression = expression.replace("{#deadline#}", "to_days('" + deadline + "')");
        //转换当前日期
        expression = expression.replace("{#yyyy-MM-dd#}", "to_days('" + DateUtils.formatDate(new Date(), "yyyy-MM-dd") + "')");
        //正则表达式取双花括号的值
        expression = SystemParamReplace.replaceParams(expression, null);
 
//        List<String> ls = this.getTeacherList(expression);
//        if(ls.size() > 0){
//            for (int i = 0; i < ls.size(); i++) {
//                String key = ls.get(i);
//                key = key.replace("{%","");
//                key = key.replace("%}", "");
//                String val = SystemParamReplace.replaceParams(key, null);
//                //不相等说明有系统变量 替换掉值
//                if(!key.equals(val)){
//                    expression = expression.replace("{%"+key+"%}",val);
//                }
//            }
//        }
 
        expression = expression.replace("{%", "");
        expression = expression.replace("%}", "");
        if (expression.contains("<") || expression.contains("=") || expression.contains(">")) {
            baseDao.executeUpdate("select" + expression);
            return true;
        } else {
            return false;
        }
    }
 
 
    /**
     * 解析运行条件表达式
     *
     * @param end_value     结果值
     * @param target_value  目标值
     * @param starting_time 起始时间
     * @param deadline      结束时间
     * @param expression    表达式
     * @return
     * @throws BaseException
     */
    public Boolean runtimeValue(Double end_value, Double target_value, String starting_time, String deadline, String expression) throws BaseException {
        //结果值
        expression = expression.replace("{#end_value#}", String.valueOf(end_value));
        //目标值
        expression = expression.replace("{#target_value#}", String.valueOf(target_value));
        //起始日期
        expression = expression.replace("{#starting_time#}", "to_days('" + starting_time + "')");
        //截止日期
        expression = expression.replace("{#deadline#}", "to_days('" + deadline + "')");
        //转换当前日期
        expression = expression.replace("{#yyyy-MM-dd#}", "to_days('" + DateUtils.formatDate(new Date(), "yyyy-MM-dd") + "')");
        //正则表达式取双花括号的值
        expression = SystemParamReplace.replaceParams(expression, null);
 
        expression = expression.replace("{%", "");
        expression = expression.replace("%}", "");
        FieldSetEntity fieldSetEntity = baseDao.getFieldSetEntityBySQL("select" + expression + " as flag ", null, false);
        String flag = fieldSetEntity.getString("flag");
        if ("1".equals(flag)) {
            return true;
        } else {
            return false;
        }
    }
 
 
    /**
     * 解析内容
     *
     * @param end_value     结果值
     * @param target_value  目标值
     * @param starting_time 起始时间
     * @param deadline      结束时间
     * @param expression    表达式
     * @return
     * @throws BaseException
     */
    public String parseTheContent(String end_value, Double target_value, String starting_time, String deadline, String expression) throws BaseException {
        //时间字符串转换为 yyyy年MM月dd日
        SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd");
        try {
            Date startDate = df.parse(starting_time);
            Date endDate = df.parse(deadline);
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy年MM月dd日");
            starting_time = sdf.format(startDate);
            deadline = sdf.format(endDate);
        } catch (ParseException e) {
            e.printStackTrace();
            throw new BaseException("public String parseTheContent(String end_value, Double target_value, String starting_time, String deadline,String expression)", e.getMessage());
        }
        //结果值
        expression = expression.replace("{#end_value#}", end_value);
        //目标值
        expression = expression.replace("{#target_value#}", String.valueOf(target_value));
        //起始日期
        expression = expression.replace("{#starting_time#}", starting_time);
        //截止日期
        expression = expression.replace("{#deadline#}", deadline);
        //转换当前日期
        expression = expression.replace("{#yyyy-MM-dd#}", DateUtils.formatDate(new Date(), "yyyy年MM月dd日"));
        //正则表达式取双花括号的值
        expression = SystemParamReplace.replaceParams(expression, null);
 
        expression = expression.replace("{%", "");
        expression = expression.replace("%}", "");
        return expression;
    }
 
 
    /**
     * 正则表达式获取系统变量
     *
     * @param managers
     * @return
     * @throws BaseException
     */
    public List<String> getTeacherList(String managers) {
        List<String> ls = new ArrayList<String>();
        //正则表达式取双花括号的值
        Pattern pattern = Pattern.compile("(\\{\\%)([\\w]+)(\\%\\})");
        Matcher matcher = pattern.matcher(managers);
        while (matcher.find())
            ls.add(matcher.group());
        return ls;
    }
 
    /**
     * 通过指标预警配置判断是否发送预警提示(结果值,目标值,起始时间,截止时间)
     *
     * @param uuid 指标预警配置uuid
     * @return
     * @throws BaseException
     */
    public void obtainingIndicatorData(String uuid) {
 
        FieldSetEntity fse = baseDao.getFieldSetEntity(CmnConst.PRODUCT_OA_TARGET_WARNING_CONFIGURATION, uuid, false);
        //关联指标
        String related_indicator = fse.getString("related_indicator");
        //预警内容
        String waringContentHide = fse.getString(CmnConst.WARNING_CONTENT_HIDE);
        //发送预警方式
        String warning_method = fse.getString(CmnConst.WARNING_METHOD);
        //预警表达式
        String conditionExpressionHide = fse.getString(CmnConst.CONDITION_EXPRESSION_HIDE);
        //责任主体关系人
        String recipient = fse.getString("recipient");
        //固定接收人
        String fixed_receiver = fse.getString(CmnConst.FIXED_RECEIVER);
 
 
        //指标任务
        FieldSetEntity targetTask = baseDao.getFieldSetEntity(CmnConst.PRODUCT_OA_TARGET_TASK, related_indicator, true);
        String target_uuid = targetTask.getString("target_uuid");
        //责任主体类型
        DataTableEntity dataTableEntity = targetTask.getSubDataTable(CmnConst.PRODUCT_OA_TARGET_TASK_SUB);
        //指标基础数据库
        FieldSetEntity targetBasic = baseDao.getFieldSetEntity(CmnConst.PRODUCT_OA_TARGET_BASIC, target_uuid, true);
        // 周期
        FieldSetEntity paramFse = new FieldSetEntity();
        paramFse.setTableName("temp_table");
        //表名
        paramFse.setValue(CmnConst.SOURCE_TABLE, targetBasic.getString(CmnConst.SOURCE_TABLE));
        //责任主体字段名 机构或人员字段
        paramFse.setValue(CmnConst.ORG_VALUE_FIELD, targetBasic.getString(CmnConst.ORG_VALUE_FIELD));
        //比较类型
        paramFse.setValue(CmnConst.COMPARE_TYPE, targetBasic.getObject(CmnConst.COMPARE_TYPE));
        //时间范围字段名 datetime_value_field
        paramFse.setValue(CmnConst.DATETIME_VALUE_FIELD, targetBasic.getString(CmnConst.DATETIME_VALUE_FIELD));
        String target_cycle = targetBasic.getString(CmnConst.TARGET_CYCLE);
        //时间范围的类型  1 任意时间段 3 动态时间(T+N) 4 周期时间
        String datetime_range_type = targetTask.getString(CmnConst.DATETIME_RANGE_TYPE);
        paramFse.setValue(CmnConst.DATETIME_RANGE_TYPE, datetime_range_type);
        //基础库表达式
        paramFse.setValue(CmnConst.EXPRESSION_STATEMENT, targetBasic.getString(CmnConst.EXPRESSION_STATEMENT));
        //是否百分比
        String isPercentage = targetBasic.getString(CmnConst.IS_PERCENTAGE);
        paramFse.setValue(CmnConst.IS_PERCENTAGE, isPercentage);
        //条件表达式
        paramFse.setValue(CmnConst.FILTER_STATEMENT, targetBasic.getString(CmnConst.FILTER_STATEMENT));
        if (!BaseUtil.dataTableIsEmpty(dataTableEntity)) {
            for (int i = 0; i < dataTableEntity.getRows(); i++) {
                FieldSetEntity fieldSetEntity = dataTableEntity.getFieldSetEntity(i);
                // 组织架构具体值
                String task_responsible = fieldSetEntity.getString(CmnConst.TASK_RESPONSIBLE);
                //责任主体类型
                paramFse.setValue(CmnConst.ORGANIZATION_TYPE, fieldSetEntity.getString(CmnConst.ORGANIZATION_TYPE));
                paramFse.setValue(CmnConst.TASK_RESPONSIBLE, task_responsible);
                //目标值
                Double target_value = fieldSetEntity.getDouble(CmnConst.TARGET_VALUE);
                paramFse.setValue(CmnConst.TARGET_VALUE, target_value);
                //时间范围
                String datetime_range = fieldSetEntity.getString(CmnConst.DATETIME_RANGE);
                paramFse.setValue(CmnConst.DATETIME_RANGE, datetime_range);
 
                //获取责任主体时间范围内的实际值
                Double targetValue = targetManagerService.getActualTargetValue(paramFse);
                //保留两位小数
                DecimalFormat df = new DecimalFormat(".##");
                String st = df.format(targetValue);
                targetValue = Double.parseDouble(st);
 
                //开始时间
                String startTime = "";
                //结束时间
                String endTime = "";
                if ("1".equals(datetime_range_type)) {
                    // 任意时间段
                    String[] timeArray = datetime_range.split(",");
                    startTime = timeArray[0];
                    endTime = timeArray[1];
                } else if ("2".equals(datetime_range_type)) {
                    // 分解时间 暂放 todo
                } else if ("3".equals(datetime_range_type)) {
                    // 动态日期(T+N)
                    //获取当前日期
                    startTime = this.getDate(0);
                    //获取 n天后
                    endTime = this.getDate(Integer.parseInt(datetime_range));
                } else if ("4".equals(datetime_range_type)) {
                    // 周期时间
                    List<String> timeArray = targetManagerService.getStartTimeAndFinalTime(target_cycle);
                    startTime = timeArray.get(0);
                    endTime = timeArray.get(1);
                } else {
                    throw new BaseException(SystemCode.UNKNOWN_DATETIME_RANGE_TYPE.getValue(), SystemCode.UNKNOWN_DATETIME_RANGE_TYPE.getText());
                }
                String value;
                if ("1".equals(isPercentage)) {
                    value = targetValue + "%";
                    targetValue = targetValue / 100;
                    target_value = target_value / 100;
                } else {
                    value = String.valueOf(targetValue);
                }
                startTime = startTime.substring(0, 10);
                endTime = endTime.substring(0, 10);
                //true  发送预警提示
                if (this.runtimeValue(targetValue, target_value, startTime, endTime, conditionExpressionHide)) {
                    //指标任务子表uuid
                    String record_uuid = fieldSetEntity.getUUID();
                    //发送信息
                    if (!StringUtils.isEmpty(warning_method)) {
                        //解析内容
                        String content = this.parseTheContent(value, target_value, startTime, endTime, waringContentHide);
 
                        //解析发送人员
                        String user = this.resolvingRecipients(task_responsible, recipient, fixed_receiver, record_uuid);
                        //如果接收人员为空 就不发送指标预警
                        if (BaseUtil.strIsNull(user)) {
                            return;
                        }
                        //自动生成预警日志信息
                        FieldSetEntity f = new FieldSetEntity();
                        //指标预警信息表
                        f.setTableName(CmnConst.PRODUCT_SYS_EARLY_WARNING_INFO);
                        //指标任务子表uuid  存入预警反馈
                        f.setValue(CmnConst.RECORD_UUID, record_uuid);
                        //预警时间
                        f.setValue(CmnConst.EARLY_WARNING_DATETIME, new Date());
                        //消息预警内容
                        f.setValue(CmnConst.WARNING_CONTENT, content);
                        //接收人员
                        f.setValue("receiver", user);
                        //发送方式
                        f.setValue("send_method", warning_method);
                        //指标预警uuid
                        f.setValue("configuration_uuid", uuid);
                        baseDao.add(f);
 
                        String[] send_method = warning_method.split(",");
                        for (int k = 0; k < send_method.length; k++) {
                            if ("1".equals(send_method[k])) {    //系统消息
                                WebsocketMesssageServiceThread.getInstance().appendMessage(user, content, "指标预警反馈", 2, "2", "1636961151856496Ax1u468?uuid=" + f.getUUID(), CmnConst.PRODUCT_SYS_EARLY_WARNING_INFO, f.getUUID(), 1, 0, 0);
                            } else if ("2".equals(send_method[k])) {    //电子邮件
                                earlyWarningServer.parseMail(content, user);
                            } else if ("3".equals(send_method[k])) {    //短信消息
                                earlyWarningServer.parseSMS(content, user);
                            }
                        }
                    }
                }
            }
        }
    }
 
    /**
     * 解析收件人
     *
     * @param responsible    责任主体
     * @param relevantPeople 业务相关人 1"当前责任人" 2"直属领导" 3"部门领导" 4"公司领导" 5"部门下所有人"
     * @param fixed_receiver 固定接收人
     * @return
     * @throws BaseException
     */
    public String resolvingRecipients(String responsible, String relevantPeople, String fixed_receiver, String record_uuid) {
        Set<String> userSet = new HashSet<>();
        String[] relevantArray = relevantPeople.split(",");
        for (int i = 0; i < relevantArray.length; i++) {
            String type = relevantArray[i];
            //1"当前责任人"
            if ("1".equals(type)) {
                userSet.add(responsible);
                // 2"直属领导"
            } else if ("2".equals(type)) {
                FieldSetEntity fieldSetEntity = baseDao.getFieldSetEntityBySQL("SELECT user_id FROM product_sys_staffs WHERE tricode = (SELECT direct_leader_code FROM product_sys_staffs WHERE user_id = ?)", new String[]{responsible}, false);
                if (fieldSetEntity != null) {
                    userSet.add(fieldSetEntity.getString("user_id"));
                }
                // 3"部门领导"
            } else if ("3".equals(type)) {
                DataTableEntity dataTableEntity;
                //userid为整数
                if (this.isInteger(responsible)) {
                    dataTableEntity = baseDao.listTable("SELECT * FROM product_sys_staffs WHERE dept_uuid = (SELECT dept_uuid FROM product_sys_staffs WHERE user_id = ?) AND is_dept_manage = 1", new String[]{responsible});
                    //部门uuid
                } else {
                    dataTableEntity = baseDao.listTable("SELECT * FROM product_sys_staffs WHERE dept_uuid = ? AND is_dept_manage = 1", new String[]{responsible});
                }
                if (!BaseUtil.dataTableIsEmpty(dataTableEntity)) {
                    for (int j = 0; j < dataTableEntity.getRows(); j++) {
                        userSet.add(dataTableEntity.getString(j, "user_id"));
                    }
                }
                //4"公司领导"
            } else if ("4".equals(type)) {
                DataTableEntity dataTableEntity;
                //userid为整数
                if (this.isInteger(responsible)) {
                    dataTableEntity = baseDao.listTable("SELECT * FROM product_sys_staffs WHERE org_level_uuid = (SELECT org_level_uuid FROM product_sys_staffs WHERE user_id = ?) AND is_org_manager = 1", new String[]{responsible});
                    //公司或部门uuid
                } else {
                    StringBuffer sql = new StringBuffer();
                    sql.append(" SELECT * FROM product_sys_staffs WHERE org_level_uuid = ( ")
                            .append(" SELECT IFNULL(org_level_uuid,uuid) org_level_uuid FROM product_sys_org_levels WHERE uuid = ? ) ")
                            .append(" and is_org_manager = 1 ");
                    dataTableEntity = baseDao.listTable(sql.toString(), new String[]{responsible});
                }
                if (!BaseUtil.dataTableIsEmpty(dataTableEntity)) {
                    for (int j = 0; j < dataTableEntity.getRows(); j++) {
                        userSet.add(dataTableEntity.getString(j, "user_id"));
                    }
                }
                //5"部门下所有人"
            } else if ("5".equals(type)) {
                DataTableEntity dataTableEntity = baseDao.listTable(" SELECT * FROM product_sys_staffs WHERE dept_uuid = ?  ", responsible);
                if (!BaseUtil.dataTableIsEmpty(dataTableEntity)) {
                    for (int j = 0; j < dataTableEntity.getRows(); j++) {
                        userSet.add(dataTableEntity.getString(j, "user_id"));
                    }
                }
            }
        }
        //从选人表提取固定人
        FieldSetEntity fseOrgUser = baseDao.getFieldSetEntity("product_sys_organizational_structure_storage", fixed_receiver, false);
        String staff_ids = fseOrgUser.getString("staff_ids");
        String[] staffArray = staff_ids.split(",");
        DataTableEntity dataTableEntity = baseDao.listTable(CmnConst.PRODUCT_SYS_STAFFS, BaseUtil.buildQuestionMarkFilter("staff_id", staffArray.length, true), staffArray);
        if (!BaseUtil.dataTableIsEmpty(dataTableEntity)) {
            for (int i = 0; i < dataTableEntity.getRows(); i++) {
                userSet.add(dataTableEntity.getString(i, "user_id"));
            }
        }
        //剔除停止发送的用户id
        this.deleteSendingUser(userSet, record_uuid);
//        return String.join(",", userSet);
        return String.join(",", userSet);
    }
 
    //剔除停止发送的用户id
    public void deleteSendingUser(Set<String> userSet, String record_uuid) {
        DataTableEntity dataTable = baseDao.listTable(CmnConst.PRODUCT_SYS_EARLY_WARNING_STOP, " record_uuid = ? ", new String[]{record_uuid});
        if (!BaseUtil.dataTableIsEmpty(dataTable)) {
            for (int i = 0; i < dataTable.getRows(); i++) {
                userSet.remove(dataTable.getString(i, CmnConst.USER_ID));
            }
        }
    }
 
    public static String getDate(Integer datetime_range) {
        Calendar calendar2 = Calendar.getInstance();
        SimpleDateFormat sdf2 = new SimpleDateFormat("yyyy-MM-dd");
        calendar2.add(Calendar.DATE, datetime_range);
        return sdf2.format(calendar2.getTime());
    }
 
    /**
     * 修改查看反馈时间 第一次查看则新增
     *
     * @param uuid
     */
    private void updateViewWarnMessageTime(String uuid) {
        int user_id = SpringMVCContextHolder.getCurrentUser().getUser_id();
        FieldSetEntity fse = baseDao.getFieldSetEntityByFilter(CmnConst.PRODUCT_SYS_EARLY_WARNING_FEEDBACK_TIME, "warning_uuid=? and look_people =?", new Object[]{uuid, user_id}, false);
        if (fse == null) {
            fse = new FieldSetEntity();
            fse.setTableName(CmnConst.PRODUCT_SYS_EARLY_WARNING_FEEDBACK_TIME);
            BaseUtil.createCreatorAndCreationTime(fse);
            fse.setValue("warning_uuid", uuid);
            fse.setValue("look_people", SpringMVCContextHolder.getCurrentUser().getUser_id());
        }
        fse.setValue("look_time", new Date());
        baseDao.saveFieldSetEntity(fse);
    }
 
    /**
     * 查看指标预警信息
     *
     * @param uuid 指标预警信息uuid
     * @return
     */
    @Override
    @Transactional
    public FieldSetEntity findWarnMessage(String uuid) throws BaseException {
        FieldSetEntity fieldSetEntity = baseDao.getFieldSetEntity(CmnConst.PRODUCT_SYS_EARLY_WARNING_INFO, uuid, false);
        //添加已查看人员
        String knownUser = fieldSetEntity.getString("known_user");
        String userId = String.valueOf(SpringMVCContextHolder.getCurrentUser().getUser_id());
        if (BaseUtil.strIsNull(knownUser)) {
            fieldSetEntity.setValue("known_user", userId);
        } else {
            List<String> knownUserArray = Arrays.asList(knownUser.split(","));
            if (!knownUserArray.contains(userId)) {
                knownUser = knownUser + "," + userId;
                fieldSetEntity.setValue("known_user", knownUser);
                baseDao.update(fieldSetEntity);
            }
        }
        updateViewWarnMessageTime(uuid);
        //获取预警名称
        StringBuffer sql = new StringBuffer();
        sql.append(" SELECT c.target_task_name FROM product_sys_early_warning_info a ")
                .append(" JOIN product_oa_target_warning_configuration b on a.configuration_uuid = b.uuid ")
                .append(" JOIN product_oa_target_task c on b.related_indicator = c.uuid WHERE a.uuid = ? ");
        FieldSetEntity fse = baseDao.getFieldSetEntityBySQL(sql.toString(), new String[]{uuid}, false);
        fieldSetEntity.setValue("target_task_name", fse.getString("target_task_name"));
        if (fieldSetEntity != null) {
            String parent_uuid = fieldSetEntity.getUUID();
            DataTableEntity warnFeedBack = earlyWarningManagerService.getWarnFeedBack(parent_uuid);
            //带入回复人
            fieldSetEntity.addSubDataTable(warnFeedBack);
        }
        //获取当前人是否已经停止指标预警
        String record_uuid = fieldSetEntity.getString(CmnConst.RECORD_UUID);
        FieldSetEntity fieldSet = baseDao.getFieldSetEntityByFilter(CmnConst.PRODUCT_SYS_EARLY_WARNING_STOP, " user_id = ? and record_uuid = ? ", new String[]{userId, record_uuid}, false);
        if (fieldSet == null) {
            fieldSetEntity.setValue("is_stop", 0);
        } else {
            fieldSetEntity.setValue("is_stop", 1);
        }
        return fieldSetEntity;
    }
 
    @Override
    @Transactional
    public String stopWarning(String record_uuid) throws BaseException {
        String user_id = String.valueOf(SpringMVCContextHolder.getCurrentUser().getUser_id());
        FieldSetEntity fieldSetEntity = new FieldSetEntity();
        fieldSetEntity.setTableName(CmnConst.PRODUCT_SYS_EARLY_WARNING_STOP);
        fieldSetEntity.setValue(CmnConst.USER_ID, user_id);
        fieldSetEntity.setValue(CmnConst.RECORD_UUID, record_uuid);
        return baseDao.add(fieldSetEntity);
    }
 
    /**
     * 指标预警信息列表
     *
     * @param fse
     * @return
     */
    public DataTableEntity listWarnMessage(FieldSetEntity fse) {
        StringBuffer sql = new StringBuffer();
        sql.append(" SELECT a.uuid,a.configuration_uuid,a.early_warning_datetime,a.warning_content,a.receiver,c.target_task_name FROM ")
                .append("product_sys_early_warning_info a JOIN product_oa_target_warning_configuration b on a.configuration_uuid = b.uuid JOIN ")
                .append(" product_oa_target_task c on b.related_indicator = c.uuid WHERE a.configuration_uuid is not null and ")
                .append(" a.configuration_uuid != '' AND CONCAT(',',receiver,',') LIKE ")
                .append(" CONCAT('%,',?,',%') order by early_warning_datetime ");
        //获取当前人
        Integer user_id = SpringMVCContextHolder.getCurrentUser().getUser_id();
        return baseDao.listTable(sql.toString(), new Object[]{user_id}, fse.getInteger(CmnConst.PAGESIZE), fse.getInteger(CmnConst.CPAGE));
    }
 
    /*
     * 判断是否为整数
     * @param str 传入的字符串
     * @return 是整数返回true,否则返回false
     */
    public boolean isInteger(String str) {
        Pattern pattern = Pattern.compile("^[-\\+]?[\\d]*$");
        return pattern.matcher(str).matches();
    }
}