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

import com.cf.imes.framework.mybatis.core.mapper.BaseMapperX;
import com.cf.imes.framework.mybatis.core.query.LambdaQueryWrapperX;
import com.cf.imes.framework.organ.core.context.OrganContextHolder;
import com.cf.imes.framework.organ.core.security.OrganSecurityWebFilter;
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.dept.vo.dept.DeptListReqVO;
import com.cf.imes.module.system.dal.dataobject.dept.DeptDO;
import com.cf.imes.module.system.dal.dataobject.user.AdminUserDO;
import org.apache.ibatis.annotations.Mapper;

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

@Mapper
public interface DeptMapper extends BaseMapperX<DeptDO> {

    default List<DeptDO> selectList(DeptListReqVO reqVO) {
        LambdaQueryWrapperX<DeptDO> lambdaQueryWrapperX = new LambdaQueryWrapperX<>();
        LoginUser loginUser = SecurityFrameworkUtils.getLoginUser();
        assert loginUser != null;
        Boolean isSupAdmin = loginUser.getIsSupAdmin();
        if(isSupAdmin && !Objects.isNull(reqVO.getOrganId())) {
            lambdaQueryWrapperX.eqIfPresent(DeptDO::getOrganId, reqVO.getOrganId());
        }else{
            lambdaQueryWrapperX.eqIfPresent(DeptDO::getOrganId, loginUser.getOrganId());
        }
        return selectList(lambdaQueryWrapperX
                .likeIfPresent(DeptDO::getName, reqVO.getName())
                .eqIfPresent(DeptDO::getStatus, reqVO.getStatus()));
    }

    default DeptDO selectByParentIdAndName(Long parentId, String name, Long organId) {
        //如果请求中没有organId 从上下文中获取
        if(Objects.isNull(organId)) {
            organId = OrganContextHolder.getOrganId();
        }
        return selectOne(new LambdaQueryWrapperX<DeptDO>()
                .eq(DeptDO::getOrganId, organId)
                .eq(DeptDO::getParentId, parentId)
                .eq(DeptDO::getName, name)
        );
        //return selectOne(DeptDO::getParentId, parentId, DeptDO::getName, name);
    }

    default Long selectCountByParentId(Long parentId) {
        return selectCount(DeptDO::getParentId, parentId);
    }

    default List<DeptDO> selectListByParentId(Collection<Long> parentIds) {
        return selectList(DeptDO::getParentId, parentIds);
    }

}
