/*
Copyright [2020] [https://www.xiaonuo.vip]

Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at

  http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.

Snowy采用APACHE LICENSE 2.0开源协议，您在使用过程中，需要注意以下几点：

1.请不要删除和修改根目录下的LICENSE文件。
2.请不要删除和修改Snowy源码头部的版权声明。
3.请保留源码和相关描述文件的项目出处，作者声明等。
4.分发源码时候，请注明软件出处 https://gitee.com/xiaonuobase/snowy
5.在修改包名，模块名称，项目代码等时，请注明软件出处 https://gitee.com/xiaonuobase/snowy
6.若您的项目无法满足以上几点，可申请商业授权，获取Snowy商业授权许可，请在官网购买授权，地址为 https://www.xiaonuo.vip
 */


package com.huimv.modular.eartagdata.service.impl;


import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.util.ObjectUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.huimv.core.exception.ServiceException;
import com.huimv.core.factory.PageFactory;
import com.huimv.core.pojo.page.PageResult;
import com.huimv.core.pojo.response.ResponseData;
import com.huimv.core.pojo.response.SuccessResponseData;
import com.huimv.core.util.PoiUtil;
import com.huimv.modular.basepigpen.mapper.BasePigpenMapper;
import com.huimv.modular.collectorregister.EartagDataCountVo;
import com.huimv.modular.collectorregister.entity.CollectorRegister;
import com.huimv.modular.collectorregister.mapper.CollectorRegisterMapper;
import com.huimv.modular.eartagdata.entity.EartagData;
import com.huimv.modular.eartagdata.entity.EartagParamVo;
import com.huimv.modular.eartagdata.entity.TempMovePenEntity;
import com.huimv.modular.eartagdata.entity.vo.EartagDataVo;
import com.huimv.modular.eartagdata.enums.EartagDataExceptionEnum;
import com.huimv.modular.eartagdata.mapper.EartagDataMapper;
import com.huimv.modular.eartagdata.param.EartagDataParam;
import com.huimv.modular.eartagdata.service.EartagDataService;
import com.huimv.modular.eartagregister.entity.EartagRegister;
import com.huimv.modular.eartagregister.mapper.EartagRegisterMapper;
import com.huimv.modular.eartagregister.service.EartagRegisterService;
import com.huimv.modular.movepigpen.entity.MovePigpen;
import com.huimv.modular.movepigpen.mapper.MovePigpenMapper;
import com.huimv.modular.utils.util.DateUtilsPublic;
import com.huimv.modular.utils.util.StringUtilsWork;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import java.text.DateFormat;
import java.text.DecimalFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;

/**
 * 耳标数据详情service接口实现类
 *
 * @author Yangdi
 * @date 2021-08-19 13:18:22
 */
@Service
public class EartagDataServiceImpl extends ServiceImpl<EartagDataMapper, EartagData> implements EartagDataService    {

    @Autowired
    private CollectorRegisterMapper collectorRegisterMapper;

    @Autowired
    private BasePigpenMapper  basePigpenMapper  ;
    
    @Autowired
    private MovePigpenMapper  movePigpenMapper  ;

    @Autowired
    private EartagRegisterMapper eartagRegisterMapper     ;

    @Autowired
    private EartagRegisterService eartagRegisterService   ;


    @Autowired
    private EartagDataMapper eartagDataMapper   ;

    @Override
    public PageResult<EartagData> findByConditionsNew(Map<String, Object> params) throws ParseException {
        String farmID = (String) params.get("farmID");//牧场编码
        String orgId = (String) params.get("orgId");//牧场编码
        String starttime = (String) params.get("startTime");//开始时间
        String endtime = (String) params.get("endTime");//结束时间
        String eartagNo = (String) params.get("eartagNo");//耳标号
        String dayAge = (String) params.get("dayAge");//最低日龄
        String dayAge2 = (String) params.get("dayage2");//最高日龄
        String highEartagTemp = (String) params.get("highEartagTemp");//耳标温度
        String lowEartagTemp = (String) params.get("lowEartagTemp");//耳标温度
        String highEnvTemp = (String) params.get("highEnvTemp");//环境温度
        String lowEnvTemp = (String) params.get("lowEnvTemp");//环境温度
        String deviceCode = (String) params.get("deviceCode");//采集器编码
        String bat = (String) params.get("pageNo");//电量
        String pageNo =  (String)params.get("pageNo");
        String pageSize =  (String)params.get("pageSize");
        String penId = (String) params.get("penId");//栋舍

        //日龄的展示多少有点问题
        System.out.println("采集器+condition---" + deviceCode + "耳标号" + eartagNo);
        //只要首页限制在第一页，其余的不需要的

        LambdaQueryWrapper<EartagData> wrapper = Wrappers.lambdaQuery();
        if (StringUtilsWork.isNotBlank(orgId)) {  //StringUtils.isNotEmpty(orderField) && StringUtils.isNotEmpty(order)
            wrapper.eq(EartagData::getOrgId, orgId);
        }
        if (StringUtilsWork.isNotBlank(farmID)) {  //StringUtils.isNotEmpty(orderField) && StringUtils.isNotEmpty(order)
            wrapper.eq(EartagData::getFarmCode, farmID);
        }
        //日龄要做判断---
        if (StringUtilsWork.isNotBlank(eartagNo)) {
            wrapper.eq(EartagData::getEartagNo, eartagNo);
        }
        if (StringUtilsWork.isNotBlank(eartagNo)) {
            wrapper.eq(EartagData::getEartagNo, eartagNo);
        }
        //栋舍id
        if (StringUtilsWork.isNotBlank(penId)) {
            wrapper.eq(EartagData::getPigpen, penId);
        }
        if (StringUtilsWork.isNotBlank(deviceCode)) {
            wrapper.eq(EartagData::getDeviceCode, deviceCode);
        }

        if (StringUtilsWork.isNotBlank(starttime) & StringUtilsWork.isNotBlank(endtime)) {
            System.out.println(starttime + "***shijian**" + endtime);
            DateFormat fmt = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            //格式化传入的时间
            Date startTime = fmt.parse(starttime);
            Date endTime = fmt.parse(endtime);
            //过滤时间
            wrapper.between(EartagData::getTime, startTime, endTime);
        }

        if (StringUtilsWork.isNotBlank(highEartagTemp) & StringUtilsWork.isNotBlank(lowEartagTemp)) {
            wrapper.between(EartagData::getEarTemp, highEartagTemp, lowEartagTemp);
        }
        if (StringUtilsWork.isNotBlank(highEnvTemp) & StringUtilsWork.isNotBlank(lowEnvTemp)) {
            wrapper.between(EartagData::getEnvTemp, highEnvTemp, lowEnvTemp);
        }
        List<EartagData> records;
        PageResult<EartagData> EartagDataPageResult ;
        //PageResult<List<EartagData> EartagDataPageResult1  = new PageResult<>();
        //如果没有传耳标号，就展示符合条件的最新一条，若是传了，就展示当前耳标下的最近数据
        if (StringUtilsWork.isNotBlank(eartagNo)) {
            System.out.println("有耳标号，展示耳标所有数据");
            wrapper.orderByDesc(EartagData::getId);
            EartagDataPageResult = new PageResult<>(this.page(PageFactory.defaultPage(), wrapper));
            records = EartagDataPageResult.getRows();  //获取信息
        } else {
            //太慢了 优化
            System.out.println("没有耳标号，展示最新的所有的耳标数据");
            wrapper.groupBy(EartagData::getEartagNo).orderByDesc(EartagData::getId);
            IPage<EartagData> iPage = new Page<>( Long.parseLong(pageNo),Long.parseLong(pageSize));
            Page<EartagData> page = baseMapper.findByCondition(iPage, wrapper);
            records=page.getRecords();
            System.out.println(page);
            EartagDataPageResult = new PageResult<>(page);

            //
            for (EartagData record : records) {
                //通过最新的转舍信息确认当前位置--之前设想转舍信息会更新  实际上是没有必要的   就用谁上传的就行
                LambdaQueryWrapper<MovePigpen> wrapper23 = Wrappers.lambdaQuery();
                wrapper23.eq(MovePigpen::getEartagNo, record.getEartagNo()).orderByAsc(MovePigpen::getId).last("limit 1");
                MovePigpen movePigpen = movePigpenMapper.selectOne(wrapper23);
                System.out.println("转舍信息" + movePigpen + "转舍耳标号" + record.getEartagNo());
                //获取注册---注册信息为空
                LambdaQueryWrapper<CollectorRegister> wrapper3 = Wrappers.lambdaQuery();
                wrapper3.eq(CollectorRegister::getDeviceCode, record.getDeviceCode());
                CollectorRegister collectorRegister = collectorRegisterMapper.selectOne(wrapper3);
                System.out.println("注册表信息" + collectorRegister);
                record.setVersion(collectorRegister.getUnitName());//这个多余字段存猪舍名字
                record.setCommand(collectorRegister.getPenName());//这个多余字段存单元名字
                //格式化传入的时---第一条不应该没有----但是新耳标上来没有存信息-应该也有的
                if (movePigpen != null) {
                    record.setTail(DateUtilsPublic.dateToString(movePigpen.getMoveDate()));//配标时间
                }
            }

            return  EartagDataPageResult;
        }


        //拼接栋舍信息在里面
        for (EartagData record : records) {
            //还要装日龄和配标日龄
            LambdaQueryWrapper<EartagRegister> wrapper231 = Wrappers.lambdaQuery();
            wrapper231.eq(EartagRegister::getEartagNo, record.getEartagNo());
            EartagRegister eartagRegister = eartagRegisterMapper.selectOne(wrapper231);
            record.setTail(String.valueOf(eartagRegister.getAge()));
            record.setPrepareField( String.valueOf(eartagRegister.getWeartagAge()));

            //这一页的数据
            System.out.println("数据record" + records);
            LambdaQueryWrapper<MovePigpen> wrapper23 = Wrappers.lambdaQuery();
            wrapper23.eq(MovePigpen::getEartagNo, record.getEartagNo()).orderByAsc(MovePigpen::getId).last("limit 1");
            MovePigpen movePigpen = movePigpenMapper.selectOne(wrapper23);
            System.out.println("转舍信息" + movePigpen + "转舍耳标号" + record.getEartagNo());
            //获取注册---注册信息为空
            LambdaQueryWrapper<CollectorRegister> wrapper3 = Wrappers.lambdaQuery();
            wrapper3.eq(CollectorRegister::getDeviceCode, record.getDeviceCode());
            CollectorRegister collectorRegister = collectorRegisterMapper.selectOne(wrapper3);
            System.out.println("注册表信息" + collectorRegister);

            record.setVersion(collectorRegister.getUnitName());//这个多余字段存猪舍名字
            record.setCommand(collectorRegister.getPenName());//这个多余字段存单元名字
            //格式化传入的时---第一条不应该没有----但是新耳标上来没有存信息
            if (movePigpen != null) {
                record.setTail(DateUtilsPublic.dateToString(movePigpen.getMoveDate()));//配标时间
            }
        }
        return  EartagDataPageResult;
    }





    @Override
    public PageResult<EartagData> findByTime(Map<String, Object> params) throws ParseException {

        String starttime = (String) params.get("startTime");//开始时间
        String endtime = (String) params.get("endTime");//结束时间
        String eartagNo = (String) params.get("eartagNo");//耳标号
        LambdaQueryWrapper<EartagData> wrapper = Wrappers.lambdaQuery();
        if (StringUtilsWork.isNotBlank(starttime) & StringUtilsWork.isNotBlank(endtime)) {
            System.out.println(starttime + "***shijian**" + endtime);
            DateFormat fmt = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            //格式化传入的时间
            Date startTime = fmt.parse(starttime);
            Date endTime = fmt.parse(endtime);
            System.out.println("yangdi" + starttime + endtime);
            //过滤时间
            wrapper.between(EartagData::getTime, startTime, endTime);

            if (StringUtilsWork.isNotBlank(eartagNo)) {
                wrapper.eq(EartagData::getEartagNo, eartagNo);
                PageResult<EartagData> EartagDataPageResult  = new PageResult<>();
                System.out.println("有耳标号，展示耳标所有数据");
                EartagDataPageResult = new PageResult<>(this.page(PageFactory.defaultPage(), wrapper));
                return EartagDataPageResult;

            }



        }
            PageResult<EartagData> EartagDataPageResult  = new PageResult<>();
            System.out.println("有耳标号，展示耳标所有数据");
            EartagDataPageResult = new PageResult<>(this.page(PageFactory.defaultPage(), wrapper));
            return EartagDataPageResult;
    }







    @Override
    public PageResult<EartagData> findByConditions(Map<String, Object> params) throws ParseException {
        String farmID = (String) params.get("farmID");//牧场编码
        String orgId = (String) params.get("orgId");//牧场编码
        String starttime = (String) params.get("startTime");//开始时间
        String endtime = (String) params.get("endTime");//结束时间
        String eartagNo = (String) params.get("eartagNo");//耳标号
        String dayAge = (String) params.get("dayAge");//最低日龄
        String dayAge2 = (String) params.get("dayage2");//最高日龄
        String highEartagTemp = (String) params.get("highEartagTemp");//耳标温度
        String lowEartagTemp = (String) params.get("lowEartagTemp");//耳标温度
        String highEnvTemp = (String) params.get("highEnvTemp");//环境温度
        String lowEnvTemp = (String) params.get("lowEnvTemp");//环境温度
        String deviceCode = (String) params.get("deviceCode");//采集器编码
        String bat = (String) params.get("pageNo");//电量
        String pageNo =  (String)params.get("pageNo");
        String pageSize =  (String)params.get("pageSize");
        String penId = (String) params.get("penId");//栋舍

         //日龄的展示多少有点问题
        System.out.println("采集器+condition---" + deviceCode + "耳标号" + eartagNo);
        //只要首页限制在第一页，其余的不需要的

        LambdaQueryWrapper<EartagData> wrapper = Wrappers.lambdaQuery();
        if (StringUtilsWork.isNotBlank(orgId)) {  //StringUtils.isNotEmpty(orderField) && StringUtils.isNotEmpty(order)
            wrapper.eq(EartagData::getOrgId, orgId);
        }
        if (StringUtilsWork.isNotBlank(farmID)) {  //StringUtils.isNotEmpty(orderField) && StringUtils.isNotEmpty(order)
            wrapper.eq(EartagData::getFarmCode, farmID);
        }
        //日龄要做判断---
        if (StringUtilsWork.isNotBlank(eartagNo)) {
            wrapper.eq(EartagData::getEartagNo, eartagNo);
        }
        if (StringUtilsWork.isNotBlank(eartagNo)) {
            wrapper.eq(EartagData::getEartagNo, eartagNo);
        }
        //栋舍id
        if (StringUtilsWork.isNotBlank(penId)) {
            wrapper.eq(EartagData::getPigpen, penId);
        }
        if (StringUtilsWork.isNotBlank(deviceCode)) {
            wrapper.eq(EartagData::getDeviceCode, deviceCode);
        }

        if (StringUtilsWork.isNotBlank(starttime) & StringUtilsWork.isNotBlank(endtime)) {
            System.out.println(starttime + "***shijian**" + endtime);
            DateFormat fmt = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            //格式化传入的时间
            Date startTime = fmt.parse(starttime);
            Date endTime = fmt.parse(endtime);
            //过滤时间
            wrapper.between(EartagData::getTime, startTime, endTime);
        }

        if (StringUtilsWork.isNotBlank(highEartagTemp) & StringUtilsWork.isNotBlank(lowEartagTemp)) {
            wrapper.between(EartagData::getEarTemp, highEartagTemp, lowEartagTemp);
        }
        if (StringUtilsWork.isNotBlank(highEnvTemp) & StringUtilsWork.isNotBlank(lowEnvTemp)) {
            wrapper.between(EartagData::getEnvTemp, highEnvTemp, lowEnvTemp);
        }
        List<EartagData> records;
        PageResult<EartagData> EartagDataPageResult ;
       //PageResult<List<EartagData> EartagDataPageResult1  = new PageResult<>();
          //如果没有传耳标号，就展示符合条件的最新一条，若是传了，就展示当前耳标下的最近数据
        if (StringUtilsWork.isNotBlank(eartagNo)) {
            System.out.println("有耳标号，展示耳标所有数据");
            wrapper.orderByDesc(EartagData::getId);
            EartagDataPageResult = new PageResult<>(this.page(PageFactory.defaultPage(), wrapper));
            records = EartagDataPageResult.getRows();  //获取信息
        } else {
            //太慢了 优化
            System.out.println("没有耳标号，展示最新的所有的耳标数据");
            wrapper.groupBy(EartagData::getEartagNo).orderByDesc(EartagData::getId);
            IPage<EartagData> iPage = new Page<>( Long.parseLong(pageNo),Long.parseLong(pageSize));
            Page<EartagData> page = baseMapper.findByCondition(iPage, wrapper);
            records=page.getRecords();
            System.out.println(page);
                  EartagDataPageResult = new PageResult<>(page);
            for (EartagData record : records) {
                LambdaQueryWrapper<MovePigpen> wrapper23 = Wrappers.lambdaQuery();
                wrapper23.eq(MovePigpen::getEartagNo, record.getEartagNo()).orderByAsc(MovePigpen::getId).last("limit 1");
                MovePigpen movePigpen = movePigpenMapper.selectOne(wrapper23);
                System.out.println("转舍信息" + movePigpen + "转舍耳标号" + record.getEartagNo());
                //获取注册---注册信息为空
                LambdaQueryWrapper<CollectorRegister> wrapper3 = Wrappers.lambdaQuery();
                wrapper3.eq(CollectorRegister::getDeviceCode, record.getDeviceCode());
                CollectorRegister collectorRegister = collectorRegisterMapper.selectOne(wrapper3);
                System.out.println("注册表信息" + collectorRegister);
                record.setVersion(collectorRegister.getUnitName());//这个多余字段存猪舍名字
                record.setCommand(collectorRegister.getPenName());//这个多余字段存单元名字
                //格式化传入的时---第一条不应该没有----但是新耳标上来没有存信息
                if (movePigpen != null) {
                    record.setTail(DateUtilsPublic.dateToString(movePigpen.getMoveDate()));//配标时间
                }
            }


            return  EartagDataPageResult;
        }


        //拼接栋舍信息在里面
        for (EartagData record : records) {
            //还要装日龄和配标日龄
            LambdaQueryWrapper<EartagRegister> wrapper231 = Wrappers.lambdaQuery();
            wrapper231.eq(EartagRegister::getEartagNo, record.getEartagNo());
            EartagRegister eartagRegister = eartagRegisterMapper.selectOne(wrapper231);
            record.setTail(String.valueOf(eartagRegister.getAge()));
            record.setPrepareField( String.valueOf(eartagRegister.getWeartagAge()));

            //这一页的数据
            System.out.println("数据record" + records);
            LambdaQueryWrapper<MovePigpen> wrapper23 = Wrappers.lambdaQuery();
            wrapper23.eq(MovePigpen::getEartagNo, record.getEartagNo()).orderByAsc(MovePigpen::getId).last("limit 1");
            MovePigpen movePigpen = movePigpenMapper.selectOne(wrapper23);
            System.out.println("转舍信息" + movePigpen + "转舍耳标号" + record.getEartagNo());
            //获取注册---注册信息为空
            LambdaQueryWrapper<CollectorRegister> wrapper3 = Wrappers.lambdaQuery();
            wrapper3.eq(CollectorRegister::getDeviceCode, record.getDeviceCode());
            CollectorRegister collectorRegister = collectorRegisterMapper.selectOne(wrapper3);
            System.out.println("注册表信息" + collectorRegister);

            record.setVersion(collectorRegister.getUnitName());//这个多余字段存猪舍名字
            record.setCommand(collectorRegister.getPenName());//这个多余字段存单元名字
            //格式化传入的时---第一条不应该没有----但是新耳标上来没有存信息
            if (movePigpen != null) {
                record.setTail(DateUtilsPublic.dateToString(movePigpen.getMoveDate()));//配标时间
            }
        }
        return  EartagDataPageResult;
    }


    @Override
    public  PageResult<EartagDataVo>  queryPageIndex(EartagParamVo eartagParamVo) throws ParseException {

        IPage<EartagDataVo> eartagDataVoIPage = new Page<>();
        System.out.println(eartagParamVo.getPage());
        System.out.println(eartagParamVo.getLimit());
        eartagDataVoIPage.setCurrent(Integer.parseInt(eartagParamVo.getPage()));
        eartagDataVoIPage.setSize(Integer.parseInt(eartagParamVo.getLimit()));

        PageResult<EartagDataVo> eartagDataVoPageResult = new PageResult<>(eartagDataMapper.pageIndex(eartagDataVoIPage, eartagParamVo));
        
        return      eartagDataVoPageResult ;
    }


    //迁移接口
    //耳标详细数据
    @Override
    public   Map  queryEartagDeatils(EartagParamVo eartagParamVo) throws ParseException {
        
        System.out.println("耳标号="+eartagParamVo.getEartagNo());
        LambdaQueryWrapper<EartagData> wrapper = Wrappers.lambdaQuery();
        wrapper.eq(EartagData::getEartagNo, eartagParamVo.getEartagNo()).orderByDesc(EartagData::getId);
        if(eartagParamVo.getStarTime()!=null){
            //传了时间按照时间
            wrapper.between(EartagData::getTime, eartagParamVo.getStarTime(), eartagParamVo.getEndTime());
        }else {
            //没有时间返回最近的1000条
            wrapper.last( "limit 2000");
        }
        System.out.println("耳标号="+eartagParamVo.getEartagNo());
        List<EartagData> eartagDataEntities = eartagDataMapper.selectList(wrapper);
        Map resultMap  = new HashMap();
        List<String> timeList = new ArrayList<>();
        List<Double> earTempList = new ArrayList<>();
        List<Integer> sportsList = new ArrayList<>();
        List<Integer> electricList = new ArrayList<>();
        List<Double> environmentTempList = new ArrayList<>();
        List<Object> averangeTemp = new ArrayList<>();
        List<Integer> exerciseList = new ArrayList<>();
        DateFormat fmt = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");

        for (EartagData eartagDataEntity : eartagDataEntities) {
            timeList.add( fmt.format(eartagDataEntity.getTime() ));
            earTempList.add( eartagDataEntity.getEarTemp()  );
            electricList.add(eartagDataEntity.getBat());
            environmentTempList.add(eartagDataEntity.getEnvTemp());
            sportsList.add(eartagDataEntity.getSportGap());
            exerciseList.add(eartagDataEntity.getExercise());
        }


        Collections.reverse(timeList);
        Collections.reverse(earTempList);
        Collections.reverse(electricList);
        Collections.reverse(environmentTempList);
        Collections.reverse(sportsList);
        Collections.reverse(exerciseList);

        resultMap.put("timeList",timeList);
        resultMap.put("earTempList",earTempList);
        resultMap.put("electricList",electricList);
        resultMap.put("environmentTempList",environmentTempList);
        resultMap.put("sportsList",sportsList);
        resultMap.put("exerciseList",exerciseList);
        return resultMap;

    }





    
    
    
    


/*

    //直接构建wapper
    //时间还是要判断，如果没有时间直接倒序  有时间就按时间过滤
    LambdaQueryWrapper<EartagData> wrapper = Wrappers.lambdaQuery();
        wrapper.eq(EartagData::getEartagNo, eartagParamVo.getEartagNo()).orderByDesc(EartagData::getId);
        if(eartagParamVo.getStarTime()!=null){
        //传了时间按照时间
        wrapper.between(EartagData::getTime, eartagParamVo.getStarTime(), eartagParamVo.getEndTime());
    }else {
        //没有时间返回最近的1000条
        wrapper.last( "limit 2000");
    }
        System.out.println("耳标号="+eartagParamVo.getEartagNo());
    List<EartagData> eartagDataEntities = eartagDataMapper.selectList(wrapper);
    Map resultMap  = new HashMap();
    List<String> timeList = new ArrayList<>();
    List<Double> earTempList = new ArrayList<>();
    List<Integer> sportsList = new ArrayList<>();
    List<Integer> electricList = new ArrayList<>();
    List<Double> environmentTempList = new ArrayList<>();
    List<Object> averangeTemp = new ArrayList<>();
    List<Integer> exerciseList = new ArrayList<>();
    DateFormat fmt = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");

        for (EartagData eartagDataEntity : eartagDataEntities) {
        timeList.add( fmt.format(eartagDataEntity.getTime() ));
        earTempList.add( eartagDataEntity.getEarTemp()  );
        electricList.add(eartagDataEntity.getBat());
        environmentTempList.add(eartagDataEntity.getEnvTemp());
        sportsList.add(eartagDataEntity.getSportGap());
        exerciseList.add(eartagDataEntity.getExercise());
    }
        Collections.reverse(timeList);
        Collections.reverse(earTempList);
        Collections.reverse(electricList);
        Collections.reverse(environmentTempList);
        Collections.reverse(sportsList);
        Collections.reverse(exerciseList);

        resultMap.put("timeList",timeList);
        resultMap.put("earTempList",earTempList);
        resultMap.put("electricList",electricList);
        resultMap.put("environmentTempList",environmentTempList);
        resultMap.put("sportsList",sportsList);
        resultMap.put("exerciseList",exerciseList);
        return resultMap;







*/



















    @Override
    public Map<String, Object> queryDetailsByEarTag(Map<String, Object> params) throws ParseException {

        System.out.println("eartagno = "+params.get("eartagNo"));
        System.out.println("orgId = "+params.get("orgId"));
        String  eartagno1 = String.valueOf(params.get("eartagNo"));
        String  orgId = String.valueOf(params.get("orgId"));
        String starttime = String.valueOf(params.get("startTime"));
        String endtime = String.valueOf( params.get("endTime"));


        //找出对应的ID
        LambdaQueryWrapper<EartagData> wrapper = Wrappers.lambdaQuery();
        wrapper.eq(EartagData::getEartagNo, eartagno1 ).orderByDesc( EartagData::getId ).last( "limit 1");
        EartagData  earTagData = eartagDataMapper.selectOne(wrapper);
        if(earTagData==null){
            Map map = new HashMap();
            map.put("error" ,"当前数据不存在");
            return  map;
        }

        //找出对应的ID
        LambdaQueryWrapper<EartagRegister> wrapper12 = Wrappers.lambdaQuery();
        wrapper12.eq(EartagRegister::getEartagNo, eartagno1 ).orderByDesc( EartagRegister::getId ).last( "limit 1");
        EartagRegister eartagRegister = eartagRegisterMapper.selectOne(wrapper12);
        if(earTagData==null){
            Map map = new HashMap();
            map.put("error" ,"当前数据不存在");
            return  map;
        }

        //对数据进行包装
        LambdaQueryWrapper<CollectorRegister> wrapper1 = Wrappers.lambdaQuery();
        wrapper1.eq(CollectorRegister::getDeviceCode, earTagData.getDeviceCode() );

        CollectorRegister collectorRegister = collectorRegisterMapper.selectOne(wrapper1);
        Map<String ,Object>    map1 = new HashMap<>();
        map1.put("Registentity",collectorRegister);//耳标所在的机器信息
        Map<String, Object>  pen = new HashMap<>();
        //倒数yi条
        LambdaQueryWrapper<MovePigpen> wrapper2 = Wrappers.lambdaQuery();
        wrapper2.eq(MovePigpen::getEartagNo , earTagData.getEartagNo()).orderByDesc( MovePigpen::getId ).last( "limit 1");
        List<MovePigpen> movePigpenEntities = movePigpenMapper.selectList(wrapper2);
        //时间最开始的一条
        LambdaQueryWrapper<MovePigpen> wrapper23 = Wrappers.lambdaQuery();
        wrapper23.eq(MovePigpen::getEartagNo , earTagData.getEartagNo()).orderByAsc( MovePigpen::getId ).last( "limit 1");
        MovePigpen  movePigpen = movePigpenMapper.selectOne(wrapper23);

        movePigpenEntities.add(movePigpen);//加上去l

        System.out.println(movePigpen+"ioioio");//最开始不为空

        System.out.println(movePigpenEntities+"opop");

        if ( movePigpen!=null ) {
            List<Object> movePigpe111 = new ArrayList<>();
            for (MovePigpen MovePigpen : movePigpenEntities) {
                Map<String, Object> c = new HashMap<>();

                LambdaQueryWrapper<CollectorRegister> wrapper3 = Wrappers.lambdaQuery();
                wrapper3.eq(CollectorRegister::getDeviceCode, MovePigpen.getDeviceCode());
                CollectorRegister collectorRegisterEntit = collectorRegisterMapper.selectOne(wrapper3);

                TempMovePenEntity tempMovePenEntity = new TempMovePenEntity();
                tempMovePenEntity.setDeviceCode(MovePigpen.getDeviceCode());
                tempMovePenEntity.setEartagNo(MovePigpen.getEartagNo());
                tempMovePenEntity.setPenName(collectorRegisterEntit.getPenName());
                tempMovePenEntity.setUnitname(collectorRegisterEntit.getUnitName());
                tempMovePenEntity.setMoveDate(MovePigpen.getMoveDate());
                tempMovePenEntity.setId(MovePigpen.getId());
                tempMovePenEntity.setStage(MovePigpen.getStage());
                movePigpe111.add(tempMovePenEntity);
            }
            map1.put("movePigPenData",movePigpe111);
        }else{
            map1.put("movePigPenData",null);}

        map1.put("eartagdeta",earTagData);  //点击的耳标信息

        //获取运动等信息
        String eartag = earTagData.getEartagNo();
        DateFormat fmt = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");

        //格式化传入的时间
        Date startTime = fmt.parse(starttime);
        Date   endTime = fmt.parse(endtime);
        System.out.println("yangdi"+starttime+endtime);

        LambdaQueryWrapper<EartagData> lambdaQuery = Wrappers.lambdaQuery();
        lambdaQuery.eq(EartagData::getEartagNo,eartag);
        //过滤时间
        lambdaQuery.between(EartagData::getTime,startTime, endTime);
        List<EartagData> eartagDateEntities = baseMapper.selectList(lambdaQuery);
        //生成平均温度 -----如果刚刚转舍就没办法操作了---数据不会立马出来需要等

        LambdaQueryWrapper<EartagData> lambdaQuery1 = Wrappers.lambdaQuery();
        lambdaQuery1.eq(EartagData::getDeviceCode,earTagData.getDeviceCode());
        //过滤时间
        lambdaQuery1.between(EartagData::getTime,startTime, endTime);
        List<EartagData> eartagDateEntities1 = baseMapper.selectList(lambdaQuery1);
        Map averange = getAverange(starttime, endtime, eartagDateEntities1);

        //这样，时间轴

        List<String> timeList = new ArrayList<>();
        List<Double>  tempList = new ArrayList<>();
        List<Integer>  sportsList = new ArrayList<>();
        List<Integer> electricList = new ArrayList<>();
        List<Double> environmenttempList = new ArrayList<>();
        List<Object> averangeTemp = new ArrayList<>();

        for (EartagData data : eartagDateEntities) {
            timeList.add(fmt.format(data.getTime()));
            tempList.add(data.getEarTemp());
            if (data.getDeviceCode() == null) {
                sportsList.add(0);
            } else {
                sportsList.add(data.getSportGap());
            }
            electricList.add(data.getBat());
            //sleeptime.add(data.getSleepStatus());    用来存睡眠状态了
            environmenttempList.add(data.getEnvTemp());
            averangeTemp.add(averange.get(getMonthDayHour(  data.getTime()  ) ) );
        }

        map1.put("time",timeList);
        map1.put("temp",tempList);
        map1.put("sports",sportsList);
        map1.put("electric",electricList);
        map1.put("environmenttemp",environmenttempList);
        map1.put("averangeTemp",averangeTemp);
        map1.put("eartagRegistInfo",eartagRegister);
        System.out.println("changdu"+timeList.size()+"**"+averangeTemp.size()
        );
        //对time循环--用contains来处理稍微快一点
        //map1.put("averangeTemp",averange);
        //关于耳标存在的位置的信息，这里需要做记录，如果发生位置迁移那么需要将位置迁移信息记录到一张表中
        return map1;
    }




    public   Map<String ,String>    getAverange(String  starttime , String endtime  , List<EartagData> entityList     ) throws ParseException {
        DecimalFormat df = new DecimalFormat("####0.00");
        DateFormat fmt1 = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");

        //格式化传入的时间
        Date startTime = fmt1.parse(starttime);
        Date endTime  =    fmt1.parse(endtime);
        Map<String ,String> map = new HashMap<>();
        while(startTime.before(endTime)){
            double totlatemp = 0.0;
            double avreange = 0.0;
            System.out.println("开始时间"+startTime+"----"+"结束时间"+endTime);
            int a =0;
            for (EartagData data : entityList) {
                //这个操作占用时间太多
                if(data.getTime().after(startTime)&data.getTime().before(DateUtilsPublic.addDateHour(startTime,1))){
                    a++;
                    totlatemp += data.getEarTemp();
                    System.out.println(data.getEarTemp());
                }
            }

            System.out.println("结果"+totlatemp+a+totlatemp/a);
            //直接三元
            if(totlatemp/a>0.01){
                avreange  =  totlatemp/a;
            }
            //这个时间有点麻烦，需要对应进去
            // map.put(format.format(startTime),df.format(avreange));
            //时间变为年+天+小时
            map.put(getMonthDayHour(startTime),df.format(avreange));

            startTime =DateUtilsPublic.addDateHour(startTime,1);
        }

        return  map;
    }

     //用于匹配时间
    public  String getMonthDayHour(  Date date  ){
        String year=String.format("%tY", date);
        String mon=String .format("%tm", date);
        String day=String .format("%td", date);
        String h=String .format("%tH", date);
        String m=String .format("%tM", date);
        String s=String .format("%tS", date);
        return mon+day+h;

    }








































    @Override
    public PageResult<EartagData> page(EartagDataParam eartagDataParam) {
        QueryWrapper<EartagData> queryWrapper = new QueryWrapper<>();
        if (ObjectUtil.isNotNull(eartagDataParam)) {

            // 根据组织id 查询
            if (ObjectUtil.isNotEmpty(eartagDataParam.getOrgId())) {
                queryWrapper.lambda().eq(EartagData::getOrgId, eartagDataParam.getOrgId());
            }
            // 根据采集器编码 查询
            if (ObjectUtil.isNotEmpty(eartagDataParam.getDeviceCode())) {
                queryWrapper.lambda().eq(EartagData::getDeviceCode, eartagDataParam.getDeviceCode());
            }
            // 根据耳标号 查询
            if (ObjectUtil.isNotEmpty(eartagDataParam.getEartagNo())) {
                queryWrapper.lambda().eq(EartagData::getEartagNo, eartagDataParam.getEartagNo());
            }
            // 根据采集时间 查询
            if (ObjectUtil.isNotEmpty(eartagDataParam.getTime())) {
                queryWrapper.lambda().eq(EartagData::getTime, eartagDataParam.getTime());
            }
            // 根据耳根温度 查询
            if (ObjectUtil.isNotEmpty(eartagDataParam.getEarTemp())) {
                queryWrapper.lambda().eq(EartagData::getEarTemp, eartagDataParam.getEarTemp());
            }
            // 根据运动量 查询
            if (ObjectUtil.isNotEmpty(eartagDataParam.getExercise())) {
                queryWrapper.lambda().eq(EartagData::getExercise, eartagDataParam.getExercise());
            }
            // 根据栋舍 查询
            if (ObjectUtil.isNotEmpty(eartagDataParam.getPigpen())) {
                queryWrapper.lambda().eq(EartagData::getPigpen, eartagDataParam.getPigpen());
            }
            // 根据环境温度 查询
            if (ObjectUtil.isNotEmpty(eartagDataParam.getEnvTemp())) {
                queryWrapper.lambda().eq(EartagData::getEnvTemp, eartagDataParam.getEnvTemp());
            }
            // 根据电池电量 查询
            if (ObjectUtil.isNotEmpty(eartagDataParam.getBat())) {
                queryWrapper.lambda().eq(EartagData::getBat, eartagDataParam.getBat());
            }
            // 根据信号强度 查询
            if (ObjectUtil.isNotEmpty(eartagDataParam.getRssi())) {
                queryWrapper.lambda().eq(EartagData::getRssi, eartagDataParam.getRssi());
            }
            // 根据命令头 查询
            if (ObjectUtil.isNotEmpty(eartagDataParam.getHead())) {
                queryWrapper.lambda().eq(EartagData::getHead, eartagDataParam.getHead());
            }
            // 根据指令 查询
            if (ObjectUtil.isNotEmpty(eartagDataParam.getCommand())) {
                queryWrapper.lambda().eq(EartagData::getCommand, eartagDataParam.getCommand());
            }
            // 根据版本号 查询
            if (ObjectUtil.isNotEmpty(eartagDataParam.getVersion())) {
                queryWrapper.lambda().eq(EartagData::getVersion, eartagDataParam.getVersion());
            }
            // 根据耳标帧序号 查询
            if (ObjectUtil.isNotEmpty(eartagDataParam.getFrameSerialNo())) {
                queryWrapper.lambda().eq(EartagData::getFrameSerialNo, eartagDataParam.getFrameSerialNo());
            }
            // 根据重启次数 查询
            if (ObjectUtil.isNotEmpty(eartagDataParam.getRebootTimes())) {
                queryWrapper.lambda().eq(EartagData::getRebootTimes, eartagDataParam.getRebootTimes());
            }
            // 根据预留字段 查询
            if (ObjectUtil.isNotEmpty(eartagDataParam.getPrepareField())) {
                queryWrapper.lambda().eq(EartagData::getPrepareField, eartagDataParam.getPrepareField());
            }
            // 根据校验码 查询
            if (ObjectUtil.isNotEmpty(eartagDataParam.getChk())) {
                queryWrapper.lambda().eq(EartagData::getChk, eartagDataParam.getChk());
            }
            // 根据命令尾 查询
            if (ObjectUtil.isNotEmpty(eartagDataParam.getTail())) {
                queryWrapper.lambda().eq(EartagData::getTail, eartagDataParam.getTail());
            }
            // 根据牧场编码 查询
            if (ObjectUtil.isNotEmpty(eartagDataParam.getFarmCode())) {
                queryWrapper.lambda().eq(EartagData::getFarmCode, eartagDataParam.getFarmCode());
            }
            // 根据阶段 查询
            if (ObjectUtil.isNotEmpty(eartagDataParam.getStage())) {
                queryWrapper.lambda().eq(EartagData::getStage, eartagDataParam.getStage());
            }
            // 根据 查询
            if (ObjectUtil.isNotEmpty(eartagDataParam.getSportGap())) {
                queryWrapper.lambda().eq(EartagData::getSportGap, eartagDataParam.getSportGap());
            }
        }
        return new PageResult<>(this.page(PageFactory.defaultPage(), queryWrapper));
    }

    @Override
    public List<EartagData> list(EartagDataParam eartagDataParam) {
        return this.list();
    }

    @Override
    public void add(EartagDataParam eartagDataParam) {
        EartagData eartagData = new EartagData();
        BeanUtil.copyProperties(eartagDataParam, eartagData);
        this.save(eartagData);
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public void delete(List<EartagDataParam> eartagDataParamList) {
        eartagDataParamList.forEach(eartagDataParam -> {
            this.removeById(eartagDataParam.getId());
        });
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public void edit(EartagDataParam eartagDataParam) {
        EartagData eartagData = this.queryEartagData(eartagDataParam);
        BeanUtil.copyProperties(eartagDataParam, eartagData);
        this.updateById(eartagData);
    }

    @Override
    public EartagData detail(EartagDataParam eartagDataParam) {
        return this.queryEartagData(eartagDataParam);
    }

    /**
     * 获取耳标数据详情
     *
     * @author Yangdi
     * @date 2021-08-19 13:18:22
     */
    private EartagData queryEartagData(EartagDataParam eartagDataParam) {
        EartagData eartagData = this.getById(eartagDataParam.getId());
        if (ObjectUtil.isNull(eartagData)) {
            throw new ServiceException(EartagDataExceptionEnum.NOT_EXIST);
        }
        return eartagData;
    }

    @Override
    public void export(EartagDataParam eartagDataParam) {
        List<EartagData> list = this.list(eartagDataParam);
        PoiUtil.exportExcelWithStream("SnowyEartagData.xls", EartagData.class, list);
    }

    @Override
    public ResponseData countByTime(Map<String, Object> params) {
        String startTime = (String) params.get("startTime");
        String endTime = (String) params.get("endTime");
        String deviceCode = (String) params.get("deviceCode");


        QueryWrapper<EartagData> wrapper = new QueryWrapper<>();
        wrapper.eq(StringUtils.isNotBlank(deviceCode), "device_code", deviceCode);
        wrapper.ge(StringUtils.isNotBlank(startTime), "time", startTime);
        wrapper.le(StringUtils.isNotBlank(endTime), "time", endTime);
        wrapper.groupBy("count_time");
        List<EartagDataCountVo> eartagDataCountVos = baseMapper.countByTime(wrapper);

        List timeList = new ArrayList();
        List envTempList = new ArrayList();
        List count = new ArrayList();
        for (EartagDataCountVo eartagDataCountVo : eartagDataCountVos) {
            timeList.add(eartagDataCountVo.getCountTime());
            envTempList.add(eartagDataCountVo.getEnvTemp());
            count.add(eartagDataCountVo.getUploadCount());
        }
        Map map = new HashMap();
        map.put("time", timeList);
        map.put("envTemp", envTempList);
        map.put("count", count);


        return new SuccessResponseData(map);
    }


    @Override
    public ResponseData countByDay(Map<String, Object> params) {
        String startTime = (String) params.get("startTime");
        String endTime = (String) params.get("endTime");
        String deviceCode = (String) params.get("deviceCode");


        QueryWrapper<EartagData> wrapper = new QueryWrapper<>();
        wrapper.eq(StringUtils.isNotBlank(deviceCode), "device_code", deviceCode);
        wrapper.ge(StringUtils.isNotBlank(startTime), "time", startTime);
        wrapper.le(StringUtils.isNotBlank(endTime), "time", endTime);
        wrapper.groupBy("count_time");
        List<EartagDataCountVo> eartagDataCountVos = baseMapper.countByDay(wrapper);

        List<String> timeList = new ArrayList<>();
        List<Double> envTempList = new ArrayList<>();
        List<Integer> count = new ArrayList<>();
        for (EartagDataCountVo eartagDataCountVo : eartagDataCountVos) {
            timeList.add(eartagDataCountVo.getCountTime());
            envTempList.add(eartagDataCountVo.getEnvTemp());
            count.add(eartagDataCountVo.getUploadCount());
        }
        Map map = new HashMap();
        map.put("time", timeList);
        map.put("envTemp", envTempList);
        map.put("count", count);


        return new SuccessResponseData(map);
    }
}
