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

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

/**
 * 公务外出流程信息 Mapper
 *
 * @author dp
 */
@Mapper
public interface OaOutMapper extends BaseMapperX<OaOutDO> {

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

    }

}