package com.yhy.module.core.dal.mysql.resource;

import cn.iocoder.yudao.framework.mybatis.core.mapper.BaseMapperX;
import cn.iocoder.yudao.framework.mybatis.core.query.LambdaQueryWrapperX;
import com.yhy.module.core.dal.dataobject.resource.ResourceInfoPriceMappingDO;
import java.util.List;
import org.apache.ibatis.annotations.Mapper;

/**
 * 工料机-信息价关联 Mapper
 *
 * @author yhy
 */
@Mapper
public interface ResourceInfoPriceMappingMapper extends BaseMapperX<ResourceInfoPriceMappingDO> {

    /**
     * 根据工料机ID查询关联的信息价列表
     */
    default List<ResourceInfoPriceMappingDO> selectListByResourceItemId(Long resourceItemId) {
        return selectList(new LambdaQueryWrapperX<ResourceInfoPriceMappingDO>()
                .eq(ResourceInfoPriceMappingDO::getResourceItemId, resourceItemId));
    }
    
    /**
     * 根据项目ID和工料机ID查询关联的信息价列表
     */
    default List<ResourceInfoPriceMappingDO> selectListByProjectAndResourceItem(Long projectId, Long resourceItemId) {
        return selectList(new LambdaQueryWrapperX<ResourceInfoPriceMappingDO>()
                .eq(ResourceInfoPriceMappingDO::getProjectId, projectId)
                .eq(ResourceInfoPriceMappingDO::getResourceItemId, resourceItemId));
    }

    /**
     * 根据信息价工料机ID查询关联的工料机列表
     */
    default List<ResourceInfoPriceMappingDO> selectListByInfoPriceResourceId(Long infoPriceResourceId) {
        return selectList(new LambdaQueryWrapperX<ResourceInfoPriceMappingDO>()
                .eq(ResourceInfoPriceMappingDO::getInfoPriceResourceId, infoPriceResourceId));
    }

    /**
     * 统计工料机关联的信息价数量
     */
    default Long selectCountByResourceItemId(Long resourceItemId) {
        return selectCount(new LambdaQueryWrapperX<ResourceInfoPriceMappingDO>()
                .eq(ResourceInfoPriceMappingDO::getResourceItemId, resourceItemId));
    }

    /**
     * 检查关联是否已存在
     */
    default boolean existsByResourceAndInfoPrice(Long resourceItemId, Long infoPriceResourceId) {
        return selectCount(new LambdaQueryWrapperX<ResourceInfoPriceMappingDO>()
                .eq(ResourceInfoPriceMappingDO::getResourceItemId, resourceItemId)
                .eq(ResourceInfoPriceMappingDO::getInfoPriceResourceId, infoPriceResourceId)) > 0;
    }

    /**
     * 删除指定工料机的所有关联
     */
    default int deleteByResourceItemId(Long resourceItemId) {
        return delete(new LambdaQueryWrapperX<ResourceInfoPriceMappingDO>()
                .eq(ResourceInfoPriceMappingDO::getResourceItemId, resourceItemId));
    }

    /**
     * 物理删除指定的关联记录（包括已软删除的）
     * 用于避免唯一约束冲突
     */
    @org.apache.ibatis.annotations.Delete("DELETE FROM yhy_resource_info_price_mapping WHERE resource_item_id = #{resourceItemId} AND info_price_resource_id = #{infoPriceResourceId}")
    int physicalDeleteByResourceAndInfoPrice(@org.apache.ibatis.annotations.Param("resourceItemId") Long resourceItemId, 
                                              @org.apache.ibatis.annotations.Param("infoPriceResourceId") Long infoPriceResourceId);

    /**
     * 清除工料机的所有当前价标记
     */
    @org.apache.ibatis.annotations.Update("UPDATE yhy_resource_info_price_mapping SET is_current = 0 WHERE resource_item_id = #{resourceItemId} AND deleted = 0")
    int clearCurrentByResourceItemId(@org.apache.ibatis.annotations.Param("resourceItemId") Long resourceItemId);
    
    /**
     * 清除项目下工料机的所有当前价标记
     */
    @org.apache.ibatis.annotations.Update("UPDATE yhy_resource_info_price_mapping SET is_current = 0 WHERE project_id = #{projectId} AND resource_item_id = #{resourceItemId} AND deleted = 0")
    int clearCurrentByProjectAndResourceItem(@org.apache.ibatis.annotations.Param("projectId") Long projectId,
                                              @org.apache.ibatis.annotations.Param("resourceItemId") Long resourceItemId);

    /**
     * 设置当前价格来源
     */
    @org.apache.ibatis.annotations.Update("UPDATE yhy_resource_info_price_mapping SET is_current = 1, selected_price_id = #{selectedPriceId} WHERE resource_item_id = #{resourceItemId} AND info_price_resource_id = #{infoPriceResourceId} AND deleted = 0")
    int setCurrentPrice(@org.apache.ibatis.annotations.Param("resourceItemId") Long resourceItemId,
                        @org.apache.ibatis.annotations.Param("infoPriceResourceId") Long infoPriceResourceId,
                        @org.apache.ibatis.annotations.Param("selectedPriceId") Long selectedPriceId);
    
    /**
     * 设置当前价格来源（按项目ID和工料机ID）
     */
    @org.apache.ibatis.annotations.Update("UPDATE yhy_resource_info_price_mapping SET is_current = 1, selected_price_id = #{selectedPriceId} WHERE project_id = #{projectId} AND resource_item_id = #{resourceItemId} AND info_price_resource_id = #{infoPriceResourceId} AND deleted = 0")
    int setCurrentPriceByProject(@org.apache.ibatis.annotations.Param("projectId") Long projectId,
                        @org.apache.ibatis.annotations.Param("resourceItemId") Long resourceItemId,
                        @org.apache.ibatis.annotations.Param("infoPriceResourceId") Long infoPriceResourceId,
                        @org.apache.ibatis.annotations.Param("selectedPriceId") Long selectedPriceId);

    /**
     * 更新公式（项目级别）
     */
    @org.apache.ibatis.annotations.Update("UPDATE yhy_resource_info_price_mapping SET formula = #{formula} WHERE resource_item_id = #{resourceItemId} AND info_price_resource_id = #{infoPriceResourceId} AND project_id = #{projectId} AND deleted = 0")
    int updateFormulaByProject(@org.apache.ibatis.annotations.Param("resourceItemId") Long resourceItemId,
                      @org.apache.ibatis.annotations.Param("infoPriceResourceId") Long infoPriceResourceId,
                      @org.apache.ibatis.annotations.Param("projectId") Long projectId,
                      @org.apache.ibatis.annotations.Param("formula") String formula);
    
    /**
     * 更新公式（兼容旧逻辑）
     */
    @org.apache.ibatis.annotations.Update("UPDATE yhy_resource_info_price_mapping SET formula = #{formula} WHERE resource_item_id = #{resourceItemId} AND info_price_resource_id = #{infoPriceResourceId} AND deleted = 0")
    int updateFormula(@org.apache.ibatis.annotations.Param("resourceItemId") Long resourceItemId,
                      @org.apache.ibatis.annotations.Param("infoPriceResourceId") Long infoPriceResourceId,
                      @org.apache.ibatis.annotations.Param("formula") String formula);

    /**
     * 批量查询有当前价格来源的工料机ID
     */
    default java.util.Set<Long> selectCurrentPriceResourceIds(java.util.List<Long> resourceItemIds) {
        if (resourceItemIds == null || resourceItemIds.isEmpty()) {
            return java.util.Collections.emptySet();
        }
        java.util.List<ResourceInfoPriceMappingDO> list = selectList(new cn.iocoder.yudao.framework.mybatis.core.query.LambdaQueryWrapperX<ResourceInfoPriceMappingDO>()
                .in(ResourceInfoPriceMappingDO::getResourceItemId, resourceItemIds)
                .eq(ResourceInfoPriceMappingDO::getIsCurrent, 1));
        return list.stream()
                .map(ResourceInfoPriceMappingDO::getResourceItemId)
                .collect(java.util.stream.Collectors.toSet());
    }
    
    /**
     * 批量查询当前价格来源的详细信息（包含 selectedPriceId）
     * @return Map<resourceItemId, ResourceInfoPriceMappingDO>
     * @deprecated 使用 selectCurrentPriceMappingsByWbBoqResourceIds 替代
     */
    default java.util.Map<Long, ResourceInfoPriceMappingDO> selectCurrentPriceMappings(java.util.List<Long> resourceItemIds) {
        if (resourceItemIds == null || resourceItemIds.isEmpty()) {
            return java.util.Collections.emptyMap();
        }
        java.util.List<ResourceInfoPriceMappingDO> list = selectList(new cn.iocoder.yudao.framework.mybatis.core.query.LambdaQueryWrapperX<ResourceInfoPriceMappingDO>()
                .in(ResourceInfoPriceMappingDO::getResourceItemId, resourceItemIds)
                .eq(ResourceInfoPriceMappingDO::getIsCurrent, 1));
        return list.stream()
                .collect(java.util.stream.Collectors.toMap(
                        ResourceInfoPriceMappingDO::getResourceItemId,
                        m -> m,
                        (existing, replacement) -> existing));
    }
    
    /**
     * 批量查询项目下当前价格来源的详细信息
     * @return Map<resourceItemId, ResourceInfoPriceMappingDO>
     */
    default java.util.Map<Long, ResourceInfoPriceMappingDO> selectCurrentPriceMappingsByProject(Long projectId, java.util.List<Long> resourceItemIds) {
        if (projectId == null || resourceItemIds == null || resourceItemIds.isEmpty()) {
            return java.util.Collections.emptyMap();
        }
        java.util.List<ResourceInfoPriceMappingDO> list = selectList(new cn.iocoder.yudao.framework.mybatis.core.query.LambdaQueryWrapperX<ResourceInfoPriceMappingDO>()
                .eq(ResourceInfoPriceMappingDO::getProjectId, projectId)
                .in(ResourceInfoPriceMappingDO::getResourceItemId, resourceItemIds)
                .eq(ResourceInfoPriceMappingDO::getIsCurrent, 1));
        return list.stream()
                .collect(java.util.stream.Collectors.toMap(
                        ResourceInfoPriceMappingDO::getResourceItemId,
                        m -> m,
                        (existing, replacement) -> existing));
    }

    default java.util.Map<Long, ResourceInfoPriceMappingDO> selectCurrentPriceMappingsByResourceItemIds(java.util.List<Long> resourceItemIds) {
        if (resourceItemIds == null || resourceItemIds.isEmpty()) {
            return java.util.Collections.emptyMap();
        }
        java.util.List<ResourceInfoPriceMappingDO> list = selectList(new cn.iocoder.yudao.framework.mybatis.core.query.LambdaQueryWrapperX<ResourceInfoPriceMappingDO>()
                .in(ResourceInfoPriceMappingDO::getResourceItemId, resourceItemIds)
                .eq(ResourceInfoPriceMappingDO::getIsCurrent, 1));
        return list.stream()
                .collect(java.util.stream.Collectors.toMap(
                        ResourceInfoPriceMappingDO::getResourceItemId,
                        m -> m,
                        (existing, replacement) -> existing));
    }
    
    /**
     * 查询租户下该工料机+信息价组合最后修改的公式（按更新时间倒序取第一条非空公式）
     * 用于：公式是项目级，相同工料机且公式为空时，按最后一次修改的值出现
     */
    default String selectLastFormulaByResourceAndInfoPrice(Long resourceItemId, Long infoPriceResourceId) {
        java.util.List<ResourceInfoPriceMappingDO> list = selectList(new cn.iocoder.yudao.framework.mybatis.core.query.LambdaQueryWrapperX<ResourceInfoPriceMappingDO>()
                .eq(ResourceInfoPriceMappingDO::getResourceItemId, resourceItemId)
                .eq(ResourceInfoPriceMappingDO::getInfoPriceResourceId, infoPriceResourceId)
                .isNotNull(ResourceInfoPriceMappingDO::getFormula)
                .ne(ResourceInfoPriceMappingDO::getFormula, "")
                .orderByDesc(ResourceInfoPriceMappingDO::getUpdateTime)
                .last("LIMIT 1"));
        return list.isEmpty() ? null : list.get(0).getFormula();
    }
    
    /**
     * 查询租户下该工料机已关联的所有信息价ID集合（用于弹窗置顶，租户级）
     */
    default java.util.Set<Long> selectAssociatedInfoPriceIdsByResourceItem(Long resourceItemId) {
        java.util.List<ResourceInfoPriceMappingDO> list = selectList(new cn.iocoder.yudao.framework.mybatis.core.query.LambdaQueryWrapperX<ResourceInfoPriceMappingDO>()
                .eq(ResourceInfoPriceMappingDO::getResourceItemId, resourceItemId)
                .select(ResourceInfoPriceMappingDO::getInfoPriceResourceId));
        return list.stream()
                .map(ResourceInfoPriceMappingDO::getInfoPriceResourceId)
                .collect(java.util.stream.Collectors.toSet());
    }
}
