package cn.ey.biz.module.system.dal.mapper.permission;

import cn.ey.biz.common.pojo.PageResult;
import cn.ey.biz.framework.mybatis.core.dataobject.BaseDO;
import cn.ey.biz.framework.mybatis.core.mapper.BaseMapperX;
import cn.ey.biz.framework.mybatis.core.query.LambdaQueryWrapperX;
import cn.ey.biz.module.system.controller.admin.permission.vo.role.RoleExportReqVO;
import cn.ey.biz.module.system.controller.admin.permission.vo.role.RoleFunctionalReqVO;
import cn.ey.biz.module.system.controller.admin.permission.vo.role.RolePageReqVO;
import cn.ey.biz.module.system.controller.admin.permission.vo.role.RoleSimpleFunctionalRespVO;
import cn.ey.biz.module.system.dal.dataobject.permission.RoleDO;
import org.apache.ibatis.annotations.Mapper;
import org.apache.ibatis.annotations.Param;
import org.apache.ibatis.annotations.Select;
import org.springframework.lang.Nullable;

import java.util.Collection;
import java.util.Date;
import java.util.List;

@Mapper
public interface RoleMapper extends BaseMapperX<RoleDO> {

    default PageResult<RoleDO> selectPage(RolePageReqVO reqVO) {
        return selectPage(reqVO, new LambdaQueryWrapperX<RoleDO>()
                .likeIfPresent(RoleDO::getName, reqVO.getName())
                .likeIfPresent(RoleDO::getCode, reqVO.getCode())
                .eqIfPresent(RoleDO::getStatus, reqVO.getStatus())
                .eqIfPresent(RoleDO::getApp, reqVO.getApp())
                .betweenIfPresent(BaseDO::getCreateTime, reqVO.getCreateTime())
                .orderByDesc(RoleDO::getId));
    }

    default List<RoleDO> selectList(RoleExportReqVO reqVO) {
        return selectList(new LambdaQueryWrapperX<RoleDO>()
                .likeIfPresent(RoleDO::getName, reqVO.getName())
                .likeIfPresent(RoleDO::getCode, reqVO.getCode())
                .eqIfPresent(RoleDO::getStatus, reqVO.getStatus())
                .betweenIfPresent(BaseDO::getCreateTime, reqVO.getCreateTime()));
    }

    default RoleDO selectByName(String name) {
        return selectOne(RoleDO::getName, name);
    }

    default RoleDO selectByCode(String code) {
        return selectOne(RoleDO::getCode, code);
    }

    default List<RoleDO> selectListByStatus(@Nullable Collection<Integer> statuses) {
        return selectList(RoleDO::getStatus, statuses);
    }

    @Select("SELECT COUNT(*) FROM system_role WHERE update_time > #{maxUpdateTime}")
    Long selectCountByUpdateTimeGt(Date maxUpdateTime);

    @Select("SELECT IFNULL(MAX(SUBSTR(`role_code`,6)),0)+1 as maxRoleCode FROM `system_role` " +
            " where app_code=#{appCode} and role_class=#{roleClass}")
    Long getMaxRoleCodeByAppAndClass(@Param("appCode") String appCode,@Param("roleClass") String roleClass);



    List<RoleSimpleFunctionalRespVO> selectFunctionalRoles(RoleFunctionalReqVO reqVO);

}
