package com.huimv.eartag.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.huimv.eartag.dao.entity.*;
import com.huimv.eartag.dao.repo.*;
import com.huimv.eartag.service.ICacheService;
import com.huimv.eartag.service.IDeviceManageService;
import com.huimv.eartag.utils.BizConst;
import com.huimv.eartag.utils.DateUtil;
import com.huimv.eartag.utils.JSONUtil;
import com.huimv.eartag.utils.MathUtil;
import com.huimv.eartag.vo.FarmAllStatusVo;
import com.huimv.eartag.vo.Result;
import com.huimv.eartag.vo.ResultCode;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.jpa.domain.Specification;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;

import javax.persistence.criteria.Order;
import javax.persistence.criteria.Predicate;
import java.math.BigDecimal;
import java.sql.Date;
import java.sql.Timestamp;
import java.text.ParseException;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

/**
 * @Project : huimv.shiwan
 * @Package : com.huimv.biosafety.uface.controller
 * @Description : TODO
 * @Version : 1.0
 * @Author : ZhuoNing
 * @Create : 2020-12-25
 **/
@Service
@Slf4j
public class DeviceManageServiceImpl implements IDeviceManageService {
    @Value("${device.online.access_mode}")
    private String deviceOnlineAccessMode;
    @Value("${service.farmAllStatus.host}")
    private String serviceFarmAllStatusHost;
    @Value("${service.farmAllStatus.ip}")
    private String serviceFarmAllStatusIp;
    @Value("${service.farmAllStatus.url}")
    private String serviceFarmAllStatusUrl;
    @Autowired
    private ICacheService cacheService;
    @Autowired
    private EartarFarmAllStatusRepo farmAllStatusRepo;
    @Autowired
    private EartagDeviceRegisterRepo deviceRegisterRepo;
    @Autowired
    private EartagEartagRegisterRepo eartagRegisterRepo;
    @Autowired
    private EartagDeviceOnlineRepo deviceOnlineRepo;
    @Autowired
    private EartagEartagOnlineRepo eartagOnlineRepo;
    @Autowired
    private EartagDeviceEartagCountRepo deviceEartagCountRepo;
    @Autowired
    private EartagEnvRepo eartagEnvRepo;
    @Autowired
    private EartagHeartbeatRepo heartbeatRepo;


    /**
     * @Method : listDeviceEnvtempByDeviceCode
     * @Description :
     * @Params : [deviceCode]
     * @Return : com.huimv.eartag2.common.utils.Result
     * @Author : ZhuoNing
     * @Date : 2022/3/8
     * @Time : 20:55
     */
    @Override
    public Result listDeviceEnvtempByDeviceCode(String deviceCode) throws ParseException {
        DateUtil du = new DateUtil();
        String todayDateText = du.getTodayDateText();
        //
        List<EartagEnvEntity> eartagEnvEntityList = eartagEnvRepo.getDeviceEnvtempByDeviceCode(deviceCode, todayDateText);
        if (eartagEnvEntityList.size() == 0) {
            return new Result(BizConst.CODE_ENVTEMP_FLOW_NO_EXIST, BizConst.MSG_ENVTEMP_FLOW_NO_EXIST, false);
        } else {
            JSONArray dataJa = new JSONArray();
            for (EartagEnvEntity eartagEnvEntity : eartagEnvEntityList) {
                JSONObject eartagEnvJo = JSONUtil.convertEntityToJSONObject(eartagEnvEntity);
                eartagEnvJo.put("addTime", du.formatDatetimeText(eartagEnvJo.getDate("addTime")));
                dataJa.add(eartagEnvJo);
            }
            return new Result(ResultCode.SUCCESS, dataJa);
        }
    }

    /**
     * @Method : listDeviceEartagOnlineCountByDeviceCodeInPager
     * @Description : 显示设备关联耳标统计（带分页）
     * @Params : [deviceCode, earmark, addDate, pageNo, pageSize]
     * @Return : com.huimv.eartag2.common.utils.Result
     * @Author : ZhuoNing
     * @Date : 2022/3/9
     * @Time : 20:08
     */
    @Override
    public Result listDeviceEartagOnlineCountByDeviceCodeInPager(String deviceCode, String earmark, String addDate, Integer pageNo, Integer pageSize) throws ParseException {
        //
        Specification<EartagDeviceEartagCountEntity> sf = (Specification<EartagDeviceEartagCountEntity>) (root, criteriaQuery, criteriaBuilder) -> {
            //
            List<Predicate> predList = new ArrayList<>();
            if (null != earmark && earmark.trim().length() > 0) {
                predList.add(criteriaBuilder.equal(root.get("earmark").as(String.class), earmark));
            }
            //
            if (null != deviceCode && deviceCode.trim().length() > 0) {
                predList.add(criteriaBuilder.equal(root.get("deviceCode").as(String.class), deviceCode));
            }
            //
            if (null != addDate && addDate.trim().length() > 0) {
                try {
                    predList.add(criteriaBuilder.equal(root.get("createDate").as(Date.class), new Date(new DateUtil().parseDateTextToLong(addDate))));
                } catch (ParseException e) {
                    e.printStackTrace();
                }
            }
            Predicate[] pred = new Predicate[predList.size()];
            Predicate and = criteriaBuilder.and(predList.toArray(pred));
            criteriaQuery.where(and);
            //
            List<Order> orders = new ArrayList<>();
            orders.add(criteriaBuilder.desc(root.get("id")));
            return criteriaQuery.orderBy(orders).getRestriction();
        };
        Pageable pageable = PageRequest.of(pageNo - 1, pageSize);
        return new Result(ResultCode.SUCCESS, deviceEartagCountRepo.findAll(sf, pageable));
    }

    @Override
    public Result listHeartbeatByDeviceCodeAndDateInPager(String deviceCode, String addDate, Integer pageNo, Integer pageSize) throws ParseException {
        System.out.println("## addDate>>" + addDate);
        //
        Specification<EartagHeartbeatEntity> sf = (Specification<EartagHeartbeatEntity>) (root, criteriaQuery, criteriaBuilder) -> {
            //
            List<Predicate> predList = new ArrayList<>();
            //
            if (null != deviceCode && deviceCode.trim().length() > 0) {
                predList.add(criteriaBuilder.equal(root.get("deviceCode").as(String.class), deviceCode));
            }
            //
            if (null != addDate && addDate.trim().length() > 0) {
                try {
                    predList.add(criteriaBuilder.equal(root.get("createDate").as(Date.class), new Date(new DateUtil().parseDateTextToLong(addDate))));
                } catch (ParseException e) {
                    e.printStackTrace();
                }
            }
            Predicate[] pred = new Predicate[predList.size()];
            Predicate and = criteriaBuilder.and(predList.toArray(pred));
            criteriaQuery.where(and);
            //
            List<Order> orders = new ArrayList<>();
            orders.add(criteriaBuilder.desc(root.get("id")));
            return criteriaQuery.orderBy(orders).getRestriction();
        };
        Pageable pageable = PageRequest.of(pageNo - 1, pageSize);
        Page<EartagHeartbeatEntity> pageHeartbeatEntity = heartbeatRepo.findAll(sf, pageable);
        DateUtil dateUtil = new DateUtil();
        JSONObject pageJo = JSONObject.parseObject(JSONObject.toJSONString(pageHeartbeatEntity));
        JSONArray contentJa = pageJo.getJSONArray("content");
        for(int a=0;a<contentJa.size();a++){
            JSONObject contentJo = contentJa.getJSONObject(a);
            contentJo.put("addTime",dateUtil.formatDatetimeText(contentJo.getDate("addTime")));
        }
        return new Result(ResultCode.SUCCESS, pageJo);
    }

    /**
     * @Method : listDeviceEnvtempByDeviceCodeInPager
     * @Description : 分页查询设备温度
     * @Params : [deviceCode, addDate, pageNo, pageSize]
     * @Return : com.huimv.eartag2.common.utils.Result
     * @Author : ZhuoNing
     * @Date : 2022/3/9
     * @Time : 21:27
     */
    @Override
    public Result listDeviceEnvtempByDeviceCodeInPager(String deviceCode, String addDate, Integer pageNo, Integer pageSize) throws ParseException {
        //
        Specification<EartagEnvEntity> sf = (Specification<EartagEnvEntity>) (root, criteriaQuery, criteriaBuilder) -> {
            //
            List<Predicate> predList = new ArrayList<>();
            //
            if (null != deviceCode && deviceCode.trim().length() > 0) {
                predList.add(criteriaBuilder.equal(root.get("deviceCode").as(String.class), deviceCode));
            }
            //
            if (null != addDate && addDate.trim().length() > 0) {
                try {
                    predList.add(criteriaBuilder.equal(root.get("createDate").as(Date.class), new Date(new DateUtil().parseDateTextToLong(addDate))));
                } catch (ParseException e) {
                    e.printStackTrace();
                }
            }
            Predicate[] pred = new Predicate[predList.size()];
            Predicate and = criteriaBuilder.and(predList.toArray(pred));
            criteriaQuery.where(and);
            //
            List<Order> orders = new ArrayList<>();
            orders.add(criteriaBuilder.desc(root.get("id")));
            return criteriaQuery.orderBy(orders).getRestriction();
        };
        Pageable pageable = PageRequest.of(pageNo - 1, pageSize);
        Page<EartagEnvEntity> pageEnvEntity = eartagEnvRepo.findAll(sf, pageable);
        DateUtil dateUtil = new DateUtil();
        String pageStr = JSONObject.toJSONString(pageEnvEntity);
        JSONObject pageJo = JSONObject.parseObject(pageStr);
        JSONArray contentJa = pageJo.getJSONArray("content");
        for(int a=0;a<contentJa.size();a++){
            JSONObject contentJo = contentJa.getJSONObject(a);
            contentJo.put("addTime",dateUtil.formatDatetimeText(contentJo.getDate("addTime")));
        }
        return new Result(ResultCode.SUCCESS, pageJo);
    }

    /**
     * @Method : listDeviceRegisterInPager
     * @Description : 列表查询分页信息（分页）
     * @Params : [farmId, deviceCode, alias, startDate, endDate, activeStatus, liveStatus, pageNo, pageSize]
     * @Return : com.huimv.eartag2.common.utils.Result
     * @Author : ZhuoNing
     * @Date : 2022/3/9
     * @Time : 22:28
     */
    @Override
    public Result listDeviceRegisterInPager(String farmId, String deviceCode, String alias, String startDate, String endDate, Integer activeStatus, Integer liveStatus, Integer pageNo, Integer pageSize) throws ParseException {
//        System.out.println("# farmId>>"+farmId);
//        System.out.println("# deviceCode>>"+deviceCode);
//        System.out.println("# alias>>"+alias);
//        System.out.println("# startDate>>"+startDate);
//        System.out.println("# endDate>>"+endDate);
//        System.out.println("# activeStatus>>"+activeStatus);
//        System.out.println("# liveStatus>>"+liveStatus);
//        System.out.println("# pageNo>>"+pageNo);
//        System.out.println("# pageSize>>"+pageSize);
        //
        Specification<EartagDeviceRegisterEntity> sf = (Specification<EartagDeviceRegisterEntity>) (root, criteriaQuery, criteriaBuilder) -> {
            //
            List<Predicate> predList = new ArrayList<>();
            //farmId
            if (null != farmId && farmId.trim().length() > 0) {
                predList.add(criteriaBuilder.equal(root.get("farmId").as(String.class), farmId));
            }
            //deviceCode
            if (null != deviceCode && deviceCode.trim().length() > 0) {
                predList.add(criteriaBuilder.equal(root.get("deviceCode").as(String.class), deviceCode));
            }
            //alias
            if (null != alias && alias.trim().length() > 0) {
                predList.add(criteriaBuilder.like(root.get("deviceAlias").as(String.class), alias));
            }
            //startDate
            if (null != startDate && startDate.trim().length() > 0) {
                try {
                    predList.add(criteriaBuilder.greaterThanOrEqualTo(root.get("createDate").as(Date.class), new Date(new DateUtil().parseDateTextToLong(startDate))));
                } catch (ParseException e) {
                    e.printStackTrace();
                }
            }
            //endDate
            if (null != endDate && endDate.trim().length() > 0) {
                try {
                    predList.add(criteriaBuilder.lessThanOrEqualTo(root.get("createDate").as(Date.class), new Date(new DateUtil().parseDateTextToLong(endDate))));
                } catch (ParseException e) {
                    e.printStackTrace();
                }
            }
            //activeStatus
            if (null != activeStatus) {
                predList.add(criteriaBuilder.equal(root.get("activeStatus").as(Integer.class), activeStatus));
            }
            //liveStatus
            if (null != liveStatus) {
                predList.add(criteriaBuilder.equal(root.get("deviceStatus").as(Integer.class), liveStatus));
            }
            Predicate[] pred = new Predicate[predList.size()];
            Predicate and = criteriaBuilder.and(predList.toArray(pred));
            criteriaQuery.where(and);
            //
            List<Order> orders = new ArrayList<>();
            orders.add(criteriaBuilder.desc(root.get("id")));
            return criteriaQuery.orderBy(orders).getRestriction();
        };
        Pageable pageable = PageRequest.of(pageNo - 1, pageSize);
        DateUtil dateUtil = new DateUtil();
        //{}
        Page<EartagDeviceRegisterEntity> pageDeviceRegister = deviceRegisterRepo.findAll(sf, pageable);
        //////////////////////////////////////////////////////////////////////////////////
//        JSONObject outDataJo = new JSONObject();
//        outDataJo.put("pageable", pageDeviceRegister.getPageable());
//        outDataJo.put("last", pageDeviceRegister.isLast());
//        outDataJo.put("totalElements", pageDeviceRegister.getTotalElements());
//        outDataJo.put("totalPages", pageDeviceRegister.getTotalPages());
//        outDataJo.put("number", pageDeviceRegister.getNumber());
//        outDataJo.put("size", pageDeviceRegister.getSize());
//        outDataJo.put("sort", pageDeviceRegister.getSort());
//        outDataJo.put("numberOfElements", pageDeviceRegister.getNumberOfElements());
//        outDataJo.put("first", pageDeviceRegister.isFirst());
//        outDataJo.put("empty", pageDeviceRegister.isEmpty());
//
//        List<EartagDeviceRegisterEntity> deviceRegisterEntityList = pageDeviceRegister.getContent();
////        System.out.println("## deviceRegisterEntityList.size>>"+deviceRegisterEntityList.size());
//        JSONArray outJa = new JSONArray();
//        outDataJo.put("content", outJa);
//        for (EartagDeviceRegisterEntity deviceRegisterEntity : deviceRegisterEntityList) {
//            JSONObject outJo = new JSONObject();
//            outJa.add(outJo);
//            outJo.put("id", deviceRegisterEntity.getId());
//            outJo.put("deviceCode", deviceRegisterEntity.getDeviceCode());
//            outJo.put("countyCode", deviceRegisterEntity.getCountyCode());
//            outJo.put("countyName", deviceRegisterEntity.getCountyName());
//            outJo.put("farmId", deviceRegisterEntity.getFarmId());
//            outJo.put("farmName", deviceRegisterEntity.getFarmName());
//            outJo.put("typeF", deviceRegisterEntity.getTypeF());
//            outJo.put("stage", deviceRegisterEntity.getStage());
//            outJo.put("pigpenId", deviceRegisterEntity.getPigpenId());
//            outJo.put("unitId", deviceRegisterEntity.getUnitId());
////            outJo.put("registerTime", dateUtil.formatDatetimeText(deviceRegisterEntity.getRegisterTime()));
////            outJo.put("lastTime", dateUtil.formatDatetimeText(deviceRegisterEntity.getLastTime()));
//            outJo.put("activeStatus", deviceRegisterEntity.getActiveStatus());
////            outJo.put("activeTime", dateUtil.formatDatetimeText(deviceRegisterEntity.getActiveTime()));
//            outJo.put("deviceStatus", deviceRegisterEntity.getDeviceStatus());
//            outJo.put("deviceAlias", deviceRegisterEntity.getDeviceAlias());
//            outJo.put("location", deviceRegisterEntity.getLocation());
//            outJo.put("remark", deviceRegisterEntity.getRemark());
//            outJo.put("createDate", deviceRegisterEntity.getCreateDate());
//            outJo.put("updateType", deviceRegisterEntity.getUpdateType());
//        }
        ///////////////////////////////////////////////////////////////////////
        JSONObject pageJo = JSONObject.parseObject(JSONObject.toJSONString(pageDeviceRegister));
        JSONArray contentJa = pageJo.getJSONArray("content");
        for(int a=0;a<contentJa.size();a++){
            JSONObject contentJo = contentJa.getJSONObject(a);
            contentJo.put("registerTime",dateUtil.formatDatetimeText(contentJo.getDate("registerTime")));
            contentJo.put("lastTime",dateUtil.formatDatetimeText(contentJo.getDate("lastTime")));
            contentJo.put("activeTime",dateUtil.formatDatetimeText(contentJo.getDate("activeTime")));
        }
        return new Result(ResultCode.SUCCESS, pageJo);
    }

    @Override
    public Result listDeviceOnlineCountByDeviceCodeInPager(String deviceCode, String startDate, String endDate, Integer pageNo, Integer pageSize) throws ParseException {
        //
        Specification<EartagDeviceOnlineEntity> sf = (Specification<EartagDeviceOnlineEntity>) (root, criteriaQuery, criteriaBuilder) -> {
            List<Predicate> predList = new ArrayList<>();
            //deviceCode
            if (null != deviceCode && deviceCode.trim().length() > 0) {
                predList.add(criteriaBuilder.equal(root.get("deviceCode").as(String.class), deviceCode));
            }
            //startDate
            if (null != startDate && startDate.trim().length() > 0) {
                try {
                    predList.add(criteriaBuilder.greaterThanOrEqualTo(root.get("addDate").as(Date.class), new Date(new DateUtil().parseDateTextToLong(startDate))));
                } catch (ParseException e) {
                    e.printStackTrace();
                }
            }
            //endDate
            if (null != endDate && endDate.trim().length() > 0) {
                try {
                    predList.add(criteriaBuilder.lessThanOrEqualTo(root.get("addDate").as(Date.class), new Date(new DateUtil().parseDateTextToLong(endDate))));
                } catch (ParseException e) {
                    e.printStackTrace();
                }
            }
            Predicate[] pred = new Predicate[predList.size()];
            Predicate and = criteriaBuilder.and(predList.toArray(pred));
            criteriaQuery.where(and);
            //
            List<Order> orders = new ArrayList<>();
            orders.add(criteriaBuilder.desc(root.get("id")));
            return criteriaQuery.orderBy(orders).getRestriction();
        };
        Pageable pageable = PageRequest.of(pageNo - 1, pageSize);
        DateUtil dateUtil = new DateUtil();
        //{}
        Page<EartagDeviceOnlineEntity> pageDeviceOnline = deviceOnlineRepo.findAll(sf, pageable);
        JSONObject outDataJo = new JSONObject();
        JSONArray outJa = new JSONArray();
        outDataJo.put("content", outJa);
        List<EartagDeviceOnlineEntity> deviceRegisterEntityList = pageDeviceOnline.getContent();
//        System.out.println("## deviceRegisterEntityList.size>>"+deviceRegisterEntityList.size());
        for (EartagDeviceOnlineEntity deviceRegisterEntity : deviceRegisterEntityList) {
            JSONObject outJo = new JSONObject();
            outJa.add(outJo);
            outJo.put("id", deviceRegisterEntity.getId());
            outJo.put("deviceCode", deviceRegisterEntity.getDeviceCode());
            outJo.put("alias", deviceRegisterEntity.getAlias());
            outJo.put("heartbeatTotal", deviceRegisterEntity.getHeartbeatTotal());
            outJo.put("envtempTotal", deviceRegisterEntity.getEnvtempTotal());
            outJo.put("eartagTotal", deviceRegisterEntity.getEartagTotal());
            outJo.put("lastEnvtemp", deviceRegisterEntity.getLastEnvtemp());
            outJo.put("lastEartag", deviceRegisterEntity.getLastEartag());
            outJo.put("heartbeatFirstTime", dateUtil.formatDatetimeText(deviceRegisterEntity.getHeartbeatFirstTime()));
            outJo.put("heartbeatLastTime", dateUtil.formatDatetimeText(deviceRegisterEntity.getHeartbeatLastTime()));
            outJo.put("envtempFirstTime", dateUtil.formatDatetimeText(deviceRegisterEntity.getEnvtempFirstTime()));
            outJo.put("envtempLastTime", dateUtil.formatDatetimeText(deviceRegisterEntity.getEnvtempLastTime()));
            outJo.put("eartagFirstTime", dateUtil.formatDatetimeText(deviceRegisterEntity.getEartagFirstTime()));
            outJo.put("eartagLastTime", dateUtil.formatDatetimeText(deviceRegisterEntity.getEartagLastTime()));
            outJo.put("addDate", deviceRegisterEntity.getAddDate());
            outJo.put("farmId", deviceRegisterEntity.getFarmId());
        }
        outDataJo.put("pageable", pageDeviceOnline.getPageable());
        outDataJo.put("last", pageDeviceOnline.isLast());
        outDataJo.put("totalElements", pageDeviceOnline.getTotalElements());
        outDataJo.put("totalPages", pageDeviceOnline.getTotalPages());
        outDataJo.put("number", pageDeviceOnline.getNumber());
        outDataJo.put("size", pageDeviceOnline.getSize());
        outDataJo.put("sort", pageDeviceOnline.getSort());
        outDataJo.put("numberOfElements", pageDeviceOnline.getNumberOfElements());
        outDataJo.put("first", pageDeviceOnline.isFirst());
        outDataJo.put("empty", pageDeviceOnline.isEmpty());
        return new Result(ResultCode.SUCCESS, outDataJo);
    }

    @Override
    public void countEffectiveDeviceTotal (JSONObject deviceRegisterJo) {
        String farmId = deviceRegisterJo.getString("farmId");
        //{}
        Integer effectiveDeviceTotal = getEffectiveDeviceSum(farmId);
        System.out.println("## effectiveDeviceTotal>>"+effectiveDeviceTotal);
        //{设置设备总数}
        cacheService.putDeviceTotal_(effectiveDeviceTotal,farmId);
    }

//    @Override
//    public void countFarmAllStatus(JSONObject deviceRegisterJo) throws ParseException {
//        String farmId = deviceRegisterJo.getString("farmId");
//        //{}
//        remoteProcessFarmAllStatus(farmId);
//    }

    @Override
    public Result listDeviceEartagOnlineStatusByDeviceCodeAndDate(String deviceCode, String earmark, String addDate) {
        //
        Specification<EartagDeviceEartagCountEntity> sf = (Specification<EartagDeviceEartagCountEntity>) (root, criteriaQuery, criteriaBuilder) -> {
            //
            List<Predicate> predList = new ArrayList<>();
            if (null != earmark && earmark.trim().length() > 0) {
                predList.add(criteriaBuilder.equal(root.get("earmark").as(String.class), earmark));
            }
            //
            if (null != deviceCode && deviceCode.trim().length() > 0) {
                predList.add(criteriaBuilder.equal(root.get("deviceCode").as(String.class), deviceCode));
            }
            //
            if (null != addDate && addDate.trim().length() > 0) {
                try {
                    predList.add(criteriaBuilder.equal(root.get("createDate").as(Date.class), new Date(new DateUtil().parseDateTextToLong(addDate))));
                } catch (ParseException e) {
                    e.printStackTrace();
                }
            }
            Predicate[] pred = new Predicate[predList.size()];
            Predicate and = criteriaBuilder.and(predList.toArray(pred));
            criteriaQuery.where(and);
            //
            List<Order> orders = new ArrayList<>();
            orders.add(criteriaBuilder.desc(root.get("total")));
            return criteriaQuery.orderBy(orders).getRestriction();
        };
        List<EartagDeviceEartagCountEntity> deviceEartagCountEntityList = deviceEartagCountRepo.findAll(sf);
        JSONArray dataJa = new JSONArray();
        for(EartagDeviceEartagCountEntity deviceEartagCountEntity:deviceEartagCountEntityList){
            JSONObject eartagJo = new JSONObject();
            dataJa.add(eartagJo);
            String earmark1 = deviceEartagCountEntity.getEarmark();
//            eartagJo.put("earmark",earmark1.substring(9,earmark1.length()));
            eartagJo.put("earmark",earmark1);
            eartagJo.put("value",deviceEartagCountEntity.getTotal());
        }
        return new Result(ResultCode.SUCCESS, dataJa);
    }

//    @Override
//    public void remoteProcessFarmAllStatus(String farmId) throws ParseException {
//        String todayDateText = new com.huimv.eartag.utils.DateUtil().getTodayDateText();
//        java.sql.Date todayDate = new java.sql.Date(new java.util.Date().getTime());
//        Timestamp nowTimestamp = new Timestamp(new java.util.Date().getTime());
//
//        RestTemplate restTemplate = new RestTemplate();
//
//        String url = "http://" + serviceFarmAllStatusHost + ":" + serviceFarmAllStatusIp + serviceFarmAllStatusUrl;
//        System.out.println("## url>>"+url);
//
//        FarmAllStatusVo farmAllStatusVo = new FarmAllStatusVo();
//        farmAllStatusVo.setFarmId(farmId);
//        farmAllStatusVo.setTodayDateText(todayDateText);
//        farmAllStatusVo.setTodayDate(todayDate);
//        farmAllStatusVo.setNowTimestamp(nowTimestamp);
//        //{}
//        String result = restTemplate.postForObject(url,farmAllStatusVo,String.class);
//        System.out.println("result>>"+result);
//    }

//    @Override
//    public void remoteProcessFarmAllStatus2(String farmId) throws ParseException {
//        String todayDateText = new com.huimv.eartag.utils.DateUtil().getTodayDateText();
//        java.sql.Date todayDate = new java.sql.Date(new java.util.Date().getTime());
//        Timestamp nowTimestamp = new Timestamp(new java.util.Date().getTime());
//
//        RestTemplate restTemplate = new RestTemplate();
//        String host = "192.168.1.30";
//        String port = "8092";
//        String service = "/deviceController/updateFarmAllStatus";
//        String url = "http://" + host + ":" + port + service+"?farmId="+farmId+"&todayDateText="+todayDateText+"&todayDate="+todayDate+"&nowTimestamp="+nowTimestamp;
//        System.out.println("## url>>"+url);
//        //{}
//        String result = restTemplate.getForObject(url,String.class);
//        System.out.println("result>>"+result);
//    }

    public Integer getEffectiveDeviceSum(String farmId){
        List<Object[]> deviceRegisterList = deviceRegisterRepo.getDeviceCountByFarmId(farmId);
        Object[] deviceRegObj = (Object[]) deviceRegisterList.get(0);
        System.out.println(">>>>>>>>>>>>>>>>>>>>>>>>>>>>>"+deviceRegObj[0].toString());
        //设备总数
        return Integer.parseInt(deviceRegObj[0].toString());
    }
    /**
     * @Method : listOnlineDevice
     * @Description :
     * @Params : [farmId, deviceCode, alias, addDate, pageNo, pageSize]
     * @Return : com.huimv.eartag2.common.utils.Result
     * @Author : ZhuoNing
     * @Date : 2022/3/8
     * @Time : 20:55
     */
    @Override
    public Result listOnlineDevice(String farmId, String deviceCode, String alias, String addDate, Integer pageNo, Integer pageSize) throws ParseException {
        DateUtil dateUtil = new DateUtil();
        String todayDate = dateUtil.getTodayDateText();
        //* 这里提供2种方式：1、从数据库读取 2、从缓存中取数（后期优化)，但是同时提供2种方式都可用，防止缓存方式失效 */
//        System.out.println("deviceOnlineAccessMode>>" + deviceOnlineAccessMode);
        if (deviceOnlineAccessMode.trim().equalsIgnoreCase("mysql")) {
            //
            return listDeviceOnlineFromMySQL(farmId, addDate, deviceCode, alias, pageNo, pageSize);
        } else {
            //
            return listDeviceOnlineFromCache(farmId, todayDate);
        }
    }

    //分页查询
    private Result listDeviceOnlineFromMySQL(String farmId, String addDate, String deviceCode, String alias, Integer pageNo, Integer pageSize) throws ParseException {
//        //
//        List<EartagDeviceOnlineEntity> deviceOnlineEntityList = deviceOnlineRepo.getDeviceOnlineByFarmIdAndCreateDate(farmId,addDate);
//        if(deviceOnlineEntityList.size()==0){
//            return new Result(BizConst.CODE_DEVICE_ONLINE_NO_EXIST,BizConst.MSG_DEVICE_ONLINE_NO_EXIST,false);
//        }else{
//            return new Result(ResultCode.SUCCESS,JSONObject.toJSONString(deviceOnlineEntityList));
//        }
        Integer liveStatus = 1;
        DateUtil dateUtil = new DateUtil();
        //
        Specification<EartagDeviceOnlineEntity> sf = (Specification<EartagDeviceOnlineEntity>) (root, criteriaQuery, criteriaBuilder) -> {
            //
            List<Predicate> predList = new ArrayList<>();
            //
            if (null != farmId && farmId.trim().length() > 0) {
                predList.add(criteriaBuilder.equal(root.get("farmId").as(String.class), farmId));
            }
            //
            if (null != deviceCode && deviceCode.trim().length() > 0) {
                predList.add(criteriaBuilder.equal(root.get("deviceCode").as(String.class), deviceCode));
            }
            //
            if (null != addDate && addDate.trim().length() > 0) {
                try {
                    predList.add(criteriaBuilder.equal(root.get("addDate").as(Date.class), new Date(dateUtil.parseDateTextToLong(addDate))));
                } catch (ParseException e) {
                    e.printStackTrace();
                }
            }
            //
            if (null != alias && alias.trim().length() > 0) {
                predList.add(criteriaBuilder.equal(root.get("alias").as(String.class), alias));
            }
            predList.add(criteriaBuilder.equal(root.get("liveStatus").as(Integer.class), liveStatus));
            Predicate[] pred = new Predicate[predList.size()];
            Predicate and = criteriaBuilder.and(predList.toArray(pred));
            criteriaQuery.where(and);
            //
            List<Order> orders = new ArrayList<>();
//            orders.add(criteriaBuilder.desc(root.get("id")));
            orders.add(criteriaBuilder.desc(root.get("lastTime")));
            return criteriaQuery.orderBy(orders).getRestriction();
        };
        Pageable pageable = PageRequest.of(pageNo - 1, pageSize);
        Page<EartagDeviceOnlineEntity> pageDeviceOnlineEntity = deviceOnlineRepo.findAll(sf, pageable);
        JSONObject outDataJo = new JSONObject();
        outDataJo.put("pageable",pageDeviceOnlineEntity.getPageable());
        outDataJo.put("last",pageDeviceOnlineEntity.isLast());
        outDataJo.put("totalElements",pageDeviceOnlineEntity.getTotalElements());
        outDataJo.put("totalPages",pageDeviceOnlineEntity.getTotalPages());
        outDataJo.put("number",pageDeviceOnlineEntity.getNumber());
        outDataJo.put("size",pageDeviceOnlineEntity.getSize());
        outDataJo.put("sort",pageDeviceOnlineEntity.getSort());
        outDataJo.put("numberOfElements",pageDeviceOnlineEntity.getNumberOfElements());
        outDataJo.put("first",pageDeviceOnlineEntity.isFirst());
        outDataJo.put("empty",pageDeviceOnlineEntity.isEmpty());

        List<EartagDeviceOnlineEntity> deviceOnlineEntityList = pageDeviceOnlineEntity.getContent();
        System.out.println(">>>>>>>>>>>>>>>>>>>>>>>>deviceOnlineEntityList.size>>"+deviceOnlineEntityList.size());
        JSONArray outJa = new JSONArray();
        outDataJo.put("content",outJa);
        for(EartagDeviceOnlineEntity deviceOnlineEntity:deviceOnlineEntityList){
            JSONObject outJo = new JSONObject();
            outJa.add(outJo);
            outJo.put("id",deviceOnlineEntity.getId());
            outJo.put("deviceCode",deviceOnlineEntity.getDeviceCode());
            outJo.put("alias",deviceOnlineEntity.getAlias());
            outJo.put("heartbeatTotal",deviceOnlineEntity.getHeartbeatTotal());
            outJo.put("envtempTotal",deviceOnlineEntity.getEnvtempTotal());
            outJo.put("eartagTotal",deviceOnlineEntity.getEartagTotal());
            outJo.put("firstTime",dateUtil.formatDatetimeText(deviceOnlineEntity.getFirstTime()));
            outJo.put("lastTime",dateUtil.formatDatetimeText(deviceOnlineEntity.getLastTime()));
            outJo.put("lastEnvtemp",deviceOnlineEntity.getLastEnvtemp());
            outJo.put("lastEartag",deviceOnlineEntity.getLastEartag());
            outJo.put("addDate",deviceOnlineEntity.getAddDate());
            outJo.put("farmId",deviceOnlineEntity.getFarmId());
            outJo.put("heartbeatFirstTime",dateUtil.formatDatetimeText(deviceOnlineEntity.getHeartbeatFirstTime()));
            outJo.put("heartbeatLastTime",dateUtil.formatDatetimeText(deviceOnlineEntity.getHeartbeatLastTime()));
            outJo.put("envtempFirstTime",dateUtil.formatDatetimeText(deviceOnlineEntity.getEnvtempFirstTime()));
            outJo.put("envtempLastTime",dateUtil.formatDatetimeText(deviceOnlineEntity.getEnvtempLastTime()));
            outJo.put("eartagFirstTime",dateUtil.formatDatetimeText(deviceOnlineEntity.getEartagFirstTime()));
            outJo.put("eartagLastTime",dateUtil.formatDatetimeText(deviceOnlineEntity.getEartagLastTime()));
        }
        return new Result(ResultCode.SUCCESS, outDataJo);
    }

    /**
     * @Method : listDeviceEartagOnlineCountByDeviceCode
     * @Description :
     * @Params : [deviceCode]
     * @Return : com.huimv.eartag2.common.utils.Result
     * @Author : ZhuoNing
     * @Date : 2022/3/7
     * @Time : 17:13
     */
    @Override
    public Result listDeviceEartagOnlineCountByDeviceCode(String deviceCode) throws ParseException {
        DateUtil du = new DateUtil();
        String todayDateText = du.getTodayDateText();
        //
        List<EartagDeviceEartagCountEntity> deviceEartagCountEntityList = deviceEartagCountRepo.getOnlineEartagByDeviceCode(deviceCode, todayDateText);
        if (deviceEartagCountEntityList.size() == 0) {
            return new Result(BizConst.CODE_DEVICE_EARTAG_COUNT_NO_EXIST, BizConst.MSG_DEVICE_EARTAG_COUNT_NO_EXIST, false);
        } else {
            return new Result(ResultCode.SUCCESS, JSON.toJSON(deviceEartagCountEntityList));
        }
    }

    /**
     * @Method : listDeviceOnlineStatusByDeviceCode
     * @Description : 列表在线设备关联在线耳标统计
     * @Params : [deviceCode, pastDays]
     * @Return : com.huimv.eartag2.common.utils.Result
     * @Author : ZhuoNing
     * @Date : 2022/3/7
     * @Time : 17:13
     */
    @Override
    public Result listDeviceOnlineStatusByDeviceCode(String deviceCode, Integer pastDays) throws ParseException {
        DateUtil du = new DateUtil();
        DateUtil dateUtil = new DateUtil();
        String pastDate = dateUtil.getPastDate(pastDays);
        String todayDate = dateUtil.getTodayDateText();
        //
        List<EartagDeviceOnlineEntity> deviceOnlineEntityList = deviceOnlineRepo.getDeviceOnlineByDeviceCode(deviceCode, pastDate, todayDate);
        if (deviceOnlineEntityList.size() > 0) {
            List<String> pastDateList = du.getPastIntervalsASC(pastDays);
            JSONArray dataJa = new JSONArray();
            for (String pastDayDate : pastDateList) {
                JSONObject newJo = new JSONObject();
                dataJa.add(newJo);
                newJo.put("time", pastDayDate);
                boolean ieFound = false;
                for (EartagDeviceOnlineEntity deviceOnlineEntity : deviceOnlineEntityList) {
                    int compareTo = du.parseDate(pastDayDate).compareTo(deviceOnlineEntity.getAddDate());
                    if (compareTo == 0) {
                        newJo.put("value", 1);
                        ieFound = true;
                        break;
                    }
                }
                if (!ieFound) {
                    newJo.put("value", 0);
                }
            }
            return new Result(ResultCode.SUCCESS, dataJa);
        } else {
            return new Result(BizConst.CODE_DEVICE_ONLINE_NO_EXIST, BizConst.MSG_DEVICE_ONLINE_NO_EXIST, false);
        }
    }

    /**
     * @Method : listDeviceOnlineByDeviceCode
     * @Description : 查询单个设备N天在线记录
     * @Params : [deviceCode]
     * @Return : com.huimv.eartag2.common.utils.Result
     * @Author : ZhuoNing
     * @Date : 2022/3/7
     * @Time : 14:08
     */
    @Override
    public Result listDeviceOnlineCountByDeviceCode(String deviceCode, Integer pastDays) throws ParseException {
        DateUtil dateUtil = new DateUtil();
        String pastDate = dateUtil.getPastDate(pastDays);
        String todayDate = dateUtil.getTodayDateText();
        System.out.println("# deviceCode>>"+deviceCode);
        System.out.println("# pastDate>>"+pastDate);
        System.out.println("# todayDate>>"+todayDate);
        List<EartagDeviceOnlineEntity> deviceOnlineEntityList = deviceOnlineRepo.getDeviceOnlineByDeviceCode(deviceCode, pastDate, todayDate);
        System.out.println("deviceOnlineEntityList.size>>"+deviceOnlineEntityList.size());
        if (deviceOnlineEntityList.size() > 0) {
            JSONArray dataJa = new JSONArray();
            for (EartagDeviceOnlineEntity deviceOnlineEntity : deviceOnlineEntityList) {
                JSONObject newJo = new JSONObject();
                dataJa.add(newJo);
                newJo.put("time", dateUtil.formatDateText(deviceOnlineEntity.getAddDate()));
                newJo.put("value1", deviceOnlineEntity.getHeartbeatTotal());
                newJo.put("value2", deviceOnlineEntity.getEnvtempTotal());
                newJo.put("value3", deviceOnlineEntity.getEartagTotal());
            }
            return new Result(ResultCode.SUCCESS, dataJa);
        } else {
            return new Result(BizConst.CODE_DEVICE_ONLINE_NO_EXIST, BizConst.MSG_DEVICE_ONLINE_NO_EXIST, false);
        }
    }

    /**
     * @Method : getDeviceRegisterByDeviceCode
     * @Description : 通过设备编号显示设备注册信息
     * @Params : [deviceCode]
     * @Return : void
     * @Author : ZhuoNing
     * @Date : 2022/3/7
     * @Time : 13:55
     */
    @Override
    public Result getDeviceRegisterByDeviceCode(String deviceCode) throws ParseException {
        DateUtil dateUtil = new DateUtil();
        //
        EartagDeviceRegisterEntity deviceRegisterEntity = deviceRegisterRepo.getDeviceRegister(deviceCode);
        if (deviceRegisterEntity == null) {
            log.error(BizConst.MSG_DEVICE_REGISTER_NO_EXIST);
            return new Result(BizConst.CODE_DEVICE_REGISTER_NO_EXIST, BizConst.MSG_DEVICE_REGISTER_NO_EXIST, false);
        } else {
            JSONObject resultJo = (JSONObject) JSON.toJSON(deviceRegisterEntity);
            resultJo.put("activeTime", dateUtil.formatDatetimeText(resultJo.getDate("activeTime")));
            resultJo.put("registerTime", dateUtil.formatDatetimeText(resultJo.getDate("registerTime")));
            resultJo.put("lastTime", dateUtil.formatDatetimeText(resultJo.getDate("lastTime")));
            return new Result(ResultCode.SUCCESS, resultJo);
        }
    }

    /**
     * @Method : listOnlineDevice
     * @Description : 显示在线设备记录
     * @Params : [farmId]
     * @Return : com.huimv.eartag2.common.utils.Result
     * @Author : ZhuoNing
     * @Date : 2022/3/7
     * @Time : 13:21
     */
    @Override
    public Result listOnlineDevice(String farmId, String date) throws ParseException {
        DateUtil dateUtil = new DateUtil();
        if (date == null) {
            date = dateUtil.getTodayDateText();
        }
        //* 这里提供2种方式：1、从数据库读取 2、从缓存中取数（后期优化)，但是同时提供2种方式都可用，防止缓存方式失效 */
        System.out.println("deviceOnlineAccessMode>>" + deviceOnlineAccessMode);
        if (deviceOnlineAccessMode.trim().equalsIgnoreCase("mysql")) {
            //
            return listDeviceOnlineFromMySQL(farmId, date);
        } else {
            //
            return listDeviceOnlineFromCache(farmId, date);
        }
    }


    //从缓存读取在线记录（后期优化）
    private Result listDeviceOnlineFromCache(String farmId, String todayDate) {



        return null;
    }

    //从数据库读取在线记录
    private Result listDeviceOnlineFromMySQL(String farmId, String todayDate) throws ParseException {
        DateUtil du = new DateUtil();
        //
        List<EartagDeviceOnlineEntity> deviceOnlineEntityList = deviceOnlineRepo.getDeviceOnlineByFarmIdAndCreateDate(farmId, todayDate);
        if (deviceOnlineEntityList.size() == 0) {
            return new Result(BizConst.CODE_DEVICE_ONLINE_NO_EXIST, BizConst.MSG_DEVICE_ONLINE_NO_EXIST, false);
        } else {
//            for(EartagDeviceOnlineEntity deviceOnlineEntity:deviceOnlineEntityList){
//                deviceOnlineEntity.setHeartbeatFirstTime(du.formatDatetimeText());
//            }
            JSONArray resultJa = (JSONArray) JSON.toJSON(deviceOnlineEntityList);
            for (int a = 0; a < resultJa.size(); a++) {
                JSONObject resultJo = resultJa.getJSONObject(a);
                resultJo.put("envtempFirstTime", du.formatDateText(resultJo.getTimestamp("envtempFirstTime")));
                resultJo.put("envtempLastTime", du.formatDateText(resultJo.getTimestamp("envtempLastTime")));
            }
            return new Result(ResultCode.SUCCESS, resultJa);
        }
    }

    /**
     * @Method      : processReturnResult
     * @Description : 处理返回结果
     * @Params      : [resultJo]
     * @Return      : void
     *
     * @Author      : ZhuoNing
     * @Date        : 2022/3/30
     * @Time        : 18:31
     */
    public void processReturnResult(JSONObject resultJo) throws ParseException {
        MathUtil mathUtil = new MathUtil();
        DateUtil dateUtil = new DateUtil();
        resultJo.put("deviceRate",mathUtil.countRate(resultJo.getFloat("deviceRate"),1)+"%");
        resultJo.put("eartagRate",mathUtil.countRate(resultJo.getIntValue("eartagOnline"),resultJo.getIntValue("eartagTotal"),1)+"%");
        resultJo.put("updateTime", dateUtil.formatDatetimeText(resultJo.getDate("updateTime")));
//        resultJo.put("deviceTotal",resultJo.getString("deviceTotal")+"个");
//        resultJo.put("deviceOnline",resultJo.getString("deviceOnline")+"个");
//        resultJo.put("deviceOffline",resultJo.getString("deviceOffline")+"个");
//        resultJo.put("eartagTotal",resultJo.getString("eartagTotal")+"枚");
//        resultJo.put("eartagOnline",resultJo.getString("eartagOnline")+"枚");
    }

    @Override
    public Result getNowAllStatus(String farmId) throws ParseException {
        //#读取设备和耳标总状态缓存;
        //      总状态缓存存在：从缓存读取数据返回；
        //      总状态缓存不存在：从数据库读取记录：
        //              {
        //              数据库记录存在：读取记录返回，并初始化缓存；
        //              数据库记录不存在：则构建数据库记录，并初始化缓存，返回结果；
        //              }

        //{从总状态缓存钟读取缓存数据}
        DateUtil dateUtil = new DateUtil();
        Map farmAllStatusMap = cacheService.getFarmAllStatusByFarmId(farmId);
        if (farmAllStatusMap.size() > 0) {
            log.info("返回缓存数据.");
            JSONObject resultJo = (JSONObject) JSON.toJSON(farmAllStatusMap);
            //{处理返回结果}
            processReturnResult(resultJo);
//            return new Result(ResultCode.SUCCESS, JSON.toJSON(farmAllStatusMap));
            return new Result(ResultCode.SUCCESS, resultJo);
        } else {
            //#从数据库读取总状态表
            String todayDateText = dateUtil.getTodayDateText();
            Date todayDate = dateUtil.getTodayMySQLDate();
            Timestamp timestamp = dateUtil.getTimestamp();
            EartarFarmAllStatusEntity farmAllStatusEntity = farmAllStatusRepo.getOneByFarmIdAndCreateDate(farmId, todayDateText);
            if (farmAllStatusEntity != null) {
                //#初始化总状态缓存
                cacheService.putFarmAllStatusCache(farmId, farmAllStatusEntity);
                JSONObject resultJo = (JSONObject) JSON.toJSON(farmAllStatusEntity);
                //{处理返回结果}
                processReturnResult(resultJo);
//                return new Result(ResultCode.SUCCESS, JSON.toJSON(farmAllStatusEntity));
                return new Result(ResultCode.SUCCESS, resultJo);
            } else {
                //*构建总状态数据 */
                int deviceTotal = getDeviceCancelTotalFromDeviceRegister(farmId);
                int eartagTotal = getEartagRegTotalByFarmId(farmId);
                int deviceOnlineTotal = cacheService.getDeviceOnlineTotal(farmId, todayDateText);
                int eartagOnlineTotal = cacheService.getEartagOnlineTotal(farmId, todayDateText);
                int deviceOffline = deviceTotal - deviceOnlineTotal;
                BigDecimal deviceRateBd = new BigDecimal(deviceOnlineTotal).divide(new BigDecimal(deviceTotal), 1, BigDecimal.ROUND_HALF_UP);
                BigDecimal eartagRateBd = new BigDecimal(eartagOnlineTotal).divide(new BigDecimal(eartagTotal), 1, BigDecimal.ROUND_HALF_UP);

                EartarFarmAllStatusEntity newFarmAllStatusEntity = new EartarFarmAllStatusEntity();
                newFarmAllStatusEntity.setDeviceTotal(deviceTotal);
                newFarmAllStatusEntity.setDeviceOnline(deviceOnlineTotal);
                newFarmAllStatusEntity.setDeviceOffline(deviceOffline);
                newFarmAllStatusEntity.setDeviceRate(Float.parseFloat(deviceRateBd.toString()));
                newFarmAllStatusEntity.setEartagTotal(eartagTotal);
                newFarmAllStatusEntity.setEartagOnline(eartagOnlineTotal);
                newFarmAllStatusEntity.setEartagRate(Float.parseFloat(eartagRateBd.toString()));
                newFarmAllStatusEntity.setFarmId(farmId);
                newFarmAllStatusEntity.setUpdateTime(timestamp);
                newFarmAllStatusEntity.setCreateDate(todayDate);
                farmAllStatusRepo.saveAndFlush(newFarmAllStatusEntity);
                //*初始化总状态缓存*/
                cacheService.putFarmAllStatusCache(farmId, newFarmAllStatusEntity);
//                return new Result(ResultCode.SUCCESS, JSON.toJSON(newFarmAllStatusEntity));
                JSONObject resultJo = (JSONObject) JSON.toJSON(newFarmAllStatusEntity);
                //{处理返回结果}
                processReturnResult(resultJo);
                return new Result(ResultCode.SUCCESS, resultJo);
            }
        }

    }

    @Override
    public Result listManyDaysAllStatus(String farmId, Integer days) throws ParseException {
        DateUtil dateUtil = new DateUtil();
        String pastDate = dateUtil.getPastDate(days);
        String todayDate = dateUtil.getTodayDateText();
        List<EartarFarmAllStatusEntity> FarmAllStatusEntityList = farmAllStatusRepo.getOneByFarmIdAndCreateDateAndPastDate(farmId, pastDate, todayDate);
        JSONArray dataJa = new JSONArray();
        for (EartarFarmAllStatusEntity farmAllStatusEntity : FarmAllStatusEntityList) {
            JSONObject newJo = new JSONObject();
            dataJa.add(newJo);
            newJo.put("time", dateUtil.formatDateText(farmAllStatusEntity.getCreateDate()));
            newJo.put("value", farmAllStatusEntity.getDeviceOnline());
//            newJo.put("total", farmAllStatusEntity.getDeviceTotal());
//            newJo.put("rate", farmAllStatusEntity.getDeviceRate());
//            newJo.put("offline", farmAllStatusEntity.getDeviceOffline());
        }
        return new Result(ResultCode.SUCCESS, dataJa);
    }

    //计算注册设备数量
    private int getDeviceCancelTotalFromDeviceRegister(String farmId) {
        List<Object[]> deviceRegList = deviceRegisterRepo.getDeviceCountByFarmId(farmId);
        Object[] deviceRegObj = (Object[]) deviceRegList.get(0);
        //设备总数
        return Integer.parseInt(deviceRegObj[0].toString());
    }

    //计算注册耳标数量
    public Integer getEartagRegTotalByFarmId(String farmId) {
        int eartagTotal = 0;
        List<Object[]> eartagRegList = eartagRegisterRepo.getEartagCountByFarmId(farmId);
        Object[] eartagRegObj = (Object[]) eartagRegList.get(0);
        //处于工作状态的耳标总数
        return Integer.parseInt(eartagRegObj[0].toString());
    }
}
