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

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.purchase.vo.OaPurchasePageReqVO;
import cn.iocoder.yudao.module.bpm.controller.admin.oa.purchase.vo.OaPurchaseRespVO;
import cn.iocoder.yudao.module.bpm.controller.admin.oa.purchase.vo.OaPurchaseSaveReqVO;
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.purchase.OaPurchaseDO;
import cn.iocoder.yudao.module.bpm.dal.dataobject.oa.purchase.OaPurchaseObjDO;
import cn.iocoder.yudao.module.bpm.dal.mysql.oa.purchase.OaPurchaseMapper;
import cn.iocoder.yudao.module.bpm.dal.mysql.oa.purchase.OaPurchaseObjMapper;
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.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 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_PURCHASE_NOT_EXISTS;

/**
 * 采购流程信息 Service 实现类
 *
 * @author dp
 */
@Service
@Validated
public class OaPurchaseServiceImpl implements OaPurchaseService {

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


    @Resource
    private OaPurchaseMapper oaPurchaseMapper;

    @Resource
    private OaPurchaseObjMapper oaPurchaseObjMapper;

    @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 NotifyMessageSendApi notifyMessageSendApi;


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

        OaPurchaseDO oaPurchase = BeanUtils.toBean(stagingReqVO, OaPurchaseDO.class);
        if (StringUtils.isBlank(oaPurchase.getPurchaseUuid())) {
            // 创建单据uuid
            String uuid = IdUtil.fastSimpleUUID();
            oaPurchase.setPurchaseUuid(uuid);
        }
        oaPurchase.setEmployeeId(loginEmployee.getId());
        oaPurchase.setEmployeeName(loginEmployee.getName());
        oaPurchase.setEmployeePhone(loginEmployee.getPhone());
        oaPurchase.setDeptId(loginEmployee.getDeptId());
        oaPurchase.setPostId(loginEmployee.getPostId());
        oaPurchase.setPosition(loginEmployee.getPosition());
        oaPurchase.setUserId(loginUserId);
        oaPurchase.setAuditStatus(DictDataConstants.OA_AUDIT_STATUS_STAGING);
        oaPurchase.setInfoSource("0");
        oaPurchase.setApplyEmployeeId(loginEmployee.getId());
        oaPurchase.setApplyEmployeeName(loginEmployee.getName());
        oaPurchase.setCreator(String.valueOf(loginEmployee.getId()));
        // 暂存不保存审批人信息
        oaPurchase.setStartUserSelectAssignees(null);
        // 连续暂存，回显时前端会直接显示上次缓存的数据，会让用户认为第一次暂存没保存审批人，第二次却保存了
        // 为了前后一致，暂存时如果选择了审批人，也保存一下
        List<Long> selectAssignees = stagingReqVO.getStartUserSelectAssignees();
        if (CollectionUtil.isNotEmpty(selectAssignees)) {
            String collect = selectAssignees.stream().map(String::valueOf).collect(Collectors.joining(","));
            oaPurchase.setStartUserSelectAssignees(collect);
        } else {
            if (oaPurchase.getId() != null) {
                // 单独更新审批人字段
                oaPurchaseMapper.update(new LambdaUpdateWrapper<OaPurchaseDO>()
                        .eq(OaPurchaseDO::getId, oaPurchase.getId())
                        .set(OaPurchaseDO::getStartUserSelectAssignees, null));
            }
        }

        // 保存或更新表单信息
        if (oaPurchase.getId() == null) {
            oaPurchaseMapper.insert(oaPurchase);
        } else {
            validateOaPurchaseExists(oaPurchase.getId());
            oaPurchaseMapper.updateById(oaPurchase);
        }
        // 保存子表信息
        List<OaPurchaseObjDO> oaPurchaseObjs = stagingReqVO.getOaPurchaseObjs();
        if (CollectionUtil.isNotEmpty(oaPurchaseObjs)) {
            updateOaPurchaseObjList(oaPurchase.getId(), oaPurchaseObjs);
        }

        // 保存业务uuid到附件中
        fileApi.updateFileBiz(stagingReqVO.getFileIdList(), oaPurchase.getPurchaseUuid());

        return oaPurchase.getId();
    }

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


        OaPurchaseDO oaPurchase = BeanUtils.toBean(commitReqVO, OaPurchaseDO.class);
        if (StringUtils.isBlank(oaPurchase.getPurchaseUuid())) {
            // 创建单据uuid
            String uuid = IdUtil.fastSimpleUUID();
            oaPurchase.setPurchaseUuid(uuid);
        }
        oaPurchase.setEmployeeId(loginEmployee.getId());
        oaPurchase.setEmployeeName(loginEmployee.getName());
        oaPurchase.setEmployeePhone(loginEmployee.getPhone());
        oaPurchase.setDeptId(loginEmployee.getDeptId());
        oaPurchase.setPostId(loginEmployee.getPostId());
        oaPurchase.setPosition(loginEmployee.getPosition());
        oaPurchase.setUserId(loginUserId);
        oaPurchase.setInfoSource("0");
        oaPurchase.setApplyEmployeeId(loginEmployee.getId());
        oaPurchase.setApplyEmployeeName(loginEmployee.getName());
        oaPurchase.setCreator(String.valueOf(loginEmployee.getId()));

        // 子表信息
        List<OaPurchaseObjDO> oaPurchaseObjs = commitReqVO.getOaPurchaseObjs();
        for (OaPurchaseObjDO oaPurchaseObj : oaPurchaseObjs) {
            if (StrUtil.isBlank(oaPurchaseObj.getName())) {
                throw exception(ErrorCodeConstants.OA_PURCHASE_OBJ_NAME_BLANK);
            }
            if (oaPurchaseObj.getAmount() == null || oaPurchaseObj.getAmount() == 0) {
                throw exception(ErrorCodeConstants.OA_PURCHASE_OBJ_AMOUNT_ZERO);
            }
            if (oaPurchaseObj.getBudget() == null) {
                throw exception(ErrorCodeConstants.OA_PURCHASE_OBJ_BUDGET_ZERO);
            }
        }

        // 保存或更新表单信息
        if (oaPurchase.getId() == null) {
            oaPurchaseMapper.insert(oaPurchase);
        } else {
            OaPurchaseDO oaPurchaseDO = validateOaPurchaseExists(oaPurchase.getId());
            if (StrUtil.isNotBlank(oaPurchaseDO.getProcInstId())) {
                throw exception(ErrorCodeConstants.PROCESS_INSTANCE_CREATE_FAIL_HAS_PROCESS);
            }
            oaPurchaseMapper.updateById(oaPurchase);
        }
        // 保存子表
        if (CollectionUtil.isNotEmpty(oaPurchaseObjs)) {
            updateOaPurchaseObjList(oaPurchase.getId(), oaPurchaseObjs);
        }

        // 发起流程
        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(oaPurchase.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、单据状态、最后一次审批时间、当前审批人更新到单据信息中
        oaPurchaseMapper.updateById(new OaPurchaseDO()
                .setId(oaPurchase.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(), oaPurchase.getPurchaseUuid());

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

    @Override
    @Transactional(rollbackFor = Exception.class)
    public Long agreeOaPurchase(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<OaPurchaseDO> lambdaQueryWrapper = new LambdaQueryWrapper<>();
        lambdaQueryWrapper.eq(OaPurchaseDO::getProcInstId, currentTask.getProcessInstanceId());
        OaPurchaseDO oaPurchase = oaPurchaseMapper.selectOne(lambdaQueryWrapper);
        // 如果是最后一个人审批同意，设置流程审批状态为已审核
        String[] auditPersons = oaPurchase.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();
        OaPurchaseDO oaPurchaseDO = new OaPurchaseDO();
        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);
            oaPurchaseDO.setAuditStatus(DictDataConstants.OA_AUDIT_STATUS_AUDITING)
                    .setCurrentAuditEmployeeId(currentAuditEmployeeId)
                    .setCurrentAuditEmployeeName(currentAuditEmployee.getName())
                    .setFinalAuditDate(LocalDateTime.now())
                    .setId(oaPurchase.getId());

        } else {
            oaPurchaseDO.setAuditStatus(DictDataConstants.OA_AUDIT_STATUS_AUDITED)
                    .setCurrentAuditEmployeeId(null)
                    .setCurrentAuditEmployeeName(null)
                    .setFinalAuditDate(LocalDateTime.now())
                    .setId(oaPurchase.getId());
        }
        oaPurchaseMapper.updateById(oaPurchaseDO);

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

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

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

        return 1L;
    }

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

        OaPurchaseDO oaPurchaseNew = BeanUtils.toBean(reCommitReqVO, OaPurchaseDO.class);
        OaPurchaseDO oaPurchaseOld = validateOaPurchaseExists(oaPurchaseNew.getId());
        oaPurchaseNew.setPurchaseUuid(oaPurchaseOld.getPurchaseUuid())
                .setProcInstId(oaPurchaseOld.getProcInstId());

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

        // 子表信息
        List<OaPurchaseObjDO> oaPurchaseObjs = reCommitReqVO.getOaPurchaseObjs();
        for (OaPurchaseObjDO oaPurchaseObj : oaPurchaseObjs) {
            if (StrUtil.isBlank(oaPurchaseObj.getName())) {
                throw exception(ErrorCodeConstants.OA_PURCHASE_OBJ_NAME_BLANK);
            }
            if (oaPurchaseObj.getAmount() == null || oaPurchaseObj.getAmount() == 0) {
                throw exception(ErrorCodeConstants.OA_PURCHASE_OBJ_AMOUNT_ZERO);
            }
        }

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

        // 保存子表信息
        if (CollectionUtil.isNotEmpty(oaPurchaseObjs)) {
            updateOaPurchaseObjList(oaPurchaseNew.getId(), oaPurchaseObjs);
        }

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

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

        OaPurchaseDO oaPurchaseDO = oaPurchaseMapper.selectById(id);
        if (!DictDataConstants.OA_AUDIT_STATUS_RETURNED.equals(oaPurchaseDO.getAuditStatus())
                && !DictDataConstants.OA_AUDIT_STATUS_RECALLED.equals(oaPurchaseDO.getAuditStatus())) {
            throw exception(ErrorCodeConstants.TASK_CLOSE_NOT_ALLOWED);
        }

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

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void deleteOaPurchase(Long id) {
        // 校验存在
        validateOaPurchaseDelete(id);
        // 删除
        oaPurchaseMapper.deleteById(id);
        // 删除子表数据
        deleteOaPurchaseObjByPurchaseId(id);
    }

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

        OaPurchaseDO oaPurchaseDO = validateOaPurchaseExists(id);
        OaPurchaseRespVO oaPurchaseRespVO = BeanUtils.toBean(oaPurchaseDO, OaPurchaseRespVO.class);
        if (oaPurchaseDO.getDeptId() != null) {
            DeptRespDTO dept = deptApi.getDept(oaPurchaseDO.getDeptId());
            if (dept != null) {
                oaPurchaseRespVO.setDeptName(dept.getName());
            }
        }
        // 职位
        if (oaPurchaseDO.getPostId() != null) {
            PostRespDTO post = postApi.getPost(oaPurchaseDO.getPostId());
            if (post != null) {
                oaPurchaseRespVO.setPosition(post.getName());
            }
        }
        // 状态
        if (StrUtil.isNotBlank(oaPurchaseDO.getAuditStatus())) {
            oaPurchaseRespVO.setAuditStatusDesc(OaAuditStatusEnum.getByStatus(oaPurchaseDO.getAuditStatus()));
        }
        // 子表数据
        List<OaPurchaseObjDO> oaPurchaseObjDOS = getOaPurchaseObjListByPurchaseId(oaPurchaseDO.getId());
        oaPurchaseRespVO.setOaPurchaseObjs(oaPurchaseObjDOS);

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

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

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

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

        return oaPurchaseRespVO;
    }

    @Override
    public OaPurchaseRespVO getOaPurchaseByProcInstId(String procInstId) {
        OaPurchaseDO oaPurchaseDO = oaPurchaseMapper.selectOne(OaPurchaseDO::getProcInstId, procInstId);
        OaPurchaseRespVO oaPurchaseRespVO = BeanUtils.toBean(oaPurchaseDO, OaPurchaseRespVO.class);
        if (oaPurchaseDO.getDeptId() != null) {
            DeptRespDTO dept = deptApi.getDept(oaPurchaseDO.getDeptId());
            if (dept != null) {
                oaPurchaseRespVO.setDeptName(dept.getName());
            }
        }

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

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

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

        return oaPurchaseRespVO;
    }

    @Override
    public PageResult<OaPurchaseRespVO> getOaPurchasePage(OaPurchasePageReqVO pageReqVO) {
        PageResult<OaPurchaseDO> oaPurchaseDOPageResult = oaPurchaseMapper.selectPage(pageReqVO);
        PageResult<OaPurchaseRespVO> oaPurchaseRespVOPageResult = BeanUtils.toBean(oaPurchaseDOPageResult, OaPurchaseRespVO.class);

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

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

            // 职位
            List<Long> postIdList = oaPurchaseRespVOList.stream().map(OaPurchaseRespVO::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 (OaPurchaseRespVO respVO : oaPurchaseRespVOList) {
                // 当前处理人
                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 oaPurchaseRespVOPageResult;
    }

    @Override
    public PageResult<OaPurchaseRespVO> exportOaPurchaseExcel(OaPurchasePageReqVO pageReqVO) {
        pageReqVO.setPageSize(PageParam.PAGE_SIZE_NONE);
        return getOaPurchasePage(pageReqVO);
    }

    private void validateOaPurchaseDelete(Long id) {
        OaPurchaseDO oaPurchaseDO = validateOaPurchaseExists(id);
        if (!DictDataConstants.OA_AUDIT_STATUS_STAGING.equals(oaPurchaseDO.getAuditStatus())) {
            throw exception(ErrorCodeConstants.DELETE_FAIL_NOT_STAGING);
        }
    }

    private OaPurchaseDO validateOaPurchaseExists(Long id) {
        OaPurchaseDO oaPurchaseDO = oaPurchaseMapper.selectById(id);
        if (oaPurchaseDO == null) {
            throw exception(OA_PURCHASE_NOT_EXISTS);
        }
        return oaPurchaseDO;
    }


    // @Resource
    // private OaPurchaseMapper oaPurchaseMapper;
    // @Resource
    // private OaPurchaseObjMapper oaPurchaseObjMapper;
    //
    // @Override
    // @Transactional(rollbackFor = Exception.class)(rollbackFor = Exception.class)
    // public Long createOaPurchase(OaPurchaseSaveReqVO createReqVO) {
    //     // 插入
    //     OaPurchaseDO oaPurchase = BeanUtils.toBean(createReqVO, OaPurchaseDO.class);
    //     oaPurchaseMapper.insert(oaPurchase);
    //
    //     // 插入子表
    //     createOaPurchaseObjList(oaPurchase.getId(), createReqVO.getOaPurchaseObjs());
    //     // 返回
    //     return oaPurchase.getId();
    // }
    //
    // @Override
    // @Transactional(rollbackFor = Exception.class)(rollbackFor = Exception.class)
    // public void updateOaPurchase(OaPurchaseSaveReqVO updateReqVO) {
    //     // 校验存在
    //     validateOaPurchaseExists(updateReqVO.getId());
    //     // 更新
    //     OaPurchaseDO updateObj = BeanUtils.toBean(updateReqVO, OaPurchaseDO.class);
    //     oaPurchaseMapper.updateById(updateObj);
    //
    //     // 更新子表
    //     updateOaPurchaseObjList(updateReqVO.getId(), updateReqVO.getOaPurchaseObjs());
    // }
    //
    // @Override
    // @Transactional(rollbackFor = Exception.class)(rollbackFor = Exception.class)
    // public void deleteOaPurchase(Long id) {
    //     // 校验存在
    //     validateOaPurchaseExists(id);
    //     // 删除
    //     oaPurchaseMapper.deleteById(id);
    //
    //     // 删除子表
    //     deleteOaPurchaseObjByPurchaseId(id);
    // }
    //
    // private void validateOaPurchaseExists(Long id) {
    //     if (oaPurchaseMapper.selectById(id) == null) {
    //         throw exception(OA_PURCHASE_NOT_EXISTS);
    //     }
    // }
    //
    // @Override
    // public OaPurchaseDO getOaPurchase(Long id) {
    //     return oaPurchaseMapper.selectById(id);
    // }
    //
    // @Override
    // public PageResult<OaPurchaseDO> getOaPurchasePage(OaPurchasePageReqVO pageReqVO) {
    //     return oaPurchaseMapper.selectPage(pageReqVO);
    // }

    // ==================== 子表（采购流程信息子表） ====================

    @Override
    public List<OaPurchaseObjDO> getOaPurchaseObjListByPurchaseId(Long purchaseId) {
        return oaPurchaseObjMapper.selectListByPurchaseId(purchaseId);
    }

    private void createOaPurchaseObjList(Long purchaseId, List<OaPurchaseObjDO> list) {
        list.forEach(o -> o.setPurchaseId(purchaseId));
        oaPurchaseObjMapper.insertBatch(list);
    }

    private void updateOaPurchaseObjList(Long purchaseId, List<OaPurchaseObjDO> list) {
        deleteOaPurchaseObjByPurchaseId(purchaseId);
		list.forEach(o -> o.setId(null).setCreator(null).setCreateTime(null).setUpdater(null).setUpdateTime(null).setDeleted(null)); // 解决更新情况下：1）id 冲突；2）updateTime 不更新
        createOaPurchaseObjList(purchaseId, list);
    }

    private void deleteOaPurchaseObjByPurchaseId(Long purchaseId) {
        oaPurchaseObjMapper.deleteByPurchaseId(purchaseId);
    }

}