package com.ruoyi.app.service.impl;

import com.ruoyi.app.DTO.PorkProduceDTO;
import com.ruoyi.app.DTO.ProductTraceDTO;
import com.ruoyi.app.DTO.SlaughterBatchDTO;
import com.ruoyi.app.DTO.WeightOfProductTraceDTO;
import com.ruoyi.app.domain.request.ProductTraceParam;
import com.ruoyi.app.domain.request.ReqEntranceAndDistribute;
import com.ruoyi.app.mapper.EntranceBatchMapper;
import com.ruoyi.app.mapper.SlaughterBatchMapper;
import com.ruoyi.app.service.IProductTraceService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.util.List;
import java.util.Objects;
import java.util.stream.Collectors;

@Service
public class ProductTraceServiceImpl implements IProductTraceService {
    @Autowired
    private EntranceBatchMapper entranceBatchMapper;

    @Autowired
    private SlaughterBatchMapper slaughterBatchMapper;


    /**
     * 产品追溯-根据肉商名称，供应商名称，血码，检疫证号查询
     *@param productTraceParam 查询条件
     * @return 结果
     */
    public List<ProductTraceDTO> selectProductTrace(ProductTraceParam productTraceParam) {
        return entranceBatchMapper.selectProductTrace(productTraceParam).stream()
                .map(item -> {
                    WeightOfProductTraceDTO weight = calculateTotalWeights(item.getSlaughterBatchs());
                    item.setWeightOfProductTrace(weight);
                    return item;
                })
                .collect(Collectors.toList());
    }

    private WeightOfProductTraceDTO calculateTotalWeights(List<SlaughterBatchDTO> slaughterBatches) {
        WeightOfProductTraceDTO weight = new WeightOfProductTraceDTO();

        weight.setTotalSideWeight(slaughterBatches.stream()
                .map(SlaughterBatchDTO::getSideWeight)
                .filter(Objects::nonNull)
                .reduce(BigDecimal.ZERO, BigDecimal::add));

        weight.setTotalHeadWeight(slaughterBatches.stream()
                .map(SlaughterBatchDTO::getHeadWeight)
                .filter(Objects::nonNull)
                .reduce(BigDecimal.ZERO, BigDecimal::add));

        weight.setTotalRedWeight(slaughterBatches.stream()
                .map(SlaughterBatchDTO::getRedWeight)
                .filter(Objects::nonNull)
                .reduce(BigDecimal.ZERO, BigDecimal::add));

        weight.setTotalWhiteWeight(slaughterBatches.stream()
                .map(SlaughterBatchDTO::getWhiteWeight)
                .filter(Objects::nonNull)
                .reduce(BigDecimal.ZERO, BigDecimal::add));

        return weight;
    }

    /**
     * 根据入场批次和分销批次ID获取各部位称重记录
     *
     * @param  reqEntranceAndDistribute 入场和分销批次信息
     * @return 结果
     */
    public List<PorkProduceDTO> selectPorkProduceByBatch(ReqEntranceAndDistribute reqEntranceAndDistribute){
        return slaughterBatchMapper.selectPorkProduceByBatch(reqEntranceAndDistribute);
    }
}
