package com.bonus.material.ma.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.enums.BackTaskStatusEnum;
import com.bonus.common.biz.enums.LeaseTaskStatusEnum;
import com.bonus.common.biz.enums.TmTaskTypeEnum;
import com.bonus.common.core.utils.DateUtils;
import com.bonus.common.core.web.domain.AjaxResult;
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.event.InsertWorkflowEvent;
import com.bonus.material.lease.domain.LeaseApplyDetails;
import com.bonus.material.lease.mapper.LeaseApplyDetailsMapper;
import com.bonus.material.lease.mapper.LeaseApplyInfoMapper;
import com.bonus.material.lease.mapper.LeaseOutDetailsMapper;
import com.bonus.material.ma.domain.*;
import com.bonus.material.ma.mapper.DirectRotationMapper;
import com.bonus.material.ma.mapper.TypeMapper;
import com.bonus.material.ma.service.DirectRotationService;
import com.bonus.material.ma.service.WorkSiteDirectManageService;
import com.bonus.material.settlement.domain.SltAgreementInfo;
import com.bonus.material.settlement.mapper.SltAgreementInfoMapper;
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.SysWorkflowRecord;
import com.bonus.material.work.domain.SysWorkflowRecordHistory;
import com.bonus.material.work.mapper.SysWorkflowRecordHistoryMapper;
import com.bonus.material.work.mapper.SysWorkflowRecordMapper;
import com.bonus.material.work.service.SysWorkflowRecordService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationEventPublisher;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.transaction.interceptor.TransactionAspectSupport;
import org.springframework.transaction.support.TransactionSynchronization;
import org.springframework.transaction.support.TransactionSynchronizationAdapter;
import org.springframework.transaction.support.TransactionSynchronizationManager;

import javax.annotation.Resource;
import javax.sql.DataSource;
import java.math.BigDecimal;
import java.sql.Connection;
import java.sql.SQLException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import static com.bonus.common.biz.enums.TmTaskTypeEnum.TM_TASK_DIRECT;

/**
 * @author hay
 * @description 直转申请
 * @date 2025/2/17 19:34
 */
@Service(value = "directRotationService")
@Slf4j
public class DirectRotationImpl implements DirectRotationService {

    @Resource
    private DirectRotationMapper mapper;

    @Resource
    private SysWorkflowRecordMapper wfMapper;

    @Resource
    private SysWorkflowRecordHistoryMapper hisMapper;

    @Resource(name = "workSiteDirectManageService")
    private WorkSiteDirectManageService workSiteDirectManageService;

    @Resource
    private SysWorkflowRecordService sysWorkflowRecordService;

    @Resource
    private DataSource dataSource;

    @Resource
    private TypeMapper typeMapper;

    @Resource
    private TmTaskMapper taskMapper;

    @Resource
    private TmTaskMapper tmTaskMapper;

    @Resource
    private TmTaskAgreementMapper taskAgreementMapper;

    @Resource
    private LeaseApplyInfoMapper leaseApplyInfoMapper;

    @Resource
    private LeaseApplyDetailsMapper leaseApplyDetailsMapper;

    @Resource
    private BackApplyInfoMapper backApplyInfoMapper;

    @Resource
    private LeaseOutDetailsMapper leaseOutDetailsMapper;

    @Resource
    private SltAgreementInfoMapper sltAgreementInfoMapper;

    @Resource
    private ApplicationEventPublisher applicationEventPublisher;

    @Override
    public List<SltAgreementInfo> getUseringData(SltAgreementInfo sltAgreementInfo) {
        return mapper.getUseringData(sltAgreementInfo);
    }

    @Override
    public List<DirectApplyExportInfo> getList(DirectApplyInfo directApplyInfo) {
        return mapper.getList(directApplyInfo);
    }

    @Override
//    @Transactional(propagation = Propagation.REQUIRES_NEW)
    public AjaxResult submit(DirectApplyInfoDetails directApplyInfoDetails) throws SQLException {
        try (Connection connection = dataSource.getConnection()) {
            System.out.println("连接池是否 auto-commit: " + connection.getAutoCommit());
        }
        int id;
        String code;
        String leaseMan;
        int leaseAgreementId;
        int backAgreementId;
        if (directApplyInfoDetails != null) {
            if (directApplyInfoDetails.getDirectApplyInfo() != null) {
                DirectApplyInfo directApplyInfos = directApplyInfoDetails.getDirectApplyInfo();
                if (directApplyInfos.getBackAgreementId()==directApplyInfos.getLeaseAgreementId()){
                    return AjaxResult.error("申请失败，不能转入同单位同工程");
                }
                 code = workSiteDirectManageService.genderLeaseCode();
                directApplyInfos.setCode(code);
                directApplyInfos.setCreateTime(new Date());
                List<String> urls = new ArrayList<>();
                if (directApplyInfoDetails.getDirectApplyInfo().getDirUrls() != null) {
                   List<DirectApplyUrl> dirUrls = directApplyInfoDetails.getDirectApplyInfo().getDirUrls();
                   for (DirectApplyUrl dirUrl : dirUrls){
                       urls.add(dirUrl.getUrl());
                   }
                   //将urls所有内容用逗号拼接
                    directApplyInfos.setDirUrl(String.join(",", urls));
                }
                directApplyInfos.setCreateBy(SecurityUtils.getLoginUser().getUserid().toString());
                leaseMan = directApplyInfos.getLeaseMan();
                leaseAgreementId = directApplyInfos.getLeaseAgreementId();
                backAgreementId = directApplyInfos.getBackAgreementId();
                int i = workSiteDirectManageService.saveDirectApplyInfo(directApplyInfos);
                if (i < 0) {
                    return AjaxResult.error("保存失败");
                }
                id = directApplyInfos.getId();
            } else {
                return AjaxResult.error("保存失败");
            }

            if (directApplyInfoDetails.getDirectApplyInfoDetails() != null) {
                List<DirectApplyDetails> directApplyDetails = directApplyInfoDetails.getDirectApplyInfoDetails();
                for (DirectApplyDetails directApplyDetail : directApplyDetails) {
                    directApplyDetail.setDirectId(id);
                    int i = workSiteDirectManageService.saveDirectApplyDetails(directApplyDetail);
                    if (i < 0) {
                        return AjaxResult.error("保存失败");
                    }
                }
            }
        } else {
            return AjaxResult.error("保存失败");
        }

        // 执行审批流方法🚀
        //sysWorkflowRecordService.addSysWorkflowRecord(id, code, TM_TASK_DIRECT.getTaskTypeId());
        // 注册一个在事务提交之后触发事件发布的回调，防止事物未提交时查询数据库数据为空
//        TransactionSynchronizationManager.registerSynchronization(new TransactionSynchronization() {
//            @Override
//            public void afterCommit() {
                // 发布审批流程事件
                applicationEventPublisher.publishEvent(new InsertWorkflowEvent(id, code, TM_TASK_DIRECT.getTaskTypeId(),leaseAgreementId,backAgreementId,leaseMan));
//            }
//        });

        //initAuditDir(id,code);

        return AjaxResult.success("保存成功");
    }

    private void initAuditDir(int id, String code) {

        //1 生成直转审核节点任务
        SysWorkflowRecord wf = new SysWorkflowRecord();
        wf.setTaskId(id);
        wf.setTaskType(TM_TASK_DIRECT.getTaskTypeId());
        wf.setTaskCode(code);
        wf.setWorkflowId(15);
        wfMapper.addSysWorkflowRecord(wf);
        //2 生成直转审核人
        SysWorkflowRecordHistory his = new SysWorkflowRecordHistory();

        his.setRecordId(wf.getId());
        his.setNodeId(9);
        his.setNextNodeId(10);
        his.setIsAccept(1);
        his.setCreateBy(SecurityUtils.getLoginUser().getSysUser().getNickName());
        his.setCreateTime(new Date());
        hisMapper.addSysWorkflowRecordHistory(his) ;

    }


    @Override
    public AjaxResult edit(DirectApplyInfoDetails directApplyInfoDetails) {
        if (directApplyInfoDetails != null) {
            if (directApplyInfoDetails.getDirectApplyInfo() != null && directApplyInfoDetails.getDirectApplyInfo().getId() != null) {
                DirectApplyInfo directApplyInfos = directApplyInfoDetails.getDirectApplyInfo();
                if (directApplyInfos.getBackAgreementId()==directApplyInfos.getLeaseAgreementId()){
                    return AjaxResult.error("申请失败，不能转入同单位同工程");
                }
                directApplyInfos.setUpdateTime(new Date());
                List<String> urls = new ArrayList<>();
                if (directApplyInfoDetails.getDirectApplyInfo().getDirUrls() != null) {
                    List<DirectApplyUrl> dirUrls = directApplyInfoDetails.getDirectApplyInfo().getDirUrls();
                    for (DirectApplyUrl dirUrl : dirUrls){
                        urls.add(dirUrl.getUrl());
                    }
                    //将urls所有内容用逗号拼接
                    directApplyInfos.setDirUrl(String.join(",", urls));
                    //修改info表
                    int i = mapper.updateDirectApplyInfo(directApplyInfos);
                    //删除详情表内容
                    int i1 = mapper.deleteDirectApplyDetails(directApplyInfos.getId());
                    if (directApplyInfoDetails.getDirectApplyInfoDetails() != null) {
                        List<DirectApplyDetails> directApplyDetails = directApplyInfoDetails.getDirectApplyInfoDetails();
                        for (DirectApplyDetails directApplyDetail : directApplyDetails) {
                            directApplyDetail.setDirectId(directApplyInfos.getId());
                            int i2 = workSiteDirectManageService.saveDirectApplyDetails(directApplyDetail);
                        }
                    }
                    return AjaxResult.success("修改成功");
                }
            } else {
                return AjaxResult.error("修改失败");
            }
        } else {
            return AjaxResult.error("修改失败");
        }
        return AjaxResult.success();
    }

    @Override
    public DirectApplyInfo getInfoById(SltAgreementInfo sltAgreementInfo) {
        DirectApplyInfo directApplyInfo = mapper.getInfoById(sltAgreementInfo);
        if (directApplyInfo.getDirUrl()!= null){
            //用逗号分割放入数组
            String[] split = directApplyInfo.getDirUrl().split(",");
            List<DirectApplyUrl> list1 = new ArrayList<>();
            for (String s : split) {
                list1.add(new DirectApplyUrl(s));
            }
            directApplyInfo.setDirUrls(list1);
        }
        List<DirectApplyDetails> detailById = mapper.getDetailById(sltAgreementInfo);
        directApplyInfo.setDirectApplyDetails(detailById);
        return directApplyInfo;
    }

    @Override
    public DirectApplyInfo getInfoApp(SltAgreementInfo sltAgreementInfo) {
        DirectApplyInfo directApplyInfo = mapper.getInfoById(sltAgreementInfo);
        if (directApplyInfo != null){
            if (sltAgreementInfo.getAgreementId()!=directApplyInfo.getLeaseAgreementId()){
                return new DirectApplyInfo();
            }
        }
        if (directApplyInfo.getDirUrl()!= null){
            //用逗号分割放入数组
            String[] split = directApplyInfo.getDirUrl().split(",");
            List<DirectApplyUrl> list1 = new ArrayList<>();
            for (String s : split) {
                list1.add(new DirectApplyUrl(s));
            }
            directApplyInfo.setDirUrls(list1);
        }
        List<DirectApplyDetails> detailById = mapper.getDetailById(sltAgreementInfo);
        directApplyInfo.setDirectApplyDetails(detailById);
        return directApplyInfo;
    }

    @Override
    public int delData(Long id) {
        try {
            mapper.deleteDirectApply(id);
            return 1;
        } catch (Exception e) {
            return 0;
        }
    }

    @Override
    public AjaxResult getTypeNameList(SltAgreementInfo bean) {
        List<SltAgreementInfo> list =new ArrayList<>();
        try {
            list = mapper.getTypeNameList(bean);
        } catch (Exception e) {
            return AjaxResult.success(new ArrayList());
        }
        return AjaxResult.success(list);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public AjaxResult submitNew(DirectApplyInfoDetails directApplyInfoDetails) {
        try {
            if (directApplyInfoDetails != null && directApplyInfoDetails.getDirectApplyInfo() != null && directApplyInfoDetails.getDirectApplyInfoDetails() != null) {
                DirectApplyInfo directApplyInfos = directApplyInfoDetails.getDirectApplyInfo();
                if (directApplyInfos.getBackAgreementId()==directApplyInfos.getLeaseAgreementId()){
                    return AjaxResult.error("直转失败，不能转入同单位同工程");
                }
                String code = workSiteDirectManageService.genderLeaseCode();
                directApplyInfos.setCode(code);
                directApplyInfos.setCreateTime(new Date());
                List<String> urls = new ArrayList<>();
                if (directApplyInfoDetails.getDirectApplyInfo().getDirUrls() != null) {
                    List<DirectApplyUrl> dirUrls = directApplyInfoDetails.getDirectApplyInfo().getDirUrls();
                    for (DirectApplyUrl dirUrl : dirUrls){
                        urls.add(dirUrl.getUrl());
                    }
                    //将urls所有内容用逗号拼接
                    directApplyInfos.setDirUrl(String.join(",", urls));
                }
                directApplyInfos.setCreateBy(SecurityUtils.getLoginUser().getUserid().toString());
                //将数据插入直转表direct_apply_info
                int res = workSiteDirectManageService.saveDirectApplyInfo(directApplyInfos);
                int id =directApplyInfos.getId();
                List<DirectApplyDetails> directApplyDetails = directApplyInfoDetails.getDirectApplyInfoDetails();
                //插入直转详情表direct_apply_details
                for (DirectApplyDetails directApplyDetail : directApplyDetails) {
                    directApplyDetail.setDirectId(id);
                    int i = workSiteDirectManageService.saveDirectApplyDetails(directApplyDetail);
                }


                //以下走退料、领料方法
                SltAgreementInfo sltAgreementInfo = new SltAgreementInfo();
                sltAgreementInfo.setId(Long.valueOf(id));
                DirectApplyInfo info = mapper.getInfoById(sltAgreementInfo);
                BackApplyInfo backApplyInfo = new BackApplyInfo();
                if (info != null) {
                    backApplyInfo.setAgreementId(Long.valueOf(info.getBackAgreementId()));
                    backApplyInfo.setBackPerson(info.getBackMan());
                    backApplyInfo.setPhone(info.getBackPhone());
                }
                List<DirectApplyDetails> detailById = mapper.getDetailById(sltAgreementInfo);
                List<DirectApplyDetails> list = mapper.selectDetails(sltAgreementInfo);
                int thisMonthMaxOrder = taskMapper.getMonthMaxOrderByDate(DateUtils.getCurrentYear(), DateUtils.getCurrentMonth(), TmTaskTypeEnum.TM_TASK_BACK.getTaskTypeId());
                String codes = genderTaskCode(thisMonthMaxOrder);
                TmTask task = new TmTask(null, TmTaskTypeEnum.TM_TASK_BACK.getTaskTypeId(),
                        BackTaskStatusEnum.BACK_TASK_IN_FINISHED.getStatus(),
                        null,thisMonthMaxOrder + 1, codes);
                task.setCreateTime(DateUtils.getNowDate());
                task.setCreateBy(SecurityUtils.getUsername());
                backApplyInfo.setCode(codes);
                backApplyInfo.setCreateBy(SecurityUtils.getUsername());
                backApplyInfo.setCreateTime(DateUtils.getNowDate());
                // 保存退料信息到 tm_task 表中
                int result = 0;
                result = taskMapper.insertTmTask(task);
                // 新增退料表back_apply_info信息
                result = getBackInfoResult(info, backApplyInfo, task, result);
                if (result > 0) {
                    // 保存退料详情数据 back_apply_details
                    result = getBackDetailsResult(backApplyInfo, list, result);
                    // 保存退料详情数据 back_check_details
                    extractedCheckDetails(backApplyInfo, detailById, result);
                }
                // 审核通过，处理转入单位领料逻辑
                int maxOrderByDate = tmTaskMapper.getMonthMaxOrderByDate(DateUtils.getCurrentYear(), DateUtils.getCurrentMonth(), TmTaskTypeEnum.TM_TASK_LEASE.getTaskTypeId());
                String taskCode = genderLeaseTaskCode(maxOrderByDate);
                TmTask tmTask1 = new TmTask(null, TmTaskTypeEnum.TM_TASK_LEASE.getTaskTypeId(),
                        LeaseTaskStatusEnum.LEASE_TASK_FINISHED.getStatus(),null
                        ,maxOrderByDate + 1, taskCode);
                tmTask1.setCreateTime(DateUtils.getNowDate());
                tmTask1.setCreateBy(SecurityUtils.getUsername());
                tmTaskMapper.insertTmTask(tmTask1);
                TmTaskAgreement tmTaskAgreement = new TmTaskAgreement(tmTask1.getTaskId(), Long.valueOf(info.getLeaseAgreementId()));
                tmTaskAgreement.setCreateTime(DateUtils.getNowDate());
                tmTaskAgreement.setCreateBy(SecurityUtils.getUsername());
                taskAgreementMapper.insertTmTaskAgreement(tmTaskAgreement);
                /** 设置审批人为默认的董班长 --防止代码冲突 **/
                Long peopleId = leaseApplyInfoMapper.getDirectAuditBy();
                LeaseApplyInfo applyInfo = new LeaseApplyInfo();
                applyInfo.setDirectAuditBy(peopleId);
                applyInfo.setCode(taskCode);
                applyInfo.setTaskId(tmTask1.getTaskId());
                applyInfo.setLeasePerson(info.getLeaseMan());
                applyInfo.setPhone(info.getLeasePhone());
                applyInfo.setCreateBy(SecurityUtils.getUsername());
                applyInfo.setCreateTime(DateUtils.getNowDate());
                /** 设置审批人为默认的董班长 --防止代码冲突 **/
                int count = leaseApplyInfoMapper.insertLeaseApplyInfo(applyInfo);
                if (count > 0) {
                    // 新增lease_apply_details表数据
                    count = getLeaseApplyCount(list, applyInfo, count);
                    // 插入 lease_out_details表数据
                    if (count > 0) {
                        extracted(sltAgreementInfo, info, detailById, applyInfo);
                    }
                }

                return AjaxResult.success("直转成功");

            } else {
                return AjaxResult.error("直转失败,数据为空");
            }
        } catch (Exception e) {
            e.printStackTrace();
            log.error("直转失败:" + e.getMessage());
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
            return AjaxResult.error("直转失败");
        }
    }


    /**
     * 生成退料单号
     * @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);
    }

    /**
     * 新增退料信息
     * @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;
    }

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

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

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

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

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


}
