package com.ruoyi.web.v2.v1.service.impl;

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.extension.plugins.pagination.Page;
import com.ruoyi.app.DTO.AncimalDTO;
import com.ruoyi.app.model.EntranceBatch;
import com.ruoyi.app.model.HarmlessTreatment;
import com.ruoyi.app.model.Purchaser;
import com.ruoyi.app.model.Supplier;
import com.ruoyi.app.mapper.*;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.web.v2.v1.model.*;
import com.ruoyi.web.v2.v1.model.vo.*;
import com.ruoyi.web.v2.v1.mapper.*;
import com.ruoyi.web.v2.v1.service.IJsDrugCheckService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.ruoyi.web.v2.v1.utils.PaginationUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.ObjectUtils;

import java.text.DecimalFormat;
import java.time.ZoneId;
import java.util.*;
import java.util.stream.Collectors;

import static com.ruoyi.common.core.domain.AjaxResult.error;
import static com.ruoyi.common.core.domain.AjaxResult.success;

/**
 * <p>
 * v2.0违禁药物登记 服务实现类
 * </p>
 *
 * @author author
 * @since 2025-05-22
 */
@Service
public class JsDrugCheckServiceImpl extends ServiceImpl<JsDrugCheckMapper, JsDrugCheck> implements IJsDrugCheckService {

    @Autowired
    private JsDrugCheckMapper drugCheckMapper;
    @Autowired
    private JsProduceCheckMapper produceCheckMapper;
    @Autowired
    private EntranceBatchMapper entranceBatchMapper;
    @Autowired
    private JsDivideCircleMapper circleMapper;
    @Autowired
    private JsRestInspectionMapper restInspectionMapper;
    @Autowired
    private HarmlessTreatmentMapper harmlessTreatmentMapper;
    @Autowired
    private JsDistributionMapper distributionMapper;
    @Autowired
    private PurchaserMapper purchaserMapper;
    @Autowired
    private SupplierMapper supplierMapper;
    @Autowired
    private JsProduceCodeMapper produceCodeMapper;

    @Transactional
    @Override
    public AjaxResult add(JsDrugCheck drugCheck) {
        EntranceBatch entranceBatch = entranceBatchMapper.selectEntranceBatchById(drugCheck.getEntranceBatchId().longValue());
        HarmlessTreatment harmlessTreatment = harmlessTreatmentMapper.selectByEntraceBatchId(entranceBatch.getId());//无害化病害数量
        if (ObjectUtil.isEmpty(harmlessTreatment)) {
            return error("请先进行无害化处理");
        }
        List<JsDivideCircle> circles = circleMapper.selectList(new QueryWrapper<JsDivideCircle>().eq("entrance_batch_id", entranceBatch.getId()));
        Integer dealAmount = 0;
        if (circles.size() != 0) {
            List<Integer> userIds = circles.stream().map(JsDivideCircle::getId).collect(Collectors.toList());
            QueryWrapper<JsRestInspection> queryWrapper1 = new QueryWrapper<>();
            queryWrapper1.in("divide_circle_id", userIds);
            queryWrapper1.select(" IFNULL(sum(deal_amount),'0') dealAmount");
            JsRestInspection restInspection = restInspectionMapper.selectOne(queryWrapper1);//静养病死病害数量
            dealAmount = restInspection.getDealAmount();
            //新增加批次序列号字段，多个批次序列号使用逗号分割
            drugCheck.setSeriesNoGroup(circles.stream().map(JsDivideCircle::getSeriesNo).distinct()
                    .collect(Collectors.joining(",")));
        }
        int amount = entranceBatch.getAmount() - dealAmount -
                harmlessTreatment.getIllnessDeadAmount() - harmlessTreatment.getIllnessDiseaseAmount()
                - harmlessTreatment.getRoadDealAmount();
        if (amount < drugCheck.getCheckAmount()) {
            return error("抽检头数超过批次中先存活猪只数量！");
        }
        drugCheckMapper.insert(drugCheck);
        return success();
    }

    @Transactional
    @Override
    public AjaxResult edit(JsDrugCheck drugCheck) {
        EntranceBatch entranceBatch = entranceBatchMapper.selectEntranceBatchById(drugCheck.getEntranceBatchId().longValue());
        if(ObjectUtil.isNotEmpty(entranceBatch)){
            HarmlessTreatment harmlessTreatment = harmlessTreatmentMapper.selectByEntraceBatchId(entranceBatch.getId());//无害化病害数量
            List<JsDivideCircle> circles = circleMapper.selectList(new QueryWrapper<JsDivideCircle>().eq("entrance_batch_id", entranceBatch.getId()));
            Integer dealAmount = 0;
            if (circles.size() != 0) {
                List<Integer> userIds = circles.stream().map(JsDivideCircle::getId).collect(Collectors.toList());
                QueryWrapper<JsRestInspection> queryWrapper1 = new QueryWrapper<>();
                queryWrapper1.in("divide_circle_id", userIds);
                queryWrapper1.select(" IFNULL(sum(deal_amount),'0') dealAmount");
                JsRestInspection restInspection = restInspectionMapper.selectOne(queryWrapper1);//静养病死病害数量
                dealAmount = restInspection.getDealAmount();
            }
            int amount = entranceBatch.getAmount() - dealAmount -
                    harmlessTreatment.getIllnessDeadAmount() - harmlessTreatment.getIllnessDiseaseAmount()
                    - harmlessTreatment.getRoadDealAmount();
            if (amount < drugCheck.getCheckAmount()) {
                return error("抽检头数超过批次中先存活猪只数量！");
            }

        }
        drugCheckMapper.updateById(drugCheck);
        return success();
    }

    @Override
    public AjaxResult delete(String ids) {
        String[] split = ids.split(",");
        for (String s : split) {
            drugCheckMapper.deleteById(s);
        }
        return success();
    }

    @Override
    public AjaxResult page(Integer pageNum, Integer pageSize, String startTime, String endTime, String animalCertNo, String type) {
        Page<JsDrugCheck> page = new Page<>(pageNum, pageSize);
        QueryWrapper<JsDrugCheck> queryWrapper = new QueryWrapper<>();
        if ("".equals(startTime) || null == startTime) {

        } else {
            queryWrapper.between("check_time", startTime + " 00:00:00", endTime + " 23:59:59");
        }
        if(!ObjectUtils.isEmpty(type)) {
            queryWrapper.eq("check_type", type);
        }
        queryWrapper.orderByDesc("check_time");
        queryWrapper.like(StringUtils.isNotEmpty(animalCertNo), "animal_cert_no", animalCertNo);
        return success(drugCheckMapper.selectPage(page, queryWrapper));
    }

    @Override
    public AjaxResult listAll() {
        return success(drugCheckMapper.selectList(null));
    }

    @Override
    public PaginationUtil.PageResult<DrugAndProduce> drugAndProduce(Integer pageNum, Integer pageSize, String startTime, String endTime, String cargoOwner) {
        List<EntranceBatch> entranceBatchList = new ArrayList<>();
        if ("".equals(startTime) || null == startTime) {
            entranceBatchList = entranceBatchMapper.getAll(null, null, null,cargoOwner);
        } else {
            entranceBatchList = entranceBatchMapper.getAll(startTime + " 00:00:00", endTime + " 23:59:59",  null,cargoOwner);
        }
        List<DrugAndProduce> drugAndProduces = new ArrayList<>();
        if (entranceBatchList.size() != 0) {
            for (EntranceBatch entranceBatch : entranceBatchList) {
                //违禁药品
                List<DrugCheckVo> jsDrugChecks = drugCheckMapper.getDrug(entranceBatch.getId());
                //宰前所有都列出来，合格为检疫证数量减去无害化所有和静养所有
                List<JsDivideCircle> circles = circleMapper.selectList(new QueryWrapper<JsDivideCircle>().eq("entrance_batch_id", entranceBatch.getId()));
                Integer dealAmount = 0;
                if (circles.size() != 0) {
                    List<Integer> userIds = circles.stream().map(JsDivideCircle::getId).collect(Collectors.toList());
                    QueryWrapper<JsRestInspection> queryWrapper1 = new QueryWrapper<>();
                    queryWrapper1.in("divide_circle_id", userIds);
                    queryWrapper1.select(" IFNULL(sum(deal_amount),'0') dealAmount");
                    JsRestInspection restInspection = restInspectionMapper.selectOne(queryWrapper1);//静养病死病害数量
                    dealAmount = restInspection.getDealAmount();
                }

                HarmlessTreatment harmlessTreatment = harmlessTreatmentMapper.selectByEntraceBatchId(entranceBatch.getId());//无害化病害数量

                List<JsProduceCheck> produceChecks = produceCheckMapper.selectList(new QueryWrapper<JsProduceCheck>().eq("entrance_batch_id", entranceBatch.getId()));//生产检验

                DrugAndProduce drugAndProduce = new DrugAndProduce();
                drugAndProduce.setDrugs(jsDrugChecks);
                drugAndProduce.setNum(entranceBatch.getId());
                Supplier supplier = supplierMapper.selectSupplierById(entranceBatch.getSupplierId());
                drugAndProduce.setCargoOwner(supplier.getSupplierName());
                drugAndProduce.setDealAmount(dealAmount);
                int amount = 0;
                if (ObjectUtil.isNotEmpty(harmlessTreatment)) {
                    drugAndProduce.setIllnessDeadAmount(harmlessTreatment.getIllnessDeadAmount());
                    drugAndProduce.setIllnessDiseaseAmount(harmlessTreatment.getIllnessDiseaseAmount());
                    drugAndProduce.setRoadDealAmount(harmlessTreatment.getRoadDealAmount());
                    drugAndProduce.setSnapKillAmount(harmlessTreatment.getSnapKillAmount());
                     amount = entranceBatch.getAmount() - dealAmount -
                            harmlessTreatment.getIllnessDeadAmount() - harmlessTreatment.getIllnessDiseaseAmount()
                            - harmlessTreatment.getRoadDealAmount() - harmlessTreatment.getSnapKillAmount();//宰前合格头数
                    drugAndProduce.setQualifiedAmountBefore(amount);
                    drugAndProduce.setTuzaiAmount(amount);
                } else {
                    drugAndProduce.setIllnessDeadAmount(0);
                    drugAndProduce.setIllnessDiseaseAmount(0);
                    drugAndProduce.setRoadDealAmount(0);
                    drugAndProduce.setSnapKillAmount(0);
                    drugAndProduce.setQualifiedAmountBefore(0);
                    drugAndProduce.setTuzaiAmount(0);
                }


                Double weight = 0.00;
                Double number = 0.0;
                if (produceChecks.size() != 0) {
                    for (JsProduceCheck produceCheck : produceChecks) {
                        if (produceCheck.getTypes() == 0) {
                            weight = weight + Double.valueOf(produceCheck.getUnqualifiedNum());
                        }
                        if ("白条".equals(produceCheck.getProduceName())) {
                            number = number + Double.valueOf(produceCheck.getUnqualifiedNum());
                        }
                    }
                }

                drugAndProduce.setWeight(weight.toString());
                drugAndProduce.setQualifiedAmountAfter((amount*2-number)/2.0);
                drugAndProduce.setCreateTime(Date.from(entranceBatch.getEntranceTime().atZone(ZoneId.systemDefault()).toInstant()));
                drugAndProduces.add(drugAndProduce);
            }
        }
        return PaginationUtil.paginate(drugAndProduces, pageNum, pageSize);
    }

    @Override
    public PaginationUtil.PageResult<HarmlessVo> harmlessTreatment(Integer pageNum, Integer pageSize, String startTime, String endTime, String cargoOwner) {
        List<EntranceBatch> entranceBatchList = new ArrayList<>();
        if ("".equals(startTime) || null == startTime) {
            entranceBatchList = entranceBatchMapper.getAll(null, null, null,cargoOwner);
        } else {
            entranceBatchList = entranceBatchMapper.getAll(startTime + " 00:00:00", endTime + " 23:59:59", null ,cargoOwner);
        }
        List<HarmlessVo> harmlessVos = new ArrayList<>();
        Integer id = 1;
        if (entranceBatchList.size() != 0) {
            for (EntranceBatch entranceBatch : entranceBatchList) {
                HarmlessVo harmlessVo = new HarmlessVo();
                harmlessVo.setId(id);
                Supplier supplier = supplierMapper.selectSupplierById(entranceBatch.getSupplierId());
                harmlessVo.setCargoOwner(supplier.getSupplierName());
                harmlessVo.setCreateTime(Date.from(entranceBatch.getEntranceTime().atZone(ZoneId.systemDefault()).toInstant()));
                HarmlessTreatment harmlessTreatment = harmlessTreatmentMapper.selectByEntraceBatchId(entranceBatch.getId());
                //查询静养登记数据，获取静养登记病死数量
                List<JsRestInspection> restInspections = restInspectionMapper.selectList(
                        new LambdaQueryWrapper<JsRestInspection>()
                                .like(JsRestInspection::getSeriesNo, entranceBatch.getAnimalCertNo())
                                .groupBy(JsRestInspection::getDealAmount));
                if (ObjectUtil.isNotEmpty(harmlessTreatment)) {
                    harmlessVo.setDealReason(harmlessTreatment.getDealReason());
                    harmlessVo.setIllnessDeadAmount(harmlessTreatment.getIllnessDeadAmount());
                    harmlessVo.setIllnessDiseaseAmount(harmlessTreatment.getIllnessDiseaseAmount());
                    harmlessVo.setRoadDealAmount(harmlessTreatment.getRoadDealAmount());
                    //harmlessVo.setSnapKillAmount(harmlessTreatment.getSnapKillAmount());
                    if(!ObjectUtils.isEmpty(restInspections)) {
                        harmlessVo.setDealAmount(restInspections.stream()
                                .filter(item -> item.getDealAmount() != null)
                                .mapToInt(JsRestInspection::getDealAmount).sum());
                        //这里为了前端不做调整，将静养死亡的数量直接设置到急宰数量中（按老的逻辑，页面上显示的是静养死亡数量，实际映射的是急宰数量）
                        harmlessVo.setSnapKillAmount(harmlessVo.getDealAmount());
                    }else {
                        harmlessVo.setSnapKillAmount(0);
                        harmlessVo.setDealAmount(0);
                    }
                } else {
                    harmlessVo.setDealReason("");
                    harmlessVo.setIllnessDeadAmount(0);
                    harmlessVo.setIllnessDiseaseAmount(0);
                    harmlessVo.setRoadDealAmount(0);
                    harmlessVo.setSnapKillAmount(0);
                    harmlessVo.setDealAmount(0);
                }
                List<ProduceCheckVo> checkVos = new ArrayList<>();
                checkVos = produceCheckMapper.getAll(entranceBatch.getId().intValue());//生产检验
                harmlessVo.setProduceCheckVos(checkVos);
                harmlessVos.add(harmlessVo);
                id++;
            }
        }
        return PaginationUtil.paginate(harmlessVos, pageNum, pageSize);
    }

    @Override
    public PaginationUtil.PageResult<AdmissionVo> Admission(Integer pageNum, Integer pageSize, String startTime
            , String endTime, String animalCertNo, String cargoOwner) {
        List<EntranceBatch> entranceBatchList = new ArrayList<>();
        if ("".equals(startTime) || null == startTime) {
            entranceBatchList = entranceBatchMapper.getAll(null, null, animalCertNo, cargoOwner);
        } else {
            entranceBatchList = entranceBatchMapper.getAll(startTime + " 00:00:00", endTime + " 23:59:59", animalCertNo, cargoOwner);
        }
        List<AdmissionVo> admissionVos = new ArrayList<>();
        if (entranceBatchList.size() != 0) {
            for (EntranceBatch entranceBatch : entranceBatchList) {
                AdmissionVo admissionVo = new AdmissionVo();
                admissionVo.setCreateTime(Date.from(entranceBatch.getEntranceTime().atZone(ZoneId.systemDefault()).toInstant()));
                admissionVo.setNum(entranceBatch.getId());
                Supplier supplier = supplierMapper.selectSupplierById(entranceBatch.getSupplierId());
                admissionVo.setCargoOwner(supplier.getSupplierName());
                if ("1".equals(entranceBatch.getOriginPlace())) {
                    admissionVo.setOriginPlace("本市");
                } else if ("2".equals(entranceBatch.getOriginPlace())) {
                    admissionVo.setOriginPlace("市外");
                } else if ("3".equals(entranceBatch.getOriginPlace())) {
                    admissionVo.setOriginPlace("省外");
                } else {
                    admissionVo.setOriginPlace("本市");
                }

                admissionVo.setAnimalCertNo(entranceBatch.getAnimalCertNo());

                HarmlessTreatment harmlessTreatment = harmlessTreatmentMapper.selectByEntraceBatchId(entranceBatch.getId());
                if (ObjectUtil.isNotEmpty(harmlessTreatment)) {
                    admissionVo.setIllnessDeadAmount(harmlessTreatment.getIllnessDeadAmount());
                    admissionVo.setIllnessDiseaseAmount(harmlessTreatment.getIllnessDiseaseAmount());
                    admissionVo.setRoadDealAmount(harmlessTreatment.getRoadDealAmount());
                    admissionVo.setSnapKillAmount(harmlessTreatment.getSnapKillAmount());
                    int amount = entranceBatch.getAmount() - harmlessTreatment.getIllnessDeadAmount() -
                            harmlessTreatment.getIllnessDiseaseAmount() - harmlessTreatment.getRoadDealAmount() - harmlessTreatment.getSnapKillAmount();
                    admissionVo.setQualifiedAmount(amount);
                    admissionVo.setAmount(entranceBatch.getAmount() - harmlessTreatment.getRoadDealAmount());
                } else {
                    admissionVo.setIllnessDeadAmount(0);
                    admissionVo.setIllnessDiseaseAmount(0);
                    admissionVo.setRoadDealAmount(0);
                    admissionVo.setSnapKillAmount(0);
                    admissionVo.setQualifiedAmount(0);
                    admissionVo.setAmount(0);
                }
                admissionVos.add(admissionVo);
            }
        }

        return PaginationUtil.paginate(admissionVos, pageNum, pageSize);
    }

    @Override
    public PaginationUtil.PageResult<OutPlaceVo> outPlace(Integer pageNum, Integer pageSize, String startTime, String endTime, String cargoOwner) {
        List<OutPlaceVo> outPlaceVos = new ArrayList<>();
        QueryWrapper<JsDistribution> queryWrapper = new QueryWrapper<>();
        queryWrapper.like(StringUtils.isNotEmpty(cargoOwner), "supplier_name", cargoOwner);
        queryWrapper.orderByDesc("distribution_time");
        if ("".equals(startTime) || null == startTime) {

        } else {
            queryWrapper.between("distribution_time", startTime + " 00:00:00", endTime + " 23:59:59");
        }
        List<JsDistribution> jsDistributions = distributionMapper.selectList(queryWrapper);
        if (jsDistributions.size() != 0) {
            for (JsDistribution jsDistribution : jsDistributions) {
                OutPlaceVo placeVo = new OutPlaceVo();
                placeVo.setNum(jsDistribution.getId());
                placeVo.setUnit(jsDistribution.getUnit());
                placeVo.setCreateTime(jsDistribution.getDistributionTime());
                Supplier supplier = supplierMapper.selectSupplierById(jsDistribution.getSupplierId().longValue());
                placeVo.setCargoOwner(supplier.getSupplierName());
                JsProduceCode jsProduceCode = produceCodeMapper.selectOne(new QueryWrapper<JsProduceCode>().eq("one_code", jsDistribution.getOneCode()));
                if (ObjectUtil.isNotEmpty(jsProduceCode)) {
                    placeVo.setAnimalCert(jsProduceCode.getAnimalCert());
                    placeVo.setMeatCert(jsProduceCode.getMeatCert());
                }else {
                AncimalDTO oneAnimal = purchaserMapper.getOneAnimal(jsDistribution.getPurchaserId().toString());
                    if (ObjectUtil.isNotEmpty(oneAnimal)) {
                        placeVo.setAnimalCert(oneAnimal.getAnimalCert());
                        placeVo.setMeatCert(oneAnimal.getMeatCert());
                    }
                }

                placeVo.setProduceName(jsDistribution.getProduceName());
                Purchaser purchaser = purchaserMapper.selectPurchaserById((long) jsDistribution.getPurchaserId());
                if (ObjectUtil.isNotEmpty(purchaser)) {
                        if ("1".equals(purchaser.getSalePlace())) {
                            placeVo.setAmount(jsDistribution.getAmount().toString());
                        } else if ("2".equals(purchaser.getSalePlace())) {
                            placeVo.setAmount2(jsDistribution.getAmount().toString());
                        } else if ("3".equals(purchaser.getSalePlace())) {
                            placeVo.setAmount3(jsDistribution.getAmount().toString());
                        }
//                    }
                    if ("1".equals(purchaser.getSalePlace())) {
                        placeVo.setWeight(jsDistribution.getWeight());
                    } else if ("2".equals(purchaser.getSalePlace())) {
                        placeVo.setWeight2(jsDistribution.getWeight());
                    } else if ("3".equals(purchaser.getSalePlace())) {
                        placeVo.setWeight3(jsDistribution.getWeight());
                    }
                }
                outPlaceVos.add(placeVo);
            }
        }
        return PaginationUtil.paginate(outPlaceVos, pageNum, pageSize);
    }

    @Override
    public PaginationUtil.PageResult<SummaryVo> SummaryVo(Integer pageNum, Integer pageSize, String startTime, String endTime) {
        List<EntranceBatch> entranceBatchList = new ArrayList<>();

        if ("".equals(startTime) || null == startTime) {
            entranceBatchList = entranceBatchMapper.getAll(null, null, null, null);
        } else {
            entranceBatchList = entranceBatchMapper.getAll(startTime+" 00:00:00", endTime+" 23:59:59", null, null);
        }



        List<SummaryVo> summaryVos = new ArrayList<>();
        List<SummaryVo> summaryVoList = new ArrayList<>();
        List<SummaryVo> result = new ArrayList<>();
        if (!entranceBatchList.isEmpty()) {
            for (EntranceBatch entranceBatch : entranceBatchList) {
                SummaryVo summaryVo = new SummaryVo();
                summaryVo.setCreateTime(Date.from(entranceBatch.getEntranceTime().atZone(ZoneId.systemDefault()).toInstant()));
                summaryVo.setAmount(entranceBatch.getAmount());
                QueryWrapper<JsDrugCheck> queryWrapper = new QueryWrapper<>();
                queryWrapper.eq("entrance_batch_id", entranceBatch.getId());
                List<JsDrugCheck> jsDrugChecks = drugCheckMapper.selectList(queryWrapper);
                Integer checkAmount = 0;
                Integer resultAmount = 0;
                if (!jsDrugChecks.isEmpty()) {
                    for (JsDrugCheck jsDrugCheck : jsDrugChecks) {
                        //抽检头数
                        checkAmount = checkAmount + jsDrugCheck.getCheckAmount();
                        //合格头数
                        if ("阴性".equals(jsDrugCheck.getResult())) {
                            resultAmount = resultAmount + jsDrugCheck.getCheckAmount();
                        }

                    }

                }
                summaryVo.setCheckAmount(checkAmount);
                summaryVo.setQualifiedAmount(resultAmount);
                summaryVo.setAmount(entranceBatch.getAmount());//到场活猪头数


                QueryWrapper<JsDistribution> queryWrapper1 = new QueryWrapper<>();
                queryWrapper1.eq("entrance_batch_id", entranceBatch.getId());
                queryWrapper1.select(" amount amount,after_weight afterWeight,produce_name produceName");
                List<JsDistribution> jsDistributions = distributionMapper.selectList(queryWrapper1);
                Integer amount = 0;
                Double values = 0.00;
                if (jsDistributions.size() != 0) {
                    for (JsDistribution jsDistribution : jsDistributions) {
                        if ("白条".equals(jsDistribution.getProduceName())) {
                            amount = amount + jsDistribution.getAmount();
                        } else {
                            values = values + Double.parseDouble(jsDistribution.getAfterWeight());
                        }
                    }
                }
                summaryVo.setDongAmount(amount / 2.0);//胴体头数
                DecimalFormat def = new DecimalFormat("0.00");
                if (values == 0) {
                    summaryVo.setWeight("0.00");
                } else {
                    summaryVo.setWeight(def.format(values));//产品重量
                }

                HarmlessTreatment harmlessTreatment = harmlessTreatmentMapper.selectByEntraceBatchId(entranceBatch.getId());

                if (ObjectUtil.isNotEmpty(harmlessTreatment)) {
                    summaryVo.setIllnessDeadAmount(harmlessTreatment.getIllnessDeadAmount());
                    summaryVo.setIllnessDiseaseAmount(harmlessTreatment.getIllnessDiseaseAmount());
                    summaryVo.setRoadDealAmount(harmlessTreatment.getRoadDealAmount());
                    summaryVo.setSnapKillAmount(harmlessTreatment.getSnapKillAmount());
                    int amount1 = entranceBatch.getAmount() - harmlessTreatment.getIllnessDeadAmount() -
                            harmlessTreatment.getIllnessDiseaseAmount() - harmlessTreatment.getRoadDealAmount() - harmlessTreatment.getSnapKillAmount();
                    summaryVo.setTuzaiAmount(amount1);//待宰头数
                } else {
                    summaryVo.setIllnessDeadAmount(0);
                    summaryVo.setIllnessDiseaseAmount(0);
                    summaryVo.setRoadDealAmount(0);
                    summaryVo.setSnapKillAmount(0);
                    summaryVo.setTuzaiAmount(entranceBatch.getAmount());//待宰头数
                }
                summaryVos.add(summaryVo);
            }
            summaryVoList = mergeObjectsByTime(summaryVos)
                    .stream().sorted(Comparator.comparing(SummaryVo::getCreateTime).reversed())
                    .collect(Collectors.toList());
            //按天分组合计
            result = summaryVoList.stream()
                    .collect(Collectors.groupingBy(
                            vo -> vo.getCreateTime().toInstant()
                                    .atZone(ZoneId.systemDefault())
                                    .toLocalDate(),
                            Collectors.reducing(
                                    new SummaryVo(null, 0, 0, 0, 0,0.0, "0.00", 0, 0, 0, 0),
                                    (sum, item) -> {
                                        double weightSum = Double.parseDouble(sum.getWeight()) + Double.parseDouble(item.getWeight());
                                        return new SummaryVo(
                                                item.getCreateTime(),
                                                sum.getAmount() + item.getAmount(),
                                                sum.getCheckAmount() + item.getCheckAmount(),
                                                sum.getQualifiedAmount() + item.getQualifiedAmount(),
                                                sum.getTuzaiAmount() + item.getTuzaiAmount(),
                                                sum.getDongAmount() + item.getDongAmount(),
                                                String.format("%.2f", weightSum),
                                                sum.getRoadDealAmount() + item.getRoadDealAmount(),
                                                sum.getIllnessDeadAmount() + item.getIllnessDeadAmount(),
                                                sum.getIllnessDiseaseAmount() + item.getIllnessDiseaseAmount(),
                                                sum.getSnapKillAmount() + item.getSnapKillAmount()
                                        );
                                    }
                            )
                    ))
                    .values().stream()
                    .sorted(Comparator.comparing(SummaryVo::getCreateTime).reversed())
                    .collect(Collectors.toList());
        }
        return PaginationUtil.paginate(result, pageNum, pageSize);
    }


    public List<SummaryVo> mergeObjectsByTime(List<SummaryVo> list) {
        Map<Date, SummaryVo> map = new HashMap<>();
        DecimalFormat def = new DecimalFormat("0.00");
        Double values = 0.00;
        for (SummaryVo summaryVo : list) {
            map.compute(summaryVo.getCreateTime(), (k, v) -> {
                if (v == null) {
                    return new SummaryVo(summaryVo.getCreateTime(), summaryVo.getAmount(), summaryVo.getCheckAmount(), summaryVo.getQualifiedAmount(),
                            summaryVo.getTuzaiAmount(), summaryVo.getDongAmount(), summaryVo.getWeight(), summaryVo.getRoadDealAmount(),
                            summaryVo.getIllnessDeadAmount(), summaryVo.getIllnessDiseaseAmount(),
                            summaryVo.getSnapKillAmount());
                }
                v.setAmount(v.getAmount() + summaryVo.getAmount());
                v.setCheckAmount(v.getCheckAmount() + summaryVo.getCheckAmount());
                v.setQualifiedAmount(v.getQualifiedAmount() + summaryVo.getQualifiedAmount());
                v.setTuzaiAmount(v.getTuzaiAmount() + summaryVo.getTuzaiAmount());
                v.setDongAmount(v.getDongAmount() + summaryVo.getDongAmount());
                double v1 = Double.valueOf(v.getWeight()) + Double.valueOf(summaryVo.getWeight());
                v.setWeight(def.format(v1));
                v.setRoadDealAmount(v.getRoadDealAmount() + summaryVo.getRoadDealAmount());
                v.setIllnessDeadAmount(v.getIllnessDeadAmount() + summaryVo.getIllnessDeadAmount());
                v.setIllnessDiseaseAmount(v.getIllnessDiseaseAmount() + summaryVo.getIllnessDiseaseAmount());
                v.setSnapKillAmount(v.getSnapKillAmount() + summaryVo.getSnapKillAmount());
                return v;
            });
        }

        return new ArrayList<>(map.values());
    }

    @Override
    public JsDrugCheck getDetail(JsDrugCheck jsDrugCheck){
        return drugCheckMapper.selectForOne(jsDrugCheck);
    }
}
