package cn.iocoder.yudao.module.mes.dal.mysql.stockindetail;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.map.MapUtil;
import cn.iocoder.yudao.framework.common.pojo.PageResult;
import cn.iocoder.yudao.framework.mybatis.core.mapper.BaseMapperX;
import cn.iocoder.yudao.framework.mybatis.core.query.LambdaQueryWrapperX;
import cn.iocoder.yudao.module.mes.controller.admin.stockindetail.vo.StockInDetailPageReqVO;
import cn.iocoder.yudao.module.mes.dal.dataobject.stockindetail.StockInDetailDO;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import org.apache.ibatis.annotations.Mapper;

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

/**
 * 生产入库分配明细 Mapper
 *
 * @author 内蒙必硕
 */
@Mapper
public interface StockInDetailMapper extends BaseMapperX<StockInDetailDO> {

    default PageResult<StockInDetailDO> selectPage(StockInDetailPageReqVO reqVO) {
        return selectPage(reqVO, new LambdaQueryWrapperX<StockInDetailDO>()
                .eqIfPresent(StockInDetailDO::getStockInId, reqVO.getStockInId())
                .eqIfPresent(StockInDetailDO::getStockInNo, reqVO.getStockInNo())
                .eqIfPresent(StockInDetailDO::getStockInItemId, reqVO.getStockInItemId())
                .eqIfPresent(StockInDetailDO::getPlanId, reqVO.getPlanId())
                .eqIfPresent(StockInDetailDO::getTaskDetailId, reqVO.getTaskDetailId())
                .eqIfPresent(StockInDetailDO::getProductId, reqVO.getProductId())
                .eqIfPresent(StockInDetailDO::getNumber, reqVO.getNumber())
                .betweenIfPresent(StockInDetailDO::getCreateTime, reqVO.getCreateTime())
                .orderByDesc(StockInDetailDO::getId));
    }

    //查询计划已经入库的总数
    default BigDecimal selectSumBy(Long planId) {

        // SQL sum 查询
        List<Map<String, Object>> result = selectMaps(new QueryWrapper<StockInDetailDO>()
                .select("SUM(number) AS sumCount")
                .eq("plan_id", planId));
        // 获得数量
        if (CollUtil.isEmpty(result)) {
            return BigDecimal.ZERO;
        }
        return BigDecimal.valueOf(MapUtil.getDouble(result.get(0), "sumCount", 0D));
    }
    //查询任务单明细已经入库的总数
    default BigDecimal selectSumByTaskDetailId(Long taskDetailId) {

        // SQL sum 查询
        List<Map<String, Object>> result = selectMaps(new QueryWrapper<StockInDetailDO>()
                .select("SUM(number) AS sumCount")
                .eq("task_detail_id", taskDetailId));
        // 获得数量
        if (CollUtil.isEmpty(result)) {
            return BigDecimal.ZERO;
        }
        return BigDecimal.valueOf(MapUtil.getDouble(result.get(0), "sumCount", 0D));
    }
}