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.IEartagManageService;
import com.huimv.eartag.utils.BizConst;
import com.huimv.eartag.utils.DateUtil;
import com.huimv.eartag.utils.JSONUtil;
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.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 javax.persistence.criteria.Order;
import javax.persistence.criteria.Predicate;
import java.sql.Date;
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 EartagManageServiceImpl implements IEartagManageService {
    @Autowired
    private EartagEartagRegisterRepo eartagRegisterRepo;
    @Autowired
    private EartagDataRepo eartagDataRepo;
    @Autowired
    private EartagEartagOnlineRepo eartagOnlineRepo;
    @Autowired
    private EartarFarmAllStatusRepo farmAllStatusRepo;
    @Autowired
    private EartagDeviceEartagCountRepo deviceEartagCountRepo;

    /**
     * @Method : listAllEartagFlow
     * @Description : 分页展示所有流水列表
     * @Params : [farmId, createDate, deviceCode, earmark, pageNo, pageSize]
     * @Return : com.huimv.eartag2.common.utils.Result
     * @Author : ZhuoNing
     * @Date : 2022/3/11
     * @Time : 11:30
     */
    @Override
    public Result listAllEartagFlow(String farmId, String createDate, String deviceCode, String earmark, Integer pageNo, Integer pageSize) throws ParseException {
        //
        Specification<EartagDataEntity> sf = (Specification<EartagDataEntity>) (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));
            }
            //earmark
            if (null != earmark && earmark.trim().length() > 0) {
                predList.add(criteriaBuilder.equal(root.get("earmark").as(String.class), earmark));
            }
            //createDate
            if (null != createDate && createDate.trim().length() > 0) {
                try {
                    predList.add(criteriaBuilder.equal(root.get("createDate").as(Date.class), new Date(new DateUtil().parseDateTextToLong(createDate))));
                } catch (ParseException e) {
                    e.printStackTrace();
                }
            }
            //deviceCode
            if (null != deviceCode && deviceCode.trim().length() > 0) {
                predList.add(criteriaBuilder.equal(root.get("device").as(String.class), deviceCode));
            }
            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<EartagDataEntity> eartagDataEntityPage = eartagDataRepo.findAll(sf, pageable);
//        return new Result(ResultCode.SUCCESS, eartagDataEntityPage);
        Page<EartagDataEntity> pageEartagData = eartagDataRepo.findAll(sf, pageable);
        JSONObject outDataJo = new JSONObject();
        outDataJo.put("pageable", pageEartagData.getPageable());
        outDataJo.put("last", pageEartagData.isLast());
        outDataJo.put("totalElements", pageEartagData.getTotalElements());
        outDataJo.put("totalPages", pageEartagData.getTotalPages());
        outDataJo.put("number", pageEartagData.getNumber());
        outDataJo.put("size", pageEartagData.getSize());
        outDataJo.put("sort", pageEartagData.getSort());
        outDataJo.put("numberOfElements", pageEartagData.getNumberOfElements());
        outDataJo.put("first", pageEartagData.isFirst());
        outDataJo.put("empty", pageEartagData.isEmpty());

        List<EartagDataEntity> dataEntityList = pageEartagData.getContent();
        JSONArray outJa = new JSONArray();
        outDataJo.put("content", outJa);
        DateUtil dateUtil = new DateUtil();
        for (EartagDataEntity eartagDataEntity : dataEntityList) {
            JSONObject outJo = new JSONObject();
            outJa.add(outJo);
            outJo.put("id", eartagDataEntity.getId());
            outJo.put("cmdHeader", eartagDataEntity.getCmdHeader());
            outJo.put("device", eartagDataEntity.getDevice());
            outJo.put("earmark", eartagDataEntity.getEarmark());
            outJo.put("bat", eartagDataEntity.getBat());
            outJo.put("earTemp", eartagDataEntity.getEarTemp());
            outJo.put("earTemp1", eartagDataEntity.getEarTemp1());
            outJo.put("envTemp", eartagDataEntity.getEnvTemp());
            outJo.put("envTemp1", eartagDataEntity.getEnvTemp1());
            outJo.put("act", eartagDataEntity.getAct());
            outJo.put("act1", eartagDataEntity.getAct1());
            outJo.put("signal1", eartagDataEntity.getSignal1());
            outJo.put("askTime", eartagDataEntity.getAskTime());
            outJo.put("other", eartagDataEntity.getOther());
            outJo.put("addTime", dateUtil.formatDatetimeText(eartagDataEntity.getAddTime()));
            outJo.put("createDate", eartagDataEntity.getCreateDate());
            outJo.put("farmId", eartagDataEntity.getFarmId());
        }
        return new Result(ResultCode.SUCCESS, outDataJo);
    }

    @Override
    public Result listManyEartagOnlineStatus(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.getEartagOnline());
//            newJo.put("total", farmAllStatusEntity.getDeviceTotal());
//            newJo.put("rate", farmAllStatusEntity.getDeviceRate());
//            newJo.put("offline", farmAllStatusEntity.getDeviceOffline());
        }
        return new Result(ResultCode.SUCCESS, dataJa);
    }

    @Override
    public Result listAllEartagRegister(String farmId, String earmark, Integer activeStatus, Integer liveStatus, Integer registerType, String startDate, String endDate, Integer pageNo, Integer pageSize) throws ParseException {
        //
        Specification<EartagEartagRegisterEntity> sf = (Specification<EartagEartagRegisterEntity>) (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));
            }
            //earmark
            if (null != earmark && earmark.trim().length() > 0) {
                predList.add(criteriaBuilder.equal(root.get("earmark").as(String.class), earmark));
            }
            //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("liveStatus").as(Integer.class), liveStatus));
            }
            //registerType
            if (null != registerType) {
                predList.add(criteriaBuilder.equal(root.get("registerType").as(Integer.class), registerType));
            }
            //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);
        Page<EartagEartagRegisterEntity> eartagRegisterPage = eartagRegisterRepo.findAll(sf, pageable);
        JSONObject outDataJo = new JSONObject();


        List<EartagEartagRegisterEntity> eartagRegisterEntityList = eartagRegisterPage.getContent();
        JSONArray outJa = new JSONArray();
        outDataJo.put("content", outJa);
        DateUtil dateUtil = new DateUtil();
        for (EartagEartagRegisterEntity eartagRegisterEntity : eartagRegisterEntityList) {
            JSONObject outJo = new JSONObject();
            outJa.add(outJo);
            outJo.put("id", eartagRegisterEntity.getId());
            outJo.put("earmark", eartagRegisterEntity.getEarmark());
            outJo.put("firstTime", dateUtil.formatDatetimeText(eartagRegisterEntity.getFirstTime()));
            outJo.put("lastTime", dateUtil.formatDatetimeText(eartagRegisterEntity.getLastTime()));
            outJo.put("firstDevice", eartagRegisterEntity.getFirstDevice());
            outJo.put("belongDevice", eartagRegisterEntity.getBelongDevice());
            outJo.put("lastDevice", eartagRegisterEntity.getLastDevice());
            outJo.put("registerTime", dateUtil.formatDatetimeText(eartagRegisterEntity.getRegisterTime()));
            outJo.put("registerType", eartagRegisterEntity.getRegisterType());
            outJo.put("remark", eartagRegisterEntity.getRemark());
            outJo.put("farmId", eartagRegisterEntity.getFarmId());
            outJo.put("activeStatus", eartagRegisterEntity.getActiveStatus());
            outJo.put("activeTime", dateUtil.formatDatetimeText(eartagRegisterEntity.getActiveTime()));
            outJo.put("liveStatus", eartagRegisterEntity.getLiveStatus());
            outJo.put("createDate", eartagRegisterEntity.getCreateDate());
        }
        outDataJo.put("pageable", eartagRegisterPage.getPageable());
        outDataJo.put("last", eartagRegisterPage.isLast());
        outDataJo.put("totalElements", eartagRegisterPage.getTotalElements());
        outDataJo.put("totalPages", eartagRegisterPage.getTotalPages());
        outDataJo.put("number", eartagRegisterPage.getNumber());
        outDataJo.put("size", eartagRegisterPage.getSize());
        outDataJo.put("sort", eartagRegisterPage.getSort());
        outDataJo.put("numberOfElements", eartagRegisterPage.getNumberOfElements());
        outDataJo.put("first", eartagRegisterPage.isFirst());
        outDataJo.put("empty", eartagRegisterPage.isEmpty());
//        System.out.println("## eartagRegisterPage>>"+eartagRegisterPage);
//        List<EartagEartagRegisterEntity> eartagRegisterEntityList = eartagRegisterPage.getContent();
//        System.out.println("## eartagRegisterEntityList.size()>>"+eartagRegisterEntityList.size());
//        JSONArray dataJa = new JSONArray();
//        for(EartagEartagRegisterEntity eartagRegisterEntity:eartagRegisterEntityList){
//            JSONObject dataJo = JSONUtil.convertEntityToJSONObject(eartagRegisterEntity);
//            dataJa.add(dataJo);
//            dataJo.put("firstTime",du.formatDatetimeText(eartagRegisterEntity.getFirstTime()));
//            dataJo.put("lastTime",du.formatDatetimeText(eartagRegisterEntity.getLastTime()));
//            dataJo.put("registerTime",du.formatDatetimeText(eartagRegisterEntity.getRegisterTime()));
//            dataJo.put("activeTime",du.formatDatetimeText(eartagRegisterEntity.getActiveTime()));
//            dataJo.put("createDate",du.formatDateText(eartagRegisterEntity.getCreateDate()));
//        }
//    for(EartagEartagRegisterEntity eartagRegisterEntity:eartagRegisterEntityList){
//        eartagRegisterEntity.setFirstTime(new Timestamp(du.parseDateTime(eartagRegisterEntity.getFirstTime().toString()).getTime()));
//        System.out.println("getFirstTime 33>>"+du.parseDateTime(eartagRegisterEntity.getFirstTime().toString()));
//    }
        return new Result(ResultCode.SUCCESS, outDataJo);
    }

    /**
     * @Method : getEartagDeviceByEarmarkAndAddDate
     * @Description :
     * @Params : [earmark, addDate]
     * @Return : com.huimv.eartag2.common.utils.Result
     * @Author : ZhuoNing
     * @Date : 2022/3/10
     * @Time : 22:39
     */
    @Override
    public Result listEartagDeviceByEarmarkAndAddDate(String earmark, String addDate) {
        //
        List<EartagDeviceEartagCountEntity> deviceEartagCountEntityList = deviceEartagCountRepo.getOnlineEartagDeviceByEarmarkAndAddDate(earmark, addDate);
        if (deviceEartagCountEntityList != null) {
            return new Result(ResultCode.SUCCESS, JSON.toJSON(deviceEartagCountEntityList));
        } else {
            return new Result(BizConst.CODE_DEVICE_EARTAG_COUNT_NO_EXIST, BizConst.MSG_DEVICE_EARTAG_COUNT_NO_EXIST, false);
        }
    }


    /**
     * @Method : listOnlineEartagCount
     * @Description :
     * @Params : [farmId, addDate, pageNo, pageSize]
     * @Return : com.huimv.eartag2.common.utils.Result
     * @Author : ZhuoNing
     * @Date : 2022/3/10
     * @Time : 21:52
     */
    @Override
    public Result listOnlineEartagCount(String farmId, String addDate, Integer pageNo, Integer pageSize, Integer showMode) throws ParseException {
        if (showMode == 1) {
            //
            return listEartagOnlineInRecords(farmId, addDate, pageNo, pageSize);
        } else {
            //
            return getEartagOnlineInChart(farmId, addDate);
        }

    }

    /**
     * @Method : getEartagOnlineInChart
     * @Description :
     * @Params : [farmId, addDate]
     * @Return : com.huimv.eartag2.common.utils.Result
     * @Author : ZhuoNing
     * @Date : 2022/3/10
     * @Time : 22:03
     */
    private Result getEartagOnlineInChart(String farmId, String addDate) throws ParseException {
        //
        List<EartagEartagOnlineEntity> eartagOnlineEntityList = eartagOnlineRepo.getEartagOnlineByFarmIdAndDate(farmId, addDate);
        if (eartagOnlineEntityList.size() > 0) {
            JSONArray dataJa = new JSONArray();
            for (EartagEartagOnlineEntity eartagOnlineEntity : eartagOnlineEntityList) {
                JSONObject newJo = new JSONObject();
                newJo.put("time", eartagOnlineEntity.getEarmark());
                newJo.put("value", eartagOnlineEntity.getTotal());
                dataJa.add(newJo);
            }
            return new Result(ResultCode.SUCCESS, dataJa);
        } else {
            return new Result(BizConst.CODE_EARTAG_ONLINE_NO_EXIST, BizConst.MSG_EARTAG_ONLINE_NO_EXIST, false);
        }
    }

    /**
     * @Method : listEartagOnlineInRecords
     * @Description :
     * @Params : [farmId, addDate, pageNo, pageSize, showMode]
     * @Return : com.huimv.eartag2.common.utils.Result
     * @Author : ZhuoNing
     * @Date : 2022/3/10
     * @Time : 21:54
     */
    private Result listEartagOnlineInRecords(String farmId, String addDate, Integer pageNo, Integer pageSize) throws ParseException {
        System.out.println("# addDate>>" + addDate);
        System.out.println("# farmId>>" + farmId);
        System.out.println("# pageNo>>" + pageNo);
        System.out.println("# pageSize>>" + pageSize);
        //
        Specification<EartagEartagOnlineEntity> sf = (Specification<EartagEartagOnlineEntity>) (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 != addDate && addDate.trim().length() > 0) {
                try {
                    predList.add(criteriaBuilder.equal(root.get("addDate").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<EartagEartagOnlineEntity> pageEartagOnline = eartagOnlineRepo.findAll(sf, pageable);
        JSONObject outDataJo = new JSONObject();
        outDataJo.put("pageable", pageEartagOnline.getPageable());
        outDataJo.put("last", pageEartagOnline.isLast());
        outDataJo.put("totalElements", pageEartagOnline.getTotalElements());
        outDataJo.put("totalPages", pageEartagOnline.getTotalPages());
        outDataJo.put("number", pageEartagOnline.getNumber());
        outDataJo.put("size", pageEartagOnline.getSize());
        outDataJo.put("sort", pageEartagOnline.getSort());
        outDataJo.put("numberOfElements", pageEartagOnline.getNumberOfElements());
        outDataJo.put("first", pageEartagOnline.isFirst());
        outDataJo.put("empty", pageEartagOnline.isEmpty());

        List<EartagEartagOnlineEntity> eartagOnlineEntityList = pageEartagOnline.getContent();
        JSONArray outJa = new JSONArray();
        outDataJo.put("content", outJa);
        DateUtil dateUtil = new DateUtil();
        for (EartagEartagOnlineEntity eartagOnlineEntity : eartagOnlineEntityList) {
            JSONObject outJo = new JSONObject();
            outJa.add(outJo);
            outJo.put("id", eartagOnlineEntity.getId());
            outJo.put("earmark", eartagOnlineEntity.getEarmark());
            outJo.put("total", eartagOnlineEntity.getTotal());
            outJo.put("firstTime", dateUtil.formatDatetimeText(eartagOnlineEntity.getFirstTime()));
            outJo.put("lastTime", dateUtil.formatDatetimeText(eartagOnlineEntity.getLastTime()));
            outJo.put("envTemp", eartagOnlineEntity.getEnvTemp());
            outJo.put("eartagTemp", eartagOnlineEntity.getEartagTemp());
            outJo.put("addDate", eartagOnlineEntity.getAddDate());
            outJo.put("farmId", eartagOnlineEntity.getFarmId());
        }

        return new Result(ResultCode.SUCCESS, outDataJo);
    }

    /**
     * @Method : listEartagOnlineAllStatus
     * @Description :
     * @Params : [farmId, days]
     * @Return : com.huimv.eartag2.common.utils.Result
     * @Author : ZhuoNing
     * @Date : 2022/3/10
     * @Time : 20:52
     */
    @Override
    public Result listEartagOnlineAllStatus(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.getEartagOnline());
//            newJo.put("total", farmAllStatusEntity.getEartagTotal());
        }
        return new Result(ResultCode.SUCCESS, dataJa);
    }

    /**
     * @Method : listEartagOnlineStatusByEarmarkAndDate
     * @Description : 显示耳标在线统计
     * @Params : [earmark, pastDays]
     * @Return : com.huimv.eartag2.common.utils.Result
     * @Author : ZhuoNing
     * @Date : 2022/3/8
     * @Time : 18:30
     */
    @Override
    public Result listEartagOnlineStatusByEarmarkAndDate(String earmark, Integer pastDays) throws ParseException {
        DateUtil du = new DateUtil();
        String todayDateText = du.getTodayDateText();
        String startDateText = du.getPastDate(pastDays);
        log.info("<listEartagOnlineStatusByEarmarkAndDate> startDateText>>" + startDateText);
        log.info("<listEartagOnlineStatusByEarmarkAndDate> todayDateText>>" + todayDateText);
        //读取耳标在线统计记录
        List<EartagEartagOnlineEntity> eartagOnlineEntityList = eartagOnlineRepo.getEartagOnlineByEarmarkAndDate(earmark, startDateText, todayDateText);
        if (eartagOnlineEntityList.size() > 0) {
            JSONArray dataJa = new JSONArray();
            List<String> pastDateList = du.getPastIntervalsASC(pastDays);
            for (String pastDayDate : pastDateList) {
                JSONObject newJo = new JSONObject();
                dataJa.add(newJo);
                newJo.put("time", pastDayDate);
                boolean ieFound = false;
                for (EartagEartagOnlineEntity eartagOnlineEntity : eartagOnlineEntityList) {
                    int compareTo = du.parseDate(pastDayDate).compareTo(eartagOnlineEntity.getAddDate());
                    if (compareTo == 0) {
                        newJo.put("value", 1);
                        ieFound = true;
                        break;
                    }
                }
                if (!ieFound) {
                    newJo.put("value", 0);
                }
            }
//            for(EartagEartagOnlineEntity eartagOnlineEntity:eartagOnlineEntityList){
//                JSONObject eartagOnlineJo = JSONUtil.convertEntityToJSONObject(eartagOnlineEntity);
//                eartagOnlineJo.put("firstTime",du.formatDatetimeText(eartagOnlineJo.getDate("firstTime")));
//                eartagOnlineJo.put("lastTime",du.formatDatetimeText(eartagOnlineJo.getDate("lastTime")));
//                eartagOnlineJo.put("addDate",du.formatDateText(eartagOnlineJo.getDate("addDate")));
//                dataJa.add(eartagOnlineJo);
//            }
            return new Result(ResultCode.SUCCESS, dataJa);
        } else {
            return new Result(BizConst.CODE_EARTAG_ONLINE_NO_EXIST, BizConst.MSG_EARTAG_ONLINE_NO_EXIST, false);
        }
    }

    /**
     * @Method : getEartagRegisterByEarmarkInPager
     * @Description : 分页查询耳标流水
     * @Params : [earmark, pageNo, pageSize]
     * @Return : com.huimv.eartag2.common.utils.Result
     * @Author : ZhuoNing
     * @Date : 2022/3/8
     * @Time : 20:19
     */
    @Override
    public Result listEartagFlowByEarmarkAndTodayInPager(String earmark, Integer pageNo, Integer pageSize, String createDate, String deviceCode) throws ParseException {
        System.out.println("earmark>>" + earmark);
        System.out.println("pageNo>>" + pageNo);
        System.out.println("pageSize>>" + pageSize);
        System.out.println("createDate>>" + createDate);
        System.out.println("deviceCode>>" + deviceCode);
        //
        Specification<EartagDataEntity> sf = (Specification<EartagDataEntity>) (root, criteriaQuery, criteriaBuilder) -> {
            //
            List<Predicate> predList = new ArrayList<>();
            //earmark
            if (null != earmark && earmark.trim().length() > 0) {
                predList.add(criteriaBuilder.equal(root.get("earmark").as(String.class), earmark));
            }
            //createDate
            if (null != createDate && createDate.trim().length() > 0) {
                try {
                    predList.add(criteriaBuilder.equal(root.get("createDate").as(Date.class), new Date(new DateUtil().parseDateTextToLong(createDate))));
                } catch (ParseException e) {
                    e.printStackTrace();
                }
            }
            //deviceCode
            if (null != deviceCode && deviceCode.trim().length() > 0) {
                predList.add(criteriaBuilder.equal(root.get("device").as(String.class), deviceCode));
            }
            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<EartagDataEntity> pageEartagData = eartagDataRepo.findAll(sf, pageable);
        JSONObject outDataJo = new JSONObject();
        outDataJo.put("pageable", pageEartagData.getPageable());
        outDataJo.put("last", pageEartagData.isLast());
        outDataJo.put("totalElements", pageEartagData.getTotalElements());
        outDataJo.put("totalPages", pageEartagData.getTotalPages());
        outDataJo.put("number", pageEartagData.getNumber());
        outDataJo.put("size", pageEartagData.getSize());
        outDataJo.put("sort", pageEartagData.getSort());
        outDataJo.put("numberOfElements", pageEartagData.getNumberOfElements());
        outDataJo.put("first", pageEartagData.isFirst());
        outDataJo.put("empty", pageEartagData.isEmpty());
        List<EartagDataEntity> dataEntityList = pageEartagData.getContent();
        System.out.println("## dataEntityList.size>>" + dataEntityList.size());
        JSONArray outJa = new JSONArray();
        outDataJo.put("content", outJa);
        DateUtil dateUtil = new DateUtil();
        for (EartagDataEntity eartagDataEntity : dataEntityList) {
//            System.out.println(">>"+deviceRegisterEntity.toString());
//            Map map = JSON.parseObject(JSONObject.toJSONString(deviceRegisterEntity),Map.class);
//            System.out.println("map>>"+map.toString());
            JSONObject outJo = new JSONObject();
            outJa.add(outJo);
            outJo.put("id", eartagDataEntity.getId());
            outJo.put("cmdHeader", eartagDataEntity.getCmdHeader());
            outJo.put("device", eartagDataEntity.getDevice());
            outJo.put("earmark", eartagDataEntity.getEarmark());
            outJo.put("bat", eartagDataEntity.getBat());
            outJo.put("earTemp", eartagDataEntity.getEarTemp());
            outJo.put("earTemp1", eartagDataEntity.getEarTemp1());
            outJo.put("envTemp", eartagDataEntity.getEnvTemp());
            outJo.put("envTemp1", eartagDataEntity.getEnvTemp1());
            outJo.put("act", eartagDataEntity.getAct());
            outJo.put("act1", eartagDataEntity.getAct1());
            outJo.put("signal1", eartagDataEntity.getSignal1());
            outJo.put("askTime", eartagDataEntity.getAskTime());
            outJo.put("other", eartagDataEntity.getOther());
            outJo.put("addTime", dateUtil.formatDatetimeText(eartagDataEntity.getAddTime()));
            outJo.put("createDate", eartagDataEntity.getCreateDate());
            outJo.put("farmId", eartagDataEntity.getFarmId());
        }

        return new Result(ResultCode.SUCCESS, outDataJo);
//        return new Result(ResultCode.SUCCESS, pageEartagData);
    }

    /**
     * @Method : listEartagFlowByDeviceCodeAndEarmarkAndTodayInPager
     * @Description :
     * @Params : [earmark, deviceCode, pageNo, pageSize]
     * @Return : com.huimv.eartag2.common.utils.Result
     * @Author : ZhuoNing
     * @Date : 2022/3/8
     * @Time : 20:37
     */
    @Override
    public Result listEartagFlowByDeviceCodeAndEarmarkAndTodayInPager(String earmark, String deviceCode, String createDate, Integer pageNo, Integer pageSize) throws ParseException {
        //
        Specification<EartagDataEntity> sf = (Specification<EartagDataEntity>) (root, criteriaQuery, criteriaBuilder) -> {
            //
            List<Predicate> predList = new ArrayList<>();
            //earmark
            if (null != earmark && earmark.trim().length() > 0) {
                predList.add(criteriaBuilder.equal(root.get("earmark").as(String.class), earmark));
            }
            //deviceCode
            if (null != deviceCode && deviceCode.trim().length() > 0) {
                predList.add(criteriaBuilder.equal(root.get("device").as(String.class), deviceCode));
            }
            //createDate
            if (null != createDate && createDate.trim().length() > 0) {
                try {
                    predList.add(criteriaBuilder.equal(root.get("createDate").as(Date.class), new Date(new DateUtil().parseDateTextToLong(createDate))));
                } 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<EartagDataEntity> pageEartagData = eartagDataRepo.findAll(sf, pageable);
        JSONObject outDataJo = new JSONObject();
        outDataJo.put("pageable", pageEartagData.getPageable());
        outDataJo.put("last", pageEartagData.isLast());
        outDataJo.put("totalElements", pageEartagData.getTotalElements());
        outDataJo.put("totalPages", pageEartagData.getTotalPages());
        outDataJo.put("number", pageEartagData.getNumber());
        outDataJo.put("size", pageEartagData.getSize());
        outDataJo.put("sort", pageEartagData.getSort());
        outDataJo.put("numberOfElements", pageEartagData.getNumberOfElements());
        outDataJo.put("first", pageEartagData.isFirst());
        outDataJo.put("empty", pageEartagData.isEmpty());

        List<EartagDataEntity> dataEntityList = pageEartagData.getContent();
        JSONArray outJa = new JSONArray();
        outDataJo.put("content", outJa);
        DateUtil dateUtil = new DateUtil();
        for (EartagDataEntity eartagDataEntity : dataEntityList) {
            JSONObject outJo = new JSONObject();
            outJa.add(outJo);
            outJo.put("id", eartagDataEntity.getId());
            outJo.put("cmdHeader", eartagDataEntity.getCmdHeader());
            outJo.put("device", eartagDataEntity.getDevice());
            outJo.put("earmark", eartagDataEntity.getEarmark());
            outJo.put("bat", eartagDataEntity.getBat());
            outJo.put("earTemp", eartagDataEntity.getEarTemp());
            outJo.put("earTemp1", eartagDataEntity.getEarTemp1());
            outJo.put("envTemp", eartagDataEntity.getEnvTemp());
            outJo.put("envTemp1", eartagDataEntity.getEnvTemp1());
            outJo.put("act", eartagDataEntity.getAct());
            outJo.put("act1", eartagDataEntity.getAct1());
            outJo.put("signal1", eartagDataEntity.getSignal1());
            outJo.put("askTime", eartagDataEntity.getAskTime());
            outJo.put("other", eartagDataEntity.getOther());
            outJo.put("addTime", dateUtil.formatDatetimeText(eartagDataEntity.getAddTime()));
            outJo.put("createDate", eartagDataEntity.getCreateDate());
            outJo.put("farmId", eartagDataEntity.getFarmId());
        }
        return new Result(ResultCode.SUCCESS, outDataJo);
//        return new Result(ResultCode.SUCCESS, pageEartagData);
    }

    /**
     * @Method : listEartagFlowByDeviceCodeAndEarmarkAndDateInPager
     * @Description :
     * @Params : [earmark, deviceCode, addDate, pageNo, pageSize]
     * @Return : com.huimv.eartag2.common.utils.Result
     * @Author : ZhuoNing
     * @Date : 2022/3/9
     * @Time : 22:14
     */
    @Override
    public Result listEartagFlowByDeviceCodeAndEarmarkAndDateInPager(String earmark, String deviceCode, String addDate, Integer pageNo, Integer pageSize) throws ParseException {
        //
        Specification<EartagDataEntity> sf = (Specification<EartagDataEntity>) (root, criteriaQuery, criteriaBuilder) -> {
            //
            List<Predicate> predList = new ArrayList<>();
            //earmark
            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("device").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<EartagDataEntity> pageEnvEntity = eartagDataRepo.findAll(sf, pageable);
        DateUtil dateUtil = new DateUtil();
        JSONObject pageJo = JSONObject.parseObject(JSONObject.toJSONString(pageEnvEntity));
        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 : listEartagOnlineCountByEarmarkAndDate
     * @Description : 显示耳标在线统计
     * @Params : [earmark, pastDays]
     * @Return : com.huimv.eartag2.common.utils.Result
     * @Author : ZhuoNing
     * @Date : 2022/3/8
     * @Time : 18:30
     */
    @Override
    public Result listEartagOnlineCountByEarmarkAndDate(String earmark, Integer pastDays, Integer showMode) throws ParseException {
        DateUtil du = new DateUtil();
        String todayDateText = du.getTodayDateText();
        String startDateText = du.getPastDate(pastDays);
        log.info("<listEartagOnlineCountByEarmarkAndDate> startDateText>>" + startDateText);
        log.info("<listEartagOnlineCountByEarmarkAndDate> todayDateText>>" + todayDateText);
        //读取耳标在线统计记录
        if (showMode == 1) {
            List<EartagEartagOnlineEntity> eartagOnlineEntityList = eartagOnlineRepo.getEartagOnlineRecordsByEarmarkAndDate(earmark, startDateText, todayDateText);
            if (eartagOnlineEntityList.size() > 0) {
                //返回在线记录
                JSONArray dataJa = new JSONArray();
                for (EartagEartagOnlineEntity eartagOnlineEntity : eartagOnlineEntityList) {
                    JSONObject eartagOnlineJo = JSONUtil.convertEntityToJSONObject(eartagOnlineEntity);
                    eartagOnlineJo.put("firstTime", du.formatDatetimeText(eartagOnlineJo.getDate("firstTime")));
                    eartagOnlineJo.put("lastTime", du.formatDatetimeText(eartagOnlineJo.getDate("lastTime")));
                    eartagOnlineJo.put("addDate", du.formatDateText(eartagOnlineJo.getDate("addDate")));
                    dataJa.add(eartagOnlineJo);
                }
                return new Result(ResultCode.SUCCESS, dataJa);
            } else {
                return new Result(BizConst.CODE_EARTAG_ONLINE_NO_EXIST, BizConst.MSG_EARTAG_ONLINE_NO_EXIST, false);
            }
        } else {
            List<EartagEartagOnlineEntity> eartagOnlineEntityList = eartagOnlineRepo.getEartagOnlineByEarmarkAndDate(earmark, startDateText, todayDateText);
            if (eartagOnlineEntityList.size() > 0) {
                //返回在线图表
                JSONArray dataJa = new JSONArray();
                for (EartagEartagOnlineEntity eartagOnlineEntity : eartagOnlineEntityList) {
//                    JSONObject eartagOnlineJo = JSONUtil.convertEntityToJSONObject(eartagOnlineEntity);
                    JSONObject newJo = new JSONObject();
                    newJo.put("time", du.formatDateText(eartagOnlineEntity.getAddDate()));
                    newJo.put("value", eartagOnlineEntity.getTotal());
                    dataJa.add(newJo);
                }
                return new Result(ResultCode.SUCCESS, dataJa);
            } else {
                return new Result(BizConst.CODE_EARTAG_ONLINE_NO_EXIST, BizConst.MSG_EARTAG_ONLINE_NO_EXIST, false);
            }
        }
    }

    public Result listEartagOnlineCountByEarmarkAndDate_old1(String earmark, Integer pastDays, Integer showMode) throws
            ParseException {
        DateUtil du = new DateUtil();
        String todayDateText = du.getTodayDateText();
        String startDateText = du.getPastDate(pastDays);
        log.info("<listEartagOnlineCountByEarmarkAndDate> startDateText>>" + startDateText);
        log.info("<listEartagOnlineCountByEarmarkAndDate> todayDateText>>" + todayDateText);
        //读取耳标在线统计记录
        List<EartagEartagOnlineEntity> eartagOnlineEntityList = eartagOnlineRepo.getEartagOnlineByEarmarkAndDate(earmark, startDateText, todayDateText);
        if (eartagOnlineEntityList.size() > 0) {
            if (showMode == 1) {
                //返回在线记录
                JSONArray dataJa = new JSONArray();
                for (EartagEartagOnlineEntity eartagOnlineEntity : eartagOnlineEntityList) {
                    JSONObject eartagOnlineJo = JSONUtil.convertEntityToJSONObject(eartagOnlineEntity);
                    eartagOnlineJo.put("firstTime", du.formatDatetimeText(eartagOnlineJo.getDate("firstTime")));
                    eartagOnlineJo.put("lastTime", du.formatDatetimeText(eartagOnlineJo.getDate("lastTime")));
                    eartagOnlineJo.put("addDate", du.formatDateText(eartagOnlineJo.getDate("addDate")));
                    dataJa.add(eartagOnlineJo);
                }
                return new Result(ResultCode.SUCCESS, dataJa);
            } else {
                //返回在线图表
                JSONArray dataJa = new JSONArray();
                for (EartagEartagOnlineEntity eartagOnlineEntity : eartagOnlineEntityList) {
//                    JSONObject eartagOnlineJo = JSONUtil.convertEntityToJSONObject(eartagOnlineEntity);
                    JSONObject newJo = new JSONObject();
                    newJo.put("time", du.formatDateText(eartagOnlineEntity.getAddDate()));
                    newJo.put("value", eartagOnlineEntity.getTotal());
                    dataJa.add(newJo);
                }
                return new Result(ResultCode.SUCCESS, dataJa);
            }
        } else {
            return new Result(BizConst.CODE_EARTAG_ONLINE_NO_EXIST, BizConst.MSG_EARTAG_ONLINE_NO_EXIST, false);
        }
    }

    /**
     * @Method : listEartagFlowByDeviceCodeAndEarmarkAndToday
     * @Description : 根据设备编码、耳标号和当天日期读取耳标流水数据
     * @Params : [earmark, deviceCode]
     * @Return : com.huimv.eartag2.common.utils.Result
     * @Author : ZhuoNing
     * @Date : 2022/3/7
     * @Time : 18:46
     */
    @Override
    public Result listEartagFlowByDeviceCodeAndEarmarkAndToday(String earmark, String deviceCode) throws
            ParseException {
        DateUtil du = new DateUtil();
        String todayDateText = du.getTodayDateText();
        //
        List<EartagDataEntity> eartagDataEntityList = eartagDataRepo.getEartagFlowByDeviceCodeAndEarmarkAndToday(deviceCode, earmark, todayDateText);
        if (eartagDataEntityList.size() > 0) {
            return new Result(ResultCode.SUCCESS, JSON.toJSON(eartagDataEntityList));
        } else {
            return new Result(BizConst.CODE_EARTAG_FLOW_NO_EXIST, BizConst.MSG_EARTAG_FLOW_NO_EXIST, false);
        }
    }

    /**
     * @Method : listEartagFlowByEarmarkAndToday
     * @Description : 根据耳标号读取今天所有流水
     * @Params : [earmark]
     * @Return : com.huimv.eartag2.common.utils.Result
     * @Author : ZhuoNing
     * @Date : 2022/3/7
     * @Time : 18:41
     */
    @Override
    public Result listEartagFlowByEarmarkAndToday(String earmark) throws ParseException {
        DateUtil du = new DateUtil();
        String todayDateText = du.getTodayDateText();
        //
        List<EartagDataEntity> eartagDataEntityList = eartagDataRepo.getEartagFlowByEarmarkAndToday(earmark, todayDateText);
        if (eartagDataEntityList.size() > 0) {
            return new Result(ResultCode.SUCCESS, JSON.toJSON(eartagDataEntityList));
        } else {
            return new Result(BizConst.CODE_EARTAG_FLOW_NO_EXIST, BizConst.MSG_EARTAG_FLOW_NO_EXIST, false);
        }
    }

    /**
     * @Method : getEartagRegisterByEarmark
     * @Description :
     * @Params : [earmark]
     * @Return : com.huimv.eartag2.common.utils.Result
     * @Author : ZhuoNing
     * @Date : 2022/3/7
     * @Time : 18:41
     */
    @Override
    public Result getEartagRegisterByEarmark(String earmark) throws ParseException {
        DateUtil dateUtil = new DateUtil();
        //
        EartagEartagRegisterEntity eartagRegisterEntity = eartagRegisterRepo.getEartagByEarmark(earmark);
        if (eartagRegisterEntity != null) {
            Map map = JSON.parseObject(JSONObject.toJSONString(eartagRegisterEntity), Map.class);
//            map.put("lastTime",dateUtil.formatDatetimeText(new Date(dateUtil.parseDateTime(map.get("lastTime").toString()).getTime())));
            map.put("firstTime", dateUtil.formatLongToDate(Long.parseLong(map.get("firstTime").toString())));
            map.put("lastTime", dateUtil.formatLongToDate(Long.parseLong(map.get("lastTime").toString())));
            map.put("activeTime", dateUtil.formatLongToDate(Long.parseLong(map.get("activeTime").toString())));
            map.put("registerTime", dateUtil.formatLongToDate(Long.parseLong(map.get("registerTime").toString())));
            return new Result(ResultCode.SUCCESS, map);
        } else {
            return new Result(BizConst.CODE_EARTAG_REGISTER_NO_EXIST, BizConst.MSG_EARTAG_REGISTER_NO_EXIST, false);
        }
    }
}
