package com.ruoyi.cs.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.util.IdUtil;
import com.alibaba.fastjson.JSON;
import com.ruoyi.common.core.domain.entity.SysRole;
import com.ruoyi.common.core.domain.entity.SysUser;
import com.ruoyi.common.enums.ServiceResponseEnum;
import com.ruoyi.common.exception.ServiceException;
import com.ruoyi.common.utils.DateUtils;
import com.ruoyi.common.utils.SecurityUtils;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.cs.domain.*;
import com.ruoyi.cs.domain.dto.*;
import com.ruoyi.cs.domain.vo.CsApprovalConfigFlowVO;
import com.ruoyi.cs.domain.vo.CsApprovalConfigNodeInfoVO;
import com.ruoyi.cs.domain.vo.CsApprovalRecordVO;
import com.ruoyi.cs.mapper.CsApprovalConfigMapper;
import com.ruoyi.cs.mapper.CsApprovalInfoMapper;
import com.ruoyi.cs.mapper.CsResourceOrderApplyMapper;
import com.ruoyi.cs.service.*;
import com.ruoyi.system.domain.vo.SysUserSelectVO;
import com.ruoyi.system.service.ISysRoleService;
import com.ruoyi.system.service.ISysUserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;
import org.springframework.util.ObjectUtils;

import javax.annotation.Resource;
import java.util.*;
import java.util.stream.Collectors;

/**
 * 审核流程节点规则配置Service业务层处理
 *
 * @author cc
 * @date 2024-04-30
 */
@Service
public class CsApprovalConfigServiceImpl implements ICsApprovalConfigService
{
    @Resource
    private CsApprovalConfigMapper csApprovalConfigMapper;

    @Resource
    private ISysRoleService roleService;

    @Resource
    private ISysUserService sysUserService;

    @Resource
    private ICsApprovalInfoService approvalInfoService;

    @Resource
    private ICsResourceOrderApplyService resourceOrderApplyService;

    @Resource
    private ICsApprovalRecordService approvalRecordService;

    @Resource
    private ICsApprovalCarbonCopyService approvalCarbonCopyService;

    @Autowired
    private ISysUserService userService;

    @Resource
    private CsApprovalInfoMapper csApprovalInfoMapper;

    @Resource
    private CsResourceOrderApplyMapper csResourceOrderApplyMapper;


    /**
     * 查询审核流程节点规则配置
     *
     * @param approvalConfigId 审核流程节点规则配置主键
     * @return 审核流程节点规则配置
     */
    @Override
    public CsApprovalConfig selectCsApprovalConfigByApprovalConfigId(String approvalConfigId)
    {
        return csApprovalConfigMapper.selectCsApprovalConfigByApprovalConfigId(approvalConfigId);
    }

    /**
     * 查询审核流程节点规则配置列表
     *
     * @param csApprovalConfig 审核流程节点规则配置
     * @return 审核流程节点规则配置
     */
    @Override
    public List<CsApprovalConfig> selectCsApprovalConfigList(CsApprovalConfig csApprovalConfig)
    {
        return csApprovalConfigMapper.selectCsApprovalConfigList(csApprovalConfig);
    }

    /**
     * 新增审核流程节点规则配置
     *
     * @param csApprovalConfig 审核流程节点规则配置
     * @return 结果
     */
    @Override
    public int insertCsApprovalConfig(CsApprovalConfig csApprovalConfig)
    {
        csApprovalConfig.setCreateTime(DateUtils.getNowDate());
        return csApprovalConfigMapper.insertCsApprovalConfig(csApprovalConfig);
    }

    /**
     * 修改审核流程节点规则配置
     *
     * @param csApprovalConfig 审核流程节点规则配置
     * @return 结果
     */
    @Override
    public int updateCsApprovalConfig(CsApprovalConfig csApprovalConfig)
    {
        return csApprovalConfigMapper.updateCsApprovalConfig(csApprovalConfig);
    }

    /**
     * 批量删除审核流程节点规则配置
     *
     * @param approvalConfigIds 需要删除的审核流程节点规则配置主键
     * @return 结果
     */
    @Override
    public int deleteCsApprovalConfigByApprovalConfigIds(String[] approvalConfigIds)
    {
        return csApprovalConfigMapper.deleteCsApprovalConfigByApprovalConfigIds(approvalConfigIds);
    }

    /**
     * 删除审核流程节点规则配置信息
     *
     * @param approvalConfigId 审核流程节点规则配置主键
     * @return 结果
     */
    @Override
    public int deleteCsApprovalConfigByApprovalConfigId(String approvalConfigId)
    {
        return csApprovalConfigMapper.deleteCsApprovalConfigByApprovalConfigId(approvalConfigId);
    }

    /**
     * 新增审核流程节点规则配置信息
     * @param dto 节点规则配置信息
     * @return
     */
    @Override
    @Transactional(rollbackFor = {Exception.class})
    public int insertCsApprovalConfigByAddDTO(CsApprovalConfigAddDTO dto) {
        String formId = dto.getFormId();
        String formType = dto.getFormType();
        String carbonCopyRecipients = dto.getCarbonCopyRecipients();
        List<CsApprovalConfigNodeInfoDTO> nodeList = dto.getNodeList();//审核列表
        Date now = new Date();


        CsResourceOrderApply csResourceOrderApply = resourceOrderApplyService.selectCsResourceOrderApplyByApplyId(formId);
        if(ObjectUtils.isEmpty(csResourceOrderApply) || !csResourceOrderApply.getApplyType().equals(formType)){
            throw new ServiceException(ServiceResponseEnum.RESOURCE_APPLY_NOT_FIND);
        }
        //资源工单状态验证

        if(!csResourceOrderApply.getApplyStatus().equals("6")){
            throw new ServiceException(ServiceResponseEnum.RESOURCE_APPLY_CANNOT_APPROVAL_WITH_STATUS);
        }
        if(formType.equals("0")){
            //删除之前已经分配过的审核流程 config info record copy(抄送暂时不删)
            int coverApprovalConfig = csApprovalConfigMapper.deleteCoverApprovalConfigsByApplyIdType(formId, formType);
            int coverApprovalInfo = approvalInfoService.deleteCoverApprovalInfoByApplyIdType(formId, formType);
            int coverApprovalRecord = approvalRecordService.deleteCoverApprovalRecordByApplyIdType(formId, formType);
            int coverApprovalCopy  = approvalCarbonCopyService.deleteCopys(formId, formType);
        }

        csResourceOrderApply.setApplyStatus("7");
        csResourceOrderApply.setUpdateAt(now);
        int updateApply = resourceOrderApplyService.updateCsResourceOrderApply(csResourceOrderApply);

        CsApprovalConfig model = new CsApprovalConfig();
        model.setFormId(formId);
        model.setFormType(formType);
        model.setApprovalAutoPass(0);
        model.setCareOf(1);
        //抄送人userId数组
        if(StringUtils.isNotBlank(carbonCopyRecipients)){
            model.setCurrentNodeApproverType(3);
            model.setCarbonCopyRecipients(carbonCopyRecipients);
            // model.setNodeType("1");
        }
        model.setCreateTime(now);
        model.setDelFlag("0");
        String groupId = IdUtil.getSnowflakeNextIdStr();
        model.setGroupId(groupId);
        List<CsApprovalConfig> configs = new ArrayList<>();
        //去重
  /*      if (!CollectionUtils.isEmpty(nodeList)){
            List<CsApprovalConfigNodeInfoDTO> nodeInfLList = new ArrayList<>();
            List<Long> userIdList = new ArrayList<>();
            for (int i = 0; i < nodeList.size(); i++) {
                CsApprovalConfigNodeInfoDTO csApprovalConfigNodeInfoDTO = nodeList.get(i);
                if (csApprovalConfigNodeInfoDTO.getCurrentNodeApprover() != null){

                }
            }
            List<CsApprovalConfigNodeInfoDTO> collect = nodeList.stream().filter(o ->o.getRoleId().equals(107L)&&o.getCurrentNodeApproverType().equals(3)).collect(Collectors.toList());
            nodeList.removeIf(nodeInfoDTO -> nodeInfoDTO.getRoleId() == 107L);
            ArrayList<CsApprovalConfigNodeInfoDTO> collected = collect.stream().collect(Collectors.collectingAndThen(Collectors.toCollection(() -> new TreeSet<>(Comparator.comparing(CsApprovalConfigNodeInfoDTO::getCurrentNodeApprover))), ArrayList::new));
            if (!CollectionUtils.isEmpty(nodeList)&&!CollectionUtils.isEmpty(collected)){
                nodeList.addAll(collected);
            }

        }*/
        buildApproval(configs, nodeList, model );
        //新增发起-发起人
        CsApprovalConfig startPerson = configs.get(0);
        approvalInfoService.insertInfo(startPerson);
        configs.remove(startPerson);
        //批量新增configs
        if (!CollectionUtils.isEmpty(configs)){
            return csApprovalConfigMapper.batchInsertConfigs(configs);
        }
        return 1;
    }

    /**
     * 构建审核链表基础信息
     * @param nodeList 节点列表
     * @param model 模板Bean
     * @param configs 结果集
     */
    private List<CsApprovalConfig> buildApproval(List<CsApprovalConfig> configs, List<CsApprovalConfigNodeInfoDTO> nodeList, CsApprovalConfig model){
        if(CollectionUtils.isEmpty(nodeList)){
          throw new ServiceException(ServiceResponseEnum.APPROVAL_ADD_LIST_IS_NULL);
        }
        nodeList.removeIf(nodeInfoDTO -> nodeInfoDTO.getCurrentNodeApprover() == null);
        nodeList = nodeList.stream().sorted(Comparator.comparing(CsApprovalConfigNodeInfoDTO::getSort)).collect(Collectors.toList());

        Long index = 0L;
        for (CsApprovalConfigNodeInfoDTO node : nodeList) {
            CsApprovalConfig config = new CsApprovalConfig();
            config = BeanUtil.toBean(model, CsApprovalConfig.class);
            config.setApprovalConfigId(IdUtil.getSnowflakeNextIdStr());
            //审批人类型
            Integer currentNodeApproverType = node.getCurrentNodeApproverType();
            Long currentNodeApprover = node.getCurrentNodeApprover();
            config.setCurrentNodeApproverType(currentNodeApproverType);
            config.setCurrentNodeApprover(currentNodeApprover);//用户ID

            config.setRoleId(node.getRoleId());
            if(null != node.getRoleId()) {
                SysRole sysRole = roleService.selectRoleById(node.getRoleId());
                if(!ObjectUtils.isEmpty(sysRole)){
                    config.setRoleName(sysRole.getRoleName());
                }
            }
            if(currentNodeApproverType != 2){
                SysUser sysUser = sysUserService.selectUserById(currentNodeApprover);
                if(!ObjectUtils.isEmpty(sysUser)){
                    config.setUserName(sysUser.getNickName());
                }
            }

            if(node.getNodeType().equals("0")){//审核流
                config.setApprovalType(2);//串行
                config.setNodeType("0");
            }else if(node.getNodeType().equals("2")){
                config.setApprovalType(1);//并行
                config.setNodeType("2");
            }

            SysUser sysUser = sysUserService.selectUserById(currentNodeApprover);

            if((!node.getNodeType().equals("2")) || (!ObjectUtils.isEmpty(sysUser) && sysUser.getIsLeader().equals("0") && node.getNodeType().equals("2"))){
                config.setApprovalNode(index++);

                configs.add(config);
            }

        }
        return configs;
    }


    /**
     * 获取工单流程、 审核信息列表
     * @param csApprovalConfig
     * @return
     */
    @Override
    public CsApprovalConfigFlowVO getOrderApprovalInfoList(CsApprovalConfig csApprovalConfig) {
        String formId = csApprovalConfig.getFormId();
        String formType = csApprovalConfig.getFormType();


        // select * from cs_resource_order_apply where apply_id
        CsResourceOrderApply csResourceOrderApply = resourceOrderApplyService.selectCsResourceOrderApplyByApplyId(formId);
        if(ObjectUtils.isEmpty(csResourceOrderApply) || !csResourceOrderApply.getApplyType().equals(formType)){
                throw new ServiceException(ServiceResponseEnum.RESOURCE_APPLY_NOT_FIND);
        }



        //审核流程  List<CsApprovalConfigNodeInfoVO>
        List<CsApprovalConfigNodeInfoVO> checkList = csApprovalConfigMapper.getFlowList(formId, formType, "('0')");
        //抄送人列表
        List<CsApprovalConfigNodeInfoVO> copyFlowNodeListInfo = new ArrayList<>();
        String cpoyUserIds = csApprovalConfigMapper.getCpoyUserIds(formId, formType);
        if(StringUtils.isNotBlank(cpoyUserIds)){
            List<String> cpoyUidList = Arrays.asList(cpoyUserIds.split(","));
            copyFlowNodeListInfo = csApprovalConfigMapper.getCopyFlowNodeListInfo(cpoyUidList);
        }

        //执行流程
        List<CsApprovalConfigNodeInfoVO> actionList = csApprovalConfigMapper.getFlowList(formId, formType, "('2','3')");

        //审批列表
        Long userId = SecurityUtils.getUserId();
        // Long userId = 1L;
        List<CsApprovalRecordVO> checkFormList = csApprovalConfigMapper.getCheckFormList(formId, formType, userId);
        //记录最后一个待审核执行节点

        CsApprovalConfig lastNode = csApprovalConfigMapper.selectIsLastNodeCsApprovalConfigAccept(formId);
        if (!ObjectUtils.isEmpty(lastNode)) {
            for (CsApprovalRecordVO approvalRecordVO : checkFormList) {
                if (Objects.equals(approvalRecordVO.getApprovalConfigId(), lastNode.getApprovalConfigId())) {
                    approvalRecordVO.setIsLastNode(1);
                    if (approvalRecordVO.getApproverResult() != null && approvalRecordVO.getApproverResult() == 1) {
                        approvalRecordVO.setToCloseApply(1);
                    }
                }
            }
        }

        if(!CollectionUtils.isEmpty(checkFormList)) {
            //最后执行节点:唯一没有记录的执行节点
            List<CsApprovalRecordVO> unRecordNodeList = checkFormList.stream()
                    .filter(form ->
                            form.getNodeType().equals("2")
                            &&
                            StringUtils.isBlank(form.getApprovalRecordId())
                    ).collect(Collectors.toList());
            if (!CollectionUtils.isEmpty(unRecordNodeList)) {
                //唯一
                if (!CollectionUtils.isEmpty(unRecordNodeList) && unRecordNodeList.size() == 1) {
                    String lastNodeConfigId = unRecordNodeList.get(0).getApprovalConfigId();
                    checkFormList = checkFormList.stream().map(form -> {
                        if (form.getApprovalConfigId().equals(lastNodeConfigId)) {
                            CsApprovalRecordVO newForm = new CsApprovalRecordVO();
                            newForm = BeanUtil.toBean(form, CsApprovalRecordVO.class);
                            newForm.setIsLastNode(1);
                            return newForm;
                        } else {
                            return form;
                        }
                    }).collect(Collectors.toList());
                }
            }

            /** 附件数组 json转数组*/
            checkFormList = checkFormList.stream().map(form -> {
                String urlJson = form.getAccessoryUrlJson();
                if (StringUtils.isNotBlank(urlJson)) {
                    List<FileJsonObj> sqlList = JSON.parseArray(urlJson, FileJsonObj.class);
                    form.setAccessoryUrl(sqlList);
                }
                return form;
            }).collect(Collectors.toList());

        }


        CsApprovalConfigFlowVO result = new CsApprovalConfigFlowVO();
        List<CsApprovalConfigNodeInfoVO> nodeList = new ArrayList<>();
        nodeList.addAll(checkList);
        nodeList.addAll(copyFlowNodeListInfo);
        nodeList.addAll(actionList);
        CsApprovalInfo csApprovalInfo1 = approvalInfoService.selectCsApprovalInfoByFormId(formId);
        if (csApprovalInfo1 != null) {
            result.setUser(sysUserService.selectUserById(csApprovalInfo1.getUserId()));
            result.setCheckInfo(csApprovalInfo1);
        }

        result.setNodeList(nodeList);
        /*List<CsApprovalRecordVO> newCheckFormList = new ArrayList<>();
        if(checkFormList.get(checkFormList.size() - 1).getApproverResult() != null && checkFormList.get(checkFormList.size() - 1).getApproverResult() == 1){
            newCheckFormList.add(checkFormList.get(checkFormList.size() - 1));
        }
        for(int i = 0;i < checkFormList.size();i++){
            if(!checkList(newCheckFormList,checkFormList.get(i).getApprovalInfoId())){// 如果不包含，则加入
                newCheckFormList.add(checkFormList.get(i));
            }
        }
        newCheckFormList = newCheckFormList.stream().sorted(Comparator.comparing(CsApprovalRecordVO::getApproverTime,Comparator.nullsLast(Comparator.naturalOrder()))).collect(Collectors.toList());*/
        result.setCheckList(checkFormList);
        result.setAcceptanceList(actionList);

        if (checkFormList.size() > 0) {
            String approvalInfoId = "";
            for (CsApprovalRecordVO approvalRecordVO : checkFormList) {
                CsApprovalInfo csApprovalInfo = approvalInfoService.selectCsApprovalInfoByApprovalConfigId(approvalRecordVO.getApprovalConfigId());
                CsApprovalConfig approvalConfig = csApprovalConfigMapper.selectAllCsApprovalConfigByApprovalConfigId(approvalRecordVO.getApprovalConfigId());
                if (ObjectUtils.isEmpty(csApprovalInfo)) {
                    CsApprovalInfo approvalInfo = new CsApprovalInfo();
                    approvalInfo.setApprovalInfoId(IdUtil.getSnowflakeNextIdStr());
                    if(StringUtils.isBlank(approvalInfoId)){
                        approvalInfoId = approvalInfo.getApprovalInfoId();
                    }
                    approvalInfo.setApprovalConfigGroupId(approvalConfig.getGroupId());
                    approvalInfo.setApprovalConfigId(approvalConfig.getApprovalConfigId());
                    approvalInfo.setNodeType("3");
                    approvalInfo.setFormId(approvalConfig.getFormId());
                    approvalInfo.setFormType(approvalConfig.getFormType());
                    approvalInfo.setFounder(1L);
                    approvalInfo.setLaunchTime(DateUtils.getNowDate());
                    approvalInfo.setUserId(approvalConfig.getCurrentNodeApprover());
                    approvalInfo.setEndState(0);
                    approvalInfo.setProcessProgress(approvalConfig.getApprovalNode());
                    approvalInfo.setDelFlag("0");
                    //发起人为起始人
                    //历史节点
                    approvalInfo.setRecordNodeHistory(",0,"+approvalConfig.getApprovalNode()+',');
                    approvalInfoService.insertCsApprovalInfo(approvalInfo);
                }
            }
            if(StringUtils.isBlank(checkFormList.get(0).getApprovalInfoId())){
                checkFormList.get(0).setApprovalInfoId(approvalInfoId);
            }
        }
        return result;
    }

    private boolean checkList(List<CsApprovalRecordVO> csApprovalRecordVOList,String approvalInfoId){
        boolean flagVal = false;
        for(int i = 0;i < csApprovalRecordVOList.size();i++){
            if(csApprovalRecordVOList.get(i).getApprovalInfoId().equals(approvalInfoId)){
                flagVal = true;
            }
        }
        return flagVal;
    }

    /**
     * 提交审核(审核/拒绝)__审核流程
     * @param dto 审核信息
     * @return
     */
    @Override
    @Transactional(rollbackFor = {Exception.class})
    public int checkFlowNode(CsApprovalRecordCheckDTO dto) {
        String configId = dto.getApprovalConfigId();
        String infoId = dto.getApprovalInfoId();

        //config存在
        CsApprovalConfig csApprovalConfig = csApprovalConfigMapper.selectCsApprovalConfigByApprovalConfigId(configId);
        if(ObjectUtils.isEmpty(csApprovalConfig)){
            throw new ServiceException(ServiceResponseEnum.APPROVAL_NODE_CONFIG_NOT_FOUND);
        }
        //资源工单状态验证
        String formId = csApprovalConfig.getFormId();
        CsResourceOrderApply csResourceOrderApply = resourceOrderApplyService.selectCsResourceOrderApplyByApplyId(formId);
        if(ObjectUtils.isEmpty(csResourceOrderApply)){
                throw new ServiceException(ServiceResponseEnum.RESOURCE_APPLY_NOT_FIND);
        }
        if(csApprovalConfig.getFormType().equals("0")){
            if(!csResourceOrderApply.getApplyStatus().equals("7")){
                throw new ServiceException(ServiceResponseEnum.APPROVAL_RESOURCE_APPLY_STATUS_ERROR);
            }
        }
        //info存在
        CsApprovalInfo csApprovalInfo = approvalInfoService.selectCsApprovalInfoByApprovalInfoId(infoId);
        if(ObjectUtils.isEmpty(csApprovalInfo)){
            throw new ServiceException(ServiceResponseEnum.APPROVAL_NODE_INFO_NOT_FOUND);
        }
        Long userId = SecurityUtils.getUserId();
        if(!String.valueOf(userId).equals(String.valueOf(csApprovalInfo.getUserId()))){
            /*CsApprovalInfo approvalInfo = csApprovalInfoMapper.searchApprovalInfoByCondition(infoId);
            if(approvalInfo != null){
                if(!String.valueOf(userId).equals(String.valueOf(approvalInfo.getUserId()))){
                    throw new ServiceException(ServiceResponseEnum.APPROVAL_NODE_USER_NOT_RIGHTS);
                }
            }else{
                throw new ServiceException(ServiceResponseEnum.APPROVAL_NODE_USER_NOT_RIGHTS);
            }*/
            throw new ServiceException(ServiceResponseEnum.APPROVAL_NODE_USER_NOT_RIGHTS);
        }


        Integer approverResult = dto.getApproverResult();
        if (dto.getApproverResult() == null) {
            approverResult = 1;
        }
        int result = 0;
        switch (approverResult){
            case (1):
                //同意审核 approverResult = 1
                System.out.println("同意审核");
                result = agreeNode(csApprovalConfig, csApprovalInfo, dto, csResourceOrderApply);
                break;
            case (2):
                //拒绝审核  approverResult = 2
                System.out.println("驳回审核");
                result = refuseNode(csApprovalConfig, csApprovalInfo, dto, csResourceOrderApply);
                break;
        }
        return result;
    }

    /**
     * 新增审核记录
     * @param dto 审核记录
     * @return
     */
    private int insertCheckApprovalRecord(CsApprovalRecordCheckDTO dto){
        CsApprovalRecord record = new CsApprovalRecord();
        record = BeanUtil.toBean(dto,CsApprovalRecord.class);
        record.setApprovalRecordId(IdUtil.getSnowflakeNextIdStr());
        record.setDelFlag("0");
        //json 附件
        List<FileJsonObj> accessoryUrl = dto.getAccessoryUrl();
        if(!CollectionUtils.isEmpty(accessoryUrl)){
            record.setAccessoryUrl(JSON.toJSONString(accessoryUrl));
        }
        return approvalRecordService.insertCsApprovalRecord(record);
    }

    /**
     * 更新审核发起的结束状态及时间
     * @param csApprovalInfo 审核发起
     * @return
     */
    private int updateEndApprovalInfo(CsApprovalInfo csApprovalInfo){
        csApprovalInfo.setEndState(1);
        csApprovalInfo.setEndTime(DateUtils.getNowDate());
        return approvalInfoService.updateCsApprovalInfo(csApprovalInfo);
    }

    /**
     * 驳回审核
     * @param csApprovalConfig
     * @param csApprovalInfo
     */
    private int refuseNode( CsApprovalConfig csApprovalConfig, CsApprovalInfo csApprovalInfo, CsApprovalRecordCheckDTO dto, CsResourceOrderApply csResourceOrderApply){
        //拒绝审核  approverResult = 2
        //记录record+抄送
        //申请单状态回退 资源单->4待审核
        //新增拒绝记录
        int addRecord = insertCheckApprovalRecord(dto);
        //修改记录对应发起的结束信息
        int updateCsApprovalInfo = updateEndApprovalInfo(csApprovalInfo);
        //todo 抄送 钉钉
        String cpoyUserIds = csApprovalConfigMapper.getCpoyUserIds(csApprovalConfig.getFormId(), csApprovalConfig.getFormType());
        if(StringUtils.isNotBlank(cpoyUserIds)) {
            CsApprovalCarbonCopyDTO copyDTO = BeanUtil.toBean(dto, CsApprovalCarbonCopyDTO.class);
            copyDTO.setUids(cpoyUserIds);
            int batchInsertCopy = approvalCarbonCopyService.batchInsertCopy(copyDTO);
        }
        //申请状态回退
        if(csApprovalConfig.getFormType().equals("0")){//资源formType=0 4-待审核
            csResourceOrderApply.setApplyStatus("4");
        }
        if(csApprovalConfig.getFormType().equals("1")){//工单formType=1 8-驳回
            csResourceOrderApply.setApplyStatus("8");
        }
        csResourceOrderApply.setUpdateAt(DateUtils.getNowDate());
        int updateApplyStatus = resourceOrderApplyService.updateCsResourceOrderApply(csResourceOrderApply);
        return addRecord;
    }


    /**
     * 同意审核
     * @param csApprovalConfig 当前同意审核的节点配置
     * @param csApprovalInfo 节点发起
     * @param dto 节点记录信息
     * @param csResourceOrderApply 申请信息
     */
    private int agreeNode(CsApprovalConfig csApprovalConfig, CsApprovalInfo csApprovalInfo, CsApprovalRecordCheckDTO dto, CsResourceOrderApply csResourceOrderApply){
        //同意审核 approverResult = 1
            String formId = csApprovalConfig.getFormId();
            String formType = csApprovalConfig.getFormType();
            String nodeType = csApprovalConfig.getNodeType();
            Integer closeApply = dto.getCloseApply();
            Integer lastActionNode = dto.getLastNode();
            if (dto.getLastNode() == null) {
                lastActionNode = 1;
            }
            Long userId = SecurityUtils.getUserId();
        //防止特殊情况：最后有两个执行节点, 这两个节点都不关闭的情况发生
            if(null == closeApply && nodeType.equals("2")){
                List<CsApprovalRecordVO> checkFormList = csApprovalConfigMapper.getCheckFormList(formId, formType, userId);
                //最后执行节点:唯一没有记录的执行节点
                String current_node_info_id = dto.getApprovalInfoId();
                List<CsApprovalRecordVO> unRecordActionNodeList = checkFormList.stream()
                        .filter(form ->
                                        form.getNodeType().equals("2")
                                        &&
                                        StringUtils.isBlank(form.getApprovalRecordId())
                                        &&
                                        !form.getApprovalInfoId().equals(current_node_info_id)
                        ).collect(Collectors.toList());
                if(CollectionUtils.isEmpty(unRecordActionNodeList)){
                    //无其他没有记录的节点-->提示需要选择完单
                        //提示为最后一个节点，且未选择关闭
                        throw new ServiceException("当前为最后一个节点，请选择是否关闭工单",500);
                }
            }


            //新增审核记录 record
            int addRecord = insertCheckApprovalRecord(dto);
            //审核记录对应发起的结束信息 info
            int updateCsApprovalInfo = updateEndApprovalInfo(csApprovalInfo);
            //todo 抄送 钉钉
            String cpoyUserIds = csApprovalConfigMapper.getCpoyUserIds(csApprovalConfig.getFormId(), csApprovalConfig.getFormType());
            if(StringUtils.isNotBlank(cpoyUserIds)) {
                CsApprovalCarbonCopyDTO copyDTO = BeanUtil.toBean(dto, CsApprovalCarbonCopyDTO.class);
                copyDTO.setUids(cpoyUserIds);
                int batchInsertCopy = approvalCarbonCopyService.batchInsertCopy(copyDTO);
            }

            if(nodeType.equals("0")){//审核节点

                //nodeType0-审核、1-抄送、2-执行、3-转交
                //当前审核节点 ————> 发起新的节点
                    Long currentNode = csApprovalConfig.getApprovalNode();
                    List<CsApprovalRecordVO> checkFormList = csApprovalConfigMapper.getCheckFormList(formId, formType, userId);
                    //发起下一个审核
                    insertNextApprovalInfo(checkFormList, currentNode);
                    if(currentNode == 0L){
                            //发起所有执行节点
                      insertALLActionApprovalInfo(checkFormList);
                    }
                //当前执行节点/转交(只有执行才能转交)不操作

            }

            if(nodeType.equals("2") && lastActionNode == 1){//是最后一个节点
                    if(closeApply == 1){//关闭工单
                        int unFlowListNum = csApprovalConfigMapper.getUnFlowListNum(formId, formType);
                        if (unFlowListNum > 0) {
                            throw new ServiceException("当前有未处理状态，请处理后再关闭工单",500);
                        }

                        //完单改变apply-->9已完成
                        csResourceOrderApply.setApplyStatus("9");
                        csResourceOrderApply.setCompleteAt(DateUtils.getNowDate());
                        csResourceOrderApply.setUpdateAt(DateUtils.getNowDate());
                        int updateApplyStatus = resourceOrderApplyService.updateCsResourceOrderApply(csResourceOrderApply);
                    }
                    //新增record时 已经记录是否最后节点和是否工单关闭了
            }

        // 工单最后一个节点审核
        // if(formType.equals("1")) {
            // 获取未操作工单审核信息流程数量
            int unFlowListNum = csApprovalConfigMapper.getUnFlowListNum(formId, formType);
            if (unFlowListNum == 0 || lastActionNode == 1) {
                //完单改变apply-->9已完成
                csResourceOrderApply.setApplyStatus("9");
                csResourceOrderApply.setCompleteAt(DateUtils.getNowDate());
                csResourceOrderApply.setUpdateAt(DateUtils.getNowDate());
                int updateApplyStatus = resourceOrderApplyService.updateCsResourceOrderApply(csResourceOrderApply);
            }
        // }


            return addRecord;

    }

    /**
     * 找到下一个待审核的节点 并发起审核
     * @return
     */
    private void insertNextApprovalInfo(List<CsApprovalRecordVO> checkFormList, Long currentNode){
        //找到下一个审核节点 发起
        CsApprovalRecordVO nextNode = checkFormList.stream().filter(s ->
                s.getApprovalNode() == currentNode + 1
                        && s.getNodeType().equals("0")
                        && StringUtils.isBlank(s.getApprovalInfoId())
        ).findAny().orElse(null);
        if(!ObjectUtils.isEmpty(nextNode)){
            String configId = nextNode.getApprovalConfigId();
            CsApprovalConfig csApprovalConfig = csApprovalConfigMapper.selectCsApprovalConfigByApprovalConfigId(configId);
            CsApprovalInfo csApprovalInfo = approvalInfoService.selectCsApprovalInfoByApprovalConfigId(configId);
            if (ObjectUtils.isEmpty(csApprovalInfo)) {
                int i = approvalInfoService.insertInfo(csApprovalConfig);
            }
        }
    }

    /**
     * 找到所有待执行的节点 并发起审核
     * @return
     */
    private void insertALLActionApprovalInfo(List<CsApprovalRecordVO> checkFormList){
        //找到下一个审核节点 发起
        List<CsApprovalRecordVO> parallel = checkFormList.stream().filter(s ->s.getNodeType().equals("2")).collect(Collectors.toList());
        if(!CollectionUtils.isEmpty(parallel)){
            for (CsApprovalRecordVO par : parallel) {
                    String configId = par.getApprovalConfigId();
                    CsApprovalConfig csApprovalConfig = csApprovalConfigMapper.selectCsApprovalConfigByApprovalConfigId(configId);
                CsApprovalInfo csApprovalInfo = approvalInfoService.selectCsApprovalInfoByApprovalConfigId(configId);
                if (ObjectUtils.isEmpty(csApprovalInfo)) {
                    int i = approvalInfoService.insertInfo(csApprovalConfig);
                }
            }
        }
    }


    //部门总管 转交 / 编辑(下发)
    private void transferNode(){

    }

    /**
     * 查询指定node编号、formId、formType的节点配置
     * @param approvalNode node编号
     * @param formId
     * @param formType 类型（0-资源，1-工单）
     * @return
     */
    @Override
    public CsApprovalConfig selectCsApprovalConfigByApprovalConfigId(Long approvalNode, String formId, String formType) {
        return csApprovalConfigMapper.selectConfigByNodeFormIdType(approvalNode,formId,formType);
    }

    /**
     * 关闭审核流程及工单
     * @param dto 相关审核记录信息
     * @return
     */
    @Override
    @Transactional(rollbackFor = {Exception.class})
    public int editRecordAndCloseApply(CsApprovalRecordCloseApplyDTO dto) {
        String approvalRecordId = dto.getApprovalRecordId();
        CsApprovalRecord csApprovalRecord = approvalRecordService.selectCsApprovalRecordByApprovalRecordId(approvalRecordId);
        if(ObjectUtils.isEmpty(csApprovalRecord)){
            throw new ServiceException(ServiceResponseEnum.APPROVAL_NODE_RECORD_NOT_FOUND);
        }
        // if(csApprovalRecord.getLastNode() != 1){
        //     throw new ServiceException(ServiceResponseEnum.APPROVAL_NODE_NOT_LAST_NODE);
        // }
        String formId = csApprovalRecord.getFormId();
        String formType = csApprovalRecord.getFormType();
        CsResourceOrderApply csResourceOrderApply = resourceOrderApplyService.selectCsResourceOrderApplyByApplyId(formId);
        if(!csResourceOrderApply.getApplyStatus().equals("7") && !csResourceOrderApply.getApplyStatus().equals("9")){
            throw new ServiceException(ServiceResponseEnum.RESOURCE_APPLY_CANNOT_CLOSE_WITH_STATUS);
        }
        //完单改变apply-->9已完成
        csResourceOrderApply.setApplyStatus("9");
        csResourceOrderApply.setCompleteAt(DateUtils.getNowDate());
        csResourceOrderApply.setUpdateAt(DateUtils.getNowDate());
        int updateApplyStatus = resourceOrderApplyService.updateCsResourceOrderApply(csResourceOrderApply);
        //改变审核记录完单状态
        csApprovalRecord.setCloseApply(1);
        return approvalRecordService.updateCsApprovalRecord(csApprovalRecord);
    }

    /**
     * xcx获取用户当前申请的未审核节点信息
     * @param formId 资源/工单Id
     * @param formType 类型（0-资源，1-工单）
     * @param userId 用户id
     * @return
     */
    @Override
    public CsApprovalRecordVO getUserNodeInfoForXcx(String formId, String formType, Long userId) {
        return csApprovalConfigMapper.getUserNodeInfoForXcx(formId,formType,userId);
    }

    /**
     * 获取申请 最新节点信息
     * @param formId 资源/工单Id
     * @param formType 类型（0-资源，1-工单）
     * @return
     */
    @Override
    public CsApprovalRecordVO getNewNodeInfoForXcx(String formId, String formType) {
        return csApprovalConfigMapper.getNewNodeInfoForXcx(formId,formType);
    }

    /**
     * 主管更改受理人员
     * @param dto 审核信息
     * @return
     */
    @Override
    public int leaderUpdateAccept(CsApprovalRecordVO dto) {
        String approvalConfigId = dto.getApprovalConfigId();
        Long acceptId = dto.getAcceptId();

        // 主管节点规则配置
        CsApprovalConfig csApprovalConfig = csApprovalConfigMapper.selectCsApprovalConfigByApprovalConfigId(approvalConfigId);
        if(ObjectUtils.isEmpty(csApprovalConfig)){
            throw new ServiceException(ServiceResponseEnum.APPROVAL_NODE_RECORD_NOT_FOUND);
        }
        if(dto.getRoleId() == null){
            throw new ServiceException(ServiceResponseEnum.UPDATE_ACCEPT_MY);
        }

        if (!Objects.equals(csApprovalConfig.getCurrentNodeApprover(), acceptId)) {
            // 受理人节点规则配置
            CsApprovalConfig accept = csApprovalConfigMapper.selectCsApprovalConfigAccept(csApprovalConfig);
            if(ObjectUtils.isEmpty(accept)){
                // throw new ServiceException(ServiceResponseEnum.APPROVAL_NODE_RECORD_NOT_FOUND);
                // 新增
                List<CsApprovalConfig> configList = new ArrayList<>();

                CsApprovalConfig config = new CsApprovalConfig();
                config.setApprovalConfigId(IdUtil.getSnowflakeNextIdStr());
                //审批人类型
                config.setCurrentNodeApproverType(csApprovalConfig.getCurrentNodeApproverType());
                config.setCurrentNodeApprover(acceptId);//用户ID
                SysRole sysRole = roleService.selectRoleById(dto.getRoleId());
                if(!ObjectUtils.isEmpty(sysRole)){
                    config.setRoleName(sysRole.getRoleName());
                }
                SysUser sysUser = sysUserService.selectUserById(acceptId);
                if(!ObjectUtils.isEmpty(sysUser)){
                    config.setUserName(sysUser.getNickName());
                }
                config.setApprovalType(1);//并行
                config.setNodeType("2");
                config.setFormId(csApprovalConfig.getFormId());
                config.setFormType(csApprovalConfig.getFormType());
                config.setCareOf(csApprovalConfig.getCareOf());
                config.setRoleId(csApprovalConfig.getRoleId());
                config.setCreateTime(DateUtils.getNowDate());
                config.setGroupId(csApprovalConfig.getGroupId());

                Long maxApprovalNode = csApprovalConfigMapper.selectMaxApprovalNodeCsApprovalConfigAccept(csApprovalConfig.getFormId());
                config.setApprovalNode(maxApprovalNode + 1);

                configList.add(config);

                //批量新增configs
                int insertConfigs = csApprovalConfigMapper.batchInsertConfigs(configList);
                //新增发起-发起人
                CsApprovalConfig startPerson = configList.get(0);
                int i = approvalInfoService.insertInfo(startPerson);
            } else {
                // 修改
                // 更改受理人节点规则配置
                SysUser leaderUser = sysUserService.selectUserById(acceptId);
                if(ObjectUtils.isEmpty(leaderUser)){
                    throw new ServiceException(ServiceResponseEnum.NO_USER);
                }
                accept.setCurrentNodeApprover(leaderUser.getUserId());
                accept.setUserName(leaderUser.getNickName());
                csApprovalConfigMapper.updateCsApprovalConfig(accept);

                CsApprovalInfo csApprovalInfo = approvalInfoService.selectCsApprovalInfoByFormIdUserId(csApprovalConfig.getFormId(), accept.getCurrentNodeApprover());
                if (!ObjectUtils.isEmpty(csApprovalInfo)) {
                    csApprovalInfo.setUserId(leaderUser.getUserId());
                    approvalInfoService.updateCsApprovalInfo(csApprovalInfo);
                }
            }
        } else {
            // 删除自己部门的节点
            CsApprovalConfig configByNodeFormIdType = csApprovalConfigMapper.selectConfigByNodeFormIdType(csApprovalConfig.getApprovalNode() + 1, csApprovalConfig.getFormId(), csApprovalConfig.getFormType());
            if (!ObjectUtils.isEmpty(configByNodeFormIdType)) {
                csApprovalConfigMapper.deleteCsApprovalConfigByApprovalConfigId(configByNodeFormIdType.getApprovalConfigId());
                approvalInfoService.deleteCsApprovalInfoByApprovalConfigId(configByNodeFormIdType.getApprovalConfigId());
            }

        }


        return 1;
    }

    /**
     * 主管转交其他部门人员
     * @param dto 审核信息
     * @return
     */
    @Override
    public int leaderTransferOther(CsApprovalRecordVO dto) {
        String approvalConfigId = dto.getApprovalConfigId();
        String approverUserId = dto.getApproverUserId();// 转交人ID
        Long roleId = dto.getRoleId();// 被转交人角色ID
        String transfereeText = dto.getTransfereeText();
        String formId = dto.getFormId();

        // 获取对应角色的部门负责人用户列表
        List<SysUserSelectVO> sysUserSelectVOS = userService.selectIsLeaderUserListByRoleId(roleId, "1");
        if (sysUserSelectVOS.size() < 1) {
            throw new ServiceException(ServiceResponseEnum.NO_USER_LEADER);
        }

        Long transferee = sysUserSelectVOS.get(0).getUserId();

        if (approverUserId.equals(transferee.toString())) {
            throw new ServiceException(ServiceResponseEnum.UPDATE_ACCEPT_MY);
        }


        // CsResourceOrderApply csResourceOrderApply = resourceOrderApplyService.selectCsResourceOrderApplyByApplyId(formId);


        // 主管节点规则配置
        CsApprovalConfig csApprovalConfig = csApprovalConfigMapper.selectCsApprovalConfigByApprovalConfigId(approvalConfigId);
        if(ObjectUtils.isEmpty(csApprovalConfig)){
            throw new ServiceException(ServiceResponseEnum.APPROVAL_NODE_RECORD_NOT_FOUND);
        }
        csApprovalConfig.setNodeType("3");
        csApprovalConfigMapper.updateCsApprovalConfig(csApprovalConfig);

        CsApprovalInfo approvalInfo = approvalInfoService.selectCsApprovalInfoByApprovalConfigId(csApprovalConfig.getApprovalConfigId());
        if(ObjectUtils.isEmpty(approvalInfo)){
            CsApprovalInfo csApprovalInfo = new CsApprovalInfo();
            csApprovalInfo.setApprovalInfoId(IdUtil.getSnowflakeNextIdStr());
            csApprovalInfo.setApprovalConfigGroupId(csApprovalConfig.getGroupId());
            csApprovalInfo.setApprovalConfigId(csApprovalConfig.getApprovalConfigId());
            csApprovalInfo.setNodeType("3");
            csApprovalInfo.setFormId(csApprovalConfig.getFormId());
            csApprovalInfo.setFormType(csApprovalConfig.getFormType());
            csApprovalInfo.setFounder(Long.valueOf(approverUserId));
            csApprovalInfo.setLaunchTime(DateUtils.getNowDate());
            csApprovalInfo.setUserId(transferee);
            csApprovalInfo.setEndState(0);
            csApprovalInfo.setProcessProgress(csApprovalConfig.getApprovalNode());
            csApprovalInfo.setDelFlag("0");
            //发起人为起始人
            //历史节点
            csApprovalInfo.setRecordNodeHistory(",0,"+csApprovalConfig.getApprovalNode()+',');
            approvalInfoService.insertCsApprovalInfo(csApprovalInfo);
        } else {
            approvalInfo.setNodeType("3");
            approvalInfoService.updateCsApprovalInfo(approvalInfo);

            // 新增审核记录
            CsApprovalRecord csApprovalRecord = new CsApprovalRecord();
            csApprovalRecord.setApprovalRecordId(IdUtil.getSnowflakeNextIdStr());
            csApprovalRecord.setApprovalInfoId(approvalInfo.getApprovalInfoId());
            csApprovalRecord.setFormId(formId);
            csApprovalRecord.setFormType(csApprovalConfig.getFormType());
            csApprovalRecord.setApproverUserId(approverUserId);
            csApprovalRecord.setApproverTime(DateUtils.getNowDate());
            csApprovalRecord.setApproverResult(3);
            csApprovalRecord.setTransferee(transferee.toString());
            csApprovalRecord.setTransfereeText(transfereeText);
            csApprovalRecord.setApprovalNode(csApprovalConfig.getApprovalNode().intValue());
            csApprovalRecord.setApproverCount(1);
            csApprovalRecord.setLastNode(1);
            csApprovalRecord.setCloseApply(0);
            csApprovalRecord.setDelFlag("0");
            approvalRecordService.insertCsApprovalRecord(csApprovalRecord);
        }

        // 删除自己部门的节点
        CsApprovalConfig configByNodeFormIdType = csApprovalConfigMapper.selectConfigByNodeFormIdType(csApprovalConfig.getApprovalNode() + 1, csApprovalConfig.getFormId(), csApprovalConfig.getFormType());
        if (!ObjectUtils.isEmpty(configByNodeFormIdType)) {
            csApprovalConfigMapper.deleteCsApprovalConfigByApprovalConfigId(configByNodeFormIdType.getApprovalConfigId());
            approvalInfoService.deleteCsApprovalInfoByApprovalConfigId(configByNodeFormIdType.getApprovalConfigId());
        }

        List<CsApprovalConfig> configList = new ArrayList<>();

        CsApprovalConfig config = new CsApprovalConfig();
        config.setApprovalConfigId(IdUtil.getSnowflakeNextIdStr());
        //审批人类型
        config.setCurrentNodeApproverType(csApprovalConfig.getCurrentNodeApproverType());
        config.setCurrentNodeApprover(transferee);//用户ID
        SysRole sysRole = roleService.selectRoleById(dto.getRoleId());
        if(!ObjectUtils.isEmpty(sysRole)){
            config.setRoleName(sysRole.getRoleName());
        }
        SysUser sysUser = sysUserService.selectUserById(transferee);
        if(!ObjectUtils.isEmpty(sysUser)){
            config.setUserName(sysUser.getNickName());
        }
        config.setApprovalType(1);//并行
        config.setNodeType("2");
        config.setFormId(csApprovalConfig.getFormId());
        config.setFormType(csApprovalConfig.getFormType());
        config.setCareOf(csApprovalConfig.getCareOf());
        config.setCarbonCopyRecipients(csApprovalConfig.getCarbonCopyRecipients());
        config.setRoleId(roleId);
        config.setCreateTime(DateUtils.getNowDate());
        config.setGroupId(csApprovalConfig.getGroupId());
        config.setTransfereeConfigId(approvalConfigId);

        Long maxApprovalNode = csApprovalConfigMapper.selectMaxApprovalNodeCsApprovalConfigAccept(csApprovalConfig.getFormId());
        config.setApprovalNode(maxApprovalNode + 1);

        configList.add(config);

        //批量新增configs
        int insertConfigs = csApprovalConfigMapper.batchInsertConfigs(configList);
        //新增发起-发起人
        CsApprovalConfig startPerson = configList.get(0);
        int i = approvalInfoService.insertInfo(startPerson);

        return 1;
    }

    /**
     * 转交其他部门人员
     * @param dto 审核信息
     * @return
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public int transferOther(CsApprovalRecordVO dto) {
        String approvalConfigId = dto.getApprovalConfigId();// 审批配置ID
        String approverUserId = dto.getApproverUserId();// 转交人ID
        String transferee = dto.getTransferee();// 被转交人ID
        Long roleId = dto.getRoleId();// 被转交人角色ID
        String transfereeText = dto.getTransfereeText();
        String formId = dto.getFormId();

        SysUser user = userService.selectUserById(Long.valueOf(transferee));
        if (ObjectUtils.isEmpty(user)) {
            throw new ServiceException(ServiceResponseEnum.NO_USER);
        }

        if (approverUserId.equals(transferee)) {
            throw new ServiceException("不可转交自己");
        }

        // 获取被转交人的部门负责人用户列表
        List<SysUserSelectVO> sysUserSelectVOS = userService.selectIsLeaderUserListByRoleId(roleId, "1");
        if (sysUserSelectVOS.size() < 1) {
            throw new ServiceException(ServiceResponseEnum.NO_USER_LEADER);
        }

        // 转交人节点规则配置
        CsApprovalConfig csApprovalConfig = csApprovalConfigMapper.selectAllCsApprovalConfigByApprovalConfigId(approvalConfigId);
        if(ObjectUtils.isEmpty(csApprovalConfig)  || csApprovalConfig.getDelFlag().equals("1")){
            throw new ServiceException(ServiceResponseEnum.APPROVAL_NODE_RECORD_NOT_FOUND);
        }
        csApprovalConfig.setNodeType("3"); // 节点类型[0-审核、1-抄送、2-执行、3-转交]
        csApprovalConfigMapper.updateCsApprovalConfig(csApprovalConfig); // 先把节点类型改为转交

        // 转交自己部门的人员
        SysRole byUserId = roleService.selectRoleByUserId(Long.valueOf(approverUserId));
        if (!ObjectUtils.isEmpty(byUserId) && Objects.equals(byUserId.getRoleId(), roleId)) {

            CsApprovalConfig configByNodeFormIdType = null;
            // 主管节点
            if (csApprovalConfig.getIsLeader().equals("1")) {            // csApprovalConfig转交前得节点信息
                // 转交主管节点
                configByNodeFormIdType = csApprovalConfigMapper.selectConfigByNodeFormIdType(csApprovalConfig.getApprovalNode() + 1, csApprovalConfig.getFormId(), csApprovalConfig.getFormType());
            } else {
                configByNodeFormIdType = csApprovalConfig;
            }

            // 人员节点不存在则新增、存在则修改
            if (ObjectUtils.isEmpty(configByNodeFormIdType)) {
                // 新增
                List<CsApprovalConfig> configList = new ArrayList<>();

                // 最大审批节点
                Long maxApprovalNode = csApprovalConfigMapper.selectMaxApprovalNodeCsApprovalConfigAccept(csApprovalConfig.getFormId());

                CsApprovalConfig config = new CsApprovalConfig();
                config.setApprovalConfigId(IdUtil.getSnowflakeNextIdStr());
                //审批人类型
                config.setCurrentNodeApproverType(csApprovalConfig.getCurrentNodeApproverType());
                config.setCurrentNodeApprover(Long.valueOf(transferee));//用户ID

                SysUser userById = sysUserService.selectUserById(Long.valueOf(transferee));
                if(!ObjectUtils.isEmpty(userById)){
                    config.setUserName(userById.getNickName());
                }
                SysRole sysRole = roleService.selectRoleById(dto.getRoleId());
                if(!ObjectUtils.isEmpty(sysRole)){
                    String roleName = sysRole.getRoleName();
                    if (userById.getIsLeader().equals("1")) {
                        roleName = roleName + "主管";
                    }
                    config.setRoleName(roleName);
                }
                config.setApprovalType(1);//并行
                config.setNodeType("2");
                config.setFormId(csApprovalConfig.getFormId());
                config.setFormType(csApprovalConfig.getFormType());
                config.setCareOf(1);
                config.setCarbonCopyRecipients(csApprovalConfig.getCarbonCopyRecipients());
                config.setRoleId(roleId);
                config.setCreateTime(DateUtils.getNowDate());
                config.setGroupId(csApprovalConfig.getGroupId());
                config.setTransfereeConfigId(approvalConfigId);
                config.setApprovalNode(maxApprovalNode + 1);
                configList.add(config);


                //批量新增configs
                int insertConfigs = csApprovalConfigMapper.batchInsertConfigs(configList);
                //新增发起-发起人
                CsApprovalConfig startPerson = configList.get(0);

                String approvalInfoId = IdUtil.getSnowflakeNextIdStr();
                startPerson.setApprovalInfoId(approvalInfoId);
                int i = approvalInfoService.insertInfo(startPerson);

                CsApprovalInfo updateCsApprovalInfo = approvalInfoService.selectCsApprovalInfoByApprovalConfigId(approvalConfigId);
                if(ObjectUtils.isEmpty(updateCsApprovalInfo)){
                    CsApprovalInfo csApprovalInfo = new CsApprovalInfo();
                    csApprovalInfo.setApprovalInfoId(IdUtil.getSnowflakeNextIdStr());
                    csApprovalInfo.setApprovalConfigGroupId(csApprovalConfig.getGroupId());
                    csApprovalInfo.setApprovalConfigId(csApprovalConfig.getApprovalConfigId());
                    csApprovalInfo.setNodeType("3");
                    csApprovalInfo.setFormId(csApprovalConfig.getFormId());
                    csApprovalInfo.setFormType(csApprovalConfig.getFormType());
                    csApprovalInfo.setFounder(Long.valueOf(approverUserId));
                    csApprovalInfo.setLaunchTime(DateUtils.getNowDate());
                    csApprovalInfo.setUserId(Long.valueOf(transferee));
                    csApprovalInfo.setEndState(0);
                    csApprovalInfo.setProcessProgress(csApprovalConfig.getApprovalNode());
                    csApprovalInfo.setDelFlag("0");
                    //发起人为起始人
                    //历史节点
                    csApprovalInfo.setRecordNodeHistory(",0,"+csApprovalConfig.getApprovalNode()+',');
                    approvalInfoService.insertCsApprovalInfo(csApprovalInfo);
                } else {
                    updateCsApprovalInfo.setNodeType("3");
                    updateCsApprovalInfo.setUserId(Long.valueOf(transferee));
                    approvalInfoService.updateCsApprovalInfo(updateCsApprovalInfo);

                    // 新增或修改审核记录
                    CsApprovalRecord byApprovalInfoId = approvalRecordService.selectCsApprovalRecordByApprovalInfoId(updateCsApprovalInfo.getApprovalInfoId());
                    if (ObjectUtils.isEmpty(byApprovalInfoId)) {
                        CsApprovalRecord csApprovalRecord = new CsApprovalRecord();
                        csApprovalRecord.setApprovalRecordId(IdUtil.getSnowflakeNextIdStr());
                        csApprovalRecord.setApprovalInfoId(updateCsApprovalInfo.getApprovalInfoId());
                        csApprovalRecord.setFormId(formId);
                        csApprovalRecord.setFormType(csApprovalConfig.getFormType());
                        csApprovalRecord.setApproverUserId(approverUserId);
                        csApprovalRecord.setApproverTime(DateUtils.getNowDate());
                        csApprovalRecord.setApproverResult(3);
                        csApprovalRecord.setTransferee(transferee.toString());
                        csApprovalRecord.setTransfereeText(transfereeText);
                        csApprovalRecord.setApprovalNode(csApprovalConfig.getApprovalNode().intValue());
                        csApprovalRecord.setApproverCount(1);
                        csApprovalRecord.setLastNode(1);
                        csApprovalRecord.setCloseApply(0);
                        csApprovalRecord.setDelFlag("0");
                        approvalRecordService.insertCsApprovalRecord(csApprovalRecord);
                    } else {
                        byApprovalInfoId.setApproverUserId(approverUserId);
                        byApprovalInfoId.setApproverTime(DateUtils.getNowDate());
                        byApprovalInfoId.setApproverResult(3);
                        byApprovalInfoId.setTransferee(transferee.toString());
                        byApprovalInfoId.setTransfereeText(transfereeText);
                        byApprovalInfoId.setApprovalNode(csApprovalConfig.getApprovalNode().intValue());
                        byApprovalInfoId.setApproverCount(1);
                        byApprovalInfoId.setLastNode(1);
                        byApprovalInfoId.setCloseApply(0);
                        approvalRecordService.updateCsApprovalRecord(byApprovalInfoId);
                    }
                }

            } else {
                // 修改
//                configByNodeFormIdType.setCurrentNodeApprover(Long.valueOf(transferee)); // 被转交人ID
//                SysUser userById = sysUserService.selectUserById(Long.valueOf(transferee)); // 查询被转交人信息
//                if(!ObjectUtils.isEmpty(userById)){
//                    configByNodeFormIdType.setUserName(userById.getNickName());
//                }                // 设置一下被转交人ID和昵称
                List<CsApprovalConfig> configList = new ArrayList<>();
                // 最大审批节点
                Long maxApprovalNode = csApprovalConfigMapper.selectMaxApprovalNodeCsApprovalConfigAccept(csApprovalConfig.getFormId());
                CsApprovalConfig config = new CsApprovalConfig();
                config.setApprovalConfigId(IdUtil.getSnowflakeNextIdStr());
                //审批人类型
                config.setCurrentNodeApproverType(csApprovalConfig.getCurrentNodeApproverType());
                config.setCurrentNodeApprover(Long.valueOf(transferee));//用户ID

                SysUser userById = sysUserService.selectUserById(Long.valueOf(transferee));
                if(!ObjectUtils.isEmpty(userById)){
                    config.setUserName(userById.getNickName());
                }
                SysRole sysRole = roleService.selectRoleById(dto.getRoleId());
                if(!ObjectUtils.isEmpty(sysRole)){
                    String roleName = sysRole.getRoleName();
                    if (userById.getIsLeader().equals("1")) {
                        roleName = roleName + "主管";
                    }
                    config.setRoleName(roleName);
                }
                config.setApprovalType(1);//并行
                config.setNodeType("2");
                config.setFormId(csApprovalConfig.getFormId());
                config.setFormType(csApprovalConfig.getFormType());
                config.setCareOf(1);
                config.setCarbonCopyRecipients(csApprovalConfig.getCarbonCopyRecipients());
                config.setRoleId(roleId);
                config.setCreateTime(DateUtils.getNowDate());
                config.setGroupId(csApprovalConfig.getGroupId());
                config.setTransfereeConfigId(approvalConfigId);
                config.setApprovalNode(maxApprovalNode + 1);
                configList.add(config);
                //批量新增configs
                int insertConfigs = csApprovalConfigMapper.batchInsertConfigs(configList);
                csApprovalConfigMapper.updateCsApprovalConfig(configByNodeFormIdType);

                CsApprovalInfo approvalInfo = approvalInfoService.selectCsApprovalInfoByApprovalConfigId(configByNodeFormIdType.getApprovalConfigId());
                if(ObjectUtils.isEmpty(approvalInfo)){
                    CsApprovalInfo csApprovalInfo = new CsApprovalInfo();
                    csApprovalInfo.setApprovalInfoId(IdUtil.getSnowflakeNextIdStr());
                    csApprovalInfo.setApprovalConfigGroupId(configByNodeFormIdType.getGroupId());
                    csApprovalInfo.setApprovalConfigId(configByNodeFormIdType.getApprovalConfigId());
                    csApprovalInfo.setNodeType("2");
//                    csApprovalInfo.
                    csApprovalInfo.setFormId(configByNodeFormIdType.getFormId());
                    csApprovalInfo.setFormType(configByNodeFormIdType.getFormType());
                    csApprovalInfo.setFounder(Long.valueOf(approverUserId));
                    csApprovalInfo.setLaunchTime(DateUtils.getNowDate());
                    csApprovalInfo.setUserId(Long.valueOf(transferee));
                    csApprovalInfo.setEndState(0);
                    csApprovalInfo.setProcessProgress(configByNodeFormIdType.getApprovalNode());
                    csApprovalInfo.setDelFlag("0");
                    //发起人为起始人
                    //历史节点
                    csApprovalInfo.setRecordNodeHistory(",0,"+configByNodeFormIdType.getApprovalNode()+',');
                    approvalInfoService.insertCsApprovalInfo(csApprovalInfo);

                    // 新增或修改审核记录
                    CsApprovalRecord byApprovalInfoId = approvalRecordService.selectCsApprovalRecordByApprovalInfoId(csApprovalInfo.getApprovalInfoId());
                    if (ObjectUtils.isEmpty(byApprovalInfoId)) {
                        CsApprovalRecord csApprovalRecord = new CsApprovalRecord();
                        csApprovalRecord.setApprovalRecordId(IdUtil.getSnowflakeNextIdStr());
                        csApprovalRecord.setApprovalInfoId(csApprovalInfo.getApprovalInfoId());
                        csApprovalRecord.setFormId(formId);
                        csApprovalRecord.setFormType(csApprovalConfig.getFormType());
                        csApprovalRecord.setApproverUserId(approverUserId);
                        csApprovalRecord.setApproverTime(DateUtils.getNowDate());
                        csApprovalRecord.setApproverResult(3);
                        csApprovalRecord.setTransferee(transferee.toString());
                        csApprovalRecord.setTransfereeText(transfereeText);
                        csApprovalRecord.setApprovalNode(csApprovalConfig.getApprovalNode().intValue());
                        csApprovalRecord.setApproverCount(1);
                        csApprovalRecord.setLastNode(1);
                        csApprovalRecord.setCloseApply(0);
                        csApprovalRecord.setDelFlag("0");
                        approvalRecordService.insertCsApprovalRecord(csApprovalRecord);
                    } else {
                        byApprovalInfoId.setApproverUserId(approverUserId);
                        byApprovalInfoId.setApproverTime(DateUtils.getNowDate());
                        byApprovalInfoId.setApproverResult(3);
                        byApprovalInfoId.setTransferee(transferee.toString());
                        byApprovalInfoId.setTransfereeText(transfereeText);
                        byApprovalInfoId.setApprovalNode(csApprovalConfig.getApprovalNode().intValue());
                        byApprovalInfoId.setApproverCount(1);
                        byApprovalInfoId.setLastNode(1);
                        byApprovalInfoId.setCloseApply(0);
                        approvalRecordService.updateCsApprovalRecord(byApprovalInfoId);
                    }
                } else {
                    // 目前部门转交走这个流程
                    approvalInfo.setNodeType("2");
                    approvalInfo.setUserId(Long.valueOf(transferee));
                    approvalInfoService.updateCsApprovalInfo(approvalInfo);

                    // 新增或修改审核记录
                    CsApprovalRecord byApprovalInfoId = approvalRecordService.selectCsApprovalRecordByApprovalInfoId(approvalInfo.getApprovalInfoId());
                    if (ObjectUtils.isEmpty(byApprovalInfoId)) {
                        CsApprovalRecord csApprovalRecord = new CsApprovalRecord();
                        csApprovalRecord.setApprovalRecordId(IdUtil.getSnowflakeNextIdStr());
                        csApprovalRecord.setApprovalInfoId(approvalInfo.getApprovalInfoId());
                        csApprovalRecord.setFormId(formId);
                        csApprovalRecord.setFormType(csApprovalConfig.getFormType());
                        csApprovalRecord.setApproverUserId(approverUserId);
                        csApprovalRecord.setApproverTime(DateUtils.getNowDate());
                        csApprovalRecord.setApproverResult(3);
                        csApprovalRecord.setTransferee(transferee.toString());
                        csApprovalRecord.setTransfereeText(transfereeText);
                        csApprovalRecord.setApprovalNode(csApprovalConfig.getApprovalNode().intValue());
                        csApprovalRecord.setApproverCount(1);
                        csApprovalRecord.setLastNode(1);
                        csApprovalRecord.setCloseApply(0);
                        csApprovalRecord.setDelFlag("0");
                        approvalRecordService.insertCsApprovalRecord(csApprovalRecord);
                    } else {
                        byApprovalInfoId.setApproverUserId(approverUserId);
                        byApprovalInfoId.setApproverTime(DateUtils.getNowDate());
                        byApprovalInfoId.setApproverResult(3);
                        byApprovalInfoId.setTransferee(transferee.toString());
                        byApprovalInfoId.setTransfereeText(transfereeText);
                        byApprovalInfoId.setApprovalNode(csApprovalConfig.getApprovalNode().intValue());
                        byApprovalInfoId.setApproverCount(1);
                        byApprovalInfoId.setLastNode(1);
                        byApprovalInfoId.setCloseApply(0);
                        approvalRecordService.updateCsApprovalRecord(byApprovalInfoId);
                    }
                    /*CsApprovalRecord csApprovalRecord = new CsApprovalRecord();
                    csApprovalRecord.setApprovalRecordId(IdUtil.getSnowflakeNextIdStr());
                    csApprovalRecord.setApprovalInfoId(approvalInfo.getApprovalInfoId());
                    csApprovalRecord.setFormId(formId);
                    csApprovalRecord.setFormType(csApprovalConfig.getFormType());
                    csApprovalRecord.setApproverUserId(approverUserId);
                    csApprovalRecord.setApproverTime(DateUtils.getNowDate());
                    csApprovalRecord.setApproverResult(3);
                    csApprovalRecord.setTransferee(transferee.toString());
                    csApprovalRecord.setTransfereeText(transfereeText);
                    csApprovalRecord.setApprovalNode(csApprovalConfig.getApprovalNode().intValue());
                    csApprovalRecord.setApproverCount(1);
                    csApprovalRecord.setLastNode(1);
                    csApprovalRecord.setCloseApply(0);
                    csApprovalRecord.setDelFlag("0");
                    csApprovalRecord.setApproverOpinions(dto.getApproverOpinions());
                    csApprovalRecord.setAccessoryUrl(JSON.toJSONString(dto.getAccessoryUrl()));
                    approvalRecordService.insertCsApprovalRecord(csApprovalRecord);*/
                }
            }

        } else {
            // 转交给其他部门得人
            Long approvalNodeLeader = csApprovalConfig.getApprovalNode();
            Long approvalNodeNoLeader = csApprovalConfig.getApprovalNode();

            if (csApprovalConfig.getIsLeader().equals("1")) {
                // 删除自己部门受理人的节点
                CsApprovalConfig configByNodeFormIdType = csApprovalConfigMapper.selectConfigByNodeFormIdType(csApprovalConfig.getApprovalNode() + 1, csApprovalConfig.getFormId(), csApprovalConfig.getFormType());
                if (!ObjectUtils.isEmpty(configByNodeFormIdType)) {
                    csApprovalConfigMapper.deleteCsApprovalConfigByApprovalConfigId(configByNodeFormIdType.getApprovalConfigId());
                    approvalInfoService.deleteCsApprovalInfoByApprovalConfigId(configByNodeFormIdType.getApprovalConfigId());
                }
                approvalNodeNoLeader = approvalNodeNoLeader + 1;
            } else {
                approvalNodeLeader = approvalNodeLeader - 1;
            }


            // 主管节点规则配置
            CsApprovalConfig leaderApprovalConfig = csApprovalConfigMapper.selectConfigByNodeFormIdType(approvalNodeLeader, csApprovalConfig.getFormId(), csApprovalConfig.getFormType());
            if(!ObjectUtils.isEmpty(leaderApprovalConfig)){

                CsApprovalInfo approvalInfo = approvalInfoService.selectCsApprovalInfoByApprovalConfigId(leaderApprovalConfig.getApprovalConfigId());
                if(ObjectUtils.isEmpty(approvalInfo)){
                    CsApprovalInfo csApprovalInfo = new CsApprovalInfo();
                    csApprovalInfo.setApprovalInfoId(IdUtil.getSnowflakeNextIdStr());
                    csApprovalInfo.setApprovalConfigGroupId(leaderApprovalConfig.getGroupId());
                    csApprovalInfo.setApprovalConfigId(leaderApprovalConfig.getApprovalConfigId());
                    csApprovalInfo.setNodeType("3");
                    csApprovalInfo.setFormId(leaderApprovalConfig.getFormId());
                    csApprovalInfo.setFormType(leaderApprovalConfig.getFormType());
                    csApprovalInfo.setFounder(Long.valueOf(approverUserId));
                    csApprovalInfo.setLaunchTime(DateUtils.getNowDate());
                    csApprovalInfo.setUserId(Long.valueOf(transferee));
                    csApprovalInfo.setEndState(0);
                    csApprovalInfo.setProcessProgress(leaderApprovalConfig.getApprovalNode());
                    csApprovalInfo.setDelFlag("0");
                    //发起人为起始人
                    //历史节点
                    csApprovalInfo.setRecordNodeHistory(",0,"+leaderApprovalConfig.getApprovalNode()+',');
                    approvalInfoService.insertCsApprovalInfo(csApprovalInfo);
                } else {
                    approvalInfo.setNodeType("3");
                    approvalInfo.setUserId(Long.valueOf(transferee));
                    approvalInfoService.updateCsApprovalInfo(approvalInfo);

                    // 新增或修改审核记录
                    CsApprovalRecord byApprovalInfoId = approvalRecordService.selectCsApprovalRecordByApprovalInfoId(approvalInfo.getApprovalInfoId());
                    if (ObjectUtils.isEmpty(byApprovalInfoId)) {
                        CsApprovalRecord csApprovalRecord = new CsApprovalRecord();
                        csApprovalRecord.setApprovalRecordId(IdUtil.getSnowflakeNextIdStr());
                        csApprovalRecord.setApprovalInfoId(approvalInfo.getApprovalInfoId());
                        csApprovalRecord.setFormId(formId);
                        csApprovalRecord.setFormType(leaderApprovalConfig.getFormType());
                        csApprovalRecord.setApproverUserId(approverUserId);
                        csApprovalRecord.setApproverTime(DateUtils.getNowDate());
                        csApprovalRecord.setApproverResult(3);
                        csApprovalRecord.setTransferee(transferee.toString());
                        csApprovalRecord.setTransfereeText(transfereeText);
                        csApprovalRecord.setApprovalNode(leaderApprovalConfig.getApprovalNode().intValue());
                        csApprovalRecord.setApproverCount(1);
                        csApprovalRecord.setLastNode(1);
                        csApprovalRecord.setCloseApply(0);
                        csApprovalRecord.setDelFlag("0");
                        approvalRecordService.insertCsApprovalRecord(csApprovalRecord);
                    } else {
                        byApprovalInfoId.setApproverUserId(approverUserId);
                        byApprovalInfoId.setApproverTime(DateUtils.getNowDate());
                        byApprovalInfoId.setApproverResult(3);
                        byApprovalInfoId.setTransferee(transferee.toString());
                        byApprovalInfoId.setTransfereeText(transfereeText);
                        byApprovalInfoId.setApprovalNode(leaderApprovalConfig.getApprovalNode().intValue());
                        byApprovalInfoId.setApproverCount(1);
                        byApprovalInfoId.setLastNode(1);
                        byApprovalInfoId.setCloseApply(0);
                        approvalRecordService.updateCsApprovalRecord(byApprovalInfoId);
                    }
                }
            }

            // 受理人节点
            CsApprovalConfig approvalConfig = csApprovalConfigMapper.selectConfigByNodeFormIdType(approvalNodeNoLeader, csApprovalConfig.getFormId(), csApprovalConfig.getFormType());
            if(!ObjectUtils.isEmpty(approvalConfig)){

                CsApprovalInfo approvalInfo = approvalInfoService.selectCsApprovalInfoByApprovalConfigId(approvalConfig.getApprovalConfigId());
                if(ObjectUtils.isEmpty(approvalInfo)){
                    CsApprovalInfo csApprovalInfo = new CsApprovalInfo();
                    csApprovalInfo.setApprovalInfoId(IdUtil.getSnowflakeNextIdStr());
                    csApprovalInfo.setApprovalConfigGroupId(approvalConfig.getGroupId());
                    csApprovalInfo.setApprovalConfigId(approvalConfig.getApprovalConfigId());
                    csApprovalInfo.setNodeType("3");
                    csApprovalInfo.setFormId(approvalConfig.getFormId());
                    csApprovalInfo.setFormType(approvalConfig.getFormType());
                    csApprovalInfo.setFounder(Long.valueOf(approverUserId));
                    csApprovalInfo.setLaunchTime(DateUtils.getNowDate());
                    csApprovalInfo.setUserId(Long.valueOf(transferee));
                    csApprovalInfo.setEndState(0);
                    csApprovalInfo.setProcessProgress(approvalConfig.getApprovalNode());
                    csApprovalInfo.setDelFlag("0");
                    //发起人为起始人
                    //历史节点
                    csApprovalInfo.setRecordNodeHistory(",0,"+approvalConfig.getApprovalNode()+',');
                    approvalInfoService.insertCsApprovalInfo(csApprovalInfo);
                } else {
                    approvalInfo.setNodeType("3");
                    approvalInfo.setUserId(Long.valueOf(transferee));
                    approvalInfoService.updateCsApprovalInfo(approvalInfo);

                    // 新增或修改审核记录
                    CsApprovalRecord byApprovalInfoId = approvalRecordService.selectCsApprovalRecordByApprovalInfoId(approvalInfo.getApprovalInfoId());
                    if (ObjectUtils.isEmpty(byApprovalInfoId)) {
                        CsApprovalRecord csApprovalRecord = new CsApprovalRecord();
                        csApprovalRecord.setApprovalRecordId(IdUtil.getSnowflakeNextIdStr());
                        csApprovalRecord.setApprovalInfoId(approvalInfo.getApprovalInfoId());
                        csApprovalRecord.setFormId(formId);
                        csApprovalRecord.setFormType(approvalConfig.getFormType());
                        csApprovalRecord.setApproverUserId(approverUserId);
                        csApprovalRecord.setApproverTime(DateUtils.getNowDate());
                        csApprovalRecord.setApproverResult(3);
                        csApprovalRecord.setTransferee(transferee.toString());
                        csApprovalRecord.setTransfereeText(transfereeText);
                        csApprovalRecord.setApprovalNode(approvalConfig.getApprovalNode().intValue());
                        csApprovalRecord.setApproverCount(1);
                        csApprovalRecord.setLastNode(1);
                        csApprovalRecord.setCloseApply(0);
                        csApprovalRecord.setDelFlag("0");
                        approvalRecordService.insertCsApprovalRecord(csApprovalRecord);
                    } else {
                        byApprovalInfoId.setApproverUserId(approverUserId);
                        byApprovalInfoId.setApproverTime(DateUtils.getNowDate());
                        byApprovalInfoId.setApproverResult(3);
                        byApprovalInfoId.setTransferee(transferee.toString());
                        byApprovalInfoId.setTransfereeText(transfereeText);
                        byApprovalInfoId.setApprovalNode(approvalConfig.getApprovalNode().intValue());
                        byApprovalInfoId.setApproverCount(1);
                        byApprovalInfoId.setLastNode(1);
                        byApprovalInfoId.setCloseApply(0);
                        approvalRecordService.updateCsApprovalRecord(byApprovalInfoId);
                    }
                }
            }

            List<SysUser> sysUsers = new ArrayList<>();
            // 添加部门负责人节点
            // 20250308 去除部门负责人节点
//            if (user.getIsLeader().equals("0")) {
//                SysUser sysUser = new SysUser();
//                sysUser.setUserId(sysUserSelectVOS.get(0).getUserId());
//                sysUsers.add(sysUser);
//            }
            sysUsers.add(user);

            List<CsApprovalConfig> configList = new ArrayList<>();

            // 最大审批节点
            Long maxApprovalNode = csApprovalConfigMapper.selectMaxApprovalNodeCsApprovalConfigAccept(csApprovalConfig.getFormId());

            for (SysUser sysUser : sysUsers) {
                CsApprovalConfig config = new CsApprovalConfig();
                config.setApprovalConfigId(IdUtil.getSnowflakeNextIdStr());
                //审批人类型
                config.setCurrentNodeApproverType(csApprovalConfig.getCurrentNodeApproverType());
                config.setCurrentNodeApprover(sysUser.getUserId());//用户ID

                SysUser userById = sysUserService.selectUserById(sysUser.getUserId());
                if(!ObjectUtils.isEmpty(userById)){
                    config.setUserName(userById.getNickName());
                }
                SysRole sysRole = roleService.selectRoleById(dto.getRoleId());
                if(!ObjectUtils.isEmpty(sysRole)){
                    String roleName = sysRole.getRoleName();
                    if (userById.getIsLeader().equals("1")) {
                        roleName = roleName + "主管";
                    }
                    config.setRoleName(roleName);
                }
                config.setApprovalType(1);//并行
                config.setNodeType("2");
                config.setFormId(csApprovalConfig.getFormId());
                config.setFormType(csApprovalConfig.getFormType());
                config.setCareOf(1);
                config.setCarbonCopyRecipients(csApprovalConfig.getCarbonCopyRecipients());
                config.setRoleId(roleId);
                config.setCreateTime(DateUtils.getNowDate());
                config.setGroupId(csApprovalConfig.getGroupId());
                config.setTransfereeConfigId(approvalConfigId);

                config.setApprovalNode(maxApprovalNode + 1);
                maxApprovalNode++;

                configList.add(config);
            }


            //批量新增configs
            int insertConfigs = csApprovalConfigMapper.batchInsertConfigs(configList);
            //新增发起-发起人
            CsApprovalConfig startPerson = configList.get(0);
            int i = approvalInfoService.insertInfo(startPerson);

            // for (CsApprovalConfig config : configList) {
            //     int i = approvalInfoService.insertInfo(config);
            // }
        }



        return 1;
    }

    /**
     * 撤回转交
     * @param dto 审核信息
     * @return
     */
    @Override
    public int withdrawTransfer(CsApprovalRecordVO dto) {
        String approvalConfigId = dto.getApprovalConfigId();

        // 撤回：把转交的节点删掉
        // csApprovalConfigMapper.deleteCsApprovalConfigByTransfereeConfigId(approvalConfigId);

        CsApprovalConfig config = csApprovalConfigMapper.selectAllCsApprovalConfigByApprovalConfigId(approvalConfigId);
        if (ObjectUtils.isEmpty(config) || config.getDelFlag().equals("1")) {
            throw new ServiceException(ServiceResponseEnum.APPROVAL_NODE_RECORD_NOT_FOUND);
        }

        CsApprovalConfig approvalConfig = new CsApprovalConfig();
        approvalConfig.setFormId(config.getFormId());
        approvalConfig.setApprovalNode(config.getApprovalNode());
        List<CsApprovalConfig> approvalConfigList = csApprovalConfigMapper.selectCsApprovalConfigListApprovalNode(approvalConfig);
        if (approvalConfigList.size() > 0) {
            csApprovalConfigMapper.bachDeleteCsApprovalConfigByList(approvalConfigList);
            // 批量删除审核流程发起信息
            approvalInfoService.bachDeleteCsApprovalInfoByList(approvalConfigList);

        }
        CsApprovalInfo csApprovalInfo = approvalInfoService.selectCsApprovalInfoByApprovalConfigId(config.getApprovalConfigId());
        // 删除审核记录信息（根据审批流程ID）
        approvalRecordService.deleteCsApprovalRecordByApprovalInfoId(csApprovalInfo.getApprovalInfoId());

        // 节点改为执行
        CsApprovalConfig csApprovalConfig = new CsApprovalConfig();
        csApprovalConfig.setApprovalConfigId(approvalConfigId);
        csApprovalConfig.setNodeType("2");
        csApprovalConfigMapper.updateCsApprovalConfig(csApprovalConfig);

        // 工单修改为进行中
        CsResourceOrderApply csResourceOrderApply = new CsResourceOrderApply();
        csResourceOrderApply.setApplyId(config.getFormId());
        csResourceOrderApply.setApplyStatus("7");// 7代表进行中
        csResourceOrderApplyMapper.updateCsResourceOrderApply(csResourceOrderApply);

        return 1;
    }

    @Override
    public int withdrawDelegation(CsApprovalRecordVO dto) {
        String formId = dto.getFormId();
        String formType = dto.getFormType();
        // 撤回：把转交的节点删掉
        // csApprovalConfigMapper.deleteCsApprovalConfigByTransfereeConfigId(approvalConfigId);
        String approvalConfigId = dto.getApprovalConfigId();

        // 撤回：把转交的节点删掉
        // csApprovalConfigMapper.deleteCsApprovalConfigByTransfereeConfigId(approvalConfigId);

        CsApprovalConfig config = csApprovalConfigMapper.selectAllCsApprovalConfigByApprovalConfigId(approvalConfigId);
        if (ObjectUtils.isEmpty(config) || config.getDelFlag().equals("1")) {
            throw new ServiceException(ServiceResponseEnum.APPROVAL_NODE_RECORD_NOT_FOUND);
        }
        CsApprovalConfig approvalConfig = new CsApprovalConfig();
        approvalConfig.setFormId(formId);
        List<CsApprovalConfig> approvalConfigList = csApprovalConfigMapper.selectCsApprovalConfigListApprovalNode(approvalConfig);
        if (CollectionUtils.isEmpty(approvalConfigList)) {
            throw new ServiceException(ServiceResponseEnum.APPROVAL_NODE_RECORD_NOT_FOUND);
        }else {
            csApprovalConfigMapper.bachDeleteCsApprovalConfigByList(approvalConfigList);
            // 批量删除审核流程发起信息
        }
        approvalInfoService.deleteCoverApprovalInfoByApplyId(formId);
        approvalRecordService.deleteCsApprovalRecordByFormId(formId);
        // 删除审核记录信息（根据审批流程ID）
        CsResourceOrderApply csResourceOrderApply = resourceOrderApplyService.selectCsResourceOrderApplyByApplyId(formId);
        if(ObjectUtils.isEmpty(csResourceOrderApply) || !csResourceOrderApply.getApplyType().equals(formType)){
            throw new ServiceException(ServiceResponseEnum.RESOURCE_APPLY_NOT_FIND);
        }
        csResourceOrderApply.setApplyStatus("6");
        csResourceOrderApply.setUpdateAt(new Date());
        return resourceOrderApplyService.updateCsResourceOrderApply(csResourceOrderApply);
    }

    /**
     * 拒绝转交
     * @param dto 审核信息
     * @return
     */
    @Override
    public int refuseTransfer(CsApprovalRecordVO dto) {
        String approvalConfigId = dto.getApprovalConfigId();

        CsApprovalConfig approvalConfig = csApprovalConfigMapper.selectCsApprovalConfigByApprovalConfigId(approvalConfigId);
        if (!ObjectUtils.isEmpty(approvalConfig)) {
            // 拒绝：把转交的节点删掉
            csApprovalConfigMapper.deleteCsApprovalConfigByTransfereeConfigId(approvalConfig.getTransfereeConfigId());

            CsApprovalConfig selectApprovalConfig = new CsApprovalConfig();
            selectApprovalConfig.setTransfereeConfigId(approvalConfig.getTransfereeConfigId());
            List<CsApprovalConfig> approvalConfigList = csApprovalConfigMapper.selectCsApprovalConfigList(selectApprovalConfig);
            if (approvalConfigList.size() > 0) {
                // 批量删除审核流程发起信息
                approvalInfoService.bachDeleteCsApprovalInfoByList(approvalConfigList);
            }

            // 节点改为执行
            CsApprovalConfig csApprovalConfig = new CsApprovalConfig();
            csApprovalConfig.setApprovalConfigId(approvalConfig.getTransfereeConfigId());
            csApprovalConfig.setNodeType("2");
            csApprovalConfigMapper.updateCsApprovalConfig(csApprovalConfig);
        }

        return 1;
    }

    /**
     * 审批回退
     * @param dto 审核信息
     * @return
     */
    @Override
    public int approvalRollback(CsApprovalRecordVO dto) {
        String approvalConfigId = dto.getApprovalConfigId();

        CsApprovalConfig config = csApprovalConfigMapper.selectAllCsApprovalConfigByApprovalConfigId(approvalConfigId);
        if (ObjectUtils.isEmpty(config) || config.getDelFlag().equals("1")) {
            throw new ServiceException(ServiceResponseEnum.APPROVAL_NODE_RECORD_NOT_FOUND);
        }

        CsApprovalConfig approvalConfig = new CsApprovalConfig();
        approvalConfig.setFormId(config.getFormId());
        approvalConfig.setNodeType(config.getNodeType());
        List<CsApprovalConfig> approvalConfigList = csApprovalConfigMapper.selectCsApprovalConfigListApprovalNode(approvalConfig);

        if (approvalConfigList.size() > 0) {
            for (CsApprovalConfig approvalConfigs : approvalConfigList) {
                CsApprovalInfo csApprovalInfo = approvalInfoService.selectCsApprovalInfoByApprovalConfigId(approvalConfigs.getApprovalConfigId());
                if (!ObjectUtils.isEmpty(config)) {
                    // 删除审核记录信息（根据审批流程ID）
                    approvalRecordService.deleteCsApprovalRecordByApprovalInfoId(csApprovalInfo.getApprovalInfoId());
                }
            }

            // 批量删除审核流程发起信息
            // approvalInfoService.bachDeleteCsApprovalInfoByList(approvalConfigList);
        }

        return 1;
    }

    /**
     * (已过节点)修改审批意见
     * @param dto 修改意见信息
     * @return
     */
    @Override
    public int editApproverOpinions(CsApprovalRecordVO dto) {
        String recordId = dto.getApprovalRecordId();
        String newOpinions = dto.getApproverOpinions();
        if(StringUtils.isBlank(recordId) || StringUtils.isBlank(newOpinions)){
            throw new ServiceException("修改缺少参数信息");
        }
        return approvalRecordService.editRecordApproverOpinions(recordId,newOpinions);
    }
}
