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

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.producereportplan.vo.ReportPlanViewReqVO;
import cn.iocoder.yudao.module.mes.dal.dataobject.workreportplan.ReportPlanViewDO;
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 ReportPlanViewMapper extends BaseMapperX<ReportPlanViewDO> {

    default PageResult<ReportPlanViewDO> selectPage(ReportPlanViewReqVO reqVO) {
        return selectPage(reqVO, new LambdaQueryWrapperX<ReportPlanViewDO>()
                .eqIfPresent(ReportPlanViewDO::getReportId, reqVO.getReportId())
                .eqIfPresent(ReportPlanViewDO::getPlanId, reqVO.getPlanId())
                .eqIfPresent(ReportPlanViewDO::getProductId, reqVO.getProductId())
                .eqIfPresent(ReportPlanViewDO::getQualityNumberPlan, reqVO.getQualityNumberPlan())
                .eqIfPresent(ReportPlanViewDO::getWasteNumberPlan, reqVO.getWasteNumberPlan())
                .eqIfPresent(ReportPlanViewDO::getReportTimePlan, reqVO.getReportTimePlan())
                .eqIfPresent(ReportPlanViewDO::getOrgType, reqVO.getOrgType())
                .eqIfPresent(ReportPlanViewDO::getGroupType, reqVO.getGroupType())
                .eqIfPresent(ReportPlanViewDO::getReportType, reqVO.getReportType())
                .eqIfPresent(ReportPlanViewDO::getTotalTimePlan, reqVO.getTotalTimePlan())
                .betweenIfPresent(ReportPlanViewDO::getReportDate, reqVO.getReportDate())
                .betweenIfPresent(ReportPlanViewDO::getCreateTime, reqVO.getCreateTime())
                .orderByDesc(ReportPlanViewDO::getId));
    }

    //查询计划某工序已经报工的总数
    default BigDecimal selectSumBy(Long planId, String orgType) {

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

}