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

import cn.hutool.core.collection.CollectionUtil;
import com.alibaba.nacos.common.utils.CollectionUtils;
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.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 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 LeaseApplyInfoMapper leaseApplyInfoMapper;

    @Resource
    private TmTaskMapper taskMapper;

    @Resource
    private TmTaskAgreementMapper taskAgreementMapper;

    @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(SysWorkflowRecordHistory sysWorkflowRecordHistory) {
        SysUser sysUser = SecurityUtils.getLoginUser().getSysUser();
        Long userId = sysUser.getUserId();
        Integer recordId = sysWorkflowRecordHistory.getRecordId();
        Integer taskId = sysWorkflowRecordHistory.getTaskId();
        Integer leaseId = sysWorkflowRecordHistory.getLeaseId();
        String recordCode = sysWorkflowRecordHistory.getTaskCode();
        String projectName = sysWorkflowRecordHistory.getProjectName();
        String userName = sysUser.getUserName();
        Integer nextNodeId = sysWorkflowRecordHistory.getNextNodeId();
        sysWorkflowRecordHistory.setCreateBy(userId.toString());
        sysWorkflowRecordHistoryMapper.addSysWorkflowRecordHistory(sysWorkflowRecordHistory);

        if (sysWorkflowRecordHistory.getIsAccept() == 1) {
            List<SysWorkflowNode> sysWorkflowNodeList = getWorkflowNodes(sysWorkflowRecordHistory);
            handleApproval(sysWorkflowNodeList, sysWorkflowRecordHistory, sysUser, taskId, leaseId, recordCode, projectName, recordId,nextNodeId);
        } else {
            handleRejection(sysWorkflowRecordHistory);
        }

        return 0;
    }

    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) {
            sysWorkflowNodeService.copeNodeConfigPersonValuesByNode(sysWorkflowNode);
            if (sysWorkflowRecordHistory.getNodeId().equals(sysWorkflowNode.getId())) {
                if (sysWorkflowNode.getConfigValues().contains(sysUser.getUserId().toString())) {
                    updateWorkflowStatus(taskId, 1);
                    updateTmTask(taskId.longValue(), LeaseTaskStatusEnum.LEASE_AUDIT_ING.getStatus());
                    log.info("-------------节点更新任务信息-------------");
                    found = true;
                    break;
                } else {
                    throw new ServiceException("当前节点不在审核中");
                }
            }
        }

        if (!found) {
            return;
        }
        updateWorkOrder(recordId, sysUser.getUserName());
        if(nextNodeId !=null){

            createWorkOrderAndPeople(sysUser, taskId, leaseId, recordCode, projectName, recordId);
        }


        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 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.getSysWorkflowRecodeByTaskId(sysWorkflowRecordHistory.getTaskId());
            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("未知的任务类型");
        }
    }

    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(SysWorkflowRecordHistory sysWorkflowRecordHistory) {
        Integer taskId = sysWorkflowRecordHistory.getTaskId();
        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);
    }


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

    }


    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/index?";
        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);

        int countWork = lMapper.insertWorkOrder(workApplyInfo);
        if (countWork > 0) {

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

            List<WorkPeopleInfo> workPeopleInfoList = lMapper.selectWorkPeopleInfoList(info);

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

            }
        }
    }



    /**
     * 插入 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(BigDecimal.valueOf(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(BigDecimal.valueOf(directApplyDetails.getDirectNum()));
                details.setAlNum(BigDecimal.valueOf(directApplyDetails.getDirectNum()));
                details.setStatus("2");
                leaseApplyDetails.add(details);
            }
            // 批量插入详情数据
            if (CollectionUtil.isNotEmpty(leaseApplyDetails)) {
                count = leaseApplyDetailsMapper.insertLeaseApplyDetailsList(leaseApplyDetails);
            }
        }
        return count;
    }

    /**
     * 生成领料任务单号
     * @param thisMonthMaxOrder
     * @return
     */
    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(BigDecimal.valueOf(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);
                Integer backNum = directApplyDetails.getDirectNum();
                if (CollectionUtils.isNotEmpty(infoList)) {
                    for (SltAgreementInfo agreementInfo : infoList) {
                        Integer num = agreementInfo.getBackNum();
                        if (backNum.equals(num)) {
                            backApplyInfoMapper.updateStlInfo(agreementInfo, backApplyInfo);
                            break;
                        } else if (backNum > num) {
                            backNum = backNum - num;
                            backApplyInfoMapper.updateStlInfo(agreementInfo, backApplyInfo);
                        } else {
                            Integer many = num - 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(BigDecimal.valueOf(directApplyDetails.getDirectNum()));
                details.setAuditNum(BigDecimal.valueOf(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);
    }

}
