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

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.stockworkshop.vo.StockWorkshopPageReqVO;
import cn.iocoder.yudao.module.mes.dal.dataobject.stockworkshop.StockWorkshopDO;
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 StockWorkshopMapper extends BaseMapperX<StockWorkshopDO> {

    default PageResult<StockWorkshopDO> selectPage(StockWorkshopPageReqVO reqVO) {
        return selectPage(reqVO, new LambdaQueryWrapperX<StockWorkshopDO>()
                .eqIfPresent(StockWorkshopDO::getItemId, reqVO.getItemId())
                .eqIfPresent(StockWorkshopDO::getCount, reqVO.getCount())
                .eqIfPresent(StockWorkshopDO::getCategoryId, reqVO.getCategoryId())
                .betweenIfPresent(StockWorkshopDO::getCreateTime, reqVO.getCreateTime())
                .orderByDesc(StockWorkshopDO::getId));
    }

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

    default StockWorkshopDO selectByItemId(Long itemId) {
        return selectOne("item_id", itemId);
    }
}