package com.cf.imes.module.system.dal.mysql.permission;

import cn.hutool.core.util.ObjectUtil;
import com.cf.imes.framework.common.pojo.PageResult;
import com.cf.imes.framework.mybatis.core.mapper.BaseMapperX;
import com.cf.imes.framework.mybatis.core.query.LambdaQueryWrapperX;
import com.cf.imes.framework.security.core.LoginUser;
import com.cf.imes.framework.security.core.util.SecurityFrameworkUtils;
import com.cf.imes.module.system.controller.admin.permission.vo.role.RolePageReqVO;
import com.cf.imes.module.system.dal.dataobject.permission.RoleDO;
import org.apache.ibatis.annotations.Mapper;
import org.springframework.lang.Nullable;

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

@Mapper
public interface RoleMapper extends BaseMapperX<RoleDO> {

    default PageResult<RoleDO> selectPage(RolePageReqVO reqVO) {
        LambdaQueryWrapperX<RoleDO> lambdaQueryWrapperX = new LambdaQueryWrapperX<RoleDO>();
        LoginUser loginUser = SecurityFrameworkUtils.getLoginUser();
        assert loginUser != null;
        Boolean isSupAdmin = loginUser.getIsSupAdmin();
        /*if(isSupAdmin && Objects.isNull(reqVO.getOrganId())) {
            //如果是超级管理员并且未传organId,就查看自己的的
            lambdaQueryWrapperX.inIfPresent(RoleDO::getOrganId,0L,loginUser.getOrganId());
        }*/
        if(isSupAdmin && ObjectUtil.isNotNull(reqVO.getOrganId())) {
            //如果是超级管理员并且传入organId,就查看组织id为0（内置角色）和传入的组织
            lambdaQueryWrapperX.inIfPresent(RoleDO::getOrganId, 0L, reqVO.getOrganId());
        } else {
            //如果不是，就查看组织id为0（内置角色）和自身的组织
            lambdaQueryWrapperX.inIfPresent(RoleDO::getOrganId, 0L, loginUser.getOrganId());
        }

        lambdaQueryWrapperX.likeIfPresent(RoleDO::getName, reqVO.getName())
                .likeIfPresent(RoleDO::getCode, reqVO.getCode())
                .eqIfPresent(RoleDO::getStatus, reqVO.getStatus())
                .betweenIfPresent(RoleDO::getCreateTime, reqVO.getCreateTime())
                .ne(RoleDO::getId, 1)
                .orderByAsc(RoleDO::getSort);

        return selectPage(reqVO, lambdaQueryWrapperX);
    }

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

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

    default List<RoleDO> selectListByStatus(@Nullable Collection<Integer> statuses, Long organId) {
        return selectList(new LambdaQueryWrapperX<RoleDO>()
                .eqIfPresent(RoleDO::getOrganId, organId)
                .eq(RoleDO::getStatus, statuses)
                .ne(RoleDO::getId, 1)
        );
    }

}
