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

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.bpm.api.task.BpmProcessInstanceApi;
import cn.iocoder.yudao.module.bpm.api.task.dto.BpmProcessInstanceCreateReqDTO;
import cn.iocoder.yudao.module.bpm.controller.admin.oa.renew.vo.OaRenewPageReqVO;
import cn.iocoder.yudao.module.bpm.controller.admin.oa.renew.vo.OaRenewRespVO;
import cn.iocoder.yudao.module.bpm.controller.admin.oa.renew.vo.OaRenewSaveReqVO;
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.renew.OaRenewDO;
import cn.iocoder.yudao.module.bpm.dal.mysql.oa.renew.OaRenewMapper;
import cn.iocoder.yudao.module.bpm.enums.DictDataConstants;
import cn.iocoder.yudao.module.bpm.enums.ErrorCodeConstants;
import cn.iocoder.yudao.module.bpm.enums.OaAuditStatusEnum;
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.relations.api.renew.RelationsRenewApi;
import cn.iocoder.yudao.module.relations.api.renew.dto.RelationsRenewCreateReqDTO;
import cn.iocoder.yudao.module.system.api.dept.DeptApi;
import cn.iocoder.yudao.module.system.api.dept.PostApi;
import cn.iocoder.yudao.module.system.api.dept.dto.DeptRespDTO;
import cn.iocoder.yudao.module.system.api.dept.dto.PostRespDTO;
import cn.iocoder.yudao.module.system.api.notify.NotifyMessageSendApi;
import cn.iocoder.yudao.module.system.api.permission.PermissionApi;
import cn.iocoder.yudao.module.system.api.permission.dto.DeptDataPermissionRespDTO;
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.LocalDate;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
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_NOT_ALLOW_OPERATE_BY_OTHER;
import static cn.iocoder.yudao.module.bpm.enums.ErrorCodeConstants.OA_RENEW_NOT_EXISTS;

/**
 * 合同续签流程信息 Service 实现类
 *
 * @author dp
 */
@Service
@Validated
public class OaRenewServiceImpl implements OaRenewService {


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

    @Resource
    private OaRenewMapper oaRenewMapper;

    @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 PostApi postApi;

    @Resource
    private RelationsRenewApi relationsRenewApi;

    @Resource
    private NotifyMessageSendApi notifyMessageSendApi;

    @Resource
    private PermissionApi permissionApi;


    @Override
    @Transactional(rollbackFor = Exception.class)
    public Long stagingOaRenew(OaRenewSaveReqVO stagingReqVO) {
        // 登录人信息
        Long loginUserId = SecurityFrameworkUtils.getLoginUserId();
        // 登录员工信息
        EmployeeRespDTO loginEmployee = employeeApi.getEmployeeByUserId(loginUserId);
        // 续签人信息
        EmployeeRespDTO employee = employeeApi.getEmployeeById(stagingReqVO.getEmployeeId());
        if (loginEmployee == null || (stagingReqVO.getEmployeeId() != null && employee == null)) {
            throw exception(ErrorCodeConstants.OA_EMPLOYEE_NOT_EXISTS);
        }
        // 续签结束日期不能小于续签开始日期
        String renewContractStartDate = stagingReqVO.getRenewContractStartDate();
        String renewContractEndDate = stagingReqVO.getRenewContractEndDate();
        if (StrUtil.isNotBlank(renewContractStartDate) && StrUtil.isNotBlank(renewContractEndDate)) {
            if (renewContractStartDate.compareTo(renewContractEndDate) > 0) {
                throw exception(ErrorCodeConstants.OA_RENEW_CONTRACT_START_DATE_GREATER_THAN_END_DATE);
            }
        }

        OaRenewDO oaRenew = BeanUtils.toBean(stagingReqVO, OaRenewDO.class);
        if (oaRenew.getId() != null) {
            OaRenewDO oaRenewDO = validateOaRenewExists(oaRenew.getId());
            validateOperator(loginUserId, Long.valueOf(oaRenewDO.getCreator()));
        } else {
            // 创建单据uuid
            String uuid = IdUtil.fastSimpleUUID();
            oaRenew.setRenewId(uuid);
        }
        if (employee != null) {
            oaRenew.setEmployeeId(employee.getId());
            oaRenew.setEmployeeName(employee.getName());
            oaRenew.setEmployeePhone(employee.getPhone());
            oaRenew.setDeptId(employee.getDeptId());
            oaRenew.setPostId(employee.getPostId());
            oaRenew.setPosition(employee.getPosition());
        }
        DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd");
        LocalDate contractStartDate = loginEmployee.getContractStartDate();
        if (contractStartDate != null) {
            oaRenew.setOldContractStartDate(formatter.format(contractStartDate));
        }
        LocalDate contractEndDate = loginEmployee.getContractEndDate();
        if (contractEndDate != null) {
            oaRenew.setOldContractEndDate(formatter.format(contractEndDate));
        }
        oaRenew.setUserId(loginUserId);
        oaRenew.setAuditStatus(DictDataConstants.OA_AUDIT_STATUS_STAGING);
        oaRenew.setInfoSource("0");
        oaRenew.setApplyEmployeeId(loginEmployee.getId());
        oaRenew.setApplyEmployeeName(loginEmployee.getName());
        // oaRenew.setCreator(String.valueOf(loginEmployee.getId()));
        // 暂存不保存审批人信息
        oaRenew.setStartUserSelectAssignees(null);
        // 连续暂存，回显时前端会直接显示上次缓存的数据，会让用户认为第一次暂存没保存审批人，第二次却保存了
        // 为了前后一致，暂存时如果选择了审批人，也保存一下
        List<Long> selectAssignees = stagingReqVO.getStartUserSelectAssignees();
        if (CollectionUtil.isNotEmpty(selectAssignees)) {
            String collect = selectAssignees.stream().map(String::valueOf).collect(Collectors.joining(","));
            oaRenew.setStartUserSelectAssignees(collect);
        } else {
            if (oaRenew.getId() != null) {
                // 单独更新审批人字段
                oaRenewMapper.update(new LambdaUpdateWrapper<OaRenewDO>()
                        .eq(OaRenewDO::getId, oaRenew.getId())
                        .set(OaRenewDO::getStartUserSelectAssignees, null));
            }
        }
        // 保存或更新表单信息
        if (oaRenew.getId() == null) {
            oaRenewMapper.insert(oaRenew);
        } else {
            validateOaRenewExists(oaRenew.getId());
            oaRenewMapper.updateById(oaRenew);
        }
        // 保存业务uuid到附件中
        fileApi.updateFileBiz(stagingReqVO.getFileIdList(), oaRenew.getRenewId());

        return oaRenew.getId();
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public Long commitOaRenew(OaRenewSaveReqVO commitReqVO) {
        if (CollectionUtil.isEmpty(commitReqVO.getStartUserSelectAssignees())) {
            throw exception(ErrorCodeConstants.TASK_CREATE_FAIL_NO_START_SELECT_ASSIGNEE);
        }
        // 登录人信息
        Long loginUserId = SecurityFrameworkUtils.getLoginUserId();
        if (loginUserId == null) {
            throw exception(ErrorCodeConstants.OA_LOGIN_USER_NOT_EXISTS);
        }
        // 登录员工信息
        EmployeeRespDTO loginEmployee = employeeApi.getEmployeeByUserId(loginUserId);
        // 续签人信息
        EmployeeRespDTO employee = employeeApi.getEmployeeById(commitReqVO.getEmployeeId());
        if (loginEmployee == null || employee == null) {
            throw exception(ErrorCodeConstants.OA_EMPLOYEE_NOT_EXISTS);
        }
        // 续签结束日期不能小于续签开始日期
        String renewContractStartDate = commitReqVO.getRenewContractStartDate();
        String renewContractEndDate = commitReqVO.getRenewContractEndDate();
        if (StrUtil.isNotBlank(renewContractStartDate) && StrUtil.isNotBlank(renewContractEndDate)) {
            if (renewContractStartDate.compareTo(renewContractEndDate) > 0) {
                throw exception(ErrorCodeConstants.OA_RENEW_CONTRACT_START_DATE_GREATER_THAN_END_DATE);
            }
        }


        OaRenewDO oaRenew = BeanUtils.toBean(commitReqVO, OaRenewDO.class);
        if (oaRenew.getId() != null) {
            OaRenewDO oaRenewDO = validateOaRenewExists(oaRenew.getId());
            validateOperator(loginUserId, Long.valueOf(oaRenewDO.getCreator()));
        } else {
            // 创建单据uuid
            String uuid = IdUtil.fastSimpleUUID();
            oaRenew.setRenewId(uuid);
        }
        oaRenew.setEmployeeId(employee.getId());
        oaRenew.setEmployeeName(employee.getName());
        oaRenew.setEmployeePhone(employee.getPhone());
        oaRenew.setDeptId(employee.getDeptId());
        oaRenew.setPostId(employee.getPostId());
        oaRenew.setPosition(employee.getPosition());
        DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd");
        LocalDate contractStartDate = loginEmployee.getContractStartDate();
        if (contractStartDate != null) {
            oaRenew.setOldContractStartDate(formatter.format(contractStartDate));
        }
        LocalDate contractEndDate = loginEmployee.getContractEndDate();
        if (contractEndDate != null) {
            oaRenew.setOldContractEndDate(formatter.format(contractEndDate));
        }
        oaRenew.setUserId(loginUserId);
        oaRenew.setInfoSource("0");
        oaRenew.setApplyEmployeeId(loginEmployee.getId());
        oaRenew.setApplyEmployeeName(loginEmployee.getName());
        // oaRenew.setCreator(String.valueOf(loginEmployee.getId()));
        // 保存或更新表单信息
        if (oaRenew.getId() == null) {
            oaRenewMapper.insert(oaRenew);
        } else {
            OaRenewDO oaRenewDO = validateOaRenewExists(oaRenew.getId());
            if (StrUtil.isNotBlank(oaRenewDO.getProcInstId())) {
                throw exception(ErrorCodeConstants.PROCESS_INSTANCE_CREATE_FAIL_HAS_PROCESS);
            }
            oaRenewMapper.updateById(oaRenew);
        }
        // 发起流程
        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(oaRenew.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、单据状态、最后一次审批时间、当前审批人更新到单据信息中
        oaRenewMapper.updateById(new OaRenewDO()
                .setId(oaRenew.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(), oaRenew.getRenewId());

        // 给审批人发送审批站内信
        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 oaRenew.getId();
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public Long agreeOaRenew(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<OaRenewDO> lambdaQueryWrapper = new LambdaQueryWrapper<>();
        lambdaQueryWrapper.eq(OaRenewDO::getProcInstId, currentTask.getProcessInstanceId());
        OaRenewDO oaRenew = oaRenewMapper.selectOne(lambdaQueryWrapper);
        // 如果是最后一个人审批同意，设置流程审批状态为已审核
        String[] auditPersons = oaRenew.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();
        LambdaUpdateWrapper<OaRenewDO> lambdaUpdateWrapper = new LambdaUpdateWrapper<>();
        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);
            lambdaUpdateWrapper.set(OaRenewDO::getAuditStatus, DictDataConstants.OA_AUDIT_STATUS_AUDITING)
                    .set(OaRenewDO::getCurrentAuditEmployeeId, currentAuditEmployeeId)
                    .set(OaRenewDO::getCurrentAuditEmployeeName, currentAuditEmployee.getName())
                    .set(OaRenewDO::getFinalAuditDate, LocalDateTime.now())
                    .eq(OaRenewDO::getId, oaRenew.getId());

        } else {
            lambdaUpdateWrapper.set(OaRenewDO::getAuditStatus, DictDataConstants.OA_AUDIT_STATUS_AUDITED)
                    .set(OaRenewDO::getCurrentAuditEmployeeId, null)
                    .set(OaRenewDO::getCurrentAuditEmployeeName, null)
                    .set(OaRenewDO::getFinalAuditDate, LocalDateTime.now())
                    .eq(OaRenewDO::getId, oaRenew.getId());
        }
        oaRenewMapper.update(lambdaUpdateWrapper);

        // 复制业务单据信息到业务模块单据表
        if(Objects.isNull(nextTask)) {
            // 查询申请单
            OaRenewDO renew = oaRenewMapper.selectById(oaRenew.getId());

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

            // 保存单据信息
            relationsRenewApi.createRenewInfoAfterAudit(renewCreateReqDTO);
        }

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

        EmployeeRespDTO applyEmployee = employeeApi.getEmployeeById(oaRenew.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 disagreeOaRenew(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<OaRenewDO> updateWrapper = new LambdaUpdateWrapper<>();
        updateWrapper.set(OaRenewDO::getCurrentAuditEmployeeId, currentAuditEmployeeId)
                .set(OaRenewDO::getCurrentAuditEmployeeName, currentAuditEmployee.getName())
                .set(OaRenewDO::getFinalAuditDate, LocalDateTime.now())
                .set(OaRenewDO::getAuditStatus, DictDataConstants.OA_AUDIT_STATUS_RETURNED)
                .eq(OaRenewDO::getProcInstId, currentTask.getProcessInstanceId());
        oaRenewMapper.update(updateWrapper);

        // 给申请人发送驳回站内信
        String assigneeName = loginEmployee.getName();
        Long applyId = -1L;
        String applyName = "";
        String processName = ProcessKeyEnum.getByProcessKey(PROCESS_KEY);
        OaRenewDO oaRenewDO = oaRenewMapper.selectOne(OaRenewDO::getProcInstId, currentTask.getProcessInstanceId());
        if (oaRenewDO != null) {
            EmployeeRespDTO applyEmployee = employeeApi.getEmployeeById(oaRenewDO.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 revocationOaRenew(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<OaRenewDO> lambdaQueryWrapper = new LambdaQueryWrapper<OaRenewDO>()
                .eq(OaRenewDO::getProcInstId, currentTask.getProcessInstanceId());
        OaRenewDO oaRenewDO = oaRenewMapper.selectOne(lambdaQueryWrapper);
        if (!DictDataConstants.OA_AUDIT_STATUS_COMMITTED.equals(oaRenewDO.getAuditStatus())
                || !Objects.equals(String.valueOf(loginUserId), oaRenewDO.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<OaRenewDO> updateWrapper = new LambdaUpdateWrapper<>();
        updateWrapper.set(OaRenewDO::getCurrentAuditEmployeeId, currentAuditEmployeeId)
                .set(OaRenewDO::getCurrentAuditEmployeeName, currentAuditEmployee.getName())
                .set(OaRenewDO::getFinalAuditDate, LocalDateTime.now())
                .set(OaRenewDO::getAuditStatus, DictDataConstants.OA_AUDIT_STATUS_RECALLED)
                .eq(OaRenewDO::getProcInstId, currentTask.getProcessInstanceId());
        oaRenewMapper.update(updateWrapper);

        return 1L;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public Long reCommitOaRenew(OaRenewSaveReqVO reCommitReqVO) {
        if (reCommitReqVO.getId() == null) {
            throw exception(ErrorCodeConstants.SERVICE_ID_NOT_EXISTS);
        }
        // 登录人信息
        Long loginUserId = SecurityFrameworkUtils.getLoginUserId();
        // 登录员工信息
        EmployeeRespDTO loginEmployee = employeeApi.getEmployeeByUserId(loginUserId);
        // 续签人信息
        EmployeeRespDTO employee = employeeApi.getEmployeeById(reCommitReqVO.getEmployeeId());
        if (loginEmployee == null || employee == null) {
            throw exception(ErrorCodeConstants.OA_EMPLOYEE_NOT_EXISTS);
        }
        // 续签结束日期不能小于续签开始日期
        String renewContractStartDate = reCommitReqVO.getRenewContractStartDate();
        String renewContractEndDate = reCommitReqVO.getRenewContractEndDate();
        if (StrUtil.isNotBlank(renewContractStartDate) && StrUtil.isNotBlank(renewContractEndDate)) {
            if (renewContractStartDate.compareTo(renewContractEndDate) > 0) {
                throw exception(ErrorCodeConstants.OA_RENEW_CONTRACT_START_DATE_GREATER_THAN_END_DATE);
            }
        }

        OaRenewDO oaRenewNew = BeanUtils.toBean(reCommitReqVO, OaRenewDO.class);
        OaRenewDO oaRenewOld = validateOaRenewExists(oaRenewNew.getId());
        oaRenewNew.setRenewId(oaRenewOld.getRenewId())
                .setProcInstId(oaRenewOld.getProcInstId());

        oaRenewNew.setEmployeeId(employee.getId());
        oaRenewNew.setEmployeeName(employee.getName());
        oaRenewNew.setEmployeePhone(employee.getPhone());
        oaRenewNew.setDeptId(employee.getDeptId());
        oaRenewNew.setPostId(employee.getPostId());
        oaRenewNew.setPosition(employee.getPosition());
        DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd");
        LocalDate contractStartDate = loginEmployee.getContractStartDate();
        if (contractStartDate != null) {
            oaRenewNew.setOldContractStartDate(formatter.format(contractStartDate));
        }
        LocalDate contractEndDate = loginEmployee.getContractEndDate();
        if (contractEndDate != null) {
            oaRenewNew.setOldContractEndDate(formatter.format(contractEndDate));
        }
        oaRenewNew.setUserId(loginUserId);
        oaRenewNew.setApplyEmployeeId(loginEmployee.getId());
        oaRenewNew.setApplyEmployeeName(loginEmployee.getName());

        Task currentTask = taskService.createTaskQuery().processInstanceId(oaRenewNew.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);
            // 保存审批人信息
            oaRenewNew.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);
        oaRenewNew.setAuditStatus(DictDataConstants.OA_AUDIT_STATUS_COMMITTED)
                .setCurrentAuditEmployeeId(currentAuditEmployeeId)
                .setCurrentAuditEmployeeName(currentAuditEmployee.getName())
                .setFinalAuditDate(LocalDateTime.now());
        oaRenewMapper.updateById(oaRenewNew);

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

        // 给审批人发送审批站内信
        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 closeOaRenew(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);
        }

        OaRenewDO oaRenewDO = validateOaRenewExists(id);
        if (!DictDataConstants.OA_AUDIT_STATUS_RETURNED.equals(oaRenewDO.getAuditStatus())
                && !DictDataConstants.OA_AUDIT_STATUS_RECALLED.equals(oaRenewDO.getAuditStatus())) {
            throw exception(ErrorCodeConstants.TASK_CLOSE_NOT_ALLOWED);
        }

        Task currentTask = taskService.createTaskQuery().processInstanceId(oaRenewDO.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<OaRenewDO> lambdaUpdateWrapper = new LambdaUpdateWrapper<>();
        lambdaUpdateWrapper.set(OaRenewDO::getAuditStatus, DictDataConstants.OA_AUDIT_STATUS_CLOSED)
                .set(OaRenewDO::getCurrentAuditEmployeeId, null)
                .set(OaRenewDO::getCurrentAuditEmployeeName, null)
                .set(OaRenewDO::getFinalAuditDate, LocalDateTime.now())
                .eq(OaRenewDO::getId, id);
        oaRenewMapper.update(lambdaUpdateWrapper);
        return 1L;
    }

    @Override
    public void deleteOaRenew(Long id) {
        // 校验存在
        OaRenewDO oaRenewDO = validateOaRenewDelete(id);
        validateOperator(SecurityFrameworkUtils.getLoginUserId(), Long.valueOf(oaRenewDO.getCreator()));
        // 删除
        oaRenewMapper.deleteById(id);
    }

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

        OaRenewDO oaRenewDO = validateOaRenewExists(id);
        OaRenewRespVO oaRenewRespVO = BeanUtils.toBean(oaRenewDO, OaRenewRespVO.class);
        if (oaRenewDO.getDeptId() != null) {
            DeptRespDTO dept = deptApi.getDept(oaRenewDO.getDeptId());
            if (dept != null) {
                oaRenewRespVO.setDeptName(dept.getName());
            }
        }
        // 职位
        if (oaRenewDO.getPostId() != null) {
            PostRespDTO post = postApi.getPost(oaRenewDO.getPostId());
            if (post != null) {
                oaRenewRespVO.setPosition(post.getName());
            }
        }
        // 状态
        if (StrUtil.isNotBlank(oaRenewDO.getAuditStatus())) {
            oaRenewRespVO.setAuditStatusDesc(OaAuditStatusEnum.getByStatus(oaRenewDO.getAuditStatus()));
        }

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

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

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

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

        return oaRenewRespVO;
    }

    @Override
    public OaRenewRespVO getOaRenewByProcInstId(String procInstId) {
        OaRenewDO oaRenewDO = oaRenewMapper.selectOne(OaRenewDO::getProcInstId, procInstId);
        OaRenewRespVO oaRenewRespVO = BeanUtils.toBean(oaRenewDO, OaRenewRespVO.class);
        if (oaRenewDO.getDeptId() != null) {
            DeptRespDTO dept = deptApi.getDept(oaRenewDO.getDeptId());
            if (dept != null) {
                oaRenewRespVO.setDeptName(dept.getName());
            }
        }

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

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

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

        return oaRenewRespVO;
    }

    @Override
    public PageResult<OaRenewRespVO> getOaRenewPage(OaRenewPageReqVO pageReqVO) {
        // 数据权限
        Long loginUserId = SecurityFrameworkUtils.getLoginUserId();
        DeptDataPermissionRespDTO deptDataPermission = permissionApi.getDeptDataPermission(loginUserId);
        pageReqVO.setDeptDataPermission(deptDataPermission);
        pageReqVO.setUserId(loginUserId);

        PageResult<OaRenewDO> oaRenewDOPageResult = oaRenewMapper.selectPage(pageReqVO);
        PageResult<OaRenewRespVO> oaRenewRespVOPageResult = BeanUtils.toBean(oaRenewDOPageResult, OaRenewRespVO.class);

        List<OaRenewRespVO> oaRenewRespVOList = oaRenewRespVOPageResult.getList();
        if (CollectionUtil.isNotEmpty(oaRenewRespVOList)) {
            List<Long> employeeIdList = oaRenewRespVOList.stream().map(OaRenewRespVO::getCurrentAuditEmployeeId).collect(Collectors.toList());
            List<EmployeeRespDTO> employeeRespDTOList = employeeApi.getEmployeeListByIds(employeeIdList);
            Map<Long, EmployeeRespDTO> longEmployeeRespDTOMap = CollectionUtils.convertMap(employeeRespDTOList, EmployeeRespDTO::getId);

            List<Long> deptIdList = oaRenewRespVOList.stream().map(OaRenewRespVO::getDeptId).collect(Collectors.toList());
            List<DeptRespDTO> deptList = deptApi.getDeptList(deptIdList);
            Map<Long, DeptRespDTO> deptMap = CollectionUtils.convertMap(deptList, DeptRespDTO::getId);

            // 职位
            List<Long> postIdList = oaRenewRespVOList.stream().map(OaRenewRespVO::getPostId).collect(Collectors.toList());
            List<PostRespDTO> postList = postApi.getPostList(postIdList);
            Map<Long, PostRespDTO> postMap = CollectionUtils.convertMap(postList, PostRespDTO::getId);

            // 状态
            Map<String, String> statusMap = Arrays.stream(OaAuditStatusEnum.values())
                    .collect(Collectors.toMap(OaAuditStatusEnum::getStatus, OaAuditStatusEnum::getStatusDesc));

            for (OaRenewRespVO respVO : oaRenewRespVOList) {
                // 当前处理人
                if (respVO.getCurrentAuditEmployeeId() != null) {
                    EmployeeRespDTO employeeRespDTO = longEmployeeRespDTOMap.get(respVO.getCurrentAuditEmployeeId());
                    if (employeeRespDTO != null) {
                        respVO.setCurrentAuditEmployeeName(employeeRespDTO.getName());
                    }
                }
                // 部门
                if (respVO.getDeptId() != null) {
                    DeptRespDTO deptRespDTO = deptMap.get(respVO.getDeptId());
                    if (deptRespDTO != null) {
                        respVO.setDeptName(deptRespDTO.getName());
                    }
                }
                // 职位
                if (respVO.getPostId() != null) {
                    PostRespDTO postRespDTO = postMap.get(respVO.getPostId());
                    if (postRespDTO != null) {
                        respVO.setPosition(postRespDTO.getName());
                    }
                }
                // 状态
                respVO.setAuditStatusDesc(statusMap.get(respVO.getAuditStatus()));
            }
        }

        return oaRenewRespVOPageResult;
    }

    @Override
    public PageResult<OaRenewRespVO> exportOaRenewExcel(OaRenewPageReqVO pageReqVO) {
        pageReqVO.setPageSize(PageParam.PAGE_SIZE_NONE);
        return getOaRenewPage(pageReqVO);
    }

    private OaRenewDO validateOaRenewDelete(Long id) {
        OaRenewDO oaRenewDO = validateOaRenewExists(id);
        if (!DictDataConstants.OA_AUDIT_STATUS_STAGING.equals(oaRenewDO.getAuditStatus())) {
            throw exception(ErrorCodeConstants.DELETE_FAIL_NOT_STAGING);
        }
        return oaRenewDO;
    }

    private OaRenewDO validateOaRenewExists(Long id) {
        OaRenewDO oaRenewDO = oaRenewMapper.selectById(id);
        if (oaRenewDO == null) {
            throw exception(OA_RENEW_NOT_EXISTS);
        }
        return oaRenewDO;
    }

    private void validateOperator(Long loginUserId, Long creator) {
        if (!Objects.equals(loginUserId, creator)) {
            throw exception(OA_NOT_ALLOW_OPERATE_BY_OTHER);
        }
    }



}