lizijie
2019-06-14 9ea24035a5a3c8c5a99551a075d47aa26eadbcaf
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
package com.moral.service.impl;
 
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.stream.Collectors;
 
import javax.annotation.Resource;
import javax.validation.constraints.NotNull;
 
import com.moral.mapper.DictionaryDataMapper;
import com.moral.mapper.OrganizationMapper;
import org.apache.commons.collections.CollectionUtils;
import org.springframework.stereotype.Service;
import org.springframework.util.ObjectUtils;
 
import com.github.pagehelper.PageHelper;
import com.moral.common.bean.Constants;
import com.moral.common.bean.PageBean;
import com.moral.common.util.ExampleUtil;
import com.moral.common.util.ParameterUtils;
import com.moral.common.util.RedisUtils;
import com.moral.common.util.StringUtils;
import com.moral.common.util.ValidateUtil;
import com.moral.entity.Device;
import com.moral.entity.MonitorPoint;
import com.moral.mapper.DeviceMapper;
import com.moral.mapper.MonitorPointMapper;
import com.moral.service.DeviceService;
import com.moral.service.MonitorPointService;
import com.moral.service.OrganizationService;
 
import tk.mybatis.mapper.entity.Example;
import tk.mybatis.mapper.entity.Example.Criteria;
 
@Service
public class MonitorPointServiceImpl implements MonitorPointService {
    @Resource
    private MonitorPointMapper monitorPointMapper;
    @Resource
    private DeviceMapper deviceMapper;
    @Resource
    private OrganizationMapper orgMapper;
    @Resource
    RedisUtils redisUtils;
    @Resource
    DictionaryDataMapper dictionaryDataMapper;
 
    @Resource
    private DeviceService deviceService;
    
    @Resource
    private OrganizationService organizationService;
    
    private static Class ENTITY_CLASS = MonitorPoint.class;
    @Override
    public List<MonitorPoint> getMonitorPointsByAreaName(Map<String, Object> parameters) {
        ValidateUtil.notNull(parameters.get("areaName"), "param.is.null");
        return monitorPointMapper.getMonitorPointsByAreaName(parameters);
    }
    @Override
    public List<MonitorPoint> queryWithStateByMap(Map<String, Object> params){
        params.put("isDelete",Constants.IS_DELETE_FALSE);
        Object orgIdObj = params.get("orgId");
        List<MonitorPoint> monitorPointList = null;
        if(orgIdObj != null) {
            Integer orgId = Integer.parseInt(orgIdObj.toString());
            List<Integer> orgIds = orgMapper.selectLowerOrgIds(orgId);
            params.put("orgIds",orgIds);
            monitorPointList = monitorPointMapper.selectByMap(params);
//            for(MonitorPoint monitorPoint:monitorPointList){
//                Integer state = getStateFromRedis(monitorPoint.getId());
//                monitorPoint.setState(state);
//            }
        }
        return monitorPointList == null ? new ArrayList<>() : monitorPointList;
    }
    private Integer getStateFromRedis(Integer monitorPointId){
        StringBuilder key = new StringBuilder();
        key.append("state_").append(monitorPointId).append("_*");
        List<Map> stateList = redisUtils.getList(key.toString(),Map.class);
        int state = -1;
        if(stateList!=null){
            for (Map deviceState:stateList){
                int s =  Integer.parseInt(deviceState.get("state").toString());
                state = s>state&&s<4?s:state;
            }
        }
        state = state==-1?4:state;
        return state;
    }
    @Override
    public PageBean queryByPageBean(PageBean pageBean) {
        Example example = ExampleUtil.generateExample(ENTITY_CLASS,pageBean);
        List<Example.Criteria> criteriaList = example.getOredCriteria();
        PageHelper.startPage(pageBean.getPageIndex(),pageBean.getPageSize());
        List<MonitorPoint> monitorPointList = monitorPointMapper.selectWithAreaNameByExample(example);
        return new PageBean(monitorPointList);
    }
    @Override
   public MonitorPoint queryWithRelationById(Integer id){
         Example example = new Example(ENTITY_CLASS);
         example.or().andEqualTo("id",id);
         List<MonitorPoint> monitorPointList = monitorPointMapper.selectWithAreaNameByExample(example);
         return monitorPointList!=null&&monitorPointList.size()>0?monitorPointList.get(0):null;
    }
    @Override
    public void addOrModify(MonitorPoint monitorPoint) {
        try{
            if(monitorPoint.getId()==null){
                monitorPoint.setIsDelete(Constants.IS_DELETE_FALSE);
                monitorPointMapper.insertSelective(monitorPoint);
            }else{
                MonitorPoint queryMonitorPoint = new MonitorPoint();
                queryMonitorPoint.setId(monitorPoint.getId());
                queryMonitorPoint.setOrganizationId(monitorPoint.getOrganizationId());
                // num = 1,说明未改变,此查询在更新之前
                Integer num =  monitorPointMapper.selectCount(queryMonitorPoint);
                boolean needRefreshCach = (num!=1);
                monitorPointMapper.updateByPrimaryKeySelective(monitorPoint);
                if(needRefreshCach){
                    // 刷新当前监控点下设备 在redis里设备信息
                    refreshDevicesInRedis(monitorPoint.getId());
                }
            }
        }
        catch (Exception ex){
            throw  ex;
        }
    }
    /*
      刷新当前监控点下设备 在redis里设备信息
     */
    private void  refreshDevicesInRedis(int monitorPointId){
        Device queryDevice = new Device();
        queryDevice.setMonitorPointId(monitorPointId);
        List<Device> deviceList = deviceMapper.select(queryDevice);
        if (!CollectionUtils.isEmpty(deviceList)){
            List<Integer> orgIds = monitorPointMapper.selectOrganizationIds(monitorPointId);
            if (!CollectionUtils.isEmpty(orgIds)){
                deviceList.stream().forEach(dev ->{
                    if(!StringUtils.isNullOrEmpty(dev.getMac())){
                        String key = "device_"+dev.getMac();
//                        // 简化的设备信息 用以缓存redis
//                        Device simpleDevice = new Device();
//                        simpleDevice.setId(dev.getId());
//                        simpleDevice.setDeviceVersion(dev.getDeviceVersion());
//                        simpleDevice.setMac(dev.getMac());
//                        simpleDevice.setMonitorPointId(dev.getMonitorPointId());
                        // 设置新组织关系,防止读写分离时数据库同步延迟
                        dev.setOrganizationIds(orgIds);
                        redisUtils.set(key,dev);
                    }
                });
            }
        }
 
    }
    @Override
    public void deleteByIds(Integer... ids) {
        MonitorPoint monitorPoint = new MonitorPoint();
        monitorPoint.setIsDelete(Constants.IS_DELETE_TRUE);
        if(ids!=null&&ids.length>0){
            if(ids.length==1){
                monitorPoint.setId(ids[0]);
                monitorPointMapper.updateByPrimaryKeySelective(monitorPoint);
            }else{
                Example example = new Example(ENTITY_CLASS);
                example.or().andIn("id", Arrays.asList(ids));
                monitorPointMapper.updateByExampleSelective(monitorPoint,example);
            }
 
        }
    }
 
    @Override
    public List<MonitorPoint> getMonitorPointsByName(String name) {
        Example example = new Example(MonitorPoint.class);
        Criteria criteria = example.createCriteria();
 
        criteria.andEqualTo("isDelete", Constants.IS_DELETE_FALSE).andLike("name", "%" + name + "%");
        example.or().andEqualTo("isDelete", Constants.IS_DELETE_FALSE)
                .andCondition("getPY(" + getReplaceStr("name") + ") like ", "%" + name + "%");
 
        List<MonitorPoint> monitorPoints = monitorPointMapper.selectByExample(example);
        return monitorPoints;
    }
 
    private String getReplaceStr(String name){
        List<String[]> list = new ArrayList<String[]>();
        list.add(new String[]{"(",""});
        list.add(new String[]{")",""});
        for (String[] string : list) {
            name = replace(name,string[0],string[1]);
        }
        return name;
    }
    
    private  String replace(String name,String fromStr,String toStr){
        return "REPLACE (" + name + ",'" + fromStr + "','" + toStr + "')";
    }
 
    /**
     *
     * @param idList
     * @return  {id:,state:}
     */
    @Override
    public List<Map<String, String>> queryMonitroPointsState(List<Integer> idList) {
        List<Map<String, String>> list = idList.stream().map( id -> {
           Integer state = getStateFromRedis(id);
           Map<String,String> stateMap = new HashMap<>();
           stateMap.put("id",id.toString());
           stateMap.put("state",state.toString());
           return stateMap;
        }).collect(Collectors.toList());
        return list;
    }
 
    /**
     * 获取所属组织的监控点总数
     * @param orgId
     * @return
     */
    @Override
    public Integer countOfSubOrgs(@NotNull  Integer orgId){
        Example example = new Example(ENTITY_CLASS);
        //过滤超级管理员账号
        if(!dictionaryDataMapper.isSupperOrgId(orgId)){
            List<Integer> orgIds = orgMapper.selectLowerOrgIds(orgId);
            example.or().andIn("organizationId",orgIds);
        }
        return monitorPointMapper.selectCountByExample(example);
    }
    @Override
    public List<MonitorPoint> getMonitorPointsByOrganizationId(Integer orgId) {
        Example example = new Example(MonitorPoint.class);
        Criteria criteria = example.createCriteria();
        
        criteria.andEqualTo("isDelete", Constants.IS_DELETE_FALSE);
        if (Constants.isNotSpecialOrgId(orgId)) {
            //criteria.andEqualTo("organizationId", orgId);
            Set<Integer> organizationIds = organizationService.getChildOrganizationIds(orgId);
            criteria.andIn("organizationId", organizationIds);
 
        }
        example.orderBy("name").asc();
        return monitorPointMapper.selectByExample(example);
    }
    @Override
    public List<MonitorPoint> getMonitorPointsByRegion(Map<String, Object> parameters) {
        Example example = new Example(MonitorPoint.class);
        Criteria criteria = example.createCriteria();
        
        criteria.andEqualTo("isDelete", Constants.IS_DELETE_FALSE);
        criteria.andEqualTo(parameters.get("name").toString(), parameters.get("value"));
        return monitorPointMapper.selectByExample(example);
    }
    @Override
    public List<Integer> queryVersionsById(Integer id){
        return  monitorPointMapper.selectVersionsById(id);
    }
    @Override
    public MonitorPoint queryMonitorPointById(Integer mpointId) {
        return  this.monitorPointMapper.selectByPrimaryKey(mpointId);
    }
 
    @Override
    public List<MonitorPoint> getMonitorPointsAndDevicesByRegion(Map<String, Object> parameters) {
        //校验参数
        Object organizationId = parameters.remove("organizationId");
        ValidateUtil.notNull(organizationId, "param.is.null");
        ValidateUtil.notNull(parameters.get("regionCode"), "param.is.null");
 
        //组装查询条件
        ParameterUtils.getRegionType4RegionCode(parameters);
        
        Example example = new Example(MonitorPoint.class);
        Criteria criteria = example.createCriteria();
        criteria.andEqualTo("isDelete", Constants.IS_DELETE_FALSE);
        if (Constants.isNotSpecialOrgId(Integer.valueOf(organizationId.toString()))) {
            //criteria.andEqualTo("organizationId", organizationId);
            Set<Integer> organizationIds = organizationService.getChildOrganizationIds(Integer.valueOf(organizationId.toString()));
            criteria.andIn("organizationId", organizationIds);
        }
        criteria.andEqualTo(parameters.get("regionType") + "Code", parameters.remove("regionCode"));
        
        //查询监控点数据
        List<MonitorPoint> monitorPoints = monitorPointMapper.selectByExample(example);
        //查询监控点下所有的设备
        Iterator<MonitorPoint> iterator = monitorPoints.iterator();
        while (iterator.hasNext()) {
            MonitorPoint monitorPoint = iterator.next();
            List<Device> devices = deviceService.getDevicesByMonitorPointId(monitorPoint.getId());
            if (ObjectUtils.isEmpty(devices)) {
                iterator.remove();
            } else {
                monitorPoint.setDevices(devices);
            }
            
        }
        return monitorPoints;
    }
 
    @SuppressWarnings("unchecked")
    @Override
    public Collection<Object> getDevicesStateByRegion(Map<String, Object> parameters) {
        //校验参数
        Object organizationId = parameters.remove("organizationId");
        ValidateUtil.notNull(organizationId, "param.is.null");
        ValidateUtil.notNull(parameters.get("regionCode"), "param.is.null");
 
        //组装查询条件
        ParameterUtils.getRegionType4RegionCode(parameters);
        
        if (Constants.isNotSpecialOrgId(Integer.valueOf(organizationId.toString()))) {
            Set<Integer> organizationIds = organizationService.getChildOrganizationIds(Integer.valueOf(organizationId.toString()));
            parameters.put("orgIds", organizationIds);
        }
        List<Map<String, Object>> monitorPoints  = deviceMapper.getDevicesStateByRegion(parameters);
        Map<String, Object> result = new HashMap<String, Object>();
        Map<String,Object> device;
        List<Map<String, Object>> devices;
        for (Map<String, Object> map : monitorPoints) {
            String id = map.get("id").toString();
 
            device = new HashMap<String,Object>();
            device.put("id", map.remove("deviceId"));
            device.put("name", map.remove("deviceName"));
            device.put("state", map.remove("state"));
            device.put("mac", map.remove("mac"));
 
            if (result.containsKey(id)) {
                Map<String, Object> monitorPoint = (Map<String, Object>) result.get(id);
                devices = (List<Map<String, Object>>) monitorPoint.get("devices");
            } else {
                devices = new ArrayList<Map<String, Object>>();
                result.put(id, map);
            }
            devices.add(device);
            map.put("devices", devices);
            result.put(id, map);
        }
        
        return result.values();
    }
    
    @Override
    public void isCompensateCalculation(Map<String, Object> parameters) {
        MonitorPoint monitorPoint = monitorPointMapper.selectByPrimaryKey(Integer.valueOf(parameters.get("monitorPointId").toString()));
        if (Integer.valueOf(320581).equals(monitorPoint.getAreaCode())) {
            parameters.put("compensate", true);
        }
        
    }
}