jinpengyong
2021-12-22 9d91dc402f279630eaa100024fd3b1542fbeb41c
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
package com.moral.api.service.impl;
 
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.googlecode.aviator.AviatorEvaluator;
import com.googlecode.aviator.Expression;
import com.moral.api.entity.*;
import com.moral.api.mapper.*;
import com.moral.api.pojo.vo.device.DeviceVO;
import com.moral.api.service.DeviceService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
 
import com.moral.api.service.OrganizationService;
import com.moral.api.service.SysDictDataService;
import com.moral.api.util.CacheUtils;
import com.moral.api.util.AdjustDataUtils;
import com.moral.api.util.LogUtils;
import com.moral.constant.Constants;
import com.moral.constant.RedisConstants;
import com.moral.util.ConvertUtils;
import com.moral.util.DateUtils;
 
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.ObjectUtils;
import org.springframework.util.StringUtils;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;
 
import java.beans.PropertyDescriptor;
import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.stream.Collectors;
 
import javax.servlet.http.HttpServletRequest;
 
/**
 * <p>
 * 设备表 服务实现类
 * </p>
 *
 * @author moral
 * @since 2021-05-11
 */
@Service
@Slf4j
public class DeviceServiceImpl extends ServiceImpl<DeviceMapper, Device> implements DeviceService {
 
    @Autowired
    private DeviceMapper deviceMapper;
 
    @Autowired
    private ManageAccountMapper manageAccountMapper;
 
    @Autowired
    private OrganizationMapper organizationMapper;
 
    @Autowired
    private MonitorPointMapper monitorPointMapper;
 
    @Autowired
    private SysDictTypeMapper sysDictTypeMapper;
 
    @Autowired
    private SysDictDataMapper sysDictDataMapper;
 
    @Autowired
    private SysDictDataService sysDictDataService;
 
 
    @Autowired
    private RedisTemplate redisTemplate;
 
    @Autowired
    private OrganizationUnitAlarmMapper organizationUnitAlarmMapper;
 
    @Autowired
    private VersionSensorUnitMapper versionSensorUnitMapper;
 
    @Autowired
    private SpecialDeviceMapper specialDeviceMapper;
 
    @Autowired
    private AdjustDataUtils adjustDataUtils;
 
    @Autowired
    private OrganizationService organizationService;
 
    /*
     * 从redis获取设备信息
     * */
    private Map<String, Object> getDeviceInfoFromRedis(String mac) {
        return (Map<String, Object>) redisTemplate.opsForHash().get(RedisConstants.DEVICE, mac);
    }
 
    /*
     * 设备信息存入redis
     */
    private void setDeviceInfoToRedis(String mac, Map<String, Object> deviceInfo) {
        redisTemplate.opsForHash().put(RedisConstants.DEVICE, mac, deviceInfo);
    }
 
    /*
     * 从redis删除设备信息
     */
    private void delDeviceInfoFromRedis(String mac) {
        redisTemplate.opsForHash().delete(RedisConstants.DEVICE, mac);
    }
 
    @Override
    @Transactional
    public void insert(Device device) {
        Integer orgId = monitorPointMapper.selectById(device.getMonitorPointId()).getOrganizationId();
        device.setOrganizationId(orgId);
        deviceMapper.insert(device);
        Map<String, Object> deviceInfo = selectDeviceInfoById(device.getId());
        //维护组织型号关系表
        insertOrganizationUnitAlarm(orgId, device.getDeviceVersionId());
        //新增设备信息存入redis
        String mac = device.getMac();
        //从redis中删除设备信息
        delDeviceInfoFromRedis(mac);
        //设备信息存入redis
        setDeviceInfoToRedis(mac, deviceInfo);
        //刷新deviceInfo缓存
        CacheUtils.refreshDeviceAlarmInfo();
        //操作日志记录
        HttpServletRequest request = ((ServletRequestAttributes) Objects.requireNonNull(RequestContextHolder.getRequestAttributes())).getRequest();
        StringBuilder content = new StringBuilder();
        content.append("添加了设备:").append(device.getName()).append(":").append("mac:").append(mac);
        LogUtils.saveOperationForManage(request, content.toString(), Constants.INSERT_OPERATE_TYPE);
    }
 
    @Override
    @Transactional
    public void delete(Integer deviceId) {
        Device device = deviceMapper.selectById(deviceId);
        UpdateWrapper<Device> updateWrapper = new UpdateWrapper<>();
        updateWrapper.eq("id", deviceId).set("is_delete", Constants.DELETE);
        deviceMapper.update(null, updateWrapper);
        String mac = device.getMac();
        //从redis中删除设备信息
        delDeviceInfoFromRedis(mac);
        //维护组织型号关系表
        Integer versionId = device.getDeviceVersionId();
        Integer orgId = device.getOrganizationId();
        deleteOrganizationUnitAlarm(orgId, versionId);
        //刷新deviceInfo缓存
        CacheUtils.refreshDeviceAlarmInfo();
        //操作日志记录
        HttpServletRequest request = ((ServletRequestAttributes) Objects.requireNonNull(RequestContextHolder.getRequestAttributes())).getRequest();
        StringBuilder content = new StringBuilder();
        content.append("删除了设备:").append(device.getName()).append(";").append("mac:").append(mac);
        LogUtils.saveOperationForManage(request, content.toString(), Constants.DELETE_OPERATE_TYPE);
    }
 
    @Override
    @Transactional
    public void update(Device device) {
        Integer deviceId = device.getId();
        Device oldDevice = deviceMapper.selectById(deviceId);
        //判断是否更新了站点,如果更新了站点则查询对应站点的组织id进行更新
        if (!ObjectUtils.isEmpty(device.getMonitorPointId())) {
            MonitorPoint monitorPoint = monitorPointMapper.selectById(device.getMonitorPointId());
            device.setOrganizationId(monitorPoint.getOrganizationId());
        }
        deviceMapper.updateById(device);
        Device updateDevice = deviceMapper.selectById(deviceId);
        String mac = updateDevice.getMac();
        //维护组织型号关系表
        Integer oldOrgId = oldDevice.getOrganizationId();
        Integer newOrgId = updateDevice.getOrganizationId();
        Integer oldVersionId = oldDevice.getDeviceVersionId();
        Integer newVersionId = updateDevice.getDeviceVersionId();
        if (!oldOrgId.equals(newOrgId) || !oldVersionId.equals(newVersionId)) {
            deleteOrganizationUnitAlarm(oldOrgId, oldVersionId);
            insertOrganizationUnitAlarm(newOrgId, newVersionId);
        }
        //从redis中删除设备信息
        delDeviceInfoFromRedis(oldDevice.getMac());
        Map<String, Object> deviceInfo = selectDeviceInfoById(deviceId);
        //设备信息存入redis
        setDeviceInfoToRedis(mac, deviceInfo);
        //刷新deviceInfo缓存
        CacheUtils.refreshDeviceAlarmInfo();
        //操作日志记录
        HttpServletRequest request = ((ServletRequestAttributes) Objects.requireNonNull(RequestContextHolder.getRequestAttributes())).getRequest();
        StringBuilder content = new StringBuilder();
        content.append("修改了设备:" + oldDevice.getMac()).append("==>").append(mac).append(":");
        Field[] fields = Device.class.getDeclaredFields();
        for (Field field : fields) {
            if (field.getName().equals("id")) {
                continue;
            }
            if ("serialVersionUID".equals(field.getName())) {
                continue;
            }
            String fieldName = field.getName();
            PropertyDescriptor pd = null;
            try {
                pd = new PropertyDescriptor(fieldName, Device.class);
                Method method = pd.getReadMethod();
                Object o1 = method.invoke(oldDevice);
                Object o2 = method.invoke(device);
                if (o2 != null) {
                    content.append(fieldName).append(":").append(o1).append("-->").append(o2).append(":");
                }
 
            } catch (Exception e) {
                e.printStackTrace();
            }
 
        }
        LogUtils.saveOperationForManage(request, content.toString(), Constants.UPDATE_OPERATE_TYPE);
    }
 
    @Override
    public List<Map<String, Object>> selectAllOperators() {
        //维护人列表
        QueryWrapper<ManageAccount> operatorWrapper = new QueryWrapper<>();
        operatorWrapper.select("id", "user_name").eq("is_delete", Constants.NOT_DELETE);
        return manageAccountMapper.selectMaps(operatorWrapper);
    }
 
    //根据字典类型获取字典数据
    @Override
    public List<Map<String, Object>> selectDeviceDictData(String dictType) {
        QueryWrapper<SysDictType> typeQueryWrapper = new QueryWrapper<>();
        typeQueryWrapper.select("id").eq("name", dictType);
        SysDictType sysDictType = sysDictTypeMapper.selectOne(typeQueryWrapper);
        QueryWrapper<SysDictData> dataQueryWrapper = new QueryWrapper<>();
        dataQueryWrapper.select("dataKey", "dataValue").eq("dict_type_id", sysDictType.getId()).eq("is_delete", Constants.NOT_DELETE);
        return sysDictDataMapper.selectMaps(dataQueryWrapper);
    }
 
    @Override
    public List<Map<String, Object>> selectMonitorsByOrgId(Integer orgId) {
        //获取所有子组织
        List<Organization> organizations = organizationService.getAllChildrenOrganization(orgId);
        List<Integer> orgIds = organizations.stream().map(Organization::getId).collect(Collectors.toList());
        orgIds.add(orgId);
        QueryWrapper<MonitorPoint> queryWrapper = new QueryWrapper<>();
        queryWrapper.select("id", "name")
                .eq("is_delete", Constants.NOT_DELETE)
                .in("organization_id", orgIds);
        return monitorPointMapper.selectMaps(queryWrapper);
    }
 
    @Override
    public Map<String, Object> selectDevicesByOrgId(Map<String, Object> parameters) {
        return selectDevices(parameters);
    }
 
    @Override
    public Map<String, Object> selectDevicesByMpId(Map<String, Object> parameters) {
        return selectDevices(parameters);
    }
 
    @Override
    public Map<String, Object> selectDevices(Map<String, Object> parameters) {
        QueryWrapper<Device> queryWrapper = new QueryWrapper<>();
        int page = Integer.parseInt(parameters.get("page").toString());
        int size = Integer.parseInt(parameters.get("size").toString());
        Object order = parameters.get("order");
        Object orderType = parameters.get("orderType");
        Object name = parameters.get("name");
        Object mac = parameters.get("mac");
        Object orgId = parameters.get("organizationId");
        Object mpId = parameters.get("monitorPointId");
 
        //查询某组织下所有设备,包括子组织
        if (orgId != null) {
            //查询所有子组织
            List<Organization> organizations = organizationService.getAllChildrenOrganization(Integer.parseInt(orgId.toString()));
            List<Integer> orgIds = organizations.stream().map(Organization::getId).collect(Collectors.toList());
            orgIds.add(Integer.parseInt(orgId.toString()));
            queryWrapper.in("organization_id", orgIds);
        }
 
        //查询某站点下所有设备
        if (mpId != null) {
            queryWrapper.eq("monitor_point_id", mpId);
        }
 
        //设备名称或mac模糊查询
        if (name != null && mac != null) {
            queryWrapper.like("name", name).or().like("mac", mac);
        }
 
        //排序参数,默认create_time降序
        if (order != null && orderType != null) {
            if (Constants.ORDER_ASC.equals(orderType)) {
                queryWrapper.orderByAsc(ConvertUtils.toLine(order.toString()));
            } else {
                queryWrapper.orderByDesc(ConvertUtils.toLine(order.toString()));
            }
        } else {
            queryWrapper.orderByDesc("create_time");
        }
        queryWrapper.eq("is_delete", Constants.NOT_DELETE);
        Page<Device> devicePage = new Page<>(page, size);
        deviceMapper.selectPage(devicePage, queryWrapper);
        List<Device> devices = devicePage.getRecords();
        List<Map<String, Object>> items = new ArrayList<>();
        for (Device device : devices) {
            Map<String, Object> deviceInfo = selectDeviceInfoById(device.getId());
            items.add(deviceInfo);
        }
        Map<String, Object> result = new LinkedHashMap<>();
        result.put("total", devicePage.getTotal());
        result.put("totalPage", devicePage.getPages());
        result.put("current", devicePage.getCurrent());
        result.put("pageSize", devicePage.getSize());
        result.put("item", items);
        return result;
    }
 
    @Override
    public Map<String, Object> selectDeviceInfoById(Integer deviceId) {
        String mac = deviceMapper.selectById(deviceId).getMac();
        Map<String, Object> deviceInfo = getDeviceInfoFromRedis(mac);
        //先从redis中取
        if (deviceInfo != null) {
            return deviceInfo;
        }
        deviceInfo = new LinkedHashMap<>();
        DeviceVO device = deviceMapper.selectDeviceInfoById(deviceId);
        //设备
        deviceInfo.put("id", device.getId());
        deviceInfo.put("name", device.getName());
        deviceInfo.put("mac", device.getMac());
        deviceInfo.put("address", device.getAddress());
        deviceInfo.put("longitude", device.getLongitude());
        deviceInfo.put("latitude", device.getLatitude());
        deviceInfo.put("createTime", DateUtils.dateToDateString(device.getCreateTime()));
        deviceInfo.put("installTime", device.getInstallTime() == null ? null : DateUtils.dateToDateString(device.getInstallTime()));
 
        //扩展字段
        deviceInfo.put("extend", device.getExtend());
 
        //乡镇街道信息
        deviceInfo.put("town", device.getTown());
 
        //行业
        deviceInfo.put("professions", device.getProfessions());
 
        //工艺
        deviceInfo.put("tech", device.getTech());
        deviceInfo.put("techName", device.getTechName());
 
        //检测器
        deviceInfo.put("detector", device.getDetector());
        deviceInfo.put("detectorName", device.getDetectorName());
 
        //采购商
        deviceInfo.put("purchaser", device.getPurchaser());
        deviceInfo.put("purchaserName", device.getPurchaserName());
 
        //型号
        Map<String, Object> versionInfo = new LinkedHashMap<>();
        Version version = device.getVersion();
        versionInfo.put("id", version.getId());
        versionInfo.put("name", version.getName());
        deviceInfo.put("version", versionInfo);
 
        //维护人
        List<Map<String, Object>> operatorsInfo = new ArrayList<>();
        List<ManageAccount> operators = device.getOperators();
        for (ManageAccount operator : operators) {
            Map<String, Object> operatorMap = new LinkedHashMap<>();
            operatorMap.put("id", operator.getId());
            operatorMap.put("name", operator.getUserName());
            operatorsInfo.add(operatorMap);
        }
        deviceInfo.put("operators", operatorsInfo);
 
        //组织
        Map<String, Object> orgInfo = new LinkedHashMap<>();
        Organization organization = device.getOrganization();
        orgInfo.put("id", organization.getId());
        orgInfo.put("name", organization.getName());
        deviceInfo.put("organization", orgInfo);
 
        //站点
        Map<String, Object> mpInfo = new LinkedHashMap<>();
        MonitorPoint monitorPoint = device.getMonitorPoint();
        mpInfo.put("id", monitorPoint.getId());
        mpInfo.put("name", monitorPoint.getName());
        mpInfo.put("areaCode", monitorPoint.getAreaCode());
        mpInfo.put("cityCode", monitorPoint.getCityCode());
        mpInfo.put("provinceCode", monitorPoint.getProvinceCode());
        deviceInfo.put("monitorPoint", mpInfo);
 
        //国控站点
        Map<String, Object> govMpInfo = new LinkedHashMap<>();
 
        govMpInfo.put("guid", null);
        govMpInfo.put("name", null);
        if (device.getGovMonitorPoint() != null) {
            govMpInfo.put("guid", device.getGovMonitorPoint().getGuid());
            govMpInfo.put("name", device.getGovMonitorPoint().getName());
        }
        deviceInfo.put("govMonitorPoint", govMpInfo);
        setDeviceInfoToRedis(mac, deviceInfo);
        return deviceInfo;
    }
 
    @Override
    public List<Map<String, Object>> selectAllOrganization() {
        QueryWrapper<Organization> queryWrapper = new QueryWrapper<>();
        queryWrapper.select("id", "name").eq("is_delete", Constants.NOT_DELETE);
        return organizationMapper.selectMaps(queryWrapper);
    }
 
    @Override
    public List<Map<String, Object>> selectAllMonitorPoint() {
        QueryWrapper<MonitorPoint> queryWrapper = new QueryWrapper<>();
        queryWrapper.select("id", "name").eq("is_delete", Constants.NOT_DELETE);
        return monitorPointMapper.selectMaps(queryWrapper);
    }
 
    @Override
    public Map<String, Object> getDeviceByMac(String mac) {
        Map<String, Object> deviceInfo = getDeviceInfoFromRedis(mac);
        if (ObjectUtils.isEmpty(deviceInfo)) {
            QueryWrapper<Device> queryWrapper = new QueryWrapper<>();
            queryWrapper.eq("mac", mac).eq("is_delete", Constants.NOT_DELETE);
            Device device = deviceMapper.selectOne(queryWrapper);
            if (device != null) {
                deviceInfo = selectDeviceInfoById(device.getId());
                setDeviceInfoToRedis(mac, deviceInfo);
            }
        }
        return deviceInfo;
    }
 
    @Override
    public Map<String, Object> adjustDeviceData(Map<String, Object> deviceData) {
        String mac = deviceData.remove("mac").toString();
        //从redis获取校准公式
        Map<String, Object> adjustFormula = redisTemplate.opsForHash().entries(RedisConstants.ADJUST + "_" + mac);
        if (!ObjectUtils.isEmpty(adjustFormula)) {
            Map<String, Object> deviceInfo = getDeviceByMac(mac);
            //获取设备绑定的国控站信息
            Map<String, Object> govMpInfo = (Map<String, Object>) deviceInfo.get("govMonitorPoint");
            Map<String, Object> aqiMap = null;
            if (govMpInfo.get("guid") != null) {
                aqiMap = (Map<String, Object>) redisTemplate.opsForHash().get(RedisConstants.AQI_DATA, govMpInfo.get("guid").toString());
            }
            return adjustDataUtils.adjust(deviceData, adjustFormula, ObjectUtils.isEmpty(aqiMap) ? null : aqiMap);
        }
        deviceData.remove("DataTime");
        return deviceData;
    }
 
    @Override
    public Map<String, Object> adjustSpecialDeviceData(Map<String, Object> deviceData) {
        String mac = deviceData.remove("mac").toString();
        //从redis获取校准公式
        Map<String, Object> adjustFormula = redisTemplate.opsForHash().entries(RedisConstants.ADJUST + "_" + mac);
        if (!ObjectUtils.isEmpty(adjustFormula)) {
            Organization organization = specialDeviceMapper.selectOrgByMac(mac);
            String areaCode = organization.getAreaCode().toString();
            String cityCode = organization.getCityCode().toString();
            Map<String, Object> aqiMap = (Map<String, Object>) redisTemplate.opsForHash().get(RedisConstants.AQI_DATA, areaCode);
            if (ObjectUtils.isEmpty(aqiMap)) {
                aqiMap = (Map<String, Object>) redisTemplate.opsForHash().get(RedisConstants.AQI_DATA, cityCode);
            }
            return adjustDataUtils.adjust(deviceData, adjustFormula, ObjectUtils.isEmpty(aqiMap) ? null : aqiMap);
        }
        deviceData.remove("DataTime");
        return deviceData;
    }
 
    @Override
    @Transactional
    public void judgeDeviceState(Map<String, Object> deviceData) {
        String mac = deviceData.remove("mac").toString();
        Device device = (Device) redisTemplate.opsForHash().get(RedisConstants.DEVICE_INFO, mac);
        Version version = device.getVersion();
        List<Sensor> sensors = version.getSensors();
        Expression expression;
        int state = 1;
        for (Sensor sensor : sensors) {
            //因子报警等级
            String alarmLevel = sensor.getAlarmLevel();
            if (StringUtils.isEmpty(alarmLevel)) {
                continue;
            }
            List<Object> list = JSONObject.parseObject(alarmLevel, List.class);
            String sensorCode = sensor.getCode();
            //转换公式
            String formula = sensor.getFormula();
            //转换单位前因子值
            String sensorValue = (String) deviceData.get(sensorCode);
            double value = Double.parseDouble(sensorValue);
            //单位转换
            if (formula != null) {
                //转换后因子值
                sensorValue = formula.replace("{0}", sensorValue);
                expression = AviatorEvaluator.compile(sensorValue);
                value = Double.parseDouble(expression.execute().toString());
            }
            int sensorState = judgeState(list, value);
            if (sensorState > state) {
                state = sensorState;
            }
        }
        //修改设备状态
        UpdateWrapper<Device> updateWrapper = new UpdateWrapper<>();
        updateWrapper.eq("id", device.getId()).set("state", String.valueOf(state));
        deviceMapper.update(null, updateWrapper);
    }
 
    //根据因子值判断状态
    private int judgeState(List<Object> levels, Double data) {
        int state = 1;
        for (int i = levels.size() - 1; i >= 0; i--) {
            Double level = Double.parseDouble(levels.get(i).toString());
            if (data >= level) {
                state = i + 1;
                break;
            }
        }
        return state;
    }
 
    /**
     * @Description: 判断组织是否含有该设备的型号,如果没有则添加到组织型号关系表中
     * @Param: [orgId, versionId]
     * @return: void
     * @Author: 陈凯裕
     * @Date: 2021/9/6
     */
    private void insertOrganizationUnitAlarm(Integer orgId, Integer versionId) {
        //查询是否含有该型号
        QueryWrapper<OrganizationUnitAlarm> queryOrganizationVersionWrapper = new QueryWrapper<>();
        queryOrganizationVersionWrapper.eq("organization_id", orgId);
        queryOrganizationVersionWrapper.eq("version_id", versionId);
        queryOrganizationVersionWrapper.eq("is_delete", Constants.NOT_DELETE);
        List<OrganizationUnitAlarm> organizationUnitAlarms = organizationUnitAlarmMapper.selectList(queryOrganizationVersionWrapper);
        //如果没有该型号则插入数据
        if (ObjectUtils.isEmpty(organizationUnitAlarms)) {
            //查询型号的因子和单位
            QueryWrapper<VersionSensorUnit> queryVersionSensorUnitWrapper = new QueryWrapper<>();
            queryVersionSensorUnitWrapper.eq("version_id", versionId);
            queryVersionSensorUnitWrapper.eq("is_delete", Constants.NOT_DELETE);
            List<VersionSensorUnit> versionSensorUnits = versionSensorUnitMapper.selectList(queryVersionSensorUnitWrapper);
            //获取所有因子的默认报警值
            Map<String, SysDictData> sensorAlarms = sysDictDataService.getDictDatasByType("defaultAlarm");
            if (!ObjectUtils.isEmpty(versionSensorUnits)) {
                for (VersionSensorUnit versionSensorUnit : versionSensorUnits) {
                    OrganizationUnitAlarm organizationUnitAlarm = new OrganizationUnitAlarm();
                    String sensorCode = versionSensorUnit.getSensorCode();
                    //设置默认报警值
                    SysDictData alarm = sensorAlarms.get(sensorCode);
                    if (alarm != null)
                        organizationUnitAlarm.setAlarmLevel(alarm.getDataValue());
                    organizationUnitAlarm.setOrganizationId(orgId);
                    organizationUnitAlarm.setVersionId(versionId);
                    organizationUnitAlarm.setSensorCode(versionSensorUnit.getSensorCode());
                    organizationUnitAlarm.setUnitKey(versionSensorUnit.getUnitKey());
                    organizationUnitAlarm.setShowUnitKey(versionSensorUnit.getUnitKey());
                    organizationUnitAlarmMapper.insert(organizationUnitAlarm);
                }
            }
        }
    }
 
    /**
     * @Description: 删除设备后,如果该组织没有这个设备型号其他的设备了,则删除组织型号关系表中该型号的信息。
     * @Param: [orgId, versionId]
     * @return: void
     * @Author: 陈凯裕
     * @Date: 2021/9/6
     */
    private void deleteOrganizationUnitAlarm(Integer orgId, Integer versionId) {
        QueryWrapper<Device> queryOrganizationVersionWrapper = new QueryWrapper<>();
        queryOrganizationVersionWrapper.eq("organization_id", orgId);
        queryOrganizationVersionWrapper.eq("device_version_id", versionId);
        queryOrganizationVersionWrapper.eq("is_delete", Constants.NOT_DELETE);
        List<Device> devices = deviceMapper.selectList(queryOrganizationVersionWrapper);
        if (ObjectUtils.isEmpty(devices)) {//如果为空,则组织没有该型号的设备了。
            UpdateWrapper deleteWrapper = new UpdateWrapper();
            deleteWrapper.eq("organization_id", orgId);
            deleteWrapper.eq("version_id", versionId);
            deleteWrapper.eq("is_delete", Constants.NOT_DELETE);
            deleteWrapper.set("is_delete", Constants.DELETE);
            organizationUnitAlarmMapper.update(null, deleteWrapper);
        }
    }
}