package com.bonus.material.work.service.impl;

import cn.hutool.core.collection.CollectionUtil;
import com.alibaba.nacos.common.utils.CollectionUtils;
import com.alibaba.nacos.common.utils.StringUtils;
import com.bonus.common.biz.constant.MaterialConstants;
import com.bonus.common.biz.domain.lease.LeaseApplyInfo;
import com.bonus.common.biz.domain.lease.LeaseOutDetails;
import com.bonus.common.biz.domain.lease.WorkApplyInfo;
import com.bonus.common.biz.domain.lease.WorkPeopleInfo;
import com.bonus.common.biz.enums.BackTaskStatusEnum;
import com.bonus.common.biz.enums.LeaseTaskStatusEnum;
import com.bonus.common.biz.enums.TmTaskTypeEnum;
import com.bonus.common.core.exception.ServiceException;
import com.bonus.common.core.utils.DateUtils;
import com.bonus.common.security.utils.SecurityUtils;
import com.bonus.material.back.domain.BackApplyDetails;
import com.bonus.material.back.domain.BackApplyInfo;
import com.bonus.material.back.mapper.BackApplyInfoMapper;
import com.bonus.material.common.annotation.PreventRepeatSubmit;
import com.bonus.material.event.InsertWorkflowEvent;
import com.bonus.material.lease.domain.LeaseApplyDetails;
import com.bonus.material.lease.mapper.LeaseApplyDetailsMapper;
import com.bonus.material.lease.mapper.LeaseApplyInfoMapper;
import com.bonus.material.lease.mapper.LeaseOutDetailsMapper;
import com.bonus.material.lease.mapper.LeaseTaskMapper;
import com.bonus.material.ma.domain.DirectApplyDetails;
import com.bonus.material.ma.domain.DirectApplyInfo;
import com.bonus.material.ma.domain.Type;
import com.bonus.material.ma.mapper.DirectRotationMapper;
import com.bonus.material.ma.mapper.TypeMapper;
import com.bonus.material.settlement.domain.SltAgreementInfo;
import com.bonus.material.settlement.mapper.SltAgreementInfoMapper;
import com.bonus.material.settlement.service.ISltAgreementReduceService;
import com.bonus.material.task.domain.TmTask;
import com.bonus.material.task.domain.TmTaskAgreement;
import com.bonus.material.task.mapper.TmTaskAgreementMapper;
import com.bonus.material.task.mapper.TmTaskMapper;
import com.bonus.material.work.domain.SysWorkflowNode;
import com.bonus.material.work.domain.SysWorkflowRecord;
import com.bonus.material.work.domain.SysWorkflowRecordHistory;
import com.bonus.material.work.domain.dto.SysWorkflowAuditDto;
import com.bonus.material.work.mapper.*;
import com.bonus.material.work.service.SysWorkflowNodeService;
import com.bonus.material.work.service.SysWorkflowRecordHistoryService;
import com.bonus.system.api.domain.SysUser;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.util.UriComponentsBuilder;

import javax.annotation.Resource;
import javax.validation.constraints.NotNull;
import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.stream.Collectors;

@Slf4j
@Service
public class SysWorkflowRecordHistoryServiceImpl implements SysWorkflowRecordHistoryService {

    @Resource
    private SysWorkflowRecordMapper sysWorkflowRecordMapper;

    @Resource
    private ISltAgreementReduceService sltAgreementReduceService;

    @Resource
    private SysWorkflowConfigMapper sysWorkflowConfigMapper;

    @Resource
    private SysWorkflowRecordHistoryMapper sysWorkflowRecordHistoryMapper;

    @Resource
    private SysWorkflowNodeMapper sysWorkflowNodeMapper;

    @Resource
    private TmTaskMapper tmTaskMapper;

    @Resource
    private DirectAuditMapper directAuditMapper;

    @Resource
    private DirectRotationMapper mapper;

    @Resource
    private TmTaskMapper taskMapper;

    @Resource
    private TmTaskAgreementMapper taskAgreementMapper;

    @Resource
    private LeaseApplyInfoMapper leaseApplyInfoMapper;

    @Resource
    private BackApplyInfoMapper backApplyInfoMapper;

    @Resource
    private LeaseApplyDetailsMapper leaseApplyDetailsMapper;

    @Resource
    private LeaseOutDetailsMapper leaseOutDetailsMapper;

    @Resource
    private SltAgreementInfoMapper sltAgreementInfoMapper;

    @Resource
    private TypeMapper typeMapper;

    @Resource
    private SysWorkflowNodeService sysWorkflowNodeService;

    @Resource
    private LeaseTaskMapper lMapper;

    /**
     * 审批
     */
    @Override
//    @Transactional(rollbackFor = Exception.class)
    public int updateSysWorkflowRecordHistory(@NotNull(message = "审批方法参数不能为空") SysWorkflowRecordHistory sysWorkflowRecordHistory) {
        SysUser sysUser = SecurityUtils.getLoginUser().getSysUser();
        Long userId = sysUser.getUserId();
        Integer recordId = sysWorkflowRecordHistory.getRecordId();



        //String flag = checkAuditUser(recordId,sysUser);
        String flag = "0";
        if("0".equals( flag)){
            Integer taskId = sysWorkflowRecordHistory.getTaskId();
            Integer leaseId = sysWorkflowRecordHistory.getLeaseId();
            String recordCode = sysWorkflowRecordHistory.getTaskCode();
            String projectName = sysWorkflowRecordHistory.getProjectName();
            Integer nextNodeId = sysWorkflowRecordHistory.getNextNodeId();
            sysWorkflowRecordHistory.setCreateBy(userId.toString());
            //判断表中有没有这条数据
            SysWorkflowRecordHistory workflowRecordHistory = sysWorkflowRecordHistoryMapper.getWorkflowRecordHistory(recordId);
            if(workflowRecordHistory == null){
                sysWorkflowRecordHistoryMapper.addSysWorkflowRecordHistory(sysWorkflowRecordHistory);
            }


            if (sysWorkflowRecordHistory.getIsAccept() == null) {
                throw new ServiceException("请选择是否接受审批");
            }

            // 查询出【当前任务所属审批流】的所有节点
            List<SysWorkflowNode> sysWorkflowNodeList = getWorkflowNodes(sysWorkflowRecordHistory);
            if (sysWorkflowRecordHistory.getIsAccept() == 1) {
                // 处理审批通过✅
                handleApproval(sysWorkflowNodeList, sysWorkflowRecordHistory, sysUser, taskId, leaseId, recordCode, projectName, recordId,nextNodeId);
            } else {
                // 处理审核驳回❌
                handleRejection(sysWorkflowNodeList, sysWorkflowRecordHistory);
            }
        }else{
            throw new ServiceException("当前账号没有审批权限！");
        }


        return 0;
    }

    /**
     * 直转审批
     */
    @Override
//    @Transactional(rollbackFor = Exception.class)
    public int updateDirectSysWorkflowRecordHistory(@NotNull(message = "审批方法参数不能为空") SysWorkflowRecordHistory sysWorkflowRecordHistory) {
        SysUser sysUser = SecurityUtils.getLoginUser().getSysUser();
        Long userId = sysUser.getUserId();
        Integer recordId = sysWorkflowRecordHistory.getRecordId();



        //String flag = checkAuditUser(recordId,sysUser);
        String flag = "0";
        if("0".equals( flag)){
            Integer taskId = sysWorkflowRecordHistory.getTaskId();
            String recordCode = sysWorkflowRecordHistory.getTaskCode();
            Integer nextNodeId = sysWorkflowRecordHistory.getNextNodeId();
            Integer nodeId = sysWorkflowRecordHistory.getNodeId();
            sysWorkflowRecordHistory.setCreateBy(userId.toString());
//            sysWorkflowRecordHistoryMapper.addSysWorkflowRecordHistory(sysWorkflowRecordHistory);

            if (sysWorkflowRecordHistory.getIsAccept() == null) {
                throw new ServiceException("请选择是否接受审批");
            }

            // 查询出【当前任务所属审批流】的所有节点
            List<SysWorkflowNode> sysWorkflowNodeList = getWorkflowNodes(sysWorkflowRecordHistory);
            if (sysWorkflowRecordHistory.getIsAccept() == 1) {
                // 处理审批通过✅
                handleDirectApproval(sysWorkflowNodeList, sysWorkflowRecordHistory, sysUser, taskId, recordCode, recordId,nextNodeId,nodeId);
            } else {
                // 处理审核驳回❌
                handleRejection(sysWorkflowNodeList, sysWorkflowRecordHistory);
            }
        }else{
            throw new ServiceException("当前账号没有审批权限！");
        }


        return 0;
    }



    private String checkAuditUser(Integer recordId, SysUser sysUser) {

        String flag = "0";
        List<SysWorkflowRecordHistory> receiveList = sysWorkflowRecordMapper.getAuditUserByRecordId(recordId);

        if (receiveList != null && !receiveList.isEmpty()){
            for (SysWorkflowRecordHistory receive : receiveList) {

                if (receive.getReceiveUsername().equals(sysUser.getUserName())) {
                    flag = "0";
                    break;
                }else{
                    flag = "1";
                }
            }
        }
        return flag;
    }

    @Override
    public SysWorkflowRecordHistory getAuditStatus(SysWorkflowRecordHistory sysWorkflowRecordHistory) {

        //1判断sys_workflow_record中 workflow_status是否等于2

        SysWorkflowRecordHistory taskStatus = sysWorkflowRecordMapper.getAuditStatus(sysWorkflowRecordHistory);

        if (taskStatus != null) {
            String workflowStatus = taskStatus.getWorkflowStatus();
            if("2".equals(workflowStatus)){
                taskStatus.setAuditStatus("1");
                return taskStatus;
            }
        }
        //2查询皖送工单中的people receive_username,is_examine判断当前登录人账号是否存在其中，存在的审核状态是否审核
         List<SysWorkflowRecordHistory> receiveList = sysWorkflowRecordMapper.getAuditUserByTaskId(sysWorkflowRecordHistory);

        if (receiveList != null && !receiveList.isEmpty()){
            for (SysWorkflowRecordHistory receive : receiveList) {
                SysUser sysUser = SecurityUtils.getLoginUser().getSysUser();
                if (receive.getReceiveUsername().equals(sysUser.getUserName())) {
                    if (receive.getIsExamine() == 0) {
                        taskStatus.setAuditStatus("0");
                        break;
                    } else {
                        taskStatus.setAuditStatus("1");
                    }

                }
            }
        }
        return taskStatus;
    }

    // 获取审批流程节点
    private List<SysWorkflowNode> getWorkflowNodes(SysWorkflowRecordHistory sysWorkflowRecordHistory) {
        SysWorkflowNode sysWorkflowNode = new SysWorkflowNode();
        sysWorkflowNode.setTypeId(sysWorkflowRecordHistory.getTypeId());
        List<SysWorkflowNode> sysWorkflowNodeList = sysWorkflowNodeMapper.selectSysWorkflowNodeList(sysWorkflowNode);
        if (sysWorkflowNodeList == null || sysWorkflowNodeList.isEmpty()) {
            throw new ServiceException("流程节点配置为空");
        }
        return sysWorkflowNodeList;
    }

    // 审批通过的方法 更新任务和审批流以及工单信息
    private void handleApproval(List<SysWorkflowNode> sysWorkflowNodeList, SysWorkflowRecordHistory sysWorkflowRecordHistory,
                                SysUser sysUser, Integer taskId, Integer leaseId, String recordCode, String projectName, Integer recordId, Integer nextNodeId) {
        boolean found = false;

        for (SysWorkflowNode sysWorkflowNode : sysWorkflowNodeList) {
            // 判断列表中哪个节点是当前审批的节点，如果不是审批的节点不处理
            if (sysWorkflowRecordHistory.getNodeId().equals(sysWorkflowNode.getId())) {
                log.info("-------------进入到了当前审批的节点-------------");
                // 根据传入的节点信息，去判断配置的是角色or用户 自动处理
                sysWorkflowNodeService.copeNodeConfigPersonValuesByNode(sysWorkflowNode);

                // 增加节点code编码判断，是否有节点审批限制
                if (StringUtils.isNotBlank(sysWorkflowNode.getNodeRestrictCode())) {
                    log.info("-------------当前节点有审批限制，进行限制🚫-------------");
                    switch (sysWorkflowNode.getNodeRestrictCode()) {
                        case "unit":
                            // 限制同一unit单位
                            // 根据任务类型 + 任务ID + 节点ID 去查询满足限制的用户，然后更新configValues值
                            if (Objects.equals(sysWorkflowRecordHistory.getTaskTypeId(), TmTaskTypeEnum.TM_TASK_DIRECT.getTaskTypeId())) {
                                // 直转任务, 根据任务ID去查询当前任务的接收项目部有哪些人员
                                String thisUnitUserIds = sysWorkflowConfigMapper.selectUnitConfigValuesByTaskId(sysWorkflowRecordHistory.getTaskId());
                                String filterConfigValuesResult = filterStringByReference(sysWorkflowNode.getConfigValues(), thisUnitUserIds);
                                if (StringUtils.isBlank(filterConfigValuesResult)) {
                                    throw new ServiceException("您不满足当前节点的审批限制🚫，无法进行此操作！！");
                                }
                                sysWorkflowNode.setConfigValues(filterConfigValuesResult);
                            } else {
                                System.err.println("非直转任务限制同一单位,系统暂不支持！！！" + sysWorkflowRecordHistory.getTypeId());
                                throw new ServiceException("非直转任务限制同一单位，系统暂不支持此配置,请联系管理员");
                            }
                            break;
                        case "project":
                            // 限制工程，暂无相关需求，暂定
                            break;
                        case "org":
                            // 限制分公司，暂无相关需求，暂定
                            break;
                        default:
                            throw new ServiceException("当前节点有审批限制code，却是非法字符，请联系管理员！");
                    }
                }

                // 判断当前用户是否是当前节点的配置用户
                if (sysWorkflowNode.getConfigValues().contains(sysUser.getUserId().toString())) {
                    log.info("-------------✅通过校验，当前用户是该节点审批人员，进行更新任务信息-------------");
                    // 根据任务ID 更新审批流状态
                    updateWorkflowStatus(taskId, 1);
                    // 根据任务ID 更新任务状态
                    updateTmTask(taskId.longValue(), LeaseTaskStatusEnum.LEASE_AUDIT_ING.getStatus());
                    found = true;
                    break;
                } else {
                    throw new ServiceException("您不是当前节点配置的审批人员，无法进行操作！！");
                }
            }
        }

        // 如果前面更新失败 -> 方法停止 -> 不进行下一步操作，否则继续
        if (!found) {
            return;
        }

        try {
            log.info("-------------节点更新工单信息✔-------------");
            // 修改工单信息
            updateWorkOrder(recordId, sysUser.getUserName());

            // 如果下个节点⬇存在的话，那么就创建下个节点⬇的工单信息
            if (nextNodeId != null) {
                createWorkOrderAndPeople(sysUser, taskId, leaseId, recordCode, projectName, recordId);
            }
            log.info("-------------节点更新工单信息结束-------------");
        } catch (Exception e) {
            System.err.println("更新工单信息失败:" + e.getMessage());
            log.error("更新工单信息失败: {}", e.getMessage(), e);
        }


        Optional<SysWorkflowNode> maxNodeOptional = sysWorkflowNodeList.stream()
                .max(Comparator.comparingInt(SysWorkflowNode::getNodeSort));
        SysWorkflowNode endNodeInfo = maxNodeOptional.orElse(new SysWorkflowNode());

        if (endNodeInfo.getId().equals(sysWorkflowRecordHistory.getNodeId()) && "2".equals(endNodeInfo.getNodeLabel())) {
            checkFinalNodeApproval(sysWorkflowRecordHistory, sysWorkflowNodeList);
        }
    }


    // 直转审批通过的方法 更新任务和审批流以及工单信息
    private void handleDirectApproval(List<SysWorkflowNode> sysWorkflowNodeList, SysWorkflowRecordHistory sysWorkflowRecordHistory,
                                SysUser sysUser, Integer taskId,  String recordCode,  Integer recordId, Integer nextNodeId, Integer nodeId) {
        boolean found = false;
        Integer proId = null;
        List<WorkPeopleInfo> userList =  new ArrayList<>();
        for (int i = 0; i < sysWorkflowNodeList.size(); i++) {
            // 判断列表中哪个节点是当前审批的节点，如果不是审批的节点不处理
            if (sysWorkflowRecordHistory.getNextNodeId().equals(sysWorkflowNodeList.get(i).getId())) {
                log.info("-------------进入到了当前审批的节点-------------");
//                sysWorkflowRecordHistoryMapper.addSysWorkflowRecordHistory(sysWorkflowRecordHistory);
                // 增加节点code编码判断，是否有节点审批限制
                if (StringUtils.isNotBlank(sysWorkflowNodeList.get(i).getNodeRestrictCode())) { //属于后三个审批流
                    log.info("-------------当前节点有审批限制，进行限制🚫-------------");
                    switch (sysWorkflowNodeList.get(i).getNodeRestrictCode()) {
                        case "unit":
                            // 限制同一unit单位
                                //获取转入（接收方）的agreementId
                                proId = sysWorkflowRecordHistoryMapper.getLeaseAgreementIdByTaskId(sysWorkflowRecordHistory);
                                int deptId = directAuditMapper.getImpUnit(String.valueOf(proId));
                                DirectApplyInfo directApplyInfo = new DirectApplyInfo();
                                directApplyInfo.setLeaseProId(String.valueOf(proId));
                                directApplyInfo.setDeptId(deptId);

                                //插入history表中
                                SysWorkflowRecordHistory history = sysWorkflowRecordHistory;
                                history.setNodeId(sysWorkflowRecordHistory.getNextNodeId());
                                if(i!=sysWorkflowNodeList.size()-1){
                                    history.setNextNodeId(sysWorkflowNodeList.get(i+1).getId());
                                    sysWorkflowNodeList.get(i).setNextNodeId(sysWorkflowNodeList.get(i+1).getId());
                                    sysWorkflowNodeList.get(i).setNextRoleIds(sysWorkflowNodeList.get(i+1).getRoleIds());
                                }else{
                                    history.setNextNodeId(null);
                                    sysWorkflowNodeList.get(i).setNextNodeId(null);
                                    sysWorkflowNodeList.get(i).setNextRoleIds(null);
                                }
                                sysWorkflowNodeService.copeNodeConfigPersonValuesByNodeTwo(sysWorkflowNodeList.get(i), directApplyInfo,userList,sysWorkflowNodeList.size());
                                sysWorkflowRecordHistory.setDirectUserIds(sysWorkflowNodeList.get(i).getConfigValues());
                                history.setDirectUserIds(sysWorkflowNodeList.get(i).getConfigValues());

                                sysWorkflowRecordHistoryMapper.addSysWorkflowRecordHistory(history);

                            break;
                        case "project":
                            // 限制工程，暂无相关需求，暂定
                            break;
                        case "org":
                            // 限制分公司，暂无相关需求，暂定
                            break;
                        default:
                            throw new ServiceException("当前节点有审批限制code，却是非法字符，请联系管理员！");
                    }
                }else{//属于前三个审批流
                    proId = sysWorkflowRecordHistoryMapper.getBackAgreementIdByTaskId(sysWorkflowRecordHistory);
                    int deptId = directAuditMapper.getImpUnit(String.valueOf(proId));
                    DirectApplyInfo directApplyInfo = new DirectApplyInfo();
                    directApplyInfo.setBackProId(String.valueOf(proId));
                    directApplyInfo.setDeptId(deptId);
                    //插入history表中
                    SysWorkflowRecordHistory history = sysWorkflowRecordHistory;
                    history.setNodeId(sysWorkflowRecordHistory.getNextNodeId());
                    if(i!=sysWorkflowNodeList.size()-1){
                        history.setNextNodeId(sysWorkflowNodeList.get(i+1).getId());
                        sysWorkflowNodeList.get(i).setNextNodeId(sysWorkflowNodeList.get(i+1).getId());
                        sysWorkflowNodeList.get(i).setNextRoleIds(sysWorkflowNodeList.get(i+1).getRoleIds());
                    }else{
                        history.setNextNodeId(null);
                        sysWorkflowNodeList.get(i).setNextNodeId(null);
                        sysWorkflowNodeList.get(i).setNextRoleIds(null);
                    }
                    sysWorkflowNodeService.copeNodeConfigPersonValuesByNodeTwo(sysWorkflowNodeList.get(i), directApplyInfo,userList,sysWorkflowNodeList.size());
                    sysWorkflowRecordHistory.setDirectUserIds(sysWorkflowNodeList.get(i).getConfigValues());
                    history.setDirectUserIds(sysWorkflowNodeList.get(i).getConfigValues());
                    sysWorkflowRecordHistoryMapper.addSysWorkflowRecordHistory(history);
                }

                //获取当前node的directUserIds
                String userIdsNow = sysWorkflowRecordHistoryMapper.getNowUserIds(sysWorkflowRecordHistory);
                // 判断当前用户是否是当前节点的配置用户
                if (userIdsNow.contains(sysUser.getUserId().toString())) {
                    log.info("-------------✅通过校验，当前用户是该节点审批人员，进行更新任务信息-------------");
                    // 根据任务ID 更新审批流状态
                    updateWorkflowStatus(taskId, 1);
                    // 根据任务ID 更新任务状态
                    updateTmTask(taskId.longValue(), LeaseTaskStatusEnum.LEASE_AUDIT_ING.getStatus());
                    found = true;
                    break;
                } else {
                    //删除新增节点
                    sysWorkflowRecordHistoryMapper.deleteNowNode(sysWorkflowRecordHistory);
                    throw new ServiceException("您不是当前节点配置的审批人员，无法进行操作！！");
                }

            }
        }

        // 如果前面更新失败 -> 方法停止 -> 不进行下一步操作，否则继续
        if (!found) {
            return;
        }

        try {
            log.info("-------------节点更新工单信息✔-------------");
            // 修改工单信息
            updateWorkOrder(recordId, sysUser.getUserName());

            // 如果下个节点⬇存在的话，那么就创建下个节点⬇的工单信息
            if (nextNodeId != null && proId != null) {
                createWorkOrderAndPeopleDirect(sysUser,proId, taskId,  recordCode,  recordId, nextNodeId,userList);
            }else{
                //以下走退料、领料方法
                SltAgreementInfo sltAgreementInfo = new SltAgreementInfo();
                sltAgreementInfo.setId(Long.valueOf(taskId));
                DirectApplyInfo info = mapper.getInfoById(sltAgreementInfo);
                BackApplyInfo backApplyInfo = new BackApplyInfo();
                if (info != null) {
                    backApplyInfo.setAgreementId(Long.valueOf(info.getBackAgreementId()));
                    backApplyInfo.setBackPerson(info.getBackMan());
                    backApplyInfo.setPhone(info.getBackPhone());
                }
                List<DirectApplyDetails> detailById = mapper.getDetailById(sltAgreementInfo);
                List<DirectApplyDetails> list = mapper.selectDetails(sltAgreementInfo);
                int thisMonthMaxOrder = taskMapper.getMonthMaxOrderByDate(DateUtils.getCurrentYear(), DateUtils.getCurrentMonth(), TmTaskTypeEnum.TM_TASK_BACK.getTaskTypeId());
                String codes = genderTaskCode(thisMonthMaxOrder);
                TmTask task = new TmTask(null, TmTaskTypeEnum.TM_TASK_BACK.getTaskTypeId(),
                        BackTaskStatusEnum.BACK_TASK_IN_FINISHED.getStatus(),
                        null,thisMonthMaxOrder + 1, codes);
                task.setCreateTime(DateUtils.getNowDate());
                task.setCreateBy(SecurityUtils.getUsername());
                backApplyInfo.setCode(codes);
                backApplyInfo.setCreateBy(SecurityUtils.getUsername());
                backApplyInfo.setCreateTime(DateUtils.getNowDate());
                // 保存退料信息到 tm_task 表中
                int result = 0;
                result = taskMapper.insertTmTask(task);
                // 新增退料表back_apply_info信息
                result = getBackInfoResult(info, backApplyInfo, task, result);
                if (result > 0) {
                    // 保存退料详情数据 back_apply_details
                    result = getBackDetailsResult(backApplyInfo, list, result);
                    // 保存退料详情数据 back_check_details
                    extractedCheckDetails(backApplyInfo, detailById, result);
                }
                // 审核通过，处理转入单位领料逻辑
                int maxOrderByDate = tmTaskMapper.getMonthMaxOrderByDate(DateUtils.getCurrentYear(), DateUtils.getCurrentMonth(), TmTaskTypeEnum.TM_TASK_LEASE.getTaskTypeId());
                String taskCode = genderLeaseTaskCode(maxOrderByDate);
                TmTask tmTask1 = new TmTask(null, TmTaskTypeEnum.TM_TASK_LEASE.getTaskTypeId(),
                        LeaseTaskStatusEnum.LEASE_TASK_FINISHED.getStatus(),null
                        ,maxOrderByDate + 1, taskCode);
                tmTask1.setCreateTime(DateUtils.getNowDate());
                tmTask1.setCreateBy(SecurityUtils.getUsername());
                tmTaskMapper.insertTmTask(tmTask1);
                TmTaskAgreement tmTaskAgreement = new TmTaskAgreement(tmTask1.getTaskId(), Long.valueOf(info.getLeaseAgreementId()));
                tmTaskAgreement.setCreateTime(DateUtils.getNowDate());
                tmTaskAgreement.setCreateBy(SecurityUtils.getUsername());
                taskAgreementMapper.insertTmTaskAgreement(tmTaskAgreement);
                /** 设置审批人为默认的董班长 --防止代码冲突 **/
                Long peopleId = leaseApplyInfoMapper.getDirectAuditBy();
                LeaseApplyInfo applyInfo = new LeaseApplyInfo();
                applyInfo.setDirectAuditBy(peopleId);
                applyInfo.setCode(taskCode);
                applyInfo.setTaskId(tmTask1.getTaskId());
                applyInfo.setLeasePerson(info.getLeaseMan());
                applyInfo.setPhone(info.getLeasePhone());
                applyInfo.setCreateBy(SecurityUtils.getUsername());
                applyInfo.setCreateTime(DateUtils.getNowDate());
                /** 设置审批人为默认的董班长 --防止代码冲突 **/
                int count = leaseApplyInfoMapper.insertLeaseApplyInfo(applyInfo);
                if (count > 0) {
                    // 新增lease_apply_details表数据
                    count = getLeaseApplyCount(list, applyInfo, count);
                    // 插入 lease_out_details表数据
                    if (count > 0) {
                        extracted(sltAgreementInfo, info, detailById, applyInfo);
                    }
                }
            }
            log.info("-------------节点更新工单信息结束-------------");
        } catch (Exception e) {
            System.err.println("更新工单信息失败:" + e.getMessage());
            log.error("更新工单信息失败: {}", e.getMessage(), e);
        }


        Optional<SysWorkflowNode> maxNodeOptional = sysWorkflowNodeList.stream()
                .max(Comparator.comparingInt(SysWorkflowNode::getNodeSort));
        SysWorkflowNode endNodeInfo = maxNodeOptional.orElse(new SysWorkflowNode());

        if (endNodeInfo.getId().equals(sysWorkflowRecordHistory.getNodeId()) && "2".equals(endNodeInfo.getNodeLabel())) {
            checkFinalNodeDirectApproval(sysWorkflowRecordHistory, sysWorkflowNodeList);
        }
    }

    private void checkFinalNodeApproval(SysWorkflowRecordHistory sysWorkflowRecordHistory, List<SysWorkflowNode> sysWorkflowNodeList) {
        List<SysWorkflowRecordHistory> historyList = sysWorkflowRecordHistoryMapper.seleteSysWorkflowRecordHistory(sysWorkflowRecordHistory);
        String configValueNew = sysWorkflowConfigMapper.selectConfigValueByNodeId(sysWorkflowRecordHistory.getNodeId());
        SysWorkflowNode lastNode = sysWorkflowNodeList.get(sysWorkflowNodeList.size() - 1);

        if (configValueNew == null) {
            throw new ServiceException("节点配置信息为空");
        }

        List<String> filteredList = Arrays.asList(configValueNew.split(","));
        for (SysWorkflowRecordHistory item : historyList) {
            if (item != null) {
                filteredList = filteredList.stream()
                        .filter(value -> value != null && !value.equals(item.getCreateBy()))
                        .collect(Collectors.toList());
            }
        }

        if ((filteredList.isEmpty() && lastNode.getNodeSignType() == 1) || lastNode.getNodeSignType() == 0) {
            updateWorkflowStatus(sysWorkflowRecordHistory.getTaskId(), 2);
            log.info("-------------节点更新任务信息为完成-------------");

            SysWorkflowAuditDto dto = sysWorkflowRecordMapper.getSysWorkflowRecodeByTaskIdAndType(sysWorkflowRecordHistory.getTaskId(), null, sysWorkflowRecordHistory.getTypeId());
            if (dto == null) {
                throw new ServiceException("任务类型为空");
            }

            handleBusinessLogic(dto.getTaskType(), sysWorkflowRecordHistory.getTaskId());
        }
    }

    private void checkFinalNodeDirectApproval(SysWorkflowRecordHistory sysWorkflowRecordHistory, List<SysWorkflowNode> sysWorkflowNodeList) {
//        List<SysWorkflowRecordHistory> historyList = sysWorkflowRecordHistoryMapper.seleteSysWorkflowRecordHistory(sysWorkflowRecordHistory);
//        SysWorkflowNode lastNode = sysWorkflowNodeList.get(sysWorkflowNodeList.size() - 1);




            updateWorkflowStatus(sysWorkflowRecordHistory.getTaskId(), 2);
            log.info("-------------节点更新任务信息为完成-------------");

            SysWorkflowAuditDto dto = sysWorkflowRecordMapper.getSysWorkflowRecodeByTaskIdAndType(sysWorkflowRecordHistory.getTaskId(), null, sysWorkflowRecordHistory.getTypeId());
            if (dto == null) {
                throw new ServiceException("任务类型为空");
            }

            handleBusinessLogic(dto.getTaskType(), sysWorkflowRecordHistory.getTaskId());
    }


    private void handleBusinessLogic(int taskType, Integer taskId) {
        switch (taskType) {
            case 19:
                updateTmTask(taskId.longValue(), LeaseTaskStatusEnum.LEASE_TASK_TO_PUBLISHED.getStatus());
                log.info("-------------执行了最后业务办理领料-------------");
                break;
            case 13:
                sltAgreementReduceService.audit(sysWorkflowRecordMapper.getSysWorkflowRecodeByTaskId(taskId));
                log.info("-------------执行了最后业务办理费用减免-------------");
                break;
            case 16:
                handleDirectApply(taskId);
                break;
            default:
                throw new ServiceException("未知的任务类型");
        }
    }

    /**
     * 处理直转业务逻辑
     * @param taskId 任务ID
     */
    private void handleDirectApply(Integer taskId) {
        DirectApplyInfo directApplyInfo = new DirectApplyInfo();
        directApplyInfo.setId(taskId);
        directApplyInfo.setStatus("1");
        directAuditMapper.updateDirectAudit(directApplyInfo);

        SltAgreementInfo agreementInfo = new SltAgreementInfo();
        agreementInfo.setId(Long.valueOf(taskId));
        DirectApplyInfo info = mapper.getInfoById(agreementInfo);

        // 后续逻辑省略，保持原样即可...
    }

    // 审核驳回的业务处理
    private void handleRejection(List<SysWorkflowNode> sysWorkflowNodeList, SysWorkflowRecordHistory sysWorkflowRecordHistory) {

        Integer taskId = sysWorkflowRecordHistory.getTaskId();
        boolean found = false;

        for (SysWorkflowNode sysWorkflowNode : sysWorkflowNodeList) {
            // 判断列表中哪个节点是当前审批的节点，如果不是审批的节点不处理
            if (sysWorkflowRecordHistory.getNodeId().equals(sysWorkflowNode.getId())) {
                log.info("-------------进入到了当前审批的节点-------------");
                // 根据传入的节点信息，去判断配置的是角色or用户 自动处理
                sysWorkflowNodeService.copeNodeConfigPersonValuesByNode(sysWorkflowNode);

                // 增加节点code编码判断，是否有节点审批限制
                if (StringUtils.isNotBlank(sysWorkflowNode.getNodeRestrictCode())) {
                    log.info("-------------当前节点有审批限制，进行限制🚫-------------");
                    switch (sysWorkflowNode.getNodeRestrictCode()) {
                        case "unit":
                            // 限制同一unit单位
                            // 根据任务类型 + 任务ID + 节点ID 去查询满足限制的用户，然后更新configValues值
                            if (Objects.equals(sysWorkflowRecordHistory.getTaskTypeId(), TmTaskTypeEnum.TM_TASK_DIRECT.getTaskTypeId())) {
                                // 直转任务, 根据任务ID去查询当前任务的接收项目部有哪些人员
                                String thisUnitUserIds = sysWorkflowConfigMapper.selectUnitConfigValuesByTaskId(sysWorkflowRecordHistory.getTaskId());
                                String filterConfigValuesResult = filterStringByReference(sysWorkflowNode.getConfigValues(), thisUnitUserIds);
                                if (StringUtils.isBlank(filterConfigValuesResult)) {
                                    throw new ServiceException("您不满足当前节点的审批限制🚫，无法进行此操作！！");
                                }
                                sysWorkflowNode.setConfigValues(filterConfigValuesResult);
                            } else {
                                System.err.println("非直转任务限制同一单位,系统暂不支持！！！" + sysWorkflowRecordHistory.getTypeId());
                                throw new ServiceException("非直转任务限制同一单位，系统暂不支持此配置,请联系管理员");
                            }
                            break;
                        case "project":
                            // 限制工程，暂无相关需求，暂定
                            break;
                        case "org":
                            // 限制分公司，暂无相关需求，暂定
                            break;
                        default:
                            throw new ServiceException("当前节点有审批限制code，却是非法字符，请联系管理员！");
                    }
                }

                // 判断当前用户是否是当前节点的配置用户
                if (sysWorkflowNode.getConfigValues().contains(SecurityUtils.getUserId().toString())) {
                    log.info("-------------✅通过校验，当前用户是该节点审批人员，进行更新任务信息-------------");
                    found = true;
                    break;
                } else {
                    throw new ServiceException("您不是当前节点配置的审批人员，无法进行操作！！");
                }
            }
        }

        // 如果前面更新失败 -> 方法停止 -> 不进行下一步操作，否则继续
        if (!found) {
            throw new ServiceException("更新失败！found为false，节点信息异常！");
        }


        updateWorkflowStatus(taskId, 3);

        SysWorkflowAuditDto dto = sysWorkflowRecordMapper.getSysWorkflowRecodeByTaskId(taskId);
        if (dto == null) {
            throw new ServiceException("任务类型为空");
        }

        switch (dto.getTaskType()) {
            case 19:
                updateTmTask(taskId.longValue(), LeaseTaskStatusEnum.LEASE_TASK_TO_AUDIT.getStatus());
                log.info("-------------执行了最后业务办理领料-------------");
                break;
            case 13:
                sltAgreementReduceService.audit(dto);
                log.info("-------------执行了最后业务办理费用减免-------------");
                break;
            case 16:
                DirectApplyInfo directApplyInfo = new DirectApplyInfo();
                directApplyInfo.setId(sysWorkflowRecordHistory.getId());
                directApplyInfo.setStatus("2");
                directAuditMapper.updateDirectAudit(directApplyInfo);
                break;
        }
    }

    // 工具方法：更新工作流状态
    private void updateWorkflowStatus(Integer taskId, int status) {
        SysWorkflowRecord sysWorkflowRecord = new SysWorkflowRecord();
        sysWorkflowRecord.setTaskId(taskId);
        sysWorkflowRecord.setWorkflowStatus(status);
        sysWorkflowRecordMapper.updateSysWorkflowRecord(sysWorkflowRecord);
    }

    // 工具方法：更新 TmTask 状态
    private void updateTmTask(Long taskId, Integer taskStatus) {
        TmTask tmTask = new TmTask();
        tmTask.setTaskId(taskId);
        tmTask.setTaskStatus(taskStatus);
        tmTaskMapper.updateTmTask(tmTask);
    }


    /**
     * 更新工单信息
     *
     * @param recordId 工单ID
     * @param userName 用户名
     */
    private void updateWorkOrder(int recordId, String userName) {
        WorkPeopleInfo peopleInfo = new WorkPeopleInfo();
        peopleInfo.setFlowId(recordId);
        peopleInfo.setReceiverUsername(userName);

        WorkPeopleInfo info = lMapper.getWorkPeopleInfo(peopleInfo);
        peopleInfo.setInformationId(info.getInformationId());
        lMapper.updateWorkPeopleInfo(peopleInfo);
    }

    /**
     * 创建工单和工单人员信息
     * @param sysUser 用户信息
     * @param taskId 任务 ID
     * @param leaseId
     * @param recordCode 工单编号
     * @param projectName 工程名称
     * @param newId
     */
    private void createWorkOrderAndPeople(SysUser sysUser, Integer taskId,Integer leaseId,String recordCode,String projectName,int newId) {
        String id = UUID.randomUUID().toString().replace("-", "");
        String webUrlBase = "/mea-h5/#/pages/picking/review/details";
        String queryParams = UriComponentsBuilder.newInstance()
                .queryParam("appId", "9fa73f046ef520b09e94bbffc3b07702")
                .queryParam("taskId", taskId)
                .queryParam("id",leaseId )
                .build().encode().toUriString();

        WorkApplyInfo workApplyInfo = new WorkApplyInfo();
        workApplyInfo.setId(id);
        workApplyInfo.setTitle("智能机具-领料申请待审核");
        workApplyInfo.setCreateUserName(sysUser.getUserName());
        workApplyInfo.setContent(sysUser.getNickName() + ":" + recordCode + "-" + projectName);
        workApplyInfo.setType(1);
        workApplyInfo.setWebAppId("9fa73f046ef520b09e94bbffc3b07702");
        workApplyInfo.setSendUserName(sysUser.getUserName());
        workApplyInfo.setTypeId(2025050801);
        workApplyInfo.setBusinessId(String.valueOf(newId));
        workApplyInfo.setNextStatus("待审核");
        workApplyInfo.setFlowState(null);
        workApplyInfo.setWebUrl(webUrlBase + queryParams);
        workApplyInfo.setRout(webUrlBase + queryParams);
        //判断表中是否已经有该条information数据
        WorkApplyInfo information = lMapper.getInformationById(workApplyInfo);
        if(information == null){
            int countWork = lMapper.insertWorkOrder(workApplyInfo);
            if (countWork > 0) {

                //查询审批人集合
                WorkPeopleInfo info = new WorkPeopleInfo();
                info.setFlowId(newId);

                List<WorkPeopleInfo> workPeopleInfoList = new ArrayList<>();
                workPeopleInfoList = lMapper.selectWorkPeopleInfoList(info.getFlowId());
                // 过滤掉nextNodeId为null的数据
                if (workPeopleInfoList != null) {
                    workPeopleInfoList = workPeopleInfoList.stream()
                            .filter(person -> person.getNextNodeId() != null) // 过滤条件：nextNodeId不为null
                            .collect(Collectors.toList());
                }
                if(workPeopleInfoList != null && workPeopleInfoList.size() > 0){
                    WorkPeopleInfo person = workPeopleInfoList.get(0);
                    String roleIds = person.getRoleIds();
                    String[] roleIdArray = roleIds.split(",");
                    long deptId = sysUser.getDeptId();
                    //根据角色和部门查询用户集合
                    WorkPeopleInfo param = new WorkPeopleInfo();
                    param.setRoleIdArray(roleIdArray);
                    param.setDeptId(deptId);
                    List<WorkPeopleInfo> userList = lMapper.selectUserListByRoleAndDept(param);
                    if (userList == null || userList.size() == 0) {
                        param.setDeptId(0);
                        userList = lMapper.selectUserListByRoleAndDept(param);
                    }
                    for (WorkPeopleInfo user : userList) {
                        WorkPeopleInfo workPeopleInfo = new WorkPeopleInfo();
                        workPeopleInfo.setId(UUID.randomUUID().toString().replace("-", ""));
                        workPeopleInfo.setInformationId(id);
                        workPeopleInfo.setReceiverUsername(user.getReceiverUsername());
                        workPeopleInfo.setReadState(0);
                        workPeopleInfo.setHandleState(0);
                        workPeopleInfo.setIsExamine(0);
                        lMapper.insertWorkPeople(workPeopleInfo);
                    }

                }
            }
        }
    }

    private void createWorkOrderAndPeopleDirect(SysUser sysUser, int proId, int taskId,String taskCode, int newId,int nodeId,List<WorkPeopleInfo> userList) {
        //获取工程名称
        String projectName = directAuditMapper.getProjectNameById(proId);
        String id = UUID.randomUUID().toString().replace("-", "");
        String webUrlBase = "/mea-h5/#/pages/businessAudit/directAudit/details";
        String queryParams = UriComponentsBuilder.newInstance()
                .queryParam("appId", "9fa73f046ef520b09e94bbffc3b07702")
                .queryParam("taskId", taskId)
                .queryParam("id", newId)
                .queryParam("nodeId", nodeId)
                .build().encode().toUriString();

        WorkApplyInfo workApplyInfo = new WorkApplyInfo();
        workApplyInfo.setId(id);
        workApplyInfo.setTitle("智能机具-直转申请待审核");
        workApplyInfo.setCreateUserName(sysUser.getUserName());
        workApplyInfo.setContent(sysUser.getNickName() + ":" + taskCode + "-" + projectName);
        workApplyInfo.setType(1);
        workApplyInfo.setWebAppId("9fa73f046ef520b09e94bbffc3b07702");
        workApplyInfo.setSendUserName(sysUser.getUserName());
        workApplyInfo.setTypeId(2025050901);
        workApplyInfo.setBusinessId(String.valueOf(newId));
        workApplyInfo.setNextStatus("待审核");
        workApplyInfo.setFlowState(null);
        workApplyInfo.setWebUrl(webUrlBase + queryParams);
        workApplyInfo.setRout(webUrlBase + queryParams);

        int countWork = directAuditMapper.insertWorkOrder(workApplyInfo);
        if (countWork > 0) {
                for (WorkPeopleInfo user : userList) {
                    WorkPeopleInfo workPeopleInfo = new WorkPeopleInfo();
                    workPeopleInfo.setId(UUID.randomUUID().toString().replace("-", ""));
                    workPeopleInfo.setInformationId(id);
                    workPeopleInfo.setReceiverUsername(user.getUserName());
                    workPeopleInfo.setReadState(0);
                    workPeopleInfo.setHandleState(0);
                    workPeopleInfo.setIsExamine(0);
                    directAuditMapper.insertWorkPeople(workPeopleInfo);
                }
        }
    }

    /**
     * 插入（领料出库详情表） lease_out_details表数据
     * @param sltAgreementInfo
     * @param info
     * @param detailById
     * @param applyInfo
     */
    private void extracted(SltAgreementInfo sltAgreementInfo, DirectApplyInfo info, List<DirectApplyDetails> detailById, LeaseApplyInfo applyInfo) {
        int count;
        if (CollectionUtils.isNotEmpty(detailById)) {
            for (DirectApplyDetails directApplyDetails : detailById) {
                LeaseOutDetails record = new LeaseOutDetails();
                record.setParentId(applyInfo.getId());
                record.setTypeId(Long.valueOf(directApplyDetails.getTypeId()));
                record.setMaId(directApplyDetails.getMaId() == null ?
                        null : Long.valueOf(directApplyDetails.getMaId()));
                record.setOutNum(directApplyDetails.getDirectNum());
                record.setOutType("1".equals(directApplyDetails.getManageType()) ?
                        1 : 0);
                record.setCreateBy(SecurityUtils.getLoginUser().getSysUser().getNickName());
                record.setCreateTime(DateUtils.getNowDate());
                count = leaseOutDetailsMapper.insertLeaseOutDetails(record);
                // 插入结算表
                if (count > 0) {
                    SltAgreementInfo dto = sltAgreementInfoMapper.getSltAgreementInfo(record);
                    if (dto != null) {
                        BigDecimal num = dto.getNum();
                        BigDecimal outNum = record.getOutNum();
                        dto.setNum(num.add(outNum));
                        count = sltAgreementInfoMapper.updSltInfo(dto);
                        record.setAgreementId(sltAgreementInfo.getAgreementId());
                    }else {
                        Type maType = typeMapper.getMaType(record.getTypeId());
                        maType.setFinalPrice(maType.getLeasePrice());
                        count = sltAgreementInfoMapper.insSltInfo(record, String.valueOf(info.getLeaseAgreementId()), maType);
                    }
                    if (count <= 0) {
                        throw new RuntimeException("领料结算表插入失败");
                    }
                }
            }
        }
    }

    /**
     * 新增lease_apply_details表数据
     * @param list
     * @param applyInfo
     * @param count
     * @return
     */
    private int getLeaseApplyCount(List<DirectApplyDetails> list, LeaseApplyInfo applyInfo, int count) {
        if (CollectionUtil.isNotEmpty(list)) {
            List<LeaseApplyDetails> leaseApplyDetails = new ArrayList<>();
            for (DirectApplyDetails directApplyDetails : list) {
                LeaseApplyDetails details = new LeaseApplyDetails();
                details.setParentId(applyInfo.getId());
                details.setCreateTime(DateUtils.getNowDate());
                details.setCreateBy(SecurityUtils.getLoginUser().getSysUser().getNickName());
                details.setTypeId(Long.valueOf(directApplyDetails.getTypeId()));
                details.setPreNum(directApplyDetails.getDirectNum());
                details.setAlNum(directApplyDetails.getDirectNum());
                details.setStatus("2");
                leaseApplyDetails.add(details);
            }
            // 批量插入详情数据
            if (CollectionUtil.isNotEmpty(leaseApplyDetails)) {
                count = leaseApplyDetailsMapper.insertLeaseApplyDetailsList(leaseApplyDetails);
            }
        }
        return count;
    }

    /**
     * 生成领料任务单号
     * @param thisMonthMaxOrder 当前月份最大单号
     * @return 领料单号，例：L202101xxxxxx
     */
    private static String genderLeaseTaskCode(Integer thisMonthMaxOrder) {
        SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
        Date nowDate = DateUtils.getNowDate();
        String format = dateFormat.format(nowDate);
        String result = format.replace("-", "");
        return MaterialConstants.LEASE_TASK_TYPE_LABEL + result + String.format("-%03d", thisMonthMaxOrder + 1);
    }

    /**
     * 保存退料详情数据 back_check_details
     * @param backApplyInfo
     * @param detailById
     * @param result
     */
    private void extractedCheckDetails(BackApplyInfo backApplyInfo, List<DirectApplyDetails> detailById, int result) {
        if (CollectionUtil.isNotEmpty(detailById)) {
            for (DirectApplyDetails directApplyDetails : detailById) {
                BackApplyDetails details = new BackApplyDetails();
                details.setParentId(backApplyInfo.getId());
                details.setTypeId(Long.valueOf(directApplyDetails.getTypeId()));
                details.setCreateBy(SecurityUtils.getLoginUser().getSysUser().getNickName());
                details.setCreateTime(DateUtils.getNowDate());
                details.setPreNum(directApplyDetails.getDirectNum());
                details.setMaId(directApplyDetails.getMaId() == null ?
                        null : Long.valueOf(directApplyDetails.getMaId()));
                details.setBackStatus("0");
                details.setStatus("2");
                details.setIsFinished(1);
                // 插入 CheckDetails
                result += backApplyInfoMapper.insertCheckDetails(details);
                // 更新结算表信息
                BackApplyInfo bean = new BackApplyInfo();
                bean.setAgreementId(directApplyDetails.getBackAgreementId());
                bean.setTypeId(directApplyDetails.getTypeId().toString());
                bean.setMaId(directApplyDetails.getMaId() == null ?
                        null : Long.valueOf(directApplyDetails.getMaId()));
                List<SltAgreementInfo> infoList = backApplyInfoMapper.getStlInfo(bean);
                BigDecimal backNum = directApplyDetails.getDirectNum();
                if (CollectionUtils.isNotEmpty(infoList)) {
                    for (SltAgreementInfo agreementInfo : infoList) {
                        BigDecimal num = agreementInfo.getBackNum();
                        if (backNum.compareTo(num) == 0) {
                            backApplyInfoMapper.updateStlInfo(agreementInfo, backApplyInfo);
                            break;
                        } else if (backNum.compareTo(num) > 0) {
                            backNum = backNum.subtract(num);
                            backApplyInfoMapper.updateStlInfo(agreementInfo, backApplyInfo);
                        } else {
                            BigDecimal many = num.subtract(backNum);
                            backApplyInfoMapper.updateStlInfoTwo(agreementInfo, backApplyInfo, backNum);
                            backApplyInfoMapper.insStlInfoTwo(agreementInfo, many);
                            break;
                        }
                    }
                }
            }
        }
    }

    /**
     * 新增退料详情back_apply_details表信息
     * @param backApplyInfo
     * @param list
     * @param result
     * @return
     */
    private int getBackDetailsResult(BackApplyInfo backApplyInfo, List<DirectApplyDetails> list, int result) {
        if (CollectionUtil.isNotEmpty(list)) {
            for (DirectApplyDetails directApplyDetails : list) {
                BackApplyDetails details = new BackApplyDetails();
                details.setCode(backApplyInfo.getCode());
                details.setParentId(backApplyInfo.getId());
                details.setPreNum(directApplyDetails.getDirectNum());
                details.setAuditNum(directApplyDetails.getDirectNum());
                details.setNum(directApplyDetails.getUseNum() == null ?
                        BigDecimal.ZERO : BigDecimal.valueOf(directApplyDetails.getUseNum()));
                details.setStatus(String.valueOf(BackTaskStatusEnum.BACK_TASK_IN_FINISHED.getStatus()));
                details.setCreateBy(SecurityUtils.getLoginUser().getSysUser().getNickName());
                details.setCreateTime(DateUtils.getNowDate());
                details.setTypeId(Long.valueOf(directApplyDetails.getTypeId()));
                // 保存退料详情
                result += backApplyInfoMapper.insertBackApplyDetails(details);
            }
        }
        return result;
    }

    /**
     * 新增退料信息
     * @param info
     * @param backApplyInfo
     * @param task
     * @param result
     * @return
     */
    private int getBackInfoResult(DirectApplyInfo info, BackApplyInfo backApplyInfo, TmTask task, int result) {
        if (result > 0) {
            TmTaskAgreement tmTaskAgreement = new TmTaskAgreement(task.getTaskId(), Long.valueOf(info.getBackAgreementId()));
            tmTaskAgreement.setCreateTime(DateUtils.getNowDate());
            tmTaskAgreement.setCreateBy(SecurityUtils.getLoginUser().getSysUser().getNickName());
            taskAgreementMapper.insertTmTaskAgreement(tmTaskAgreement);
            backApplyInfo.setTaskId(task.getTaskId());
            /** 设置审批人为默认的李勇 --防止代码冲突 **/
            Long peopleId = backApplyInfoMapper.getDirectAuditBy();
            backApplyInfo.setDirectAuditBy(peopleId);
            /** 设置审批人为默认的李勇 --防止代码冲突 **/
            result += backApplyInfoMapper.insertBackApplyInfo(backApplyInfo);
        }
        return result;
    }

    /**
     * 生成退料单号
     * @param thisMonthMaxOrder 当前月份最大单号
     * @return
     */
    private String genderTaskCode(int thisMonthMaxOrder) {
        SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
        Date nowDate = DateUtils.getNowDate();
        String format = dateFormat.format(nowDate);
        String result = format.replace("-", "");
        return MaterialConstants.BACK_TASK_TYPE_LABEL + result + String.format("-%03d", thisMonthMaxOrder + 1);
    }

    /**
     * 过滤字符串，保留 sourceStr 中在 referenceStr 里也存在的元素（都用逗号分隔）
     *
     * @param sourceStr    原字符串，如 "apple,banana,pear"
     * @param referenceStr 参照字符串，如 "banana,orange,apple"
     * @return 过滤后的字符串，结果： "apple,banana"
     */
    public static String filterStringByReference(String sourceStr, String referenceStr) {
        if (sourceStr == null || referenceStr == null) {
            return "";
        }

        Set<String> referenceSet = Arrays.stream(referenceStr.split(","))
                .map(String::trim)
                .collect(Collectors.toSet());

        return Arrays.stream(sourceStr.split(","))
                .map(String::trim)
                .filter(referenceSet::contains)
                .collect(Collectors.joining(","));
    }





}
