package com.njcn.rdms.module.system.dal.mysql.dept;

import com.njcn.rdms.framework.mybatis.core.mapper.BaseMapperX;
import com.njcn.rdms.framework.mybatis.core.query.LambdaQueryWrapperX;
import com.njcn.rdms.module.system.dal.dataobject.dept.OrgLeaderRelationDO;
import org.apache.ibatis.annotations.Mapper;

import java.time.LocalDateTime;
import java.util.List;

@Mapper
public interface OrgLeaderRelationMapper extends BaseMapperX<OrgLeaderRelationDO> {

    default List<OrgLeaderRelationDO> selectListByDeptId(Long deptId) {
        return selectList(new LambdaQueryWrapperX<OrgLeaderRelationDO>()
                .eq(OrgLeaderRelationDO::getDeptId, deptId)
                .orderByDesc(OrgLeaderRelationDO::getId));
    }

    default List<OrgLeaderRelationDO> selectListByDeptIdAndUserId(Long deptId, Long userId) {
        return selectList(new LambdaQueryWrapperX<OrgLeaderRelationDO>()
                .eq(OrgLeaderRelationDO::getDeptId, deptId)
                .eq(OrgLeaderRelationDO::getUserId, userId)
                .orderByDesc(OrgLeaderRelationDO::getId));
    }

    /**
     * 查询指定用户在指定时间点生效的负责人记录列表
     *
     * @param userId 用户 ID
     * @param now    当前时间（生效期判断基准）
     * @return 生效中的负责人关系列表
     */
    default List<OrgLeaderRelationDO> selectEffectiveListByUserId(Long userId, LocalDateTime now) {
        return selectList(new LambdaQueryWrapperX<OrgLeaderRelationDO>()
                .eq(OrgLeaderRelationDO::getUserId, userId)
                // effectiveFrom 为空或 <= now
                .and(w -> w.isNull(OrgLeaderRelationDO::getEffectiveFrom)
                        .or().le(OrgLeaderRelationDO::getEffectiveFrom, now))
                // effectiveUntil 为空或 >= now
                .and(w -> w.isNull(OrgLeaderRelationDO::getEffectiveUntil)
                        .or().ge(OrgLeaderRelationDO::getEffectiveUntil, now)));
    }

}
