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

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.boq.BoqGuideTreeDO;
import java.util.List;
import org.apache.ibatis.annotations.Mapper;

/**
 * 清单指引树 Mapper
 *
 * @author yhy
 */
@Mapper
public interface BoqGuideTreeMapper extends BaseMapperX<BoqGuideTreeDO> {

    /**
     * 根据清单子项ID查询树列表
     */
    default List<BoqGuideTreeDO> selectListByBoqSubItemId(Long boqSubItemId) {
        return selectList(new LambdaQueryWrapperX<BoqGuideTreeDO>()
                .eq(BoqGuideTreeDO::getBoqSubItemId, boqSubItemId)
                .orderByAsc(BoqGuideTreeDO::getSortOrder));
    }

    /**
     * 根据父节点ID查询子节点列表
     */
    default List<BoqGuideTreeDO> selectListByParentId(Long parentId) {
        return selectList(new LambdaQueryWrapperX<BoqGuideTreeDO>()
                .eq(BoqGuideTreeDO::getParentId, parentId)
                .orderByAsc(BoqGuideTreeDO::getSortOrder));
    }

    /**
     * 检查编码是否存在（同一清单子项下）
     */
    default BoqGuideTreeDO selectByBoqSubItemIdAndCode(Long boqSubItemId, String code) {
        return selectOne(new LambdaQueryWrapperX<BoqGuideTreeDO>()
                .eq(BoqGuideTreeDO::getBoqSubItemId, boqSubItemId)
                .eq(BoqGuideTreeDO::getCode, code));
    }

    /**
     * 检查是否有子节点
     */
    default boolean hasChildren(Long id) {
        return selectCount(new LambdaQueryWrapperX<BoqGuideTreeDO>()
                .eq(BoqGuideTreeDO::getParentId, id)) > 0;
    }

    /**
     * 根据清单子项ID删除所有节点
     */
    default int deleteByBoqSubItemId(Long boqSubItemId) {
        return delete(new LambdaQueryWrapperX<BoqGuideTreeDO>()
                .eq(BoqGuideTreeDO::getBoqSubItemId, boqSubItemId));
    }

    /**
     * 根据ID查询节点（加锁）
     */
    default BoqGuideTreeDO selectByIdForUpdate(Long id) {
        return selectOne(new LambdaQueryWrapperX<BoqGuideTreeDO>()
                .eq(BoqGuideTreeDO::getId, id)
                .last("FOR UPDATE"));
    }
}
