package com.bonus.sgzb.material.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson2.JSONObject;
import com.bonus.sgzb.base.domain.MaTypeKeeper;
import com.bonus.sgzb.base.mapper.MaTypeMapper;
import com.bonus.sgzb.common.core.constant.HttpStatus;
import com.bonus.sgzb.common.core.constant.RoleConstans;
import com.bonus.sgzb.common.core.constant.TokenConstants;
import com.bonus.sgzb.common.core.exception.ServiceException;
import com.bonus.sgzb.common.core.utils.DateUtils;
import com.bonus.sgzb.common.core.utils.HttpHelper;
import com.bonus.sgzb.common.core.utils.StringHelper;
import com.bonus.sgzb.common.core.web.domain.AjaxResult;
import com.bonus.sgzb.common.redis.service.RedisService;
import com.bonus.sgzb.common.security.utils.SecurityUtils;
import com.bonus.sgzb.material.config.ExceptionEnum;
import com.bonus.sgzb.material.config.FieldGenerator;
import com.bonus.sgzb.material.domain.*;
import com.bonus.sgzb.material.mapper.IotMachineMapper;
import com.bonus.sgzb.material.mapper.ReportAlarmMapper;
import com.bonus.sgzb.material.service.IotMachineService;
import com.bonus.sgzb.system.api.domain.SysUser;
import lombok.Data;
import lombok.extern.slf4j.Slf4j;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.transaction.interceptor.TransactionAspectSupport;

import javax.annotation.Resource;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.concurrent.TimeUnit;

/**
 * iot设备管理实现层
 * @author ma_sh
 */
@Service
@Slf4j
public class IotMachineServiceImpl implements IotMachineService {

    @Resource
    private IotMachineMapper iotMachineMapper;

    @Resource
    private RedisService redisService;

    @Resource
    private MaTypeMapper maTypeMapper;

    @Resource
    private ReportAlarmMapper reportAlarmMapper;

    /**
     * 添加设备-保存
     *
     * @param iotDto
     * @return
     */
    @Override
    public AjaxResult add(IotDto iotDto) {
        if (iotDto == null || iotDto.getIotCode() == null || iotDto.getIotType() == null) {
            return AjaxResult.error(ExceptionEnum.PARAM_NULL.getCode(), ExceptionEnum.PARAM_NULL.getMsg());
        }
        //根据前端传入设备编号判重
        IotVo iotVo = iotMachineMapper.selectIotCode(iotDto);
        if (iotVo != null) {
            return AjaxResult.error(ExceptionEnum.IOT_CODE_DUPLICATE.getCode(), ExceptionEnum.IOT_CODE_DUPLICATE.getMsg());
        }
        //后端生成二维码编号，需判重，确保表中数据唯一性
        String qrCode = FieldGenerator.generateField();
        // 设置最大尝试次数10，避免无限循环
        int maxAttempts = 10;
        for (int attempt = 0; attempt < maxAttempts; attempt++) {
            if (iotMachineMapper.selectQrCode(qrCode) == 0) {
                iotDto.setQrCode(qrCode);
                // 找到唯一的qrCode，退出循环
                break;
            } else {
                // 生成新的qrCode
                qrCode = FieldGenerator.generateField();
            }
        }
        iotDto.setCreateBy(SecurityUtils.getLoginUser().getUserid().toString());
        try {
            // 进行设备添加
            int res = iotMachineMapper.add(iotDto);
            if (res == 0) {
                // 如果添加失败，返回保存到数据库异常的错误信息
                throw new ServiceException(ExceptionEnum.SAVE_TO_DATABASE.getMsg());
            } else {
                // 添加成功，返回成功的消息和新增的记录数
                return AjaxResult.success(ExceptionEnum.SUCCESS.getMsg(), res);
            }
        } catch (Exception e) {
            log.error("Error saving to database: " + e.getMessage());
            // 捕获所有异常，返回通用的数据库操作异常信息
            return AjaxResult.error(ExceptionEnum.SAVE_TO_DATABASE.getCode(), ExceptionEnum.SAVE_TO_DATABASE.getMsg());
        }
    }

    /**
     * 设备管理-修改
     *
     * @param iotDto
     * @return
     */
    @Override
    public AjaxResult update(IotDto iotDto) {
        if (iotDto == null || iotDto.getIotId() == null) {
            return AjaxResult.error(ExceptionEnum.PARAM_NULL.getCode(), ExceptionEnum.PARAM_NULL.getMsg());
        }
        IotVo iotVo = iotMachineMapper.selectIotCode(iotDto);
        if (iotVo != null && !iotVo.getIotId().equals(iotDto.getIotId())) {
            return AjaxResult.error(ExceptionEnum.IOT_CODE_DUPLICATE.getCode(), ExceptionEnum.IOT_CODE_DUPLICATE.getMsg());
        }
        iotDto.setUpdateBy(SecurityUtils.getLoginUser().getUserid().toString());
        try {
            //设备修改
            int res = iotMachineMapper.update(iotDto);
            if (res == 0) {
                // 如果修改失败，返回修改到数据库异常的错误信息
                throw new ServiceException(ExceptionEnum.UPDATE_TO_DATABASE.getMsg());
            } else {
                // 修改成功，返回成功的消息和修改的记录数
                return AjaxResult.success(ExceptionEnum.SUCCESS.getMsg(), res);
            }
        } catch (Exception e) {
            log.error("Error updating to database: " + e.getMessage());
            //捕获异常
            return AjaxResult.error(ExceptionEnum.UPDATE_TO_DATABASE.getCode(), ExceptionEnum.UPDATE_TO_DATABASE.getMsg());
        }
    }

    /**
     * 获取设备列表
     *
     * @param iotDto
     * @return
     */
    @Override
    public List<IotVo> getIotList(IotDto iotDto) {
        return iotMachineMapper.getIotList(iotDto);
    }

    /**
     * 删除设备
     *
     * @param iotId
     * @return
     */
    @Override
    public AjaxResult deleteById(Long iotId) {
        //先进行判断，绑定设备的iot设备无法删除
        IotVo iotVo = iotMachineMapper.selectById(iotId);
        if (iotVo.getBindStatus() == 0) {
            return AjaxResult.error(ExceptionEnum.IOT_TO_DELETE.getCode(), ExceptionEnum.IOT_TO_DELETE.getMsg());
        }
        try {
            // 执行设备删除操作
            int res = iotMachineMapper.deleteById(iotId);
            if (res == 0) {
                // 如果删除操作未成功，返回删除数据库异常的错误信息
                return AjaxResult.error(ExceptionEnum.DELETE_TO_DATABASE.getCode(), ExceptionEnum.DELETE_TO_DATABASE.getMsg());
            } else {
                // 删除成功，返回成功的消息和受影响的记录数
                return AjaxResult.success(ExceptionEnum.SUCCESS.getMsg(), res);
            }
        } catch (Exception e) {
            log.error("Error deleting from database: " + e.getMessage());
            // 捕获所有异常，返回通用的数据库操作异常信息
            return AjaxResult.error(ExceptionEnum.DELETE_TO_DATABASE.getCode(), ExceptionEnum.DELETE_TO_DATABASE.getMsg());
        }
    }

    /**
     * 绑定设备
     *
     * @param iotDto
     * @return
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public AjaxResult bind(IotDto iotDto) {
        if (iotDto == null || iotDto.getIotId() == null || iotDto.getMaCode() == null) {
            return AjaxResult.error(ExceptionEnum.PARAM_NULL.getCode(), ExceptionEnum.PARAM_NULL.getMsg());
        }
        iotDto.setBinder(SecurityUtils.getLoginUser().getUserid().toString());
        int res;
        try {
            //绑定设备
            res = iotMachineMapper.bind(iotDto);
            if (res == 0) {
                throw new ServiceException(ExceptionEnum.BIND_TO_DATABASE.getMsg());
            }
            //更新绑定状态
            res = iotMachineMapper.updateBindStatus(iotDto);
            if (res == 0) {
                throw new ServiceException(ExceptionEnum.UPDATE_TO_DATABASE.getMsg());
            }
        } catch (Exception e) {
            log.error("设备绑定异常:{}", e.getMessage());
            // 添加事务回滚逻辑，保证全部成功或者全部失败
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
            return AjaxResult.error(ExceptionEnum.UPDATE_TO_DATABASE.getCode(), ExceptionEnum.UPDATE_TO_DATABASE.getMsg());
        }
        return AjaxResult.success(ExceptionEnum.SUCCESS.getMsg(), res);
    }

    /**
     * 解绑设备
     *
     * @param iotDto
     * @return
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public AjaxResult unbind(IotDto iotDto) {
        if (iotDto == null || iotDto.getIotId() == null) {
            return AjaxResult.error(ExceptionEnum.PARAM_NULL.getCode(), ExceptionEnum.PARAM_NULL.getMsg());
        }
        iotDto.setUnBinder(SecurityUtils.getLoginUser().getUserid().toString());
        int res;
        try {
            //解绑设备
            res = iotMachineMapper.unbind(iotDto);
            if (res == 0) {
                throw new ServiceException(ExceptionEnum.UN_BIND_TO_DATABASE.getMsg());
            }
            //更新绑定状态
            res = iotMachineMapper.updateUnBindStatus(iotDto);
            if (res == 0) {
                throw new ServiceException(ExceptionEnum.UPDATE_TO_DATABASE.getMsg());
            }
        } catch (Exception e) {
            log.error("设备解绑异常:{}", e.getMessage());
            // 添加事务回滚逻辑，保证入库全部成功或者全部失败
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
            return AjaxResult.error(ExceptionEnum.UPDATE_TO_DATABASE.getCode(), ExceptionEnum.UPDATE_TO_DATABASE.getMsg());
        }
        return AjaxResult.success(ExceptionEnum.SUCCESS.getMsg(), res);
    }

    /**
     * 根据类型id查询设备绑定列表
     *
     * @param iotDto
     * @return
     */
    @Override
    public List<IotVo> getTypeList(IotDto iotDto) {
        if (iotDto == null || iotDto.getMaCode() == null) {
            throw new ServiceException(ExceptionEnum.PARAM_NULL.getMsg());
        }
        return iotMachineMapper.getTypeList(iotDto);
    }

    /**
     * 根据iot设备类型查询设备编码
     *
     * @param iotDto
     * @return
     */
    @Override
    public AjaxResult selectList(IotDto iotDto) {
        if (iotDto != null && iotDto.getIotTypeId() != null) {
            // 如果传入了iot设备类型，根据iot设备类型查询设备编码
            List<IotCodeVo> iotCodeList = iotMachineMapper.selectCodeList(iotDto.getIotTypeId());
            return AjaxResult.success(iotCodeList);
        } else {
            // 如果iotDto为null或者iotDto的iotType为null，单独查询iot设备类型列表
            List<IotTypeVo> iotTypeList = iotMachineMapper.selectList();
            return AjaxResult.success(iotTypeList);
        }
    }

    /**
     * 查询iot绑定记录
     *
     * @param iotDto
     * @return
     */
    @Override
    public List<IotRecordVo> getRecordList(IotDto iotDto) {
        if (iotDto == null || iotDto.getIotId() == null) {
            throw new ServiceException(ExceptionEnum.PARAM_NULL.getMsg());
        }
        return iotMachineMapper.getRecordList(iotDto);
    }

    /**
     * 获取定位
     * @param iotLocationVo
     * @return
     */
    @Override
    public IotLocationVo getLocation(IotLocationVo iotLocationVo) {
        log.info("getLocation:{}", iotLocationVo);
        if (iotLocationVo == null || iotLocationVo.getIotId() == null) {
            throw new ServiceException(ExceptionEnum.PARAM_NULL.getMsg());
        }
        List<String> list=new ArrayList<>();
        Map<String,Object> map=new HashMap<>();
        //从redis中获取token
        String redisCode = redisService.getCacheObject(TokenConstants.TOKEN_LOCATION);
        //如果token为空，先去调登录接口，获取token
        if (redisCode == null){
            redisCode = HttpHelper.getIotToken();
            redisService.setCacheObject(TokenConstants.TOKEN_LOCATION,redisCode,23L, TimeUnit.HOURS);
        }
        map.clear();
        list.add(iotLocationVo.getIotId());
        map.put("deviceids",list);
        String param = JSON.toJSONString(map);
        String res = HttpHelper.doPost(HttpStatus.LAST_POSITION_URL+redisCode,param);
        //对返回的结果进行解析
        IotLocationVo iotLocationVoRes = resultDataHandler(res);
        log.info("返回结果resultDataHandler:{}", iotLocationVoRes);
        return iotLocationVoRes;
    }

    /**
     * 查询行程
     * @param iotLocationVo
     * @return
     */
    @Override
    public String searchItinerary(IotLocationVo iotLocationVo) {
        log.info("searchItinerary:{}", iotLocationVo);
        if (iotLocationVo == null || iotLocationVo.getBeginTime() == null || iotLocationVo.getEndTime() == null) {
            throw new ServiceException(ExceptionEnum.PARAM_NULL.getMsg());
        }
        Map<String,Object> map=new HashMap<>();
        //从redis中获取token
        String redisCode = redisService.getCacheObject(TokenConstants.TOKEN_LOCATION);
        //如果token为空，先去调登录接口，获取token
        if (redisCode == null){
            redisCode = HttpHelper.getIotToken();
            redisService.setCacheObject(TokenConstants.TOKEN_LOCATION,redisCode,23L, TimeUnit.HOURS);
        }
        map.clear();
        map.put("deviceid",iotLocationVo.getIotId());
        map.put("begintime",iotLocationVo.getBeginTime());
        map.put("endtime",iotLocationVo.getEndTime());
        String param = JSON.toJSONString(map);
        String res = HttpHelper.doPost(HttpStatus.QUERY_TRIPS_URL+redisCode,param);
        return res;
    }

    /**
     * 查询停留点
     * @param iotLocationVo
     * @return
     */
    @Override
    public List<IotLocationVo> reportParkDetailByTime(IotLocationVo iotLocationVo) {

        log.info("reportParkDetailByTime:{}", iotLocationVo);
        if (iotLocationVo == null || iotLocationVo.getBeginTime() == null || iotLocationVo.getEndTime() == null) {
            throw new ServiceException(ExceptionEnum.PARAM_NULL.getMsg());
        }
        Map<String,Object> map=new HashMap<>();
        //从redis中获取token
        String redisCode = redisService.getCacheObject(TokenConstants.TOKEN_LOCATION);
        //如果token为空，先去调登录接口，获取token
        if (redisCode == null){
            redisCode = HttpHelper.getIotToken();
            redisService.setCacheObject(TokenConstants.TOKEN_LOCATION,redisCode,23L, TimeUnit.HOURS);
        }
        map.clear();
        map.put("deviceid",iotLocationVo.getIotId());
        map.put("begintime",iotLocationVo.getBeginTime());
        map.put("endtime",iotLocationVo.getEndTime());
        String param = JSON.toJSONString(map);
        String res = HttpHelper.doPost(HttpStatus.REPORT_PARK_DETAIL_BY_TIME_URL+redisCode,param);
        //对返回的结果进行解析
        List<IotLocationVo> iotLocationVoList = resultReportParkDetailByTime(res);
        log.info("resultReportParkDetailByTime:{}", iotLocationVoList);
        return iotLocationVoList;
    }

    /**
     * 解析停留点返回报文
     * @param res
     * @return
     */
    private List<IotLocationVo> resultReportParkDetailByTime(String res) {
        if (res == null) {
            throw new ServiceException(ExceptionEnum.RETURN_DATA_IS_EMPTY.getMsg());
        }
        List<IotLocationVo> iotLocationVoList = new ArrayList<>();
        JSONObject object = JSONObject.parseObject(res);
        String cause = object.getString("cause");
        String status = object.getString("status");
        if ("OK".equals(cause) && "0".equals(status)) {
            String records = object.getString("records");
            //判断返回结果是否为空
            if (records != null){
                JSONArray jsonArray = JSON.parseArray(records);
                for (int i = 0; i < jsonArray.size(); i++) {
                    IotLocationVo iotLocationVo = new IotLocationVo();
                    JSONObject jsonObject = JSONObject.from(jsonArray.getJSONObject(i));
                    iotLocationVo.setBeginTime(jsonObject.getString("starttime"));
                    iotLocationVo.setEndTime(jsonObject.getString("endtime"));
                    iotLocationVo.setAddress(jsonObject.getString("address"));
                    iotLocationVoList.add(iotLocationVo);
                }
            }
        }
        return iotLocationVoList;
    }

    /**
     * 绑定设备APP
     * @param iotDto
     * @return
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public AjaxResult bindApp(IotDto iotDto) {
        if (iotDto == null || iotDto.getIotCode() == null || iotDto.getMaCode() == null) {
            return AjaxResult.error(ExceptionEnum.PARAM_NULL.getCode(), ExceptionEnum.PARAM_NULL.getMsg());
        }

        iotDto.setBinder(SecurityUtils.getLoginUser().getUserid().toString());
        //根据输入的iot编码查询iot设备
        IotVo iotVo = iotMachineMapper.selectIotCode(iotDto);
        if (iotVo == null) {
            return AjaxResult.error(ExceptionEnum.IOT_ENCODING_ERROR.getCode(), ExceptionEnum.IOT_ENCODING_ERROR.getMsg());
        }
        iotDto.setIotId(iotVo.getIotId());
        int res;
        try {
            //绑定设备
            res = iotMachineMapper.bind(iotDto);
            if (res == 0) {
                throw new ServiceException(ExceptionEnum.BIND_TO_DATABASE.getMsg());
            }
            //更新绑定状态
            res = iotMachineMapper.updateBindStatus(iotDto);
            if (res == 0) {
                throw new ServiceException(ExceptionEnum.UPDATE_TO_DATABASE.getMsg());
            }
        } catch (Exception e) {
            log.error("设备绑定异常:{}", e.getMessage());
            // 添加事务回滚逻辑，保证全部成功或者全部失败
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
            return AjaxResult.error(ExceptionEnum.UPDATE_TO_DATABASE.getCode(), ExceptionEnum.UPDATE_TO_DATABASE.getMsg());
        }
        return AjaxResult.success(ExceptionEnum.SUCCESS.getMsg(), res);
    }

    /**
     * 报警记录
     * @param iotLocationVo
     * @return
     */
    @Override
    public List<IotLocationVo> reportAlarm(IotLocationVo iotLocationVo) {
        log.info("reportAlarm:{}", iotLocationVo);
        if (iotLocationVo == null || iotLocationVo.getIotId() == null || iotLocationVo.getBeginTime() == null || iotLocationVo.getEndTime() == null) {
            throw new ServiceException(ExceptionEnum.PARAM_NULL.getMsg());
        }

        Map<String,Object> map=new HashMap<>();
        List<String> list=new ArrayList<>();
        //从redis中获取token
        String redisCode = redisService.getCacheObject(TokenConstants.TOKEN_LOCATION);
        //如果token为空，先去调登录接口，获取token
        if (redisCode == null){
            redisCode = HttpHelper.getIotToken();
            redisService.setCacheObject(TokenConstants.TOKEN_LOCATION,redisCode,23L, TimeUnit.HOURS);
        }
        map.clear();
        list.add(iotLocationVo.getIotId());
        map.put("devices",list);
        map.put("startday",iotLocationVo.getBeginTime());
        map.put("endday",iotLocationVo.getEndTime());
        //报警类型
        map.put("needalarm","");
        String param = JSON.toJSONString(map);
        String res = HttpHelper.doPost(HttpStatus.REPORT_ALARM_URL+redisCode,param);
        //对返回的结果进行解析
        List<IotLocationVo> iotLocationVoList = resultReportAlarm(res);
        log.info("resultDataHandler:{}", iotLocationVo);
        return iotLocationVoList;
    }

    /**
     * 报警推送
     * @param
     * @return
     * 每三个小时执行一次（3 * 60 * 60 * 1000 毫秒 = 10800000 毫秒）
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    @Scheduled(fixedRate = 10800000)
    public int alarmPush() {
        log.info("开始获取报警信息====");
        List<MaTypeKeeper> maTypeKeeperList = new ArrayList<>();
        //获取当前登录用户的所有信息
        try {
            Long userId = SecurityUtils.getLoginUser().getUserid();
            //查看当前用户名下有哪些类型的设备
            maTypeKeeperList = maTypeMapper.selectMaTypeByUserId(userId);
        } catch (Exception e) {
            log.error("获取用户信息有误！！");
            return 0;
        }
        List<IotLocationVo> iotLocationVoAll = new ArrayList<>();
        for (int i = 0; i < maTypeKeeperList.size(); i++) {
            //查询该类机具有哪些设备绑定的iot设备
            List<IotVo> iotVoList =  iotMachineMapper.selectListByTypeId(maTypeKeeperList.get(i).getTypeId());
            for (IotVo iotVo:iotVoList) {
                IotLocationVo iotLocationVo = new IotLocationVo();
                iotLocationVo.setIotId(iotVo.getIotCode());
                iotLocationVo.setBeginTime(DateUtils.getDate());
                iotLocationVo.setEndTime(DateUtils.getDate());
                //获取当前设备的报警信息
                List<IotLocationVo> iotLocationVoList = reportAlarm(iotLocationVo);
                //保存所有的报警信息
                iotLocationVoAll.addAll(iotLocationVoList);
            }
        }
        int count = handlingAlarmInformation(iotLocationVoAll);
        return count;
    }

    @Override
    public List<ReportAlarm> alarmList(IotLocationVo iotLocationVo) {
        log.info("alarmList:{}", iotLocationVo);
        return reportAlarmMapper.selectByIotCode(iotLocationVo);
    }

    @Override
    public int alarmManagement(ReportAlarm reportAlarm) {
        log.info("alarmManagement:{}", reportAlarm);
        return reportAlarmMapper.update(reportAlarm);
    }

    /**
     * 处理报警信息
     * @param iotLocationVoAll
     * @return
     */
    private int handlingAlarmInformation(List<IotLocationVo> iotLocationVoAll) {
        log.info("处理报警信息====");
        int fly = 0;
        if (iotLocationVoAll != null && iotLocationVoAll.size() > 0) {
            for (IotLocationVo iotLocationVo : iotLocationVoAll) {
                //根据当前的报警uuid查看是否有这条记录
                ReportAlarm reportAlarm = reportAlarmMapper.selectByDeviceAlarmId(iotLocationVo.getDeviceAlarmId());
                if (reportAlarm == null) {
                    reportAlarm.setIotCode(iotLocationVo.getIotId());
                    reportAlarm.setDeviceAlarmId(iotLocationVo.getDeviceAlarmId());
                    reportAlarm.setStartAlarm(iotLocationVo.getStartAlarm());
                    SimpleDateFormat sdf = new SimpleDateFormat(DateUtils.YYYY_MM_DD_HH_MM_SS);
                    try {
                        reportAlarm.setStartAlarmTime(sdf.parse(iotLocationVo.getStartAlarmTime()));
                    } catch (ParseException e) {
                        log.error("日期转换异常！！！");
                    }
                    //异常信息保存到数据库
                    reportAlarmMapper.add(reportAlarm);
                    fly=1;
                }
            }
        }
        return fly;
    }


    /**
     * 解析报警返回报文
     * @param res
     * @return
     */
    private List<IotLocationVo> resultReportAlarm(String res) {
        if (res == null) {
            throw new ServiceException(ExceptionEnum.RETURN_DATA_IS_EMPTY.getMsg());
        }
        List<IotLocationVo> iotLocationVoList = new ArrayList<>();
        JSONObject object = JSONObject.parseObject(res);
        String cause = object.getString("cause");
        String status = object.getString("status");
        if ("OK".equals(cause) && "0".equals(status)) {
            String records = object.getString("alarmrecords");
            //判断返回结果是否为空
            if (records != null){
                JSONArray jsonArray = JSON.parseArray(records);
                for (int i = 0; i < jsonArray.size(); i++) {
                    JSONObject jsonObject = JSONObject.from(jsonArray.getJSONObject(i));
                    IotLocationVo iotLocationVo = new IotLocationVo();
                    iotLocationVo.setStartAlarmTime(jsonObject.getString("startalarmtime"));
                    iotLocationVo.setStartAlarm(jsonObject.getString("stralarm"));
                    iotLocationVo.setDeviceAlarmId(jsonObject.getString("devicealarmid"));
                    iotLocationVo.setIotId(jsonObject.getString("deviceid"));
                    iotLocationVoList.add(iotLocationVo);
                }
            }
        }
        return iotLocationVoList;
    }


    /**
     * 解析定位返回报文
     * @param res
     * @return
     */
    private IotLocationVo resultDataHandler(String res) {
        if (res == null) {
            throw new ServiceException(ExceptionEnum.RETURN_DATA_IS_EMPTY.getMsg());
        }
        IotLocationVo iotLocationVo = new IotLocationVo();
        JSONObject object = JSONObject.parseObject(res);
        String status = object.getString("status");
        String cause = object.getString("cause");
        if ("0".equals(status) && "OK".equals(cause)) {
            String records = object.getString("records");
            //判断返回结果是否为空
            if (records != null){
                JSONArray jsonArray = JSON.parseArray(records);
                for (int i = 0; i < jsonArray.size(); i++) {
                    JSONObject jsonObject = JSONObject.from(jsonArray.getJSONObject(i));
                    iotLocationVo.setIotId(jsonObject.getString("deviceid"));
                    iotLocationVo.setCallat(StringHelper.conversionBigDecimal(jsonObject.getString("callat")));
                    iotLocationVo.setCallon(StringHelper.conversionBigDecimal(jsonObject.getString("callon")));
                }
            }
        }
        return iotLocationVo;
    }
}
