fengxiang
2018-09-27 ba18a3f6631c6ea3f43a134d77e2c0233f883340
src/main/java/com/moral/service/impl/MonitorPointServiceImpl.java
@@ -1,52 +1,96 @@
package com.moral.service.impl;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
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 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.MyBatisBaseMapUtil;
import org.springframework.stereotype.Service;
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.MonitorPointService;
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;
    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();
        if(criteriaList!=null&&criteriaList.size()>0){
            for(Example.Criteria cri : criteriaList){
                cri.andNotEqualTo("isDelete", Constants.IS_DELETE_TRUE);
            }
        }else {
            example.or().andNotEqualTo("isDelete",Constants.IS_DELETE_TRUE);
        }
        PageHelper.startPage(pageBean.getPageIndex(),pageBean.getPageSize());
        List<MonitorPoint> monitorPointList = monitorPointMapper.selectWithAreaNameByExample(example);
        return new PageBean(monitorPointList);
    }
    @Override
   public MonitorPoint selectWithRelationById(Integer id){
   public MonitorPoint queryWithRelationById(Integer id){
         Example example = new Example(ENTITY_CLASS);
         example.or().andEqualTo("id",id);
         List<MonitorPoint> monitorPointList = monitorPointMapper.selectWithAreaNameByExample(example);
@@ -56,16 +100,54 @@
    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();
@@ -83,4 +165,92 @@
        }
    }
   @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);
      }
      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);
    }
}