package cn.iocoder.yudao.module.bpm.dal.mysql.oa.universal;

import cn.hutool.core.collection.CollUtil;
import cn.iocoder.yudao.framework.common.pojo.PageResult;
import cn.iocoder.yudao.framework.mybatis.core.query.LambdaQueryWrapperX;
import cn.iocoder.yudao.framework.mybatis.core.mapper.BaseMapperX;
import cn.iocoder.yudao.module.bpm.controller.admin.oa.universal.vo.OaUniversalPageReqVO;
import cn.iocoder.yudao.module.bpm.dal.dataobject.oa.universal.OaUniversalDO;
import cn.iocoder.yudao.module.system.api.permission.dto.DeptDataPermissionRespDTO;
import org.apache.ibatis.annotations.Mapper;

/**
 * 通用事项审批流程信息 Mapper
 *
 * @author dp
 */
@Mapper
public interface OaUniversalMapper extends BaseMapperX<OaUniversalDO> {

    default PageResult<OaUniversalDO> selectPage(OaUniversalPageReqVO reqVO) {
        LambdaQueryWrapperX<OaUniversalDO> lambdaQueryWrapperX = new LambdaQueryWrapperX<OaUniversalDO>()
                .likeIfPresent(OaUniversalDO::getEmployeeName, reqVO.getEmployeeName())
                .likeIfPresent(OaUniversalDO::getEmployeePhone, reqVO.getEmployeePhone())
                .eqIfPresent(OaUniversalDO::getDeptId, reqVO.getDeptId())
                .eqIfPresent(OaUniversalDO::getPostId, reqVO.getPostId())
                .likeIfPresent(OaUniversalDO::getTitle, reqVO.getTitle())
                .eqIfPresent(OaUniversalDO::getAuditStatus, reqVO.getAuditStatus())
                .betweenIfPresent(OaUniversalDO::getCreateTime, reqVO.getCreateTime())
                .orderByDesc(OaUniversalDO::getId);
        // 数据权限
        DeptDataPermissionRespDTO deptDataPermission = reqVO.getDeptDataPermission();
        if (deptDataPermission != null) {
            if (deptDataPermission.getAll()) {
                // 全部数据权限
            } else {
                if (CollUtil.isNotEmpty(deptDataPermission.getDeptIds()) && deptDataPermission.getSelf()) {
                    lambdaQueryWrapperX.and(wrapper ->
                            wrapper.in(OaUniversalDO::getDeptId, deptDataPermission.getDeptIds()))
                            .or(wrapper -> wrapper.eq(OaUniversalDO::getCreator, reqVO.getUserId()));
                } else if (CollUtil.isNotEmpty(deptDataPermission.getDeptIds())) {
                    lambdaQueryWrapperX.in(OaUniversalDO::getCreator, deptDataPermission.getDeptIds());
                } else if (deptDataPermission.getSelf()) {
                    lambdaQueryWrapperX.eq(OaUniversalDO::getCreator, reqVO.getUserId());
                } else {
                    return PageResult.empty();
                }
            }
        } else {
            return PageResult.empty();
        }
        return selectPage(reqVO, lambdaQueryWrapperX);
    }

}