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

import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.util.IdUtil;
import cn.hutool.core.util.StrUtil;
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.bpm.api.task.BpmProcessInstanceApi;
import cn.iocoder.yudao.module.bpm.api.task.dto.BpmProcessInstanceCreateReqDTO;
import cn.iocoder.yudao.module.bpm.controller.admin.oa.universal.vo.OaUniversalPageReqVO;
import cn.iocoder.yudao.module.bpm.controller.admin.oa.universal.vo.OaUniversalRespVO;
import cn.iocoder.yudao.module.bpm.controller.admin.oa.universal.vo.OaUniversalSaveReqVO;
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.universal.OaUniversalDO;
import cn.iocoder.yudao.module.bpm.dal.mysql.oa.universal.OaUniversalMapper;
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.*;
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_UNIVERSAL_NOT_EXISTS;

/**
 * 通用事项审批流程信息 Service 实现类
 *
 * @author dp
 */
@Service
@Validated
public class OaUniversalServiceImpl implements OaUniversalService {

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


    @Resource
    private OaUniversalMapper oaUniversalMapper;

    @Resource
    private BpmProcessInstanceApi processInstanceApi;

    @Resource
    private BpmTaskService bpmTaskService;

    @Resource
    private TaskService taskService;

    @Resource
    private FileApi fileApi;

    @Resource
    private DeptApi deptApi;

    @Resource
    private EmployeeApi employeeApi;

    @Resource
    private NotifyMessageSendApi notifyMessageSendApi;

    @Override
    @Transactional(rollbackFor = Exception.class)
    public Long stagingOaUniversal(OaUniversalSaveReqVO stagingReqVO) {
        // 登录人信息
        Long loginUserId = SecurityFrameworkUtils.getLoginUserId();
        // 根据登录人查询出对应的员工信息
        EmployeeRespDTO loginEmployee = employeeApi.getEmployeeByUserId(loginUserId);

        OaUniversalDO oaUniversal = BeanUtils.toBean(stagingReqVO, OaUniversalDO.class);
        if (StringUtils.isBlank(oaUniversal.getUniversalId())) {
            // 创建单据uuid
            String uuid = IdUtil.fastSimpleUUID();
            oaUniversal.setUniversalId(uuid);
        }
        oaUniversal.setEmployeeId(loginEmployee.getId());
        oaUniversal.setEmployeeName(loginEmployee.getName());
        oaUniversal.setEmployeePhone(loginEmployee.getPhone());
        oaUniversal.setDeptId(loginEmployee.getDeptId());
        oaUniversal.setPostId(loginEmployee.getPostId());
        oaUniversal.setPosition(loginEmployee.getPosition());
        oaUniversal.setCreator(String.valueOf(loginEmployee.getId()));
        oaUniversal.setUserId(loginUserId);
        oaUniversal.setAuditStatus(DictDataConstants.OA_AUDIT_STATUS_STAGING);
        oaUniversal.setInfoSource("0");
        // 暂存不保存审批人信息
        oaUniversal.setStartUserSelectAssignees(null);
        // 保存或更新表单信息
        if (oaUniversal.getId() == null) {
            oaUniversalMapper.insert(oaUniversal);
        } else {
            validateOaUniversalExists(oaUniversal.getId());
            oaUniversalMapper.updateById(oaUniversal);
        }
        // 保存业务uuid到附件中
        fileApi.updateFileBiz(stagingReqVO.getFileIdList(), oaUniversal.getUniversalId());

        return oaUniversal.getId();
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public Long commitOaUniversal(OaUniversalSaveReqVO 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);

        OaUniversalDO oaUniversal = BeanUtils.toBean(commitReqVO, OaUniversalDO.class);
        if (StringUtils.isBlank(oaUniversal.getUniversalId())) {
            // 创建单据uuid
            String uuid = IdUtil.fastSimpleUUID();
            oaUniversal.setUniversalId(uuid);
        }
        oaUniversal.setEmployeeId(loginEmployee.getId());
        oaUniversal.setEmployeeName(loginEmployee.getName());
        oaUniversal.setEmployeePhone(loginEmployee.getPhone());
        oaUniversal.setDeptId(loginEmployee.getDeptId());
        oaUniversal.setPostId(loginEmployee.getPostId());
        oaUniversal.setPosition(loginEmployee.getPosition());
        oaUniversal.setCreator(String.valueOf(loginEmployee.getId()));
        oaUniversal.setUserId(loginUserId);
        oaUniversal.setInfoSource("0");
        // 保存或更新表单信息
        if (oaUniversal.getId() == null) {
            oaUniversalMapper.insert(oaUniversal);
        } else {
            OaUniversalDO oaUniversalDO = validateOaUniversalExists(oaUniversal.getId());
            if (StrUtil.isNotBlank(oaUniversalDO.getProcInstId())) {
                throw exception(ErrorCodeConstants.PROCESS_INSTANCE_CREATE_FAIL_HAS_PROCESS);
            }
            oaUniversalMapper.updateById(oaUniversal);
        }
        // 发起流程
        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(oaUniversal.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);
        }

        // 将工作流的流程实例ID、单据状态、最后一次审批时间、当前审批人更新到单据信息中
        oaUniversalMapper.updateById(new OaUniversalDO()
                .setId(oaUniversal.getId())
                .setProcInstId(processInstanceId)
                .setAuditStatus(DictDataConstants.OA_AUDIT_STATUS_COMMITTED)
                .setFinalAuditDate(LocalDateTime.now())
                .setCurrentAuditEmployeeId(Long.valueOf(nextTask.getAssignee()))
                .setStartUserSelectAssignees(selectAssignees.stream().map(String::valueOf).collect(Collectors.joining(","))));
        // 保存业务uuid到附件中
        fileApi.updateFileBiz(commitReqVO.getFileIdList(), oaUniversal.getUniversalId());
        // 给审批人发送审批站内信
        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 oaUniversal.getId();
    }

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

        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<OaUniversalDO> lambdaQueryWrapper = new LambdaQueryWrapper<>();
        lambdaQueryWrapper.eq(OaUniversalDO::getProcInstId, currentTask.getProcessInstanceId());
        OaUniversalDO oaUniversal = oaUniversalMapper.selectOne(lambdaQueryWrapper);
        // 如果是最后一个人审批同意，设置流程审批状态为已审核
        String[] auditPersons = oaUniversal.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();
        OaUniversalDO oaUniversalDO = new OaUniversalDO();
        if (nextTask != null) {
            // 如果审批人重复，实际未结束，再次更新为审核中
            taskService.setVariable(nextTask.getId(), BpmConstants.PROCESS_INSTANCE_VARIABLE_STATUS, DictDataConstants.OA_AUDIT_STATUS_AUDITING);
            oaUniversalDO.setAuditStatus(DictDataConstants.OA_AUDIT_STATUS_AUDITING)
                    .setCurrentAuditEmployeeId(Long.valueOf(nextTask.getAssignee()))
                    .setFinalAuditDate(LocalDateTime.now())
                    .setId(oaUniversal.getId());

        } else {
            oaUniversalDO.setAuditStatus(DictDataConstants.OA_AUDIT_STATUS_AUDITED)
                    .setCurrentAuditEmployeeId(null)
                    .setFinalAuditDate(LocalDateTime.now())
                    .setId(oaUniversal.getId());

            // 复制业务单据信息到业务模块单据表
            // 通用审批没有业务模块

        }
        oaUniversalMapper.updateById(oaUniversalDO);

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

        EmployeeRespDTO applyEmployee = employeeApi.getEmployeeById(oaUniversal.getEmployeeId());
        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 disagreeOaUniversal(BpmTaskReturnReqVO disagreeReqVO) {
        // 登录人信息
        Long loginUserId = SecurityFrameworkUtils.getLoginUserId();
        // 根据登录人查询出对应的员工信息
        EmployeeRespDTO loginEmployee = employeeApi.getEmployeeByUserId(loginUserId);

        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();

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

        // 给申请人发送驳回站内信
        String assigneeName = loginEmployee.getName();
        Long applyId = -1L;
        String applyName = "";
        String processName = ProcessKeyEnum.getByProcessKey(PROCESS_KEY);
        OaUniversalDO oaUniversalDO = oaUniversalMapper.selectOne(OaUniversalDO::getProcInstId, currentTask.getProcessInstanceId());
        if (oaUniversalDO != null) {
            EmployeeRespDTO applyEmployee = employeeApi.getEmployeeById(oaUniversalDO.getEmployeeId());
            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
    public Long revocationOaUniversal(BpmTaskApproveReqVO revocationReqVO) {
        // 登录人信息
        Long loginUserId = SecurityFrameworkUtils.getLoginUserId();
        // 根据登录人查询出对应的员工信息
        EmployeeRespDTO loginEmployee = employeeApi.getEmployeeByUserId(loginUserId);

        Task currentTask = bpmTaskService.getTask(revocationReqVO.getId());
        if (currentTask == null) {
            throw ServiceExceptionUtil.exception(ErrorCodeConstants.TASK_NOT_EXISTS);
        }
        LambdaQueryWrapper<OaUniversalDO> lambdaQueryWrapper = new LambdaQueryWrapper<OaUniversalDO>()
                .eq(OaUniversalDO::getProcInstId, currentTask.getProcessInstanceId());
        OaUniversalDO oaUniversalDO = oaUniversalMapper.selectOne(lambdaQueryWrapper);
        if (!DictDataConstants.OA_AUDIT_STATUS_COMMITTED.equals(oaUniversalDO.getAuditStatus())
            || !Objects.equals(String.valueOf(loginEmployee.getId()), oaUniversalDO.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();

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

        return 1L;
    }

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

        OaUniversalDO oaUniversalNew = BeanUtils.toBean(reCommitReqVO, OaUniversalDO.class);
        OaUniversalDO oaUniversalOld = validateOaUniversalExists(oaUniversalNew.getId());
        oaUniversalNew.setUniversalId(oaUniversalOld.getUniversalId())
                .setProcInstId(oaUniversalOld.getProcInstId());

        Task currentTask = taskService.createTaskQuery().processInstanceId(oaUniversalNew.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);
            // 保存审批人信息
            oaUniversalNew.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();
        oaUniversalNew.setAuditStatus(DictDataConstants.OA_AUDIT_STATUS_COMMITTED)
                .setCurrentAuditEmployeeId(Long.valueOf(nextTask.getAssignee()))
                .setFinalAuditDate(LocalDateTime.now());
        oaUniversalMapper.updateById(oaUniversalNew);

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

        // 给审批人发送审批站内信
        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
    public Long closeOaUniversal(Long id) {
        if (id == null) {
            throw exception(ErrorCodeConstants.SERVICE_ID_NOT_EXISTS);
        }
        // 登录人信息
        Long loginUserId = SecurityFrameworkUtils.getLoginUserId();
        // 根据登录人查询出对应的员工信息
        EmployeeRespDTO loginEmployee = employeeApi.getEmployeeByUserId(loginUserId);

        OaUniversalDO oaUniversalDO = validateOaUniversalExists(id);
        if (!DictDataConstants.OA_AUDIT_STATUS_RETURNED.equals(oaUniversalDO.getAuditStatus())
            && !DictDataConstants.OA_AUDIT_STATUS_RECALLED.equals(oaUniversalDO.getAuditStatus())) {
            throw exception(ErrorCodeConstants.TASK_CLOSE_NOT_ALLOWED);
        }

        Task currentTask = taskService.createTaskQuery().processInstanceId(oaUniversalDO.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<OaUniversalDO> lambdaUpdateWrapper = new LambdaUpdateWrapper<>();
        lambdaUpdateWrapper.set(OaUniversalDO::getAuditStatus, DictDataConstants.OA_AUDIT_STATUS_CLOSED)
                .set(OaUniversalDO::getCurrentAuditEmployeeId, null)
                .set(OaUniversalDO::getFinalAuditDate, LocalDateTime.now())
                .eq(OaUniversalDO::getId, id);
        oaUniversalMapper.update(lambdaUpdateWrapper);

        return 1L;
    }

    @Override
    public void deleteOaUniversal(Long id) {
        // 校验存在
        validateOaUniversalDelete(id);
        // 删除
        oaUniversalMapper.deleteById(id);
    }

    @Override
    public OaUniversalRespVO getOaUniversal(Long id) {
        // 登录人信息
        Long loginUserId = SecurityFrameworkUtils.getLoginUserId();
        // 根据登录人查询出对应的员工信息
        EmployeeRespDTO loginEmployee = employeeApi.getEmployeeByUserId(loginUserId);

        OaUniversalDO oaUniversalDO = validateOaUniversalExists(id);
        OaUniversalRespVO oaUniversalRespVO = BeanUtils.toBean(oaUniversalDO, OaUniversalRespVO.class);
        if (oaUniversalDO.getDeptId() != null) {
            DeptRespDTO dept = deptApi.getDept(oaUniversalDO.getDeptId());
            if (dept != null) {
                oaUniversalRespVO.setDeptName(dept.getName());
            }
        }

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

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

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

        // 审批人
        String startUserSelectAssignees = oaUniversalDO.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);
                }
            }
            oaUniversalRespVO.setAuditUserList(auditUserList);
        }

        return oaUniversalRespVO;
    }

    @Override
    public OaUniversalRespVO getOaUniversalByProcInstId(String procInstId) {
        OaUniversalDO oaUniversalDO = oaUniversalMapper.selectOne(OaUniversalDO::getProcInstId, procInstId);
        OaUniversalRespVO oaUniversalRespVO = BeanUtils.toBean(oaUniversalDO, OaUniversalRespVO.class);
        if (oaUniversalDO.getDeptId() != null) {
            DeptRespDTO dept = deptApi.getDept(oaUniversalDO.getDeptId());
            if (dept != null) {
                oaUniversalRespVO.setDeptName(dept.getName());
            }
        }

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

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

        // 审批人
        String startUserSelectAssignees = oaUniversalDO.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);
                }
            }
            oaUniversalRespVO.setAuditUserList(auditUserList);
        }

        return oaUniversalRespVO;
    }

    @Override
    public PageResult<OaUniversalRespVO> getOaUniversalPage(OaUniversalPageReqVO pageReqVO) {
        PageResult<OaUniversalDO> oaUniversalDOPageResult = oaUniversalMapper.selectPage(pageReqVO);
        PageResult<OaUniversalRespVO> oaUniversalRespVOPageResult = BeanUtils.toBean(oaUniversalDOPageResult, OaUniversalRespVO.class);

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

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

        return oaUniversalRespVOPageResult;
    }

    @Override
    public PageResult<OaUniversalRespVO> exportOaUniversalExcel(OaUniversalPageReqVO pageReqVO) {
        pageReqVO.setPageSize(PageParam.PAGE_SIZE_NONE);
        return getOaUniversalPage(pageReqVO);
    }

    private void validateOaUniversalDelete(Long id) {
        OaUniversalDO oaUniversalDO = validateOaUniversalExists(id);
        if (!DictDataConstants.OA_AUDIT_STATUS_STAGING.equals(oaUniversalDO.getAuditStatus())) {
            throw exception(ErrorCodeConstants.DELETE_FAIL_NOT_STAGING);
        }
    }

    private OaUniversalDO validateOaUniversalExists(Long id) {
        OaUniversalDO oaUniversalDO = oaUniversalMapper.selectById(id);
        if (oaUniversalDO == null) {
            throw exception(OA_UNIVERSAL_NOT_EXISTS);
        }
        return oaUniversalDO;
    }


}