kaiyu
2020-10-20 ec192d94be582e5fa504cb355090ce98e0880e65
src/main/java/com/moral/controller/WebController.java
@@ -1,23 +1,29 @@
package com.moral.controller;
import com.moral.common.util.BeanUtils;
import com.auth0.jwt.exceptions.JWTDecodeException;
import com.moral.common.bean.ResultBean;
import com.moral.common.exception.WebAuthException;
import com.moral.common.util.*;
import com.moral.common.webAnno.UserLoginToken;
import com.moral.entity.AreaNames;
import com.moral.entity.Device;
import com.moral.entity.MonitorPoint;
import com.moral.entity.Organization;
import com.moral.service.AccountService;
import com.moral.service.DictionaryDataService;
import com.moral.service.OrganizationService;
import com.moral.service.WebTokenService;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import com.moral.service.*;
import com.moral.util.DateUtil;
import com.moral.util.LatLngTransformation;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import jdk.nashorn.internal.runtime.logging.Logger;
import org.springframework.util.ObjectUtils;
import org.springframework.web.bind.annotation.*;
import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import javax.servlet.http.HttpServletResponse;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.stream.Collectors;
import static com.moral.common.util.WebUtils.getParametersStartingWith;
@@ -34,66 +40,286 @@
    OrganizationService organizationService;
    @Resource
    WebTokenService webTokenService;
    @Resource
    RedisHashUtil redisHashUtil;
    @Resource
    HistoryMinutelyService historyMinutelyService;
    @Resource
    MonitorPointService monitorPointService;
    @Resource
    DeviceService deviceService;
    @RequestMapping("login")
    public Map<String, Object> login(HttpServletRequest request){
    @UserLoginToken
    @GetMapping("test")
    public String add() {
        return "test success!";
    }
    /**
    * @Description: 登陆接口
            * @Param: [parameters]
            * @return: java.util.Map<java.lang.String,java.lang.Object>
            * @Author: 下雨听风
            * @Date: 2020/10/19
            */
    @PostMapping("login")
    public Map<String, Object> login(@RequestBody Map<String, Object> parameters) {
        Map<String, Object> resultMap = new HashMap<String, Object>();
        Map<String, Object> parameters = getParametersStartingWith(request, null);
        if (!(parameters.containsKey("account") && parameters.containsKey("password"))) {
            resultMap.put("msg", "用户名及密码不允许为空!");
            resultMap.put("accountId", -1);
        } else {
            resultMap = accountService.screenLoginNew(parameters);
            // 添加返回行政区信息字符串操作
            Object orgId = resultMap.get("orgId");
            if (resultMap.get("orgId") != null && resultMap.get("orgId") instanceof Integer) {
                StringBuilder areaNamesBuilder = new StringBuilder("中国");
                //判断是否为本公司开发者
                if (!((Integer) orgId).equals(dictionaryDataService.querySupperOrgId())) {
                    //不是本公司开发者则获取用户所属地区
                    Organization organization = organizationService.getOrganizationById((Integer) orgId);
                    if (organization.getAreaNames() != null) {
                        Map<String, String> areaNameMap = BeanUtils.beanToMap(organization.getAreaNames());
                        List<String> names = areaNameMap.entrySet().stream().filter(item -> {
                            return item.getValue() != null;
                        }).map(item -> {
                            return item.getValue();
                        }).collect(Collectors.toList());
                        AreaNames areaNames = organization.getAreaNames();
                        areaNamesBuilder.append("/");
                        areaNamesBuilder.append(String.join("/", names));
                    }
                    // 企业用户
                    if (organization.getRank() != null && organization.getRank() == 0) {
                        resultMap.put("type", "enterprise");
                    } else {
                        resultMap.put("type", "government");
                    }
                    Number mapAreaCode = null;
                    if (organization.getVillageCode() != null) {
                        mapAreaCode = organization.getVillageCode();
                    } else if (organization.getTownCode() != null) {
                        mapAreaCode = organization.getTownCode();
                    } else if (organization.getAreaCode() != null) {
                        mapAreaCode = organization.getAreaCode();
                    } else if (organization.getCityCode() != null) {
                        mapAreaCode = organization.getCityCode();
                    } else if (organization.getProvinceCode() != null) {
                        mapAreaCode = organization.getProvinceCode();
                    }
                    resultMap.put("mapAreaCode", mapAreaCode.toString());
                }
                resultMap.put("mapPath", areaNamesBuilder.toString());
                String accountId= String.valueOf(resultMap.get("accountId"));
                resultMap.put("token",webTokenService.getToken(accountId));
            resultMap = accountService.webLogin(parameters);
            String accountId = String.valueOf(resultMap.get("accountId"));
            if (!accountId.equals("-1")) {
                redisHashUtil.deleteMapVal("webToken",accountId);
                resultMap.put("token", webTokenService.getToken(accountId));
            }
        }
        return resultMap;
    }
    /**
    * @Description: 退出接口
            * @Param: [request]
            * @return: java.util.Map<java.lang.String,java.lang.Object>
            * @Author: 下雨听风
            * @Date: 2020/10/19
            */
    @UserLoginToken
    @GetMapping("test")
    public String add(){
        return "test success!";
    @PostMapping("logout")
    public Map<String, Object> logout(HttpServletRequest request) {
        Map<String, Object> resultMap = new HashMap<>();
        String token = request.getHeader("token");
        String id =  WebTokenUtils.getIdBytoken(token);
        redisHashUtil.addMapOne("webToken", String.valueOf(id),token);
        resultMap.put("msg", "退出成功!");
        return resultMap;
    }
    /**
    * @Description:
            * @Param: [request]
            * @return: java.util.Map<java.lang.String,java.lang.Object>
            * @Author: 下雨听风
            * @Date: 2020/10/19
            */
    @UserLoginToken
    @GetMapping("getAccountInfo")
    public Map<String, Object> getAccountInfo(HttpServletRequest request) {
        String token = request.getHeader("token");
        String id = "";
        try {
            id = WebTokenUtils.getIdBytoken(token);
        } catch (JWTDecodeException e) {
            throw new WebAuthException("401,token无效");
        }
        Map<String, Object> resultMap = accountService.getAccountInfoById(id);
        Object orgId = resultMap.get("orgId");
        if (resultMap.get("orgId") != null && resultMap.get("orgId") instanceof Integer) {
            StringBuilder areaNamesBuilder = new StringBuilder("中国");
            //判断是否为本公司开发者
            if (!((Integer) orgId).equals(dictionaryDataService.querySupperOrgId())) {
                //不是本公司开发者则获取用户所属地区
                Organization organization = organizationService.getOrganizationById((Integer) orgId);
                if (organization.getAreaNames() != null) {
                    Map<String, String> areaNameMap = BeanUtils.beanToMap(organization.getAreaNames());
                    List<String> names = areaNameMap.entrySet().stream().filter(item -> {
                        return item.getValue() != null;
                    }).map(item -> {
                        return item.getValue();
                    }).collect(Collectors.toList());
                    AreaNames areaNames = organization.getAreaNames();
                    areaNamesBuilder.append("/");
                    areaNamesBuilder.append(String.join("/", names));
                }
                // 企业用户
                if (organization.getRank() != null && organization.getRank() == 0) {
                    resultMap.put("type", "enterprise");
                } else {
                    resultMap.put("type", "government");
                }
                Number mapAreaCode = null;
                if (organization.getVillageCode() != null) {
                    mapAreaCode = organization.getVillageCode();
                } else if (organization.getTownCode() != null) {
                    mapAreaCode = organization.getTownCode();
                } else if (organization.getAreaCode() != null) {
                    mapAreaCode = organization.getAreaCode();
                } else if (organization.getCityCode() != null) {
                    mapAreaCode = organization.getCityCode();
                } else if (organization.getProvinceCode() != null) {
                    mapAreaCode = organization.getProvinceCode();
                }
                resultMap.put("mapAreaCode", mapAreaCode.toString());
            }
            resultMap.put("mapPath", areaNamesBuilder.toString());
            String accountId = String.valueOf(resultMap.get("accountId"));
            resultMap.put("token", webTokenService.getToken(accountId));
        }
        return resultMap;
    }
    /**
    * @Description: 获取传感器平均值
            * @Param: [request]
            * @return: com.moral.common.bean.ResultBean<java.util.List<java.util.Map<java.lang.String,java.lang.Object>>>
            * @Author: 下雨听风
            * @Date: 2020/10/19
            */
    @UserLoginToken
    @GetMapping("report_avg_datas")
    public ResultBean<List<Map<String, Object>>> getMonitorPointOrDeviceAvgData(HttpServletRequest request)
            throws Exception {
        Map<String, Object> parameters = WebUtils.getParametersStartingWith(request, null);
        //该方法用于判断时间是具体到年月日
        ParameterUtils.getTimeType4Time(parameters);
        Object sensorKey = parameters.remove("sensorKey");
        parameters.put("sensors", Arrays.asList(sensorKey));
        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));
            if(parameters.get("type").equals("day")){
                map.put("time", Integer.valueOf(time)+1);
            }
            map.put("value", map.remove(sensorKey));
        }
        return new ResultBean<List<Map<String, Object>>>(list);
    }
    /**
    * @Description: 获取某个站点设备信息
            * @Param: [request]
            * @return: com.moral.common.bean.ResultBean<java.util.List<com.moral.entity.MonitorPoint>>
            * @Author: 下雨听风
            * @Date: 2020/10/19
            */
    @UserLoginToken
    @GetMapping("monitorpoints-devices")
    public ResultBean<List<MonitorPoint>> getMonitorPointsAndDevicesByRegion(HttpServletRequest request)
            throws Exception {
        Map<String, Object> parameters = WebUtils.getParametersStartingWith(request, null);
        List<MonitorPoint> monitorPoints = monitorPointService.getMonitorPointsAndDevicesByRegion(parameters);
        return new ResultBean<List<MonitorPoint>>(monitorPoints);
    }
    /**
    * @Description: 获取坐标接口,前端用于建点
            * @Param: [request]
            * @return: com.moral.common.bean.ResultBean<java.util.List<com.moral.entity.Device>>
            * @Author: 下雨听风
            * @Date: 2020/10/19
            */
   /* @UserLoginToken*/
    @GetMapping("coordinates")
    public ResultBean<List<Device>> getDeviceCoordinatesAndState(HttpServletRequest request){
        Map<String, Object> parameters = WebUtils.getParametersStartingWith(request, null);
        ParameterUtils.getRegionType4RegionCode(parameters);
        return new ResultBean<List<Device>>(deviceService.queryDevice(parameters));
    }
    /**
    * @Description: 根据monitorId获取该站点下每一台设备具体传感器的五分钟平均值
            * @Param: []
            * @return: com.moral.common.bean.ResultBean<java.util.Map<java.lang.String,java.lang.Object>>
            * @Author: 下雨听风
            * @Date: 2020/10/19
            */
    @GetMapping("fiveMinuteAvgData")
    public ResultBean<List<Map<String, Object>>> getSensorFiveMinuteAvgData(HttpServletRequest request){
        //获取参数,传感器和monitorpointId
        Map<String, Object> parameters = WebUtils.getParametersStartingWith(request, null);
        if((!parameters.containsKey("sensorKey"))||(!parameters.containsKey("monitorPointId")))
            return  ResultBean.fail("参数为null");
        String sensorKey = (String) parameters.get("sensorKey");
        Integer monitorPointId = Integer.parseInt((String) parameters.get("monitorPointId"));
        //根据monitorpointId获取该站点下所有设备mac集合
        List<Device> devices = deviceService.getDevicesByMonitorPointId(monitorPointId);
        if(ObjectUtils.isEmpty(devices))
            return ResultBean.fail("站点下无设备或monitorPointId错误");
        List<String> macs = new ArrayList<>();
        devices.forEach(p->{
            macs.add(p.getMac());
        });
        //根据时间和mac号集合以及传感器参数查询五分钟平均数据
        Map<String, Object> timeAndYearMonth = getTimeAndYearMonthForFiveMinuteData();
        String time= (String) timeAndYearMonth.get("time");
        String yearAndMonth = (String) timeAndYearMonth.get("yearAndMonth");
        parameters.put("time",time);
        parameters.put("yearAndMonth",yearAndMonth);
        parameters.put("macs",macs);
        List<Map<String, Object>> datas = historyMinutelyService.getFiveMinutesDataByMacsAndTime(parameters);
        datas = insertDeviceInfo(datas,devices);
        return new ResultBean<List<Map<String, Object>>>(datas);
    }
    /**
    * @Description: 返回结果添加设备经纬度以及state
            * @Param: [datas, devices]
            * @return: java.util.List<java.util.Map<java.lang.String,java.lang.Object>>
            * @Author: 下雨听风
            * @Date: 2020/10/19
            */
    public List<Map<String, Object>> insertDeviceInfo(List<Map<String, Object>> datas,List<Device> devices ){
        Map<String,Device> map = new HashMap<>();
        devices.forEach(p->{
            map.put(p.getMac(),p);
        });
        datas.forEach(p->{
            String mac = (String) p.get("mac");
            Device device = map.get(mac);
            List list = LatLngTransformation.Convert_BD09_To_GCJ02(device.getLatitude(), device.getLongitude());
            p.put("longitude",list.get(0));
            p.put("latitude",list.get(1));
            p.put("state",device.getState());
        });
        return datas;
    }
    /**
    * @Description: 根据当前时间判断要获取五分钟平均数据在数据库中的时间
            * @Param: []
            * @return: java.lang.String
            * @Author: 下雨听风
            * @Date: 2020/10/19
            */
    private Map<String, Object> getTimeAndYearMonthForFiveMinuteData() {
        Map<String, Object> map = new HashMap<>();
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        Date date = new Date();
        String minute = DateUtil.getMinute(date);
        String year = "";
        String month = "";
        String yearAndMonth = "";
        String startTime = "";
        Integer endMinute = Integer.parseInt(String.valueOf(minute.charAt(minute.length() - 1)));
        if (endMinute >= 6||endMinute==0) {//分钟结尾如果是 6 7 8 9 0   比如12:16,12:20进入, 则获取12:10-12:15的数据
            date = DateUtil.rollMinute(date, -1);
            StringBuilder time = new StringBuilder(sdf.format(date));
            startTime = time.replace(15, 19, "0:00").toString();
        }else {// 分钟结尾如果是1 2 3 4 5 则获取上个五分钟数据 比如12:11分钟进入 则获取12:05-12:10的数据
            date = DateUtil.rollMinute(date, -9);
            StringBuilder time = new StringBuilder(sdf.format(date));
            startTime = time.replace(15, 19, "5:00").toString();
        }
        year = DateUtil.getYear(date);
        month = DateUtil.getMonth(date);
        yearAndMonth = year + month;
        map.put("time", startTime);
        map.put("yearAndMonth", yearAndMonth);
        return map;
    }
}