package cn.iocoder.byzs.module.blockly.dal.mysql.blocklyType;

import java.util.*;

import cn.iocoder.byzs.module.blockly.controller.admin.blocklyType.vo.BlocklyTypeListReqVO;
import cn.iocoder.byzs.framework.mybatis.core.query.LambdaQueryWrapperX;
import cn.iocoder.byzs.framework.mybatis.core.mapper.BaseMapperX;
import cn.iocoder.byzs.module.blockly.dal.dataobject.blocklyType.BlocklyTypeDO;
import org.apache.ibatis.annotations.Mapper;
import cn.iocoder.byzs.module.blockly.controller.admin.blocklyType.vo.*;

/**
 * 课程-类型 Mapper
 *
 * @author lyb
 */
@Mapper
public interface BlocklyTypeMapper extends BaseMapperX<BlocklyTypeDO> {

    default List<BlocklyTypeDO> selectList(BlocklyTypeListReqVO reqVO) {
        LambdaQueryWrapperX<BlocklyTypeDO> queryWrapper = getBlocklyTypeDOLambdaQueryWrapperX(reqVO);

        // 使用BaseMapperX的selectList方法执行查询
        return selectList(queryWrapper);
    }

    default List<BlocklyTypeDO> selectSimpleList(BlocklyTypeListReqVO reqVO) {
        LambdaQueryWrapperX<BlocklyTypeDO> queryWrapper = getBlocklyTypeDOLambdaQueryWrapperX(reqVO);

        // 使用BaseMapperX的selectList方法执行查询
        return selectList(queryWrapper.select(BlocklyTypeDO::getId, BlocklyTypeDO::getCtParentId, BlocklyTypeDO::getCtType, BlocklyTypeDO::getCtTypeNode, BlocklyTypeDO::getCtTypeSort));
    }

    private static LambdaQueryWrapperX<BlocklyTypeDO> getBlocklyTypeDOLambdaQueryWrapperX(BlocklyTypeListReqVO reqVO) {
        LambdaQueryWrapperX<BlocklyTypeDO> queryWrapper = new LambdaQueryWrapperX<BlocklyTypeDO>()
                .likeIfPresent(BlocklyTypeDO::getCtType, reqVO.getCtType())
                .eqIfPresent(BlocklyTypeDO::getCtParentId, reqVO.getCtParentId());

        // 处理getCtTypeNode的特殊条件：不为空且不等于0时，同时查询该值和0
        Object ctTypeNode = reqVO.getCtTypeNode();
        if (ctTypeNode != null && !ctTypeNode.toString().equals("0")) {
            queryWrapper.and(wrapper -> wrapper
                    .eq(BlocklyTypeDO::getCtTypeNode, ctTypeNode)
                    .or()
                    .eq(BlocklyTypeDO::getCtTypeNode, 0)
            );
        } else {
            // 保持原有的eqIfPresent行为
            queryWrapper.eqIfPresent(BlocklyTypeDO::getCtTypeNode, ctTypeNode);
        }

        // 完成构建queryWrapper并添加剩余条件
        queryWrapper
                .likeIfPresent(BlocklyTypeDO::getCtTypeDescribe, reqVO.getCtTypeDescribe())
                .orderByAsc(BlocklyTypeDO::getCtTypeNode, BlocklyTypeDO::getCtTypeSort);
        return queryWrapper;
    }

	default BlocklyTypeDO selectByCtParentIdAndCtType(Long ctParentId, String ctType) {
	    return selectOne(BlocklyTypeDO::getCtParentId, ctParentId, BlocklyTypeDO::getCtType, ctType);
	}

    default Long selectCountByCtParentId(Long ctParentId) {
        return selectCount(BlocklyTypeDO::getCtParentId, ctParentId);
    }

}