package com.fjhx.service.logistics.impl;

import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.fjhx.entity.logistics.LogisticsDetails;
import com.fjhx.mapper.logistics.LogisticsDetailsMapper;
import com.fjhx.params.logistics.LogisticsDetailsVo;
import com.fjhx.params.stock.GetLogisticsDetailsDto;
import com.fjhx.params.stock.GetLogisticsDetailsVo;
import com.fjhx.service.logistics.LogisticsDetailsService;
import com.fjhx.utils.Assert;
import com.fjhx.utils.wrapperUtil.IWrapper;
import org.springframework.stereotype.Service;

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

/**
 * <p>
 * 物流明细 服务实现类
 * </p>
 *
 * @author ${author}
 * @since 2022-11-30
 */
@Service
public class LogisticsDetailsServiceImpl extends ServiceImpl<LogisticsDetailsMapper, LogisticsDetails> implements LogisticsDetailsService {

    @Override
    public Page<LogisticsDetails> getPage(Map<String, Object> condition) {

        IWrapper<LogisticsDetails> wrapper = IWrapper.getWrapper(condition);

        return page(condition, wrapper);
    }

    @Override
    public void add(LogisticsDetailsVo logisticsDetailsVo) {
        save(logisticsDetailsVo);
    }

    @Override
    public void edit(LogisticsDetailsVo logisticsDetailsVo) {
        updateById(logisticsDetailsVo);
    }

    @Override
    public void delete(LogisticsDetailsVo logisticsDetailsVo) {
        removeById(logisticsDetailsVo.getId());
    }

    /**
     * 根据物流单ID查询物流明细
     */
    @Override
    public List<GetLogisticsDetailsVo> getByLogisticsInfoId(GetLogisticsDetailsDto getLogisticsDetailsDto) {
        Long logisticsInfoId = getLogisticsDetailsDto.getLogisticsInfoId();
        Assert.notEmpty(logisticsInfoId, "物流信息id不能为空");
        return baseMapper.getByLogisticsInfoId(logisticsInfoId);
    }

    @Override
    public Map<Long, BigDecimal> getDeliverQuantityMap(Long purchaseId) {

        // 已发货列表
        List<LogisticsDetails> list = this.list(q -> q.eq(LogisticsDetails::getPurchaseId, purchaseId));
        // 计算出每个采购单已出货数量
        return list.stream().collect(Collectors.toMap(
                LogisticsDetails::getApplyPurchaseId,
                LogisticsDetails::getShipmentQuantity,
                BigDecimal::add
        ));

    }

}
