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.BoqDetailTreeDO;
import org.apache.ibatis.annotations.Mapper;

import java.util.List;

/**
 * 清单明细树 Mapper
 *
 * @author yhy
 */
@Mapper
public interface BoqDetailTreeMapper extends BaseMapperX<BoqDetailTreeDO> {

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

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

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

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

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

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