fengxiang
2018-06-25 9742e7a70ac6e74d114e68ce1bc8f46670b55453
src/main/java/com/moral/controller/ScreenController.java
@@ -1,47 +1,57 @@
package com.moral.controller;
import static com.moral.common.util.RedisUtil.get;
import static com.moral.common.util.RedisUtil.hasKey;
import static com.moral.common.util.ResourceUtil.getValue;
import static com.moral.common.util.WebUtils.getParametersStartingWith;
import java.io.*;
import java.lang.reflect.InvocationTargetException;
import java.util.*;
import java.util.stream.Collectors;
import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import com.alibaba.fastjson.*;
import com.moral.common.bean.JsonData;
import com.moral.common.bean.PageResult;
import com.moral.common.xml.Version;
import com.moral.entity.Account;
import com.moral.entity.Device;
import com.moral.entity.MapBounds;
import com.moral.entity.MonitorPoint;
import com.alibaba.fastjson.JSONReader;
import com.alibaba.fastjson.TypeReference;
import com.moral.entity.*;
import com.moral.entity.alarm.AlarmConfig;
import com.moral.entity.alarm.AlarmConfigValue;
import com.moral.entity.alarm.AlarmSensorLevel;
import com.moral.entity.charts.DataSortCondition;
import com.moral.entity.layout.RealTimeDeviceLayout;
import com.moral.service.*;
import org.apache.commons.beanutils.BeanUtils;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang.ArrayUtils;
import org.apache.commons.net.ftp.FTPClient;
import org.apache.log4j.Logger;
import org.dom4j.Document;
import org.dom4j.Element;
import org.dom4j.io.SAXReader;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.cglib.beans.BeanMap;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;
import com.moral.common.bean.ResultBean;
import com.moral.common.util.ValidateUtil;
import org.springframework.util.ObjectUtils;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.servlet.ModelAndView;
import org.xml.sax.InputSource;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.moral.common.bean.Constants;
import com.moral.common.bean.JsonData;
import com.moral.common.bean.PageResult;
import com.moral.common.bean.ResultBean;
import com.moral.common.util.ValidateUtil;
import com.moral.common.xml.Version;
import com.moral.entity.alarm.AlarmSensorLevel;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
/**
 * The Class ScreenController.大屏接口
@@ -49,6 +59,8 @@
@RestController
@RequestMapping("/screen")
//@CrossOrigin(origins = "*", maxAge = 3600)
@SuppressWarnings({ "rawtypes", "unchecked", "unused" })
@Api(tags = "Screen", description = "大屏相关")
public class ScreenController {
   public  static Logger log = Logger.getLogger(ScreenController.class);
    @Resource
@@ -60,6 +72,8 @@
   SensorService sensorService;
   @Resource
   MonitorPointService monitorPointService;
   @Resource
   DeviceVersionService  deviceVersionService;
   /** The screen service. */
   @Resource
@@ -80,8 +94,8 @@
   private MachineActivateService machineActivateService;
   /** The resource. */
   @Value(value = "classpath:system/alarmLevels.json")
   private org.springframework.core.io.Resource resource;
//   @Value(value = "classpath:system/alarmLevels.json")
//   private org.springframework.core.io.Resource resource;
   /** The redis template. */
   @Resource
@@ -90,6 +104,10 @@
   /** The level key. */
   private String levelKey = "alarm_";
   @Resource
   private AlarmDailyService alarmDailyService;
   @Resource
   private OrganizationLayoutService orgLayoutService;
   /**
    * Screen login. 大屏登录
    * 
@@ -132,20 +150,55 @@
    *            the request
    * @return the alarm levels
    */
   @SuppressWarnings("resource")
   @GetMapping("alarm-levels")
   public Object getAlarmLevels(HttpServletRequest request, Integer orgId) {
   public Object getAlarmLevels(HttpServletRequest request, Optional<Integer> orgId, Optional<Integer> mpId,Optional<String> mac) {
        List<Map<String,Object>> sensorAlarmList = null;
      AlarmConfigValue alarmConfigValue = null;
      try {
         alarmConfigValue = alarmConfigService.queryValueByOrganizationId(orgId).get();
         Map<String,AlarmSensorLevel> alarmLevelMap = alarmConfigValue.getAlarmLevels();
         sensorAlarmList = alarmLevelMap.keySet().stream().map(key -> {
             AlarmSensorLevel alarmSensorLevel = alarmLevelMap.get(key);
            JSONObject alarmSensorLevelMap = (JSONObject) JSON.toJSON(alarmSensorLevel);
            alarmSensorLevelMap.put("key",key);
            return alarmSensorLevelMap;
         }).collect(Collectors.toList());
       try {
            AlarmConfig alarmConfig = null;
             if(orgId.isPresent()){
                 alarmConfig = alarmConfigService.queryValueByOrganizationId(orgId.get()).get();
             }else if(mpId.isPresent()){
                 alarmConfig = alarmConfigService.queryByMonitorPointId(mpId.get()).get();
             } else if(mac.isPresent() ){
                 alarmConfig = alarmConfigService.queryByDeviceMac(mac.get()).get();
             }
             //返回值处理
             if(alarmConfig.getValue()!=null&&alarmConfig.getValue().getAlarmLevels()!=null){
                 Map<String, AlarmSensorLevel> alarmLevelMap = alarmConfig.getValue().getAlarmLevels();
                 // 当前非取默认值,未设值将用默认值覆盖
                 Map<String,AlarmSensorLevel> defaultSensorLevelMap = null;
                 if(alarmConfig.getId()!=null){
                     AlarmConfigValue defaultAlarmValue = alarmConfigService.getDefaultAlarmConfigValue();
                     defaultSensorLevelMap = defaultAlarmValue.getAlarmLevels();
                 }
                 Map<String, AlarmSensorLevel> finalDefaultSensorLevelMap = defaultSensorLevelMap;
                 alarmLevelMap.entrySet().stream().forEach(entry -> {
                     //当 increment都为0时,替换为默认值
                     AlarmSensorLevel alarmSensorLevel = entry.getValue();
                     if(alarmSensorLevel.getIncrement()!=null){
                         boolean isAllZero = alarmSensorLevel.getIncrement().stream().allMatch(item ->  item == 0);
                         if(isAllZero){
                             AlarmSensorLevel defaultAlarmSensorLevel = finalDefaultSensorLevelMap==null?null:finalDefaultSensorLevelMap.get(entry.getKey());
                             if(defaultAlarmSensorLevel!=null){
                                 alarmSensorLevel.setIncrement(defaultAlarmSensorLevel.getIncrement());
                             }else{
                                 List<Float> tempList = Arrays.asList(0.0f,200.0f,500.0f);
                                 alarmSensorLevel.setIncrement(tempList);
                             }
                         }
                     }
                 });
                 //map to list
                 Map<String, AlarmSensorLevel> finalAlarmLevelMap = alarmLevelMap;
                 sensorAlarmList = alarmLevelMap.keySet().stream().map(key -> {
                     AlarmSensorLevel alarmSensorLevel = finalAlarmLevelMap.get(key);
                     Map<String,Object> alarmSensorLevelMap = new HashMap<>(BeanMap.create(alarmSensorLevel));
                     alarmSensorLevelMap.put("key",key);
                     return alarmSensorLevelMap;
                 }).collect(Collectors.toList());
             }else{
                 return  new ResultBean<>("提供参数有误,未查询到任何数据",ResultBean.FAIL);
             }
      } catch (Exception e) {
         e.printStackTrace();
         Map<String, Object> err = new LinkedHashMap<String, Object>();
@@ -171,6 +224,29 @@
   }
   /**
    *
    * @param dataSortCondition 数据排名查询条件
    * @return
    */
   public ResultBean<Map<String,Object>> getOrderData(DataSortCondition dataSortCondition) {
      ResultBean resultBean = new ResultBean();
      if(dataSortCondition.getCode()==null){
         resultBean.setCode(ResultBean.FAIL);
         resultBean.setMessage("code can't be null");
      } else if(dataSortCondition.getStyle()==null){
         resultBean.setCode(ResultBean.FAIL);
         resultBean.setMessage("style can't be null");
      }
      String code = dataSortCondition.getCode().toString();
      Region region = Region.create(code);
      if(region == null) {
         resultBean.setCode(ResultBean.FAIL);
         resultBean.setMessage("code is not in the correct format");
      }
      // todo
      return  null;
   }
   /**
    * Gets the day AQI by sensor.设备昨日的AQI指标
    *
    * @param request
@@ -189,9 +265,10 @@
    * @param request
    *            the request
    * @return the average by all
    * @throws Exception
    */
   @GetMapping("all-average")
   public Map<String, Object> getAllSensorAverageByDevice(HttpServletRequest request) {
   public Map<String, Object> getAllSensorAverageByDevice(HttpServletRequest request) throws Exception {
      Map<String, Object> parameters = getParametersStartingWith(request, null);
      return historyService.getAllSensorAverageByDevice(parameters);
   }
@@ -239,7 +316,7 @@
    * 大屏程序在线升级配置读取
    *********************************************/
   private String fileName = "Version.xml";
   private String ip = "121.40.92.176";
   private String ip = "47.96.19.115";
   private String userName = "ftp_user";
   private String userPwd = "qwer1234";
   private int port = 21;
@@ -253,8 +330,9 @@
         ftpClient.connect(ip, port);
         ftpClient.login(userName, userPwd);
         ftpClient.changeWorkingDirectory(path);
         //ftpClient.enterRemotePassiveMode();
         ftpClient.enterLocalPassiveMode();
         //ftpClient.enterLocalActiveMode();
         InputStream ins = ftpClient.retrieveFileStream(fileName);
         BufferedReader reader = new BufferedReader(new InputStreamReader(ins,"utf-8"));
         String line;
@@ -272,6 +350,19 @@
            ftpClient.logout();
            ftpClient.disconnect();
         }
//         String urlStr = "http://www.7drlb.com/apps/Version.xml";
//         URL realUrl = new URL(urlStr);
//         URLConnection connection = realUrl.openConnection();
//         connection.connect();
//         StringBuffer result = new StringBuffer();
//         BufferedReader in = new BufferedReader(new InputStreamReader(connection.getInputStream(), "utf-8"));
//         String line;
//         while ((line = in.readLine()) != null) {
//            result.append(line);
//         }
//         String content = result.toString();
         SAXReader saxReader = new SAXReader();
         Document document = saxReader.read(new InputSource(new ByteArrayInputStream(content.getBytes("utf-8"))));
         Element root = document.getRootElement();
@@ -283,6 +374,13 @@
      }
      return version;
   }
   public static void main(String[] args) {
      ScreenController sc = new ScreenController();
      Version a = sc.index();
      System.out.println(a.getVer());
   }
   /**
    * 地图接口
    * 开始
@@ -297,7 +395,7 @@
   @RequestMapping(value = "/map-page", method = RequestMethod.GET)
   public ModelAndView map(ModelAndView model, @RequestParam("areaCode")int code, @RequestParam("accountId")int accountId){
      Account account = accountService.getAccountById(accountId);
      String regionName = areaService.selectFullNameByCode(code);
      String regionName = areaService.queryFullNameByCode(code);
      if(account!=null&&regionName!=null){
         Object sensors = sensorService.queryAll();
         JSONObject params = new JSONObject();
@@ -317,7 +415,7 @@
         msg.append(" param[0] accountId:");
         msg.append(accountId);
         log.warn(msg);
         model.setViewName("401");
         model.setViewName("403");
         return model;
      }
   }
@@ -398,4 +496,106 @@
      jsonData.setExtData(returnMap);
      return jsonData;
   }
   @GetMapping("monitor_points")
   public ResultBean<List<MonitorPoint>> getMonitorPointsByOrganizationId(Integer orgId) {
      //Map<String, Object> parameters = getParametersStartingWith(request, null);
      List<MonitorPoint> monitorPoints = monitorPointService.getMonitorPointsByOrganizationId(orgId);
      return new ResultBean<List<MonitorPoint>>(monitorPoints);
   }
   @GetMapping("report_avg_datas")
   public ResultBean<List<Map<String, Object>>> getMonitorPointOrDeviceAvgData(HttpServletRequest request) throws Exception {
      Map<String, Object> parameters = getParametersStartingWith(request, null);
      parameters.put("type", "month");
      parameters.put("monitorPointId", parameters.remove("monitorPoint"));
      String sensorKey = parameters.remove("sensorKey").toString();
      List<String> sensorKeys = new ArrayList<String>();
      sensorKeys.add(sensorKey);
      parameters.put("sensors", sensorKeys);
      List<Map<String, Object>> list = historyMinutelyService.getMonitorPointOrDeviceAvgData(parameters);
      for (Map<String, Object> map : list) {
         String time = map.get("time").toString();
         time = time.substring(time.length() - 2);
         map.put("time", Integer.valueOf(time));
         map.put("value", map.remove(sensorKey));
      }
      return new ResultBean<List<Map<String, Object>>>(list);
   }
   @GetMapping("report_alarm_datas")
   public ResultBean<List<Map<String, Object>>> getAlarmData(HttpServletRequest request) throws Exception {
      Map<String, Object> parameters = getParametersStartingWith(request, null);
      parameters.put("type", "month");
      String sensorKey = "list";
      if (ObjectUtils.isEmpty(parameters.get("sensorKey"))) {
         parameters.put("description", "description");
      } else {
         sensorKey = parameters.remove("sensorKey").toString();
         List<String> sensorKeys = new ArrayList<String>();
         sensorKeys.add(sensorKey);
         parameters.put("sensors", sensorKeys);
      }
      if (!ObjectUtils.isEmpty(parameters.get("organizationId"))) {
         if (!Constants.isNotSpecialOrgId(Integer.valueOf(parameters.get("organizationId").toString()))) {
            parameters.remove("organizationId");
         }
      }
      Map pieData = alarmDailyService.getPieData(parameters);
      List<Map<String, Object>> list = (List<Map<String, Object>>) pieData.get(sensorKey);
      return new ResultBean<List<Map<String, Object>>>(list);
   }
   /**
    * 根据监控点id获取所属设备version数据集
    * @param mptid
    * @return
    */
   @GetMapping("getvers")
   public ResultBean<List<Integer>> getVersions(Integer mptid){
      return  new ResultBean<>(monitorPointService.queryVersionsById(mptid));
   }
   @GetMapping("region_ranking_data")
   @ApiOperation(value = "获取排名数据", notes = "获取排名数据")
   @ApiImplicitParams(value = {
         @ApiImplicitParam(name = "regionCode", value = "区域码", required = true, paramType = "query", dataType = "String"),
         @ApiImplicitParam(name = "dimension", value = "维度(profession、region、monitorPoint选一)", required = true, paramType = "query", dataType = "String"),
         @ApiImplicitParam(name = "sensorKey", value = "传感器key", required = true, paramType = "query", dataType = "String"),
         @ApiImplicitParam(name = "accountId", value = "账户id", required = true, paramType = "query", dataType = "int"),
   })
   public ResultBean<List<Map<String, Object>>> getRegionRankingData(HttpServletRequest request){
      Map<String, Object> parameters = getParametersStartingWith(request, null);
      List<Map<String, Object>> list = historyService.getRegionRankingData(parameters);
      return new ResultBean<List<Map<String, Object>>>(list);
   }
   // todo
   @Value(value = "classpath:system/realTimeMonitorLayout.json")
   private org.springframework.core.io.Resource resource;
   @ApiOperation(value = "获取实时监控页面布局", notes = "")
   @ApiImplicitParams(value = {
         @ApiImplicitParam(name = "primaryKey",defaultValue = "898607b0101730391967", value = "值为:设备mac或监控站id", required = true, paramType = "query", dataType = "String"),
         @ApiImplicitParam(name = "type", defaultValue = "device",value = "值为:'monitorPoint'或'device'", required = true, paramType = "query", dataType = "String"),
   })
   @GetMapping("rtm-layout")
   public ResultBean realTimeMonitorLayout(String primaryKey,String type){
      RealTimeDeviceLayout rtdLayout = null;
      if(type != null && type.equals("device")) {
         Device device = deviceService.getDeviceByMac(primaryKey,false);
         if(device!= null
         && device.getOrganizationIds()!=null
         && device.getOrganizationIds().size() >0
         && device.getDeviceVersionId()!=null) {
             Integer orgId = device.getOrganizationIds().get(0);
             DeviceVersion deviceVersion = deviceVersionService.queryVersionById(device.getDeviceVersionId());
              rtdLayout = orgLayoutService.queryRtdLayoutWithUnit(orgId,deviceVersion.getVersion());
         }else {
            return  ResultBean.fail();
         }
      }
      return new ResultBean(rtdLayout);
   }
}