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

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.feedingplan.vo.FeedingRecordPlanPageReqVO;
import cn.iocoder.yudao.module.mes.dal.dataobject.feedingplan.FeedingRecordPlanDO;
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 FeedingRecordPlanMapper extends BaseMapperX<FeedingRecordPlanDO> {

    default PageResult<FeedingRecordPlanDO> selectPage(FeedingRecordPlanPageReqVO reqVO) {
        return selectPage(reqVO, new LambdaQueryWrapperX<FeedingRecordPlanDO>()
                .eqIfPresent(FeedingRecordPlanDO::getRecordId, reqVO.getRecordId())
                .eqIfPresent(FeedingRecordPlanDO::getRecordDetailId, reqVO.getRecordDetailId())
                .eqIfPresent(FeedingRecordPlanDO::getPlanId, reqVO.getPlanId())
                .eqIfPresent(FeedingRecordPlanDO::getTaskDetailId, reqVO.getTaskDetailId())
                .eqIfPresent(FeedingRecordPlanDO::getItemId, reqVO.getItemId())
                .eqIfPresent(FeedingRecordPlanDO::getWeight, reqVO.getWeight())
                .eqIfPresent(FeedingRecordPlanDO::getUnitId, reqVO.getUnitId())
                .eqIfPresent(FeedingRecordPlanDO::getUserId, reqVO.getUserId())
                .betweenIfPresent(FeedingRecordPlanDO::getFeedingTime, reqVO.getFeedingTime())
                .betweenIfPresent(FeedingRecordPlanDO::getCreateTime, reqVO.getCreateTime())
                .orderByDesc(FeedingRecordPlanDO::getId));
    }

    default BigDecimal selectSumBy(Long planId, Long itemId) {
        // SQL sum 查询
        List<Map<String, Object>> result = selectMaps(new QueryWrapper<FeedingRecordPlanDO>()
                .select("SUM(weight) AS sumCount")
                .eq("item_id", itemId)
                .eq("plan_id", planId));
        // 获得数量
        if (CollUtil.isEmpty(result)) {
            return BigDecimal.ZERO;
        }
        return BigDecimal.valueOf(MapUtil.getDouble(result.get(0), "sumCount", 0D));
    }
}