package com.huimv.eartag.service.impl;

import cn.hutool.core.date.DateTime;
import cn.hutool.core.util.ObjectUtil;
import com.alibaba.fastjson.JSONObject;
import com.huimv.eartag.dao.entity.*;
import com.huimv.eartag.dao.repo.*;
import com.huimv.eartag.entity.EartagData;
import com.huimv.eartag.utils.BizConst;
import com.huimv.eartag.utils.DateUtil;
import com.huimv.eartag.service.ICacheService;
import com.huimv.eartag.service.IDeviceService;
import com.huimv.eartag.service.IEartagService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.sql.Timestamp;
import java.text.ParseException;
import java.util.Date;
import java.util.HashMap;
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 EartagServiceImpl implements IEartagService {
    @Autowired
    RabbitTemplate rabbitTemplate;  //使用RabbitTemplate,这提供了接收/发送等等方法
    @Autowired
    private RedisTemplate redisTemplate;
    @Autowired
    private EartagDataRepo eartagDataRepo;
    @Autowired
    private IDeviceService deviceService;
    @Autowired
    private ICacheService cacheService;
    @Autowired
    private EartagEartagRegisterRepo eartagRegisterRepo;
    @Autowired
    private EartagEartagOnlineRepo eartagOnlineRepo;
    @Autowired
    private EartarFarmAllStatusRepo farmAllStatusRepo;
    @Autowired
    private EartarFarmAllStatusRepo eartagFarmAllStatusRepo;
    @Autowired
    private EartagDeviceEartagCountRepo deviceEartagCountRepo;
    @Autowired
    private EartagDeviceRegisterRepo deviceRegisterRepo;
    @Autowired
    private EartagDeviceOnlineRepo eartagDeviceOnlineRepo;

    //处理耳标信息
    @Override
    public void handleEartagInfo() {
        //--处理注册表数据
        handleDeviceRegister();
        //--处理在线记录数据
        handleDeviceOnline();
        //--处理状态数据
        handleDeviceAllState();
    }

    //--处理状态数据
    private void handleDeviceAllState() {

    }

    //--处理在线记录数据
    private void handleDeviceOnline() {

    }

    //--处理注册表数据
    private void handleDeviceRegister() {

    }

    /**
     * @Method : countAct
     * @Description : 计算act数值
     * @Params : [deviceCode, nowAct0]
     * @Return : java.lang.Integer
     * @Author : ZhuoNing
     * @Date : 2022/1/18
     * @Time : 15:25
     */
    @Override
    public Integer countAct(String deviceCode, String nowAct) {
        //读取hash
        Object actObj = redisTemplate.opsForHash().get(deviceCode, "act");
        if (actObj == null) {
            //--初始化最新的redis记录
            initRedisObj(deviceCode);
            Object lastAct = redisTemplate.opsForHash().get(deviceCode, "act");
            if (lastAct == null) {
                log.error("#--- redis数据库有问题，请检查redis是否能正常连接 ---# ");
                return 0;
            }
        }
        Object lastAct = redisTemplate.opsForHash().get(deviceCode, "act");
        Integer act1 = Integer.parseInt(nowAct) - Integer.parseInt(lastAct.toString());
//        redisTemplate.opsForHash().put(deviceCode, "act1", act1);
        return act1;
    }

    /**
     * 初始化redis最新记录
     */
    private void initRedisObj(String deviceCode) {
        EartagDataEntity lastEartagDataEntity = eartagDataRepo.getLastEartagData(deviceCode);
        if (lastEartagDataEntity != null) {
//            System.out.println("## lastEartagDataEntity.toString>>" + lastEartagDataEntity.toString());
            //--从数据库读取最新记录并覆盖redis
            Map<String, String> map = new HashMap<>();
            map.put("cmdHeader", lastEartagDataEntity.getCmdHeader());
            map.put("device", lastEartagDataEntity.getDevice());
            map.put("earmark", lastEartagDataEntity.getEarmark());
            map.put("bat", lastEartagDataEntity.getBat().toString());
            map.put("earTemp", lastEartagDataEntity.getEarTemp().toString());
            map.put("earTemp1", lastEartagDataEntity.getEarTemp1().toString());
            map.put("envTemp", lastEartagDataEntity.getEnvTemp().toString());
            map.put("envTemp1", lastEartagDataEntity.getEnvTemp1().toString());
            map.put("act", lastEartagDataEntity.getAct().toString());
            map.put("act1", lastEartagDataEntity.getAct1().toString());
            map.put("signal1", lastEartagDataEntity.getSignal1().toString());
            map.put("askTime", lastEartagDataEntity.getAskTime());
            map.put("other", lastEartagDataEntity.getOther());
            map.put("addTime", lastEartagDataEntity.getAddTime().toString());
            //为hash结构设置多个键值对(hmset)
            redisTemplate.opsForHash().putAll(deviceCode, map);
        }
    }

    @Override
    public void handleEartag(JSONObject dataJo) throws ParseException {
        //设备编码
        String deviceCode = dataJo.getString("device");
        //耳标号
        String earmark = dataJo.getString("earmark");
        //电量
        String bat = dataJo.getString("bat");
        String todayDateText = new DateUtil().getTodayDateText();
        java.sql.Date todayDate = new java.sql.Date(new java.util.Date().getTime());
        Timestamp nowTimestamp = new Timestamp(new java.util.Date().getTime());
        //--设备在线统计表
        //--设备状态每日统计表
        //--设备和耳标总状态表
        //获取牧场id
        String farmId = deviceService.getFarmIdByDeviceCode(deviceCode);
        if(farmId != null) {
            //{保存耳标流水}
            saveEartagFlow(dataJo, nowTimestamp, todayDate, farmId);

            //{更新设备注册信息}
            updateDeviceRegister(deviceCode, nowTimestamp, todayDate, farmId);

            //{更新耳标注册信息}
            updateEartagRegister(earmark, deviceCode,bat, nowTimestamp, todayDate, farmId);

            //{更新设备在线统计}
            updateDeviceOnline(earmark, deviceCode, todayDateText,nowTimestamp, todayDate, dataJo,farmId);

            //{更新耳标在线统计}
            updateEartagOnline(earmark, deviceCode, todayDateText, todayDate, nowTimestamp, dataJo, farmId);

            //{更新耳标设备在线关联统计}
            updateEartagDeviceOnlineCount(earmark, deviceCode, todayDateText, todayDate,nowTimestamp, farmId);

            //判断该设备编号是否存在牧场缓存在线集合当中；
            if (!cacheService.isExistEartagOnlineSet(farmId, earmark, todayDateText)) {
                //更新总状态数据
                updateEartagPropertyOfAllStatus(farmId, todayDateText, todayDate, nowTimestamp);
                //将耳标号加入到耳标在线集合当中
                cacheService.putEartagToOnlineInSet(farmId, earmark, todayDateText);
            }
            System.out.println("## END 耳标数据。 "+new DateUtil().getTodayMissionText());
        }else{
            log.error("出错:该请求的FarmId为空.请检查该设备编码["+deviceCode+"]是否存在FarmId.");
        }
    }

    /**
     * @Author      : ZhuoNing
     * @Date        : 2022/2/9
     * @Time        : 14:33
     * @param eartagJo
     * @param nowTimestamp
     * @param todayDate
     * @param farmId
     */
    public void saveEartagFlow(JSONObject eartagJo, Timestamp nowTimestamp, java.sql.Date todayDate, String farmId) throws ParseException {
        DateUtil dateUtil = new DateUtil();
        EartagDataEntity dataEntity = new EartagDataEntity();
        dataEntity.setCmdHeader(eartagJo.getString("cmdHeader"));
        dataEntity.setDevice(eartagJo.getString("device"));
        dataEntity.setEarmark(eartagJo.getString("earmark"));
        dataEntity.setBat(Integer.parseInt(eartagJo.getString("bat")));
        dataEntity.setEarTemp(Integer.parseInt(eartagJo.getString("earTemp")));
        dataEntity.setEarTemp1(eartagJo.getFloat("earTemp1"));
        dataEntity.setEnvTemp(Integer.parseInt(eartagJo.getString("envTemp")));
        dataEntity.setEnvTemp1(eartagJo.getFloat("envTemp1"));
        dataEntity.setAct(Integer.parseInt(eartagJo.getString("act")));
        dataEntity.setAct1(Integer.parseInt(eartagJo.getString("act1")));
        dataEntity.setSignal1(Integer.parseInt(eartagJo.getString("signal")));
        dataEntity.setAskTime(getAskTime(eartagJo.getString("askTime")));
//        dataEntity.setOther(eartagJo.getString("other"));
        //计算平均温度
        dataEntity.setOther(  getAveTem(eartagJo.getFloat("envTemp1")));

        dataEntity.setAddTime(nowTimestamp);
        dataEntity.setCreateDate(todayDate);
        dataEntity.setFarmId(farmId);
        dataEntity.setAskDate(new java.sql.Date(dateUtil.parseDate(getAskDate(eartagJo.getString("askTime"))).getTime()));
        eartagDataRepo.saveAndFlush(dataEntity);

        //最新的耳标数据覆盖老数据
        cacheService.putEartagFlowToCache(dataEntity.getEarmark(),dataEntity);
    }

    private String getAveTem(Float temp1) {

        DateTime dateTime = cn.hutool.core.date.DateUtil.beginOfMinute(new Date());
        List<EartagData> s =  eartagDataRepo.getAllTem(dateTime);

        Float ertem = 0.0F;
        if (ObjectUtil.isEmpty(s)){
            return temp1+"";
        }

        for (EartagData eartagData : s) {
            ertem += eartagData.getEarTemp1();
        }
        return ertem/s.size()+"";



    }

    //
    public String getAskTime(String askTime) {
        String newAskTime = askTime.substring(0, 4) + "-" + askTime.substring(4, 6) + "-" + askTime.substring(6, 8) + " " + askTime.substring(8, 10) + ":" + askTime.substring(10, 12) + ":" + askTime.substring(12, 14);
        return newAskTime;
    }

    public String getAskDate(String askTime) {
        return askTime.substring(0, 4) + "-" + askTime.substring(4, 6) + "-" + askTime.substring(6, 8) ;
    }

    /**
     * @Method      : updateDeviceRegister
     * @Description : 更新设备注册状态信息
     * @Params      : [deviceCode, nowTimestamp, todayDate, farmId]
     * @Return      : void
     *
     * @Author      : ZhuoNing
     * @Date        : 2022/3/22
     * @Time        : 14:06
     */
    private void updateDeviceRegister(String deviceCode, Timestamp nowTimestamp, java.sql.Date todayDate, String farmId) {
        EartagDeviceRegisterEntity deviceRegisterEntity = deviceRegisterRepo.getDeviceRegister(deviceCode);
        if(deviceRegisterEntity == null){
            log.error("(updateDeviceRegister).deviceRegisterEntity=null <-- deviceCode>>"+deviceCode);
        }
        deviceRegisterEntity.setLastTime(nowTimestamp);
        deviceRegisterEntity.setActiveStatus(1);
        deviceRegisterEntity.setActiveTime(nowTimestamp);
        deviceRegisterEntity.setUpdateType("耳标");
        deviceRegisterEntity.setDeviceStatus(1);
        deviceRegisterRepo.saveAndFlush(deviceRegisterEntity);
    }

    //更新耳标注册数据
    public void updateEartagRegister(String earmark, String deviceCode, String bat, Timestamp nowTimestamp, java.sql.Date todayDate, String farmId) {
        //# 判断耳标注册表是否存在；
        //      如果不存在就注册耳标；
        //      如果存在就更新活动状态（active_status）和活动状态更新时间（active_time）
        Integer registerType = 1;
        Integer activeStatus = 1;
        Integer liveStatus = 1;        //
        EartagEartagRegisterEntity eartagRegisterEntity = eartagRegisterRepo.getOneByEarmark(earmark,farmId);
        if(eartagRegisterEntity == null){
            //{新建耳标注册信息}
            newEartagRegister(earmark,nowTimestamp,deviceCode,registerType,activeStatus,liveStatus,bat,todayDate,farmId);
        }else{
            eartagRegisterEntity.setLastTime(nowTimestamp);
            eartagRegisterEntity.setLastDevice(deviceCode);
            eartagRegisterEntity.setActiveStatus(activeStatus);
            eartagRegisterEntity.setActiveTime(nowTimestamp);
            eartagRegisterEntity.setBat(Integer.parseInt(bat));
            eartagRegisterRepo.saveAndFlush(eartagRegisterEntity);
            //更新耳标注册消息缓存
            cacheService.putEartagRegister(earmark,eartagRegisterEntity);
        }
    }

    //新建耳标注册信息
    private void newEartagRegister(String earmark, Timestamp nowTimestamp, String deviceCode, Integer registerType, Integer activeStatus, Integer liveStatus, String bat, java.sql.Date todayDate, String farmId) {
        //#创建耳标注册记录#
        EartagEartagRegisterEntity newEartagRegisterEntity = new EartagEartagRegisterEntity();
        newEartagRegisterEntity.setEarmark(earmark);
        newEartagRegisterEntity.setFirstTime(nowTimestamp);
        newEartagRegisterEntity.setLastTime(nowTimestamp);
        newEartagRegisterEntity.setFirstDevice(deviceCode);
        newEartagRegisterEntity.setBelongDevice(deviceCode);
        newEartagRegisterEntity.setLastDevice(deviceCode);
        newEartagRegisterEntity.setRegisterTime(nowTimestamp);
        newEartagRegisterEntity.setRegisterType(registerType);
        newEartagRegisterEntity.setFarmId(farmId);
        newEartagRegisterEntity.setActiveStatus(activeStatus);
        newEartagRegisterEntity.setActiveTime(nowTimestamp);
        newEartagRegisterEntity.setLiveStatus(liveStatus);
        newEartagRegisterEntity.setCreateDate(todayDate);
        newEartagRegisterEntity.setBat(Integer.parseInt(bat));
        eartagRegisterRepo.saveAndFlush(newEartagRegisterEntity);
        //{更新耳标注册消息缓存}
        cacheService.putEartagRegister(earmark,newEartagRegisterEntity);
        //{更新耳标数量}
        cacheService.putEartagTotal(getEartagSum(farmId,liveStatus),farmId);
    }

    //计算处于不同生存状态的耳标数量
    private Integer getEartagSum(String farmId,Integer liveStatus){
        List<Object[]> eartagRegList = eartagRegisterRepo.getEartagCountByFarmId(farmId,liveStatus);
        Object[] eartagRegObj = (Object[]) eartagRegList.get(0);
        //处于工作状态的耳标总数
        return Integer.parseInt(eartagRegObj[0].toString());
    }

    /**
     * @Method      : updateDeviceOnline
     * @Description : 更新设备在线统计
     * @Params      : [earmark, deviceCode, nowTimestamp, todayDate, farmId]
     * @Return      : void
     *
     * @Author      : ZhuoNing
     * @Date        : 2022/3/29
     * @Time        : 9:13
     */
    private void updateDeviceOnline(String earmark, String deviceCode, String todayDateText, Timestamp nowTimestamp, java.sql.Date todayDate, JSONObject dataJo, String farmId) {
        // 查询在线统计；
        // 不存在，则新建设备在线统计
        //存在，则直接更新耳标数量；
        String hashKey = BizConst.DEVICE_REGISTER_PREFIX+deviceCode;
        //计算设备别名
        String alias = (String)cacheService.getHashProperty(hashKey,"deviceAlias");
        String earTemp1 =  dataJo.getString("earTemp1");
        String envTemp1 = dataJo.getString("envTemp1");

        //读取在线日期
        EartagDeviceOnlineEntity eartagDeviceOnlineEntity = eartagDeviceOnlineRepo.getDeviceOnline(deviceCode, todayDateText);
        if (eartagDeviceOnlineEntity == null) {
            Integer heartbeatTotal = 0;
            Integer envtempTotal = 0;
            Timestamp heartbeatFirstTime = null;
            Timestamp heartbeatLastTime = null;
            Timestamp envtempFirstTime = null;
            Timestamp envtempLastTime = null;
            Timestamp firstTime = nowTimestamp;
            Timestamp lastTime = nowTimestamp;
            Timestamp eartagFirstTime = nowTimestamp;
            Timestamp eartagLastTime = nowTimestamp;
            Integer eartagTotal = 1;
            Integer liveStatus = 1;
            //{新建设备在线统计并创建缓存}
            newDeviceOnline(deviceCode,alias,heartbeatTotal,envtempTotal,eartagTotal,todayDate,farmId,heartbeatFirstTime,heartbeatLastTime,envtempFirstTime,envtempLastTime,firstTime,lastTime,eartagFirstTime,eartagLastTime,earTemp1,envTemp1,liveStatus);
        }else{

            eartagDeviceOnlineEntity.setAlias(alias);
            int eartagTotal = eartagDeviceOnlineEntity.getEartagTotal();
            eartagDeviceOnlineEntity.setEartagTotal(++eartagTotal);
            eartagDeviceOnlineEntity.setEartagFirstTime(nowTimestamp);
            eartagDeviceOnlineEntity.setEartagLastTime(nowTimestamp);
            eartagDeviceOnlineEntity.setLastEartag(earTemp1);
            eartagDeviceOnlineEntity.setLastEnvtemp(envTemp1);
            if(eartagDeviceOnlineEntity.getFirstTime() == null){
                eartagDeviceOnlineEntity.setFirstTime(nowTimestamp);
            }
            eartagDeviceOnlineEntity.setLastTime(nowTimestamp);
            eartagDeviceOnlineRepo.saveAndFlush(eartagDeviceOnlineEntity);
            //更新设备在线缓存数据
            cacheService.putDeviceInOnline(deviceCode,eartagDeviceOnlineEntity);
        }
    }

    /**
     * @Method      : newDeviceOnline
     * @Description : 新建设备在线
     * @Params      : [deviceCode, alias, heartbeatTotal, envtempTotal, eartagTotal, todayDate, farmId, heartbeatFirstTime, heartbeatLastTime, envtempFirstTime, envtempLastTime, firstTime, lastTime, eartagFirstTime, eartagLastTime]
     * @Return      : void
     *
     * @Author      : ZhuoNing
     * @Date        : 2022/3/29
     * @Time        : 9:44
     */
    private void newDeviceOnline(String deviceCode, String alias, Integer heartbeatTotal, Integer envtempTotal, Integer eartagTotal, java.sql.Date todayDate, String farmId, Timestamp heartbeatFirstTime, Timestamp heartbeatLastTime, Timestamp envtempFirstTime, Timestamp envtempLastTime, Timestamp firstTime, Timestamp lastTime, Timestamp eartagFirstTime, Timestamp eartagLastTime, String earTemp1, String envTemp1, Integer liveStatus) {
        EartagDeviceOnlineEntity newEartagDeviceOnlineEntity = new EartagDeviceOnlineEntity();
        newEartagDeviceOnlineEntity.setDeviceCode(deviceCode);
        newEartagDeviceOnlineEntity.setAlias(alias);
        newEartagDeviceOnlineEntity.setHeartbeatTotal(heartbeatTotal);;
        newEartagDeviceOnlineEntity.setEnvtempTotal(envtempTotal);
        newEartagDeviceOnlineEntity.setEartagTotal(eartagTotal);
        newEartagDeviceOnlineEntity.setFirstTime(firstTime);
        newEartagDeviceOnlineEntity.setLastTime(lastTime);
        newEartagDeviceOnlineEntity.setLastEnvtemp(envTemp1);
        newEartagDeviceOnlineEntity.setLastEartag(earTemp1);
        newEartagDeviceOnlineEntity.setAddDate(todayDate);
        newEartagDeviceOnlineEntity.setFarmId(farmId);
        newEartagDeviceOnlineEntity.setHeartbeatFirstTime(heartbeatFirstTime);
        newEartagDeviceOnlineEntity.setHeartbeatLastTime(heartbeatLastTime);
        newEartagDeviceOnlineEntity.setEnvtempFirstTime(envtempFirstTime);
        newEartagDeviceOnlineEntity.setEnvtempLastTime(envtempLastTime);
        newEartagDeviceOnlineEntity.setEartagFirstTime(eartagFirstTime);
        newEartagDeviceOnlineEntity.setEartagLastTime(eartagLastTime);
        newEartagDeviceOnlineEntity.setLiveStatus(liveStatus);
        eartagDeviceOnlineRepo.saveAndFlush(newEartagDeviceOnlineEntity);
        //将新建的设备在线数据更新到设备在线缓存
        cacheService.putDeviceInOnline(deviceCode,newEartagDeviceOnlineEntity);
    }

    //更新耳标在线数据
    public void updateEartagOnline(String earmark, String deviceCode, String todayDateText, java.sql.Date todayDate, Timestamp nowTimestamp, JSONObject eartagJo, String farmId) {
        //# 判断耳标在线统计数据是否存在
        //      存在，则更新上传记录数、最后上传时间、环境温度，耳根温度，并将上面数据更新到缓存数据中；
        //      不存在，则创建耳标在线记录，并更新到缓存数据中；
        String envTemp = eartagJo.getString("envTemp1");
        String earTemp = eartagJo.getString("earTemp1");
        EartagEartagOnlineEntity eartagOnlineEntity = eartagOnlineRepo.getOneByEarmarkAndFarmId(earmark,todayDateText,farmId);
        if(eartagOnlineEntity == null){
            int total = 1;
            //{新建耳标在线记录}
            newEartagOnline(earmark,total,nowTimestamp,earTemp,envTemp,todayDate,farmId);
        }else{
            int total = eartagOnlineEntity.getTotal();
            eartagOnlineEntity.setTotal(++total);
            eartagOnlineEntity.setLastTime(nowTimestamp);
            eartagOnlineEntity.setEnvTemp(envTemp);
            eartagOnlineEntity.setEartagTemp(earTemp);
            eartagOnlineRepo.saveAndFlush(eartagOnlineEntity);
            //更新耳标在线统计
            cacheService.putEartagOnlineCount(earmark,eartagOnlineEntity);
        }
    }

    //新建耳标在线记录
    private void newEartagOnline(String earmark, int total, Timestamp nowTimestamp, String earTemp, String envTemp, java.sql.Date todayDate, String farmId) {
        EartagEartagOnlineEntity newEartagOnlineEntity = new EartagEartagOnlineEntity();
        newEartagOnlineEntity.setEarmark(earmark);
        newEartagOnlineEntity.setTotal(total);
        newEartagOnlineEntity.setFirstTime(nowTimestamp);
        newEartagOnlineEntity.setLastTime(nowTimestamp);
        newEartagOnlineEntity.setEnvTemp(envTemp);
        newEartagOnlineEntity.setEartagTemp(earTemp);
        newEartagOnlineEntity.setAddDate(todayDate);
        newEartagOnlineEntity.setFarmId(farmId);
        eartagOnlineRepo.saveAndFlush(newEartagOnlineEntity);
        //更新耳标在线统计
        cacheService.putEartagOnlineCount(earmark,newEartagOnlineEntity);
    }

    //更新耳标设备在线次数
    private void updateEartagDeviceOnlineCount(String earmark, String deviceCode, String todayDateText, java.sql.Date todayDate, Timestamp nowTimestamp, String farmId) {
        //从缓存读取耳标关联数据
//        Map timesMap = cacheService.getEartagDeviceOnlineCountEntries(earmark,deviceCode,todayDateText);
//        System.out.println("###################### timesMap>>"+timesMap);
//        if(timesMap.size()==0){
//            System.out.println("==0");
//        }else{
//            System.out.println("!=0");
//        }
        //{读取耳标设备关联统计}
        List<EartagDeviceEartagCountEntity> deviceEartagCountEntityList = deviceEartagCountRepo.getEartagDeviceCount(earmark,deviceCode,todayDateText);
        if(deviceEartagCountEntityList.size()==0){
            Integer count = 1;
            //{新建耳标设备关联统计}
            newEartagDeviceCount(earmark,deviceCode,count,todayDateText,todayDate,nowTimestamp,farmId);
        }else{
            //更新次数
            EartagDeviceEartagCountEntity deviceEartagCountEntity = deviceEartagCountEntityList.get(0);
            int total = deviceEartagCountEntity.getTotal();
            ++total;
            deviceEartagCountEntity.setTotal(total);
            deviceEartagCountEntity.setUpdateTime(nowTimestamp);
            deviceEartagCountRepo.saveAndFlush(deviceEartagCountEntity);
            //缓存里计数+1
            cacheService.countEartagDeviceOnlineTimes(earmark,deviceCode,total,deviceEartagCountEntity);
        }
    }

    //新建耳标设备关联统计记录
    private void newEartagDeviceCount(String earmark, String deviceCode, Integer count, String todayDateText, java.sql.Date todayDate, Timestamp nowTimestamp, String farmId) {
        EartagDeviceEartagCountEntity newDeviceEartagCountEntity = new EartagDeviceEartagCountEntity();
        newDeviceEartagCountEntity.setDeviceCode(deviceCode);
        newDeviceEartagCountEntity.setEarmark(earmark);
        newDeviceEartagCountEntity.setTotal(count);
        newDeviceEartagCountEntity.setCreateDate(todayDate);
        newDeviceEartagCountEntity.setFarmId(farmId);
        newDeviceEartagCountEntity.setUpdateTime(nowTimestamp);
        deviceEartagCountRepo.saveAndFlush(newDeviceEartagCountEntity);
        //将数据保存到缓存中
        cacheService.putEartagDeviceOnlineCount(earmark,deviceCode,todayDateText,newDeviceEartagCountEntity);
    }

    //更新设备环境信息
    public void updateEartagPropertyOfAllStatus(String farmId, String todayDateText, java.sql.Date todayDate, Timestamp nowTimestamp) throws ParseException {
        //{获取处于工作状态的设备数量}
        Integer deviceTotal = deviceService.getDeviceTotalByFarmIdFromDeviceRegister(farmId);
        //设备在线数量
        Integer deviceOnlineSum = cacheService.getDeviceOnlineSum(farmId,todayDateText);
        //设备离线数量
        Integer deviceOfflineSum = 0;
        if(deviceTotal > deviceOnlineSum){
            deviceOfflineSum = deviceTotal - deviceOnlineSum;
        }
        //设备在线率
        BigDecimal deviceRateBd= new BigDecimal(deviceOnlineSum).divide(new BigDecimal(deviceTotal),1,BigDecimal.ROUND_HALF_UP);
        Float deviceOnlineRate = Float.parseFloat(deviceRateBd.toString());
        //{获取注销设备数量}
        Integer deviceCancelSum = deviceService.getDeviceCancelTotalFromDeviceRegister(farmId);
        //耳标总数量 eartagService.
        Integer eartagTotal = getEartagRegTotalByFarmId(farmId);
        System.out.println("## eartagTotal>>"+eartagTotal);
        Integer eartagOnlineSum = 0;
        Float eartagOnlineRate = 0F;
        if(eartagTotal != 0){
            //耳标在线数量 eartagService.
            eartagOnlineSum = getEartagOnelineTotal(farmId,todayDateText);
            eartagOnlineSum++;
            //耳标在线率
            BigDecimal eartagRateBd= new BigDecimal(eartagOnlineSum).divide(new BigDecimal(eartagTotal),1,BigDecimal.ROUND_HALF_UP);
            eartagOnlineRate = Float.parseFloat(eartagRateBd.toString());
        }
        //
        EartarFarmAllStatusEntity farmAllStatusEntity = eartagFarmAllStatusRepo.getOneByFarmIdAndCreateDate(farmId,todayDateText);
        if(farmAllStatusEntity == null){
            //{新建设备状态记录并更新缓存cache}
            newFarmAllStatus(farmId,todayDate,nowTimestamp,deviceTotal,deviceOnlineSum,deviceOfflineSum,deviceCancelSum,deviceOnlineRate,eartagTotal,eartagOnlineSum,eartagOnlineRate);
        }else{
            //计算设备状态并更新缓存cache(在线数+1，离线数-1，计算设备在线率)
            farmAllStatusEntity.setDeviceTotal(deviceTotal);
            farmAllStatusEntity.setDeviceOnline(deviceOnlineSum);
            farmAllStatusEntity.setDeviceOffline(deviceOfflineSum);
            farmAllStatusEntity.setDeviceRate(deviceOnlineRate);
            farmAllStatusEntity.setDeviceCancel(deviceCancelSum);
            farmAllStatusEntity.setEartagTotal(eartagTotal);
            farmAllStatusEntity.setEartagOnline(eartagOnlineSum);
            farmAllStatusEntity.setEartagRate(eartagOnlineRate);
            farmAllStatusEntity.setUpdateTime(nowTimestamp);
            eartagFarmAllStatusRepo.saveAndFlush(farmAllStatusEntity);
            //{同步更新牧场总状态缓存相关字段}
            cacheService.flashAllStatusCache(farmId,farmAllStatusEntity);
        }
    }

    //# 新建总状态记录 #
    private void newFarmAllStatus(String farmId, java.sql.Date todayDate, Timestamp nowTimestamp, Integer deviceTotal, Integer deviceOnlineSum, Integer deviceOfflineSum, Integer deviceCancelSum, Float deviceOnlineRate, Integer eartagTotal, Integer eartagOnlineSum, Float eartagOnlineRate) {
        Integer liveStatus = 1;
        if(deviceService.getDeviceSum(farmId,liveStatus) == 0){
            log.error("该牧场没有任何处于工作状态的采集器设备.");
        }else{
            //# 计算耳标总数（耳标注册表）
            EartarFarmAllStatusEntity farmAllStatusEntity = new EartarFarmAllStatusEntity();
            farmAllStatusEntity.setDeviceTotal(deviceTotal);
            farmAllStatusEntity.setDeviceOnline(deviceOnlineSum);
            farmAllStatusEntity.setDeviceOffline(deviceOfflineSum);
            farmAllStatusEntity.setDeviceRate(deviceOnlineRate);
            farmAllStatusEntity.setDeviceCancel(deviceCancelSum);
            farmAllStatusEntity.setEartagTotal(eartagTotal);
            farmAllStatusEntity.setEartagOnline(eartagOnlineSum);
            farmAllStatusEntity.setEartagRate(eartagOnlineRate);
            farmAllStatusEntity.setFarmId(farmId);
            farmAllStatusEntity.setUpdateTime(nowTimestamp);
            farmAllStatusEntity.setCreateDate(todayDate);
            eartagFarmAllStatusRepo.saveAndFlush(farmAllStatusEntity);
            //设置总状态缓存
            cacheService.flashAllStatusCache(farmId,farmAllStatusEntity);
        }
    }

    @Override
    public Integer getEartagRegTotalByFarmId(String farmId){
        //从缓存读取耳标总数
        Integer eartagTotal = cacheService.getEartagTotal(farmId);
        if(eartagTotal != null && eartagTotal != 0){
            return eartagTotal;
        }else{
//            List<Object[]> eartagRegList = eartagRegisterRepo.getEartagCountByFarmId(farmId);
//            Object[] eartagRegObj = (Object[]) eartagRegList.get(0);
//            Integer total = Integer.parseInt(eartagRegObj[0].toString());
            ///
            Integer liveStatus = 1;
            //{读取处于工作状态的耳标总数}
            Integer total = getEartagSum(farmId,liveStatus);
            //设置耳标总数缓存
            cacheService.putEartagTotal(total,farmId);
            //处于工作状态的耳标总数
            return total;
        }
    }

    public Integer getEartagOnelineTotal(String farmId, String todayDateText) {
        return cacheService.getEartagOnlineTotalFromCache(farmId,todayDateText);
    }

    /**
     * @Method : countAct
     * @Description : 计算act数值
     * @Params : [deviceCode, nowAct0]
     * @Return : java.lang.Integer
     * @Author : ZhuoNing
     * @Date : 2022/1/18
     * @Time : 15:25
     */
    @Override
    public Integer countEartagAct(String earmark, String nowAct) {
        //读取hash
        Object lastActObj = cacheService.getEartagLastAct(earmark);
        cacheService.putEartagAct(earmark,nowAct);
        //
//        Object testActObj = cacheService.getEartagLastAct(earmark);
//        System.out.println("## TEST testActObj>>"+testActObj);
        if (lastActObj != null) {
            return Integer.parseInt(nowAct) - Integer.parseInt(lastActObj.toString());
        }else{
            //{初始化最新的redis记录}
//            cacheService.putEartagAct(earmark,nowAct);
            //第一次的运动量计数
//            return Integer.parseInt(nowAct) - 0;
            return 0;
            //验证刚才初始化结果
//            Object lastAct = cacheService.getEartagLastAct(earmark);
//            if (lastAct == null) {
//                log.error("#--- redis数据库有问题，请检查redis是否能正常连接 ---# ");
//                return 0;
//            }else{
//                return Integer.parseInt(lastAct.toString());
//            }
        }
    }




}
