package com.zt.plat.module.base.dal.dao.businessdimension;

import java.util.*;

import com.zt.plat.framework.common.pojo.PageResult;
import com.zt.plat.framework.mybatis.core.query.LambdaQueryWrapperX;
import com.zt.plat.framework.mybatis.core.mapper.BaseMapperX;
import com.zt.plat.module.base.dal.dataobject.businessdimension.BusinessDimensionDO;
import org.apache.ibatis.annotations.Mapper;
import com.zt.plat.module.base.controller.admin.businessdimension.vo.*;

/**
 * 经营指标维度 Mapper
 *
 * @author 陈鹏
 */
@Mapper
public interface BusinessDimensionMapper extends BaseMapperX<BusinessDimensionDO> {

    default PageResult<BusinessDimensionDO> selectPage(BusinessDimensionPageReqVO reqVO) {
        return selectPage(reqVO, new LambdaQueryWrapperX<BusinessDimensionDO>()
                .eqIfPresent(BusinessDimensionDO::getTypeValue, reqVO.getTypeValue())
                .eqIfPresent(BusinessDimensionDO::getCode, reqVO.getCode())
                .likeIfPresent(BusinessDimensionDO::getName, reqVO.getName())
                .betweenIfPresent(BusinessDimensionDO::getCreateTime, reqVO.getCreateTime())
                .orderByDesc(BusinessDimensionDO::getId));
    }

    // 获取子节点, 递归查询
    default List<BusinessDimensionDO> selectListByParentId(Long parentId, Integer level) {
        LambdaQueryWrapperX<BusinessDimensionDO> queryWrapper = new LambdaQueryWrapperX<BusinessDimensionDO>();

        // 构建层次查询SQL
        StringBuilder hierarchySql = new StringBuilder();
        hierarchySql.append("START WITH ");

        if (parentId == null) {
            hierarchySql.append("PRN_ID IS NULL ");
        } else {
            hierarchySql.append("PRN_ID = ").append(parentId);
        }

        if (level == null)
            hierarchySql.append(" CONNECT BY PRIOR PRN_ID = ID ");
        else if (level < 0)  //对level取绝对值
            hierarchySql.append(" CONNECT BY PRIOR PRN_ID = ID AND LEVEL <= ").append(-level);
        else
            hierarchySql.append(" CONNECT BY PRIOR ID = PRN_ID AND LEVEL <= ").append(level);
        hierarchySql.append(" ORDER SIBLINGS BY ID DESC");
        queryWrapper.last(hierarchySql.toString());

        return selectList(queryWrapper);
    }

}