package cn.iocoder.yudao.module.bpm.service.oa.leave;

import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.util.IdUtil;
import cn.hutool.core.util.StrUtil;
import cn.iocoder.yudao.framework.common.enums.InfoSourceEnum;
import cn.iocoder.yudao.framework.common.exception.util.ServiceExceptionUtil;
import cn.iocoder.yudao.framework.common.pojo.PageParam;
import cn.iocoder.yudao.framework.common.pojo.PageResult;
import cn.iocoder.yudao.framework.common.util.collection.CollectionUtils;
import cn.iocoder.yudao.framework.common.util.object.BeanUtils;
import cn.iocoder.yudao.framework.security.core.util.SecurityFrameworkUtils;
import cn.iocoder.yudao.module.attendance.api.leave.AttendanceLeaveApi;
import cn.iocoder.yudao.module.attendance.api.leave.dto.AttendanceLeaveCreateReqDTO;
import cn.iocoder.yudao.module.bpm.api.task.BpmProcessInstanceApi;
import cn.iocoder.yudao.module.bpm.api.task.dto.BpmProcessInstanceCreateReqDTO;
import cn.iocoder.yudao.module.bpm.controller.admin.oa.leave.vo.OaLeavePageReqVO;
import cn.iocoder.yudao.module.bpm.controller.admin.oa.leave.vo.OaLeaveRespVO;
import cn.iocoder.yudao.module.bpm.controller.admin.oa.leave.vo.OaLeaveSaveReqVO;
import cn.iocoder.yudao.module.bpm.controller.admin.task.vo.task.BpmTaskApproveReqVO;
import cn.iocoder.yudao.module.bpm.controller.admin.task.vo.task.BpmTaskRespVO;
import cn.iocoder.yudao.module.bpm.controller.admin.task.vo.task.BpmTaskReturnReqVO;
import cn.iocoder.yudao.module.bpm.dal.dataobject.oa.leave.OaLeaveDO;
import cn.iocoder.yudao.module.bpm.dal.mysql.oa.leave.OaLeaveMapper;
import cn.iocoder.yudao.module.bpm.enums.DictDataConstants;
import cn.iocoder.yudao.module.bpm.enums.ErrorCodeConstants;
import cn.iocoder.yudao.module.bpm.enums.ProcessKeyEnum;
import cn.iocoder.yudao.module.bpm.framework.flowable.core.enums.BpmConstants;
import cn.iocoder.yudao.module.bpm.service.task.BpmTaskService;
import cn.iocoder.yudao.module.bpm.util.OANotifyContentUtil;
import cn.iocoder.yudao.module.employee.api.EmployeeApi;
import cn.iocoder.yudao.module.employee.api.dto.EmployeeRespDTO;
import cn.iocoder.yudao.module.infra.api.file.FileApi;
import cn.iocoder.yudao.module.infra.api.file.dto.FileDTO;
import cn.iocoder.yudao.module.system.api.dept.DeptApi;
import cn.iocoder.yudao.module.system.api.dept.dto.DeptRespDTO;
import cn.iocoder.yudao.module.system.api.notify.NotifyMessageSendApi;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import org.apache.commons.lang3.StringUtils;
import org.flowable.engine.TaskService;
import org.flowable.task.api.Task;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.validation.annotation.Validated;

import javax.annotation.Resource;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.stream.Collectors;

import static cn.iocoder.yudao.framework.common.exception.util.ServiceExceptionUtil.exception;
import static cn.iocoder.yudao.module.bpm.enums.ErrorCodeConstants.OA_LEAVE_NOT_EXISTS;

/**
 * 请假流程信息 Service 实现类
 *
 * @author dp
 */
@Service
@Validated
public class OaLeaveServiceImpl implements OaLeaveService {


    /**
     * 对应的流程定义 KEY
     */
    public static final String PROCESS_KEY = ProcessKeyEnum.OA_LEAVE.getProcessKey();


    @Resource
    private OaLeaveMapper oaLeaveMapper;

    @Resource
    private BpmProcessInstanceApi processInstanceApi;

    @Resource
    private BpmTaskService bpmTaskService;

    @Resource
    private TaskService taskService;

    @Resource
    private FileApi fileApi;

    @Resource
    private EmployeeApi employeeApi;

    @Resource
    private DeptApi deptApi;

    @Resource
    private AttendanceLeaveApi attendanceLeaveApi;

    @Resource
    private NotifyMessageSendApi notifyMessageSendApi;


    @Override
    @Transactional(rollbackFor = Exception.class)
    public Long stagingOaLeave(OaLeaveSaveReqVO stagingReqVO) {
        // 登录人信息
        Long loginUserId = SecurityFrameworkUtils.getLoginUserId();
        // 根据登录人查询出对应的员工信息
        EmployeeRespDTO loginEmployee = employeeApi.getEmployeeByUserId(loginUserId);
        if (loginEmployee == null) {
            throw exception(ErrorCodeConstants.OA_EMPLOYEE_NOT_EXISTS);
        }

        OaLeaveDO oaLeave = BeanUtils.toBean(stagingReqVO, OaLeaveDO.class);
        if (StringUtils.isBlank(oaLeave.getLeaveId())) {
            // 创建单据uuid
            String uuid = IdUtil.fastSimpleUUID();
            oaLeave.setLeaveId(uuid);
        }

        oaLeave.setEmployeeId(loginEmployee.getId());
        oaLeave.setEmployeeName(loginEmployee.getName());
        oaLeave.setEmployeePhone(loginEmployee.getPhone());
        oaLeave.setDeptId(loginEmployee.getDeptId());
        oaLeave.setPostId(loginEmployee.getPostId());
        oaLeave.setPosition(loginEmployee.getPosition());
        oaLeave.setUserId(loginUserId);
        oaLeave.setAuditStatus(DictDataConstants.OA_AUDIT_STATUS_STAGING);
        oaLeave.setInfoSource("0");
        oaLeave.setApplyEmployeeId(loginEmployee.getId());
        oaLeave.setApplyEmployeeName(loginEmployee.getName());
        oaLeave.setCreator(String.valueOf(loginEmployee.getId()));
        // 暂存不保存审批人信息
        oaLeave.setStartUserSelectAssignees(null);
        // 保存或更新表单信息
        if (oaLeave.getId() == null) {
            oaLeaveMapper.insert(oaLeave);
        } else {
            oaLeaveMapper.updateById(oaLeave);
        }
        // 保存业务uuid到附件中
        fileApi.updateFileBiz(stagingReqVO.getFileIdList(), oaLeave.getLeaveId());

        return oaLeave.getId();
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public Long commitOaLeave(OaLeaveSaveReqVO commitReqVO) {
        if (CollectionUtil.isEmpty(commitReqVO.getStartUserSelectAssignees())) {
            throw exception(ErrorCodeConstants.TASK_CREATE_FAIL_NO_START_SELECT_ASSIGNEE);
        }
        // 登录人信息
        Long loginUserId = SecurityFrameworkUtils.getLoginUserId();
        // 根据登录人查询出对应的员工信息
        EmployeeRespDTO loginEmployee = employeeApi.getEmployeeByUserId(loginUserId);
        if (loginEmployee == null) {
            throw exception(ErrorCodeConstants.OA_EMPLOYEE_NOT_EXISTS);
        }


        OaLeaveDO oaLeave = BeanUtils.toBean(commitReqVO, OaLeaveDO.class);
        if (StringUtils.isBlank(oaLeave.getLeaveId())) {
            // 创建单据uuid
            String uuid = IdUtil.fastSimpleUUID();
            oaLeave.setLeaveId(uuid);
        }
        oaLeave.setEmployeeId(loginEmployee.getId());
        oaLeave.setEmployeeName(loginEmployee.getName());
        oaLeave.setEmployeePhone(loginEmployee.getPhone());
        oaLeave.setDeptId(loginEmployee.getDeptId());
        oaLeave.setPostId(loginEmployee.getPostId());
        oaLeave.setPosition(loginEmployee.getPosition());
        oaLeave.setUserId(loginUserId);
        oaLeave.setInfoSource("0");
        oaLeave.setApplyEmployeeId(loginEmployee.getId());
        oaLeave.setApplyEmployeeName(loginEmployee.getName());
        oaLeave.setCreator(String.valueOf(loginEmployee.getId()));
        // 保存或更新表单信息
        if (oaLeave.getId() == null) {
            oaLeaveMapper.insert(oaLeave);
        } else {
            OaLeaveDO oaLeaveDO = validateOaLeaveExists(oaLeave.getId());
            if (StrUtil.isNotBlank(oaLeaveDO.getProcInstId())) {
                throw exception(ErrorCodeConstants.PROCESS_INSTANCE_CREATE_FAIL_HAS_PROCESS);
            }
            oaLeaveMapper.updateById(oaLeave);
        }
        // 发起流程
        Map<String, Object> processInstanceVariables = new HashMap<>();
        processInstanceVariables.put("auditPass", "true");
        // 添加审批人信息
        Map<String, List<Long>> startUserSelectAssignees = new HashMap<>();
        List<Long> selectAssignees = commitReqVO.getStartUserSelectAssignees();
        startUserSelectAssignees.put("approver", selectAssignees);
        String processInstanceId = processInstanceApi
                .createProcessInstance(loginEmployee.getId(),
                        new BpmProcessInstanceCreateReqDTO()
                                .setProcessDefinitionKey(PROCESS_KEY)
                                .setVariables(processInstanceVariables)
                                .setBusinessKey(String.valueOf(oaLeave.getId()))
                                .setStartUserSelectAssignees(startUserSelectAssignees));

        //获取下一个审批人
        Task task = taskService.createTaskQuery().processInstanceId(processInstanceId).singleResult();

        // 审批同意
        BpmTaskApproveReqVO agreeReqVO = new BpmTaskApproveReqVO();
        agreeReqVO.setId(task.getId());
        agreeReqVO.setReason("[首次提交]");
        agreeReqVO.setTaskStatus(Integer.valueOf(DictDataConstants.OA_AUDIT_STATUS_COMMITTED));
        taskService.setVariable(task.getId(), BpmConstants.PROCESS_INSTANCE_VARIABLE_STATUS, DictDataConstants.OA_AUDIT_STATUS_COMMITTED);
        taskService.setVariable(task.getId(), "auditPass", "true");
        bpmTaskService.approveTask(loginEmployee.getId(), agreeReqVO);

        Task nextTask = taskService.createTaskQuery().processInstanceId(processInstanceId).singleResult();
        if (nextTask == null) {
            throw exception(ErrorCodeConstants.TASK_CREATE_FAIL_NO_START_SELECT_ASSIGNEE);
        }
        Long currentAuditEmployeeId = Long.valueOf(nextTask.getAssignee());
        EmployeeRespDTO currentAuditEmployee = employeeApi.getEmployeeById(currentAuditEmployeeId);


        // 将工作流的流程实例ID、单据状态、最后一次审批时间、当前审批人更新到单据信息中
        oaLeaveMapper.updateById(new OaLeaveDO()
                .setId(oaLeave.getId())
                .setProcInstId(processInstanceId)
                .setAuditStatus(DictDataConstants.OA_AUDIT_STATUS_COMMITTED)
                .setFinalAuditDate(LocalDateTime.now())
                .setCurrentAuditEmployeeId(currentAuditEmployeeId)
                .setCurrentAuditEmployeeName(currentAuditEmployee.getName())
                .setStartUserSelectAssignees(selectAssignees.stream().map(String::valueOf).collect(Collectors.joining(","))));
        // 保存业务uuid到附件中
        fileApi.updateFileBiz(commitReqVO.getFileIdList(), oaLeave.getLeaveId());

        // 给审批人发送审批站内信
        Long assigneeId = -1L;
        String assigneeName = "";
        String applyName = loginEmployee.getName();
        String processName = ProcessKeyEnum.getByProcessKey(PROCESS_KEY);

        String assignee = nextTask.getAssignee();
        if (StrUtil.isNotBlank(assignee)) {
            EmployeeRespDTO employeeAssignee = employeeApi.getEmployeeById(Long.valueOf(assignee));
            if (employeeAssignee != null) {
                assigneeId = employeeAssignee.getId();
                assigneeName = employeeAssignee.getName();
            }
        }
        StringBuilder content = OANotifyContentUtil.buildContentSendToAssignee(assigneeName, applyName, processName);
        notifyMessageSendApi.sendSingleMessageToMemberForOA(assigneeId, content.toString());

        return oaLeave.getId();
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public Long agreeOaLeave(BpmTaskApproveReqVO agreeReqVO) {
        // 登录人信息
        Long loginUserId = SecurityFrameworkUtils.getLoginUserId();
        // 根据登录人查询出对应的员工信息
        EmployeeRespDTO loginEmployee = employeeApi.getEmployeeByUserId(loginUserId);
        if (loginEmployee == null) {
            throw exception(ErrorCodeConstants.OA_EMPLOYEE_NOT_EXISTS);
        }

        Task currentTask = bpmTaskService.getTask(agreeReqVO.getId());
        if (currentTask == null) {
            throw exception(ErrorCodeConstants.TASK_NOT_EXISTS);
        }
        // 先更新为审批中
        taskService.setVariable(currentTask.getId(), BpmConstants.PROCESS_INSTANCE_VARIABLE_STATUS, DictDataConstants.OA_AUDIT_STATUS_AUDITING);
        LambdaQueryWrapper<OaLeaveDO> lambdaQueryWrapper = new LambdaQueryWrapper<>();
        lambdaQueryWrapper.eq(OaLeaveDO::getProcInstId, currentTask.getProcessInstanceId());
        OaLeaveDO oaLeave = oaLeaveMapper.selectOne(lambdaQueryWrapper);
        // 如果是最后一个人审批同意，设置流程审批状态为已审核
        String[] auditPersons = oaLeave.getStartUserSelectAssignees().split(",");
        String lastAuditPerson = Arrays.stream(auditPersons)
                .reduce((first, second) -> second)
                .orElse(null);
        if (currentTask.getAssignee().equals(lastAuditPerson)) {
            // 更新为已审核(暂时未生效，未找到原因，先不处理)
            taskService.setVariable(agreeReqVO.getId(),BpmConstants.PROCESS_INSTANCE_VARIABLE_STATUS, DictDataConstants.OA_AUDIT_STATUS_AUDITED);
        }
        // 审批同意
        String reason = "[同意]";
        if (StrUtil.isNotBlank(agreeReqVO.getReason())) {
            reason = reason + agreeReqVO.getReason();
        }
        agreeReqVO.setReason(reason);
        agreeReqVO.setTaskStatus(Integer.valueOf(DictDataConstants.OA_AUDIT_STATUS_AUDITING));
        taskService.setVariable(agreeReqVO.getId(), "auditPass", "true");
        bpmTaskService.approveTask(loginEmployee.getId(), agreeReqVO);

        Task nextTask = taskService.createTaskQuery().processInstanceId(currentTask.getProcessInstanceId()).singleResult();
        OaLeaveDO oaLeaveDO = new OaLeaveDO();
        if (nextTask != null) {
            Long currentAuditEmployeeId = Long.valueOf(nextTask.getAssignee());
            EmployeeRespDTO currentAuditEmployee = employeeApi.getEmployeeById(currentAuditEmployeeId);

            // 如果审批人重复，实际未结束，再次更新为审核中
            taskService.setVariable(nextTask.getId(), BpmConstants.PROCESS_INSTANCE_VARIABLE_STATUS, DictDataConstants.OA_AUDIT_STATUS_AUDITING);
            oaLeaveDO.setAuditStatus(DictDataConstants.OA_AUDIT_STATUS_AUDITING)
                    .setCurrentAuditEmployeeId(currentAuditEmployeeId)
                    .setCurrentAuditEmployeeName(currentAuditEmployee.getName())
                    .setFinalAuditDate(LocalDateTime.now())
                    .setId(oaLeave.getId());

        } else {
            oaLeaveDO.setAuditStatus(DictDataConstants.OA_AUDIT_STATUS_AUDITED)
                    .setCurrentAuditEmployeeId(null)
                    .setCurrentAuditEmployeeName(null)
                    .setFinalAuditDate(LocalDateTime.now())
                    .setId(oaLeave.getId());
        }
        oaLeaveMapper.updateById(oaLeaveDO);
        // 复制业务单据信息到业务模块单据表
        if(Objects.isNull(nextTask)) {
            // 查询申请单
            OaLeaveDO leave = oaLeaveMapper.selectById(oaLeaveDO.getId());

            // 转换为DTO
            AttendanceLeaveCreateReqDTO leaveCreateReqDTO = BeanUtils.toBean(leave, AttendanceLeaveCreateReqDTO.class);
            leaveCreateReqDTO.setStatus(0);
            leaveCreateReqDTO.setCreatorEmployeeId(leave.getApplyEmployeeId());
            leaveCreateReqDTO.setCreatorEmployeeName(leave.getApplyEmployeeName());
            leaveCreateReqDTO.setInfoSource(InfoSourceEnum.FLOW.getSource());

            // 保存单据信息
            attendanceLeaveApi.createLeaveInfoAfterAudit(leaveCreateReqDTO);
        }

        // 发送站内信
        Long assignId = -1L;
        String assigneeName = "";
        Long applyId = -1L;
        String applyName = "";
        String processName = ProcessKeyEnum.getByProcessKey(PROCESS_KEY);

        EmployeeRespDTO applyEmployee = employeeApi.getEmployeeById(oaLeave.getApplyEmployeeId());
        if (applyEmployee != null) {
            applyId = applyEmployee.getId();
            applyName = applyEmployee.getName();
        }
        if (nextTask != null) {
            EmployeeRespDTO employeeAssignee = employeeApi.getEmployeeById(Long.valueOf(nextTask.getAssignee()));
            if (employeeAssignee != null) {
                assignId = employeeAssignee.getId();
                assigneeName = employeeAssignee.getName();
            }
            // 给审批人发送审批站内信
            StringBuilder content = OANotifyContentUtil.buildContentSendToAssignee(assigneeName, applyName, processName);
            notifyMessageSendApi.sendSingleMessageToMemberForOA(assignId, content.toString());
        } else {
            // 给申请人发送审批完成站内信
            StringBuilder content = OANotifyContentUtil.buildContentSendToApplyForComplete(applyName, processName);
            notifyMessageSendApi.sendSingleMessageToMemberForOA(applyId, content.toString());
        }


        // 返回
        return 1L;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public Long disagreeOaLeave(BpmTaskReturnReqVO disagreeReqVO) {
        // 登录人信息
        Long loginUserId = SecurityFrameworkUtils.getLoginUserId();
        // 根据登录人查询出对应的员工信息
        EmployeeRespDTO loginEmployee = employeeApi.getEmployeeByUserId(loginUserId);
        if (loginEmployee == null) {
            throw exception(ErrorCodeConstants.OA_EMPLOYEE_NOT_EXISTS);
        }

        Task currentTask = bpmTaskService.getTask(disagreeReqVO.getId());

        disagreeReqVO.setTargetTaskDefinitionKey("modifyApply");
        disagreeReqVO.setReason("[驳回]" + disagreeReqVO.getReason());
        disagreeReqVO.setTaskStatus(Integer.valueOf(DictDataConstants.OA_AUDIT_STATUS_RETURNED));
        taskService.setVariable(disagreeReqVO.getId(), "auditPass", "false");
        taskService.setVariable(disagreeReqVO.getId(),BpmConstants.PROCESS_INSTANCE_VARIABLE_STATUS, DictDataConstants.OA_AUDIT_STATUS_RETURNED);
        bpmTaskService.returnTask(loginEmployee.getId(), disagreeReqVO);

        Task nextTask = taskService.createTaskQuery().processInstanceId(currentTask.getProcessInstanceId()).singleResult();
        Long currentAuditEmployeeId = Long.valueOf(nextTask.getAssignee());
        EmployeeRespDTO currentAuditEmployee = employeeApi.getEmployeeById(currentAuditEmployeeId);

        // 更新单据状态，当前处理人，最后处理时间
        LambdaUpdateWrapper<OaLeaveDO> updateWrapper = new LambdaUpdateWrapper<>();
        updateWrapper.set(OaLeaveDO::getCurrentAuditEmployeeId, currentAuditEmployeeId)
                .set(OaLeaveDO::getCurrentAuditEmployeeName, currentAuditEmployee.getName())
                .set(OaLeaveDO::getFinalAuditDate, LocalDateTime.now())
                .set(OaLeaveDO::getAuditStatus, DictDataConstants.OA_AUDIT_STATUS_RETURNED)
                .eq(OaLeaveDO::getProcInstId, currentTask.getProcessInstanceId());
        oaLeaveMapper.update(updateWrapper);

        // 给申请人发送驳回站内信
        String assigneeName = loginEmployee.getName();
        Long applyId = -1L;
        String applyName = "";
        String processName = ProcessKeyEnum.getByProcessKey(PROCESS_KEY);
        OaLeaveDO oaLeaveDO = oaLeaveMapper.selectOne(OaLeaveDO::getProcInstId, currentTask.getProcessInstanceId());
        if (oaLeaveDO != null) {
            EmployeeRespDTO applyEmployee = employeeApi.getEmployeeById(oaLeaveDO.getApplyEmployeeId());
            if (applyEmployee != null) {
                applyId = applyEmployee.getId();
                applyName = applyEmployee.getName();
            }
        }
        StringBuilder content = OANotifyContentUtil.buildContentSendToApplyForDisagree(assigneeName, applyName, processName);
        notifyMessageSendApi.sendSingleMessageToMemberForOA(applyId, content.toString());


        return 1L;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public Long revocationOaLeave(BpmTaskApproveReqVO revocationReqVO) {
        // 登录人信息
        Long loginUserId = SecurityFrameworkUtils.getLoginUserId();
        // 根据登录人查询出对应的员工信息
        EmployeeRespDTO loginEmployee = employeeApi.getEmployeeByUserId(loginUserId);
        if (loginEmployee == null) {
            throw exception(ErrorCodeConstants.OA_EMPLOYEE_NOT_EXISTS);
        }

        Task currentTask = bpmTaskService.getTask(revocationReqVO.getId());
        if (currentTask == null) {
            throw ServiceExceptionUtil.exception(ErrorCodeConstants.TASK_NOT_EXISTS);
        }
        LambdaQueryWrapper<OaLeaveDO> lambdaQueryWrapper = new LambdaQueryWrapper<OaLeaveDO>()
                .eq(OaLeaveDO::getProcInstId, currentTask.getProcessInstanceId());
        OaLeaveDO oaLeaveDO = oaLeaveMapper.selectOne(lambdaQueryWrapper);
        if (!DictDataConstants.OA_AUDIT_STATUS_COMMITTED.equals(oaLeaveDO.getAuditStatus())
                || !Objects.equals(String.valueOf(loginUserId), oaLeaveDO.getCreator())) {
            throw ServiceExceptionUtil.exception(ErrorCodeConstants.TASK_REVOCATION_NOT_ALLOWED);
        }

        BpmTaskReturnReqVO returnReqVO = BeanUtils.toBean(revocationReqVO, BpmTaskReturnReqVO.class);
        returnReqVO.setTargetTaskDefinitionKey("modifyApply");
        String reason = "[撤回]";
        if (StrUtil.isNotBlank(returnReqVO.getReason())) {
            reason = reason + returnReqVO.getReason();
        }
        returnReqVO.setReason(reason);
        returnReqVO.setTaskStatus(Integer.valueOf(DictDataConstants.OA_AUDIT_STATUS_RECALLED));
        taskService.setVariable(currentTask.getId(),BpmConstants.PROCESS_INSTANCE_VARIABLE_STATUS, DictDataConstants.OA_AUDIT_STATUS_RECALLED);
        bpmTaskService.revocationTask(loginEmployee.getId(), returnReqVO);

        Task nextTask = taskService.createTaskQuery().processInstanceId(currentTask.getProcessInstanceId()).singleResult();
        Long currentAuditEmployeeId = Long.valueOf(nextTask.getAssignee());
        EmployeeRespDTO currentAuditEmployee = employeeApi.getEmployeeById(currentAuditEmployeeId);

        // 更新单据状态，当前处理人，最后处理时间
        LambdaUpdateWrapper<OaLeaveDO> updateWrapper = new LambdaUpdateWrapper<>();
        updateWrapper.set(OaLeaveDO::getCurrentAuditEmployeeId, currentAuditEmployeeId)
                .set(OaLeaveDO::getCurrentAuditEmployeeName, currentAuditEmployee.getName())
                .set(OaLeaveDO::getFinalAuditDate, LocalDateTime.now())
                .set(OaLeaveDO::getAuditStatus, DictDataConstants.OA_AUDIT_STATUS_RECALLED)
                .eq(OaLeaveDO::getProcInstId, currentTask.getProcessInstanceId());
        oaLeaveMapper.update(updateWrapper);

        return 1L;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public Long reCommitOaLeave(OaLeaveSaveReqVO reCommitReqVO) {
        if (reCommitReqVO.getId() == null) {
            throw exception(ErrorCodeConstants.SERVICE_ID_NOT_EXISTS);
        }
        // 登录人信息
        Long loginUserId = SecurityFrameworkUtils.getLoginUserId();
        // 根据登录人查询出对应的员工信息
        EmployeeRespDTO loginEmployee = employeeApi.getEmployeeByUserId(loginUserId);
        if (loginEmployee == null) {
            throw exception(ErrorCodeConstants.OA_EMPLOYEE_NOT_EXISTS);
        }

        OaLeaveDO oaLeaveNew = BeanUtils.toBean(reCommitReqVO, OaLeaveDO.class);
        OaLeaveDO oaLeaveOld = validateOaLeaveExists(oaLeaveNew.getId());
        oaLeaveNew.setLeaveId(oaLeaveOld.getLeaveId())
                .setProcInstId(oaLeaveOld.getProcInstId());

        oaLeaveNew.setEmployeeId(loginEmployee.getId());
        oaLeaveNew.setEmployeeName(loginEmployee.getName());
        oaLeaveNew.setEmployeePhone(loginEmployee.getPhone());
        oaLeaveNew.setDeptId(loginEmployee.getDeptId());
        oaLeaveNew.setPostId(loginEmployee.getPostId());
        oaLeaveNew.setPosition(loginEmployee.getPosition());
        oaLeaveNew.setUserId(loginUserId);
        oaLeaveNew.setApplyEmployeeId(loginEmployee.getId());
        oaLeaveNew.setApplyEmployeeName(loginEmployee.getName());


        Task currentTask = taskService.createTaskQuery().processInstanceId(oaLeaveNew.getProcInstId()).singleResult();
        BpmTaskApproveReqVO approveReqVO = new BpmTaskApproveReqVO();
        approveReqVO.setId(currentTask.getId())
                .setReason("[再次提交]");
        approveReqVO.setTaskStatus(Integer.valueOf(DictDataConstants.OA_AUDIT_STATUS_COMMITTED));
        if (CollectionUtil.isNotEmpty(reCommitReqVO.getStartUserSelectAssignees())) {
            // 添加审批人信息到流程参数中
            Map<String, List<Long>> startUserSelectAssignees = new HashMap<>();
            List<Long> selectAssignees = reCommitReqVO.getStartUserSelectAssignees();
            startUserSelectAssignees.put("approver", selectAssignees);
            taskService.setVariable(currentTask.getId(), BpmConstants.PROCESS_INSTANCE_VARIABLE_START_USER_SELECT_ASSIGNEES, startUserSelectAssignees);
            // 保存审批人信息
            oaLeaveNew.setStartUserSelectAssignees(selectAssignees.stream().map(String::valueOf).collect(Collectors.joining(",")));
        }
        taskService.setVariable(currentTask.getId(), "auditPass", "true");
        taskService.setVariable(currentTask.getId(),BpmConstants.PROCESS_INSTANCE_VARIABLE_STATUS, DictDataConstants.OA_AUDIT_STATUS_COMMITTED);
        // 再次提交，和审批通过逻辑相同
        bpmTaskService.approveTask(loginEmployee.getId(), approveReqVO);

        Task nextTask = taskService.createTaskQuery().processInstanceId(currentTask.getProcessInstanceId()).singleResult();
        Long currentAuditEmployeeId = Long.valueOf(nextTask.getAssignee());
        EmployeeRespDTO currentAuditEmployee = employeeApi.getEmployeeById(currentAuditEmployeeId);
        oaLeaveNew.setAuditStatus(DictDataConstants.OA_AUDIT_STATUS_COMMITTED)
                .setCurrentAuditEmployeeId(currentAuditEmployeeId)
                .setCurrentAuditEmployeeName(currentAuditEmployee.getName())
                .setFinalAuditDate(LocalDateTime.now());
        oaLeaveMapper.updateById(oaLeaveNew);

        // 保存业务uuid到附件中
        fileApi.updateFileBiz(reCommitReqVO.getFileIdList(), oaLeaveNew.getLeaveId());

        // 给审批人发送审批站内信
        Long assigneeId = -1L;
        String assigneeName = "";
        String applyName = loginEmployee.getName();
        String processName = ProcessKeyEnum.getByProcessKey(PROCESS_KEY);

        String assignee = nextTask.getAssignee();
        if (StrUtil.isNotBlank(assignee)) {
            EmployeeRespDTO assigneeEmployee = employeeApi.getEmployeeById(Long.valueOf(assignee));
            if (assigneeEmployee != null) {
                assigneeId = assigneeEmployee.getId();
                assigneeName = assigneeEmployee.getName();
            }
        }
        StringBuilder content = OANotifyContentUtil.buildContentSendToAssignee(assigneeName, applyName, processName);
        notifyMessageSendApi.sendSingleMessageToMemberForOA(assigneeId, content.toString());


        return 1L;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public Long closeOaLeave(Long id) {
        if (id == null) {
            throw exception(ErrorCodeConstants.SERVICE_ID_NOT_EXISTS);
        }
        // 登录人信息
        Long loginUserId = SecurityFrameworkUtils.getLoginUserId();
        // 根据登录人查询出对应的员工信息
        EmployeeRespDTO loginEmployee = employeeApi.getEmployeeByUserId(loginUserId);
        if (loginEmployee == null) {
            throw exception(ErrorCodeConstants.OA_EMPLOYEE_NOT_EXISTS);
        }

        OaLeaveDO oaLeaveDO = oaLeaveMapper.selectById(id);
        if (!DictDataConstants.OA_AUDIT_STATUS_RETURNED.equals(oaLeaveDO.getAuditStatus())
                && !DictDataConstants.OA_AUDIT_STATUS_RECALLED.equals(oaLeaveDO.getAuditStatus())) {
            throw exception(ErrorCodeConstants.TASK_CLOSE_NOT_ALLOWED);
        }

        Task currentTask = taskService.createTaskQuery().processInstanceId(oaLeaveDO.getProcInstId()).singleResult();
        BpmTaskApproveReqVO approveReqVO = new BpmTaskApproveReqVO();
        approveReqVO.setId(currentTask.getId())
                .setReason("[关闭]");
        approveReqVO.setTaskStatus(Integer.valueOf(DictDataConstants.OA_AUDIT_STATUS_CLOSED));
        taskService.setVariable(currentTask.getId(), "auditPass", "false");
        taskService.setVariable(currentTask.getId(),BpmConstants.PROCESS_INSTANCE_VARIABLE_STATUS, DictDataConstants.OA_AUDIT_STATUS_CLOSED);
        // 关闭，使用审批通过的方法实现
        bpmTaskService.approveTask(loginEmployee.getId(), approveReqVO);

        LambdaUpdateWrapper<OaLeaveDO> lambdaUpdateWrapper = new LambdaUpdateWrapper<>();
        lambdaUpdateWrapper.set(OaLeaveDO::getAuditStatus, DictDataConstants.OA_AUDIT_STATUS_CLOSED)
                .set(OaLeaveDO::getCurrentAuditEmployeeId, null)
                .set(OaLeaveDO::getCurrentAuditEmployeeName, null)
                .set(OaLeaveDO::getFinalAuditDate, LocalDateTime.now())
                .eq(OaLeaveDO::getId, id);
        oaLeaveMapper.update(lambdaUpdateWrapper);
        return 1L;
    }

    @Override
    public void deleteOaLeave(Long id) {
        // 校验存在
        validateOaLeaveDelete(id);
        // 删除
        oaLeaveMapper.deleteById(id);
    }

    @Override
    public OaLeaveRespVO getOaLeave(Long id) {
        // 登录人信息
        Long loginUserId = SecurityFrameworkUtils.getLoginUserId();
        // 根据登录人查询出对应的员工信息
        EmployeeRespDTO loginEmployee = employeeApi.getEmployeeByUserId(loginUserId);
        if (loginEmployee == null) {
            throw exception(ErrorCodeConstants.OA_EMPLOYEE_NOT_EXISTS);
        }

        OaLeaveDO oaLeaveDO = validateOaLeaveExists(id);
        OaLeaveRespVO oaLeaveRespVO = BeanUtils.toBean(oaLeaveDO, OaLeaveRespVO.class);
        if (oaLeaveDO.getDeptId() != null) {
            DeptRespDTO dept = deptApi.getDept(oaLeaveDO.getDeptId());
            if (dept != null) {
                oaLeaveRespVO.setDeptName(dept.getName());
            }
        }

        String procInstId = oaLeaveDO.getProcInstId();
        if (StrUtil.isNotBlank(procInstId)) {
            Task task = taskService.createTaskQuery()
                    .processInstanceId(procInstId)
                    .taskAssignee(String.valueOf(loginEmployee.getId()))
                    .singleResult();
            if (DictDataConstants.OA_AUDIT_STATUS_COMMITTED.equals(oaLeaveDO.getAuditStatus())) {
                // 如果是已提交，不限制任务处理人是当前登录人，用于直接撤回
                task = taskService.createTaskQuery()
                        .processInstanceId(procInstId)
                        .singleResult();
            }
            if (task != null) {
                oaLeaveRespVO.setTaskId(task.getId());
            }
        }

        // 附件列表
        List<FileDTO> fileList = fileApi.getFileDTOListByBiz(oaLeaveDO.getLeaveId());
        oaLeaveRespVO.setFileList(fileList);
        List<Long> fileIdList = fileList.stream().map(FileDTO::getId).collect(Collectors.toList());
        oaLeaveRespVO.setFileIdList(fileIdList);

        // 审批记录
        if (StrUtil.isNotBlank(oaLeaveDO.getProcInstId())) {
            List<BpmTaskRespVO> auditRecordList = bpmTaskService.getAuditRecordListByProcessInstanceId(oaLeaveDO.getProcInstId());
            oaLeaveRespVO.setAuditRecordList(auditRecordList);
        }

        // 审批人
        String startUserSelectAssignees = oaLeaveDO.getStartUserSelectAssignees();
        if (StrUtil.isNotEmpty(startUserSelectAssignees)) {
            List<Long> employeeIdList = Arrays.stream(startUserSelectAssignees.split(","))
                    .map(Long::valueOf).collect(Collectors.toList());
            List<EmployeeRespDTO> employeeRespDTOList = employeeApi.getEmployeeListByIds(employeeIdList);
            Map<Long, EmployeeRespDTO> longEmployeeRespDTOMap = CollectionUtils.convertMap(employeeRespDTOList, EmployeeRespDTO::getId);
            List<EmployeeRespDTO> auditUserList = new ArrayList<>();
            for (Long employeeId : employeeIdList) {
                EmployeeRespDTO employeeRespDTO = longEmployeeRespDTOMap.get(employeeId);
                if (employeeRespDTO != null) {
                    employeeRespDTO.setNickname(employeeRespDTO.getName());
                    auditUserList.add(employeeRespDTO);
                }
            }
            oaLeaveRespVO.setAuditUserList(auditUserList);
        }

        return oaLeaveRespVO;
    }

    @Override
    public OaLeaveRespVO getOaLeaveByProcInstId(String procInstId) {
        OaLeaveDO oaLeaveDO = oaLeaveMapper.selectOne(OaLeaveDO::getProcInstId, procInstId);
        OaLeaveRespVO oaLeaveRespVO = BeanUtils.toBean(oaLeaveDO, OaLeaveRespVO.class);
        if (oaLeaveDO.getDeptId() != null) {
            DeptRespDTO dept = deptApi.getDept(oaLeaveDO.getDeptId());
            if (dept != null) {
                oaLeaveRespVO.setDeptName(dept.getName());
            }
        }

        // 附件列表
        List<FileDTO> fileList = fileApi.getFileDTOListByBiz(oaLeaveDO.getLeaveId());
        oaLeaveRespVO.setFileList(fileList);
        List<Long> fileIdList = fileList.stream().map(FileDTO::getId).collect(Collectors.toList());
        oaLeaveRespVO.setFileIdList(fileIdList);

        // 审批记录
        if (StrUtil.isNotBlank(oaLeaveDO.getProcInstId())) {
            List<BpmTaskRespVO> auditRecordList = bpmTaskService.getAuditRecordListByProcessInstanceId(oaLeaveDO.getProcInstId());
            oaLeaveRespVO.setAuditRecordList(auditRecordList);
        }

        // 审批人
        String startUserSelectAssignees = oaLeaveDO.getStartUserSelectAssignees();
        if (StrUtil.isNotEmpty(startUserSelectAssignees)) {
            List<Long> employeeIdList = Arrays.stream(startUserSelectAssignees.split(","))
                    .map(Long::valueOf).collect(Collectors.toList());
            List<EmployeeRespDTO> employeeRespDTOList = employeeApi.getEmployeeListByIds(employeeIdList);
            Map<Long, EmployeeRespDTO> longEmployeeRespDTOMap = CollectionUtils.convertMap(employeeRespDTOList, EmployeeRespDTO::getId);
            List<EmployeeRespDTO> auditUserList = new ArrayList<>();
            for (Long employeeId : employeeIdList) {
                EmployeeRespDTO employeeRespDTO = longEmployeeRespDTOMap.get(employeeId);
                if (employeeRespDTO != null) {
                    employeeRespDTO.setNickname(employeeRespDTO.getName());
                    auditUserList.add(employeeRespDTO);
                }
            }
            oaLeaveRespVO.setAuditUserList(auditUserList);
        }

        return oaLeaveRespVO;
    }

    @Override
    public PageResult<OaLeaveRespVO> getOaLeavePage(OaLeavePageReqVO pageReqVO) {
        PageResult<OaLeaveDO> oaLeaveDOPageResult = oaLeaveMapper.selectPage(pageReqVO);
        PageResult<OaLeaveRespVO> oaLeaveRespVOPageResult = BeanUtils.toBean(oaLeaveDOPageResult, OaLeaveRespVO.class);

        List<OaLeaveRespVO> oaLeaveRespVOList = oaLeaveRespVOPageResult.getList();
        if (CollectionUtil.isNotEmpty(oaLeaveRespVOList)) {
            List<Long> employeeIdList = oaLeaveRespVOList.stream().map(OaLeaveRespVO::getCurrentAuditEmployeeId).collect(Collectors.toList());
            List<EmployeeRespDTO> employeeRespDTOList = employeeApi.getEmployeeListByIds(employeeIdList);
            Map<Long, EmployeeRespDTO> longEmployeeRespDTOMap = CollectionUtils.convertMap(employeeRespDTOList, EmployeeRespDTO::getId);
            for (OaLeaveRespVO respVO : oaLeaveRespVOList) {
                EmployeeRespDTO employeeRespDTO = longEmployeeRespDTOMap.get(respVO.getCurrentAuditEmployeeId());
                if (employeeRespDTO != null) {
                    respVO.setCurrentAuditEmployeeName(employeeRespDTO.getName());
                }
            }

            List<Long> deptIdList = oaLeaveRespVOList.stream().map(OaLeaveRespVO::getDeptId).collect(Collectors.toList());
            List<DeptRespDTO> deptList = deptApi.getDeptList(deptIdList);
            for (OaLeaveRespVO respVO : oaLeaveRespVOList) {
                for (DeptRespDTO dept : deptList) {
                    if (dept.getId() != null && dept.getId().equals(respVO.getDeptId())) {
                        respVO.setDeptName(dept.getName());
                        break;
                    }
                }
            }
        }

        return oaLeaveRespVOPageResult;
    }

    @Override
    public PageResult<OaLeaveRespVO> exportOaLeaveExcel(OaLeavePageReqVO pageReqVO) {
        pageReqVO.setPageSize(PageParam.PAGE_SIZE_NONE);
        return getOaLeavePage(pageReqVO);
    }

    private void validateOaLeaveDelete(Long id) {
        OaLeaveDO oaLeaveDO = validateOaLeaveExists(id);
        if (!DictDataConstants.OA_AUDIT_STATUS_STAGING.equals(oaLeaveDO.getAuditStatus())) {
            throw exception(ErrorCodeConstants.DELETE_FAIL_NOT_STAGING);
        }
    }

    private OaLeaveDO validateOaLeaveExists(Long id) {
        OaLeaveDO oaLeaveDO = oaLeaveMapper.selectById(id);
        if (oaLeaveDO == null) {
            throw exception(OA_LEAVE_NOT_EXISTS);
        }
        return oaLeaveDO;
    }

}