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

import java.io.OutputStream;
import java.math.BigDecimal;
import java.net.URLEncoder;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.stream.Collectors;

import com.bonus.common.biz.constant.GlobalConstants;
import com.bonus.common.biz.enums.*;
import lombok.extern.slf4j.Slf4j;

import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.json.JSONObject;
import com.ah.sbd.SmsTool;
import com.ah.sbd.utils.param.BatchSmsByContentParam;
import com.bonus.common.biz.config.DateTimeHelper;
import com.bonus.common.biz.config.PoiOutPage;
import com.bonus.common.biz.constant.BmConfigItems;
import com.bonus.common.biz.constant.MaterialConstants;
import com.bonus.common.biz.domain.BmFileInfo;
import com.bonus.common.biz.domain.lease.*;
import com.bonus.common.core.exception.ServiceException;
import com.bonus.common.core.utils.DateUtils;
import com.bonus.common.core.utils.StringUtils;
import com.bonus.common.core.web.domain.AjaxResult;
import com.bonus.common.security.utils.SecurityUtils;
import com.bonus.material.back.domain.vo.MaCodeVo;
import com.bonus.material.basic.domain.BmQrcodeInfo;
import com.bonus.material.basic.mapper.BmFileInfoMapper;
import com.bonus.material.lease.domain.LeaseApplyDetails;
import com.bonus.material.lease.domain.LeasePublishDetails;
import com.bonus.material.lease.domain.vo.LeaseApplyRequestVo;
import com.bonus.material.lease.domain.vo.LeaseOutVo;
import com.bonus.material.lease.mapper.LeaseApplyDetailsMapper;
import com.bonus.material.lease.mapper.LeaseOutDetailsMapper;
import com.bonus.material.lease.mapper.LeaseTaskMapper;
import com.bonus.material.lease.service.ILeaseOutDetailsService;
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 org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.springframework.dao.DataAccessException;
import org.springframework.stereotype.Service;
import com.bonus.material.lease.mapper.LeaseApplyInfoMapper;
import com.bonus.material.lease.service.ILeaseApplyInfoService;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.transaction.interceptor.TransactionAspectSupport;
import org.springframework.util.CollectionUtils;
import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;

/**
 * 领料任务Service业务层处理
 *
 * @author xsheng
 * @date 2024-10-16
 */
@Service
@Slf4j
public class LeaseApplyInfoServiceImpl implements ILeaseApplyInfoService {

    @Resource
    private ILeaseOutDetailsService leaseOutDetailsService;

    @Resource
    private LeaseApplyInfoMapper leaseApplyInfoMapper;

    @Resource
    private LeaseApplyDetailsMapper leaseApplyDetailsMapper;

    @Resource
    private TmTaskMapper tmTaskMapper;

    @Resource
    TmTaskAgreementMapper tmTaskAgreementMapper;

    @Resource
    private BmFileInfoMapper bmFileInfoMapper;

    @Resource
    private LeaseOutDetailsMapper leaseOutDetailsMapper;

    @Resource
    private LeaseTaskMapper mapper;

    /**
     * 查询领料任务
     *
     * @param id 领料任务主键
     * @return 领料任务
     */
    @Override
    public LeaseApplyRequestVo selectLeaseApplyInfoById(Long id, String keyword, String publishTask) {
        // 性能监控开始
        long startTime = System.currentTimeMillis();
        Map<String, Long> stepTimes = new LinkedHashMap<>();
        Set<String> userRoles = SecurityUtils.getLoginUser().getRoles();
        // 检查用户是否具有特殊角色
        boolean hasSpecialRole = hasSpecialRole(userRoles);
        
        log.info("=== selectLeaseApplyInfoById开始执行，id: {}, keyword: {}, publishTask: {}", id, keyword, publishTask);
        
        try {
            // 步骤1: 初始化查询对象和获取用户信息
            long step1Start = System.currentTimeMillis();
            LeaseApplyInfo leaseApplyInfo = new LeaseApplyInfo();
            leaseApplyInfo.setId(id);
            Long userId = SecurityUtils.getLoginUser().getUserid();
            stepTimes.put("初始化和获取用户信息", System.currentTimeMillis() - step1Start);
            
            // 步骤2: 查询用户绑定的物资类型
            long step2Start = System.currentTimeMillis();
            //List<Long> typeIdList = leaseApplyInfoMapper.selectTypeIdList(userId);
            stepTimes.put("查询用户绑定物资类型", System.currentTimeMillis() - step2Start);

            // 步骤3: 设置查询参数
            long step3Start = System.currentTimeMillis();
            if (!hasSpecialRole) {
                leaseApplyInfo.setUserId(userId);
            }
            if (StringUtils.isNotBlank(keyword)) {
                leaseApplyInfo.setKeyWord(keyword);
            }
            if (StringUtils.isNotBlank(publishTask)) {
                leaseApplyInfo.setPublishTask(publishTask);
            }
            stepTimes.put("设置查询参数", System.currentTimeMillis() - step3Start);
            
            // 步骤4: 查询主要的申请信息
            long step4Start = System.currentTimeMillis();
            Optional<LeaseApplyInfo> optionalInfo = Optional.ofNullable(leaseApplyInfoMapper.selectLeaseApplyInfoById(leaseApplyInfo));
            stepTimes.put("查询主要申请信息", System.currentTimeMillis() - step4Start);
            LeaseApplyRequestVo leaseApplyRequestVo = new LeaseApplyRequestVo();
            
            // 步骤5: 查询领用出库数据（可选）
            if (StringUtils.isNotBlank(publishTask)) {
                long step5Start = System.currentTimeMillis();
                leaseApplyInfo.setPublishTask(publishTask);
                List<LeaseApplyInfo> leaseApplyOutList = leaseApplyInfoMapper.selectPublishList(leaseApplyInfo);
                if (!CollectionUtils.isEmpty(leaseApplyOutList)) {
                    LeaseApplyInfo applyInfo = leaseApplyOutList.get(0);
                    if (applyInfo.getPreCountNum().compareTo(applyInfo.getAlNum()) == 0) {
                        applyInfo.setTaskStatus(LeaseTaskStatusEnum.LEASE_TASK_FINISHED.getStatus());
                        applyInfo.setTaskStatusName(LeaseTaskStatusEnum.LEASE_TASK_FINISHED.getStatusName());
                    } else {
                        applyInfo.setTaskStatus(LeaseTaskStatusEnum.LEASE_TASK_IN_PROGRESS.getStatus());
                        applyInfo.setTaskStatusName(LeaseTaskStatusEnum.LEASE_TASK_IN_PROGRESS.getStatusName());
                    }
                    optionalInfo = Optional.of(leaseApplyOutList.get(0));
                }
                stepTimes.put("查询领用出库数据", System.currentTimeMillis() - step5Start);
            } else {
                stepTimes.put("查询领用出库数据", 0L); // 跳过此步骤
            }
            optionalInfo.ifPresent(info -> {
                // 步骤6: 查询附件信息
                long step6Start = System.currentTimeMillis();
                BmFileInfo bmFileInfo = new BmFileInfo();
                bmFileInfo.setModelId(id);
                bmFileInfo.setTaskType(2);
                bmFileInfo.setFileType(5L);
                List<BmFileInfo> bmFileInfoList = bmFileInfoMapper.selectBmFileInfoList(bmFileInfo);
                if (!CollectionUtils.isEmpty(bmFileInfoList)) {
                    info.setBmFileInfos(bmFileInfoList);
                }
                stepTimes.put("查询附件信息", System.currentTimeMillis() - step6Start);
                
                // 步骤7: 设置审批人签名和发料单位
                long step7Start = System.currentTimeMillis();
                /** 设置审批人签名url  防止代码冲突  **/
                String directAuditUrl = leaseApplyInfoMapper.getDirectAuditUrl(info);
                info.setDirectAuditSignUrl(directAuditUrl);
                /** 设置审批人签名url  防止代码冲突  **/

                /** 设置发料单位  防止代码冲突  **/
                if(info.getDirectAuditBy() != null){
                    String sendUnit = leaseApplyInfoMapper.getSendUnit(info);
                    info.setSendUnit(sendUnit);
                }
                // 电子签名进行base64拼接
                if (StringUtils.isNotBlank(info.getLeaseSignUrl())) {
                    if (!info.getLeaseSignUrl().startsWith("http")) {
                        info.setLeaseSignUrl("data:image/png;base64," + info.getLeaseSignUrl());
                    }
                }
                /** 设置发料单位  防止代码冲突  **/
                stepTimes.put("设置签名和单位信息", System.currentTimeMillis() - step7Start);
                
                leaseApplyRequestVo.setLeaseApplyInfo(info);
                // 步骤8: 获取领料单详情
                long step8Start = System.currentTimeMillis();
                List<LeaseApplyDetails> details;
                if (hasSpecialRole) {
                    details = leaseApplyDetailsMapper.selectLeaseApplyDetailsList(new LeaseApplyDetails(info.getId(), keyword, null, null));
                } else {
                    details = leaseApplyDetailsMapper.selectLeaseApplyDetailsList(new LeaseApplyDetails(info.getId(), keyword, userId, null));
                }
                stepTimes.put("获取领料单详情", System.currentTimeMillis() - step8Start);

                // 步骤81: 获取领料单详情
                long step81Start = System.currentTimeMillis();
                // 走单独的领用详情查询
                if (StringUtils.isNotBlank(publishTask)) {
                    // 根据领用批次查询领用详情
                    details = leaseApplyDetailsMapper.getDetailsPublish(leaseApplyInfo);
                    if (!CollectionUtils.isEmpty(details)) {
                        for (LeaseApplyDetails detail : details) {
                            // 根据parent_id和type_id查询出库数量
                            BigDecimal outNum = leaseApplyDetailsMapper.getOutNum(detail);
                            detail.setAlNum(outNum);
                            detail.setOutNum(detail.getPreNum().subtract(outNum));
                            if (detail.getPreNum().compareTo(detail.getAlNum()) == 0) {
                                detail.setStatus("2");
                            } else {
                                detail.setStatus("1");
                            }
                        }
                    }
                }
                if (details.size()>0){
                    for (LeaseApplyDetails detail : details){
                        //查询类型的库存和总待出库数量
                        LeaseApplyDetails pendingOutNum = mapper.selectPendingOutNum(detail);
                        detail.setPendingOutNum(pendingOutNum.getPendingOutNum());
                        detail.setStorageNum(pendingOutNum.getStorageNum());
                    }
                }
                stepTimes.put("领用发布查询", System.currentTimeMillis() - step81Start);

                if (!CollectionUtils.isEmpty(details)) {
                    leaseApplyRequestVo.setLeaseApplyDetailsList(details);
                    
                    // 步骤9: 获取编码详情（批量优化）
                    long step9Start = System.currentTimeMillis();
                    
                    // 收集所有typeId
                    List<Long> typeIds = details.stream()
                        .map(LeaseApplyDetails::getTypeId)
                        .filter(Objects::nonNull)
                        .distinct()
                        .collect(Collectors.toList());
                    
                    if (!CollectionUtils.isEmpty(typeIds)) {
                        // 一次性批量查询所有编码详情
                        List<MaCodeVo> allMaCodeList = leaseApplyDetailsMapper.getCodeListBatch(id, typeIds);
                        
                        // 按typeId分组
                        Map<String, List<MaCodeVo>> maCodeMap = allMaCodeList.stream()
                            .filter(maCode -> maCode.getTypeId() != null)
                            .collect(Collectors.groupingBy(MaCodeVo::getTypeId));
                        
                        // 分配给对应的detail
                        for (LeaseApplyDetails detail : details) {
                            if (detail.getTypeId() != null) {
                                List<MaCodeVo> maCodeVoList = maCodeMap.get(detail.getTypeId().toString());
                                if (!CollectionUtils.isEmpty(maCodeVoList)) {
                                    detail.setMaCodeVoList(maCodeVoList);
                                }
                            }
                        }
                    }
                    
                    stepTimes.put("获取编码详情(批量优化)", System.currentTimeMillis() - step9Start);
                    
                    // 步骤10: 处理审批签名
                    long step10Start = System.currentTimeMillis();
                    // 提取details中的signType和signUrl，单独作为一个集合，并去重
                    List<LeaseOutSign> approveSignList = details.stream()
                            .filter(detail -> detail.getSignUrl() != null)
                            .map(detail -> new LeaseOutSign(detail.getSignType(), detail.getSignUrl()))
                            .distinct()  // 去重操作
                            .collect(Collectors.toList());
                    if (!CollectionUtils.isEmpty(approveSignList)) {
                        for (LeaseOutSign leaseOutSign : approveSignList) {
                            if (StringUtils.isNotBlank(leaseOutSign.getOutSignUrl())) {
                                if (!leaseOutSign.getOutSignUrl().startsWith("http")) {
                                    leaseOutSign.setOutSignUrl("data:image/png;base64," + leaseOutSign.getOutSignUrl());
                                }
                            }
                        }
                        leaseApplyRequestVo.setApproveSignList(approveSignList);
                    }
                    stepTimes.put("处理审批签名", System.currentTimeMillis() - step10Start);
                } else {
                    stepTimes.put("获取编码详情", 0L);
                    stepTimes.put("处理审批签名", 0L);
                }
                // 步骤11: 查询出库库管员电子签名详情
                long step11Start = System.currentTimeMillis();
                List<LeaseOutSign> outSignList = leaseApplyInfoMapper.selectLeaseApplyOutList(id);
                if (!CollectionUtils.isEmpty(outSignList)) {
                    for (LeaseOutSign applyInfo : outSignList) {
                        if (StringUtils.isNotBlank(applyInfo.getOutSignUrl())) {
                            if (!applyInfo.getOutSignUrl().startsWith("http")) {
                                applyInfo.setOutSignUrl("data:image/png;base64," + applyInfo.getOutSignUrl());
                            }
                        }
                    }
                    leaseApplyRequestVo.setKgSignList(outSignList);
                }
                stepTimes.put("查询库管员签名", System.currentTimeMillis() - step11Start);

                // 步骤12: 查询领料人电子签名详情
                long step12Start = System.currentTimeMillis();
                List<LeaseOutSign> signList = leaseApplyInfoMapper.selectOutList(id, null);
                if (!CollectionUtils.isEmpty(signList)) {
                    for (LeaseOutSign applyInfo : signList) {
                        if (StringUtils.isNotBlank(applyInfo.getOutSignUrl())) {
                            if (!applyInfo.getOutSignUrl().startsWith("http")) {
                                applyInfo.setOutSignUrl("data:image/png;base64," + applyInfo.getOutSignUrl());
                            }
                        }
                    }
                    leaseApplyRequestVo.setOutSignList(signList);
                }
                stepTimes.put("查询领料人签名", System.currentTimeMillis() - step12Start);

            });

            // 性能分析总结
            long totalTime = System.currentTimeMillis() - startTime;
            DateTimeHelper.logPerformanceAnalysis("selectLeaseApplyInfoById", totalTime, stepTimes);
            
            return leaseApplyRequestVo;
        } catch (Exception e) {
            // 记录异常日志和性能数据
            long totalTime = System.currentTimeMillis() - startTime;
            log.error("selectLeaseApplyInfoById执行异常，耗时: {}ms, id: {}, 错误: {}", totalTime, id, e.getMessage());
            DateTimeHelper.logPerformanceAnalysis("selectLeaseApplyInfoById(异常)", totalTime, stepTimes);
            
            System.err.println("Error occurred while selecting lease apply info by ID: " + id + e.getMessage());
            throw new RuntimeException("查询失败，请联系管理员");
        }
    }

    @Override
    public List<LeaseApplyDetails> selectLeaseApplyInfoByIdTwo(LeaseApplyInfo bean) {
        try {
            if(bean.getId() == null){
                throw new RuntimeException("领料id不能为空" );
            }
            List<LeaseApplyDetails> leaseApplyDetailsList = leaseApplyInfoMapper.selectOutDetailsList(bean);
            return leaseApplyDetailsList;
        } catch (Exception e) {
            // 记录异常日志
            throw new RuntimeException("Failed to select lease apply info", e);
        }
    }

    @Override
    public LeaseApplyRequestVo getLeaseRequestVo(LeaseApplyDetails bean) {
        try {
            LeaseApplyInfo leaseApplyInfo = new LeaseApplyInfo();
            leaseApplyInfo.setId(bean.getId());
            Long userId = SecurityUtils.getLoginUser().getUserid();
            //leaseApplyInfo.setUserId(userId);
            LeaseApplyInfo info = leaseApplyInfoMapper.getLeaseInfoById(leaseApplyInfo);
            if (StringUtils.isNotBlank(bean.getPublishTask())) {
                leaseApplyInfo.setPublishTask(bean.getPublishTask());
                List<LeaseApplyInfo> leaseApplyOutList = leaseApplyInfoMapper.selectPublishList(leaseApplyInfo);
                if (!CollectionUtils.isEmpty(leaseApplyOutList)) {
                    info = leaseApplyOutList.get(0);
                    info.setUnitName(info.getLeaseUnit());
                    info.setProjectName(info.getLeaseProject());
                }
            }
            LeaseApplyRequestVo leaseApplyRequestVo = new LeaseApplyRequestVo();
            // 查询领用出库数据
                /** 设置审批人签名url  防止代码冲突  **/
                String directAuditUrl =   leaseApplyInfoMapper.getDirectAuditUrl(info);
                info.setDirectAuditSignUrl(directAuditUrl);
                /** 设置审批人签名url  防止代码冲突  **/

                // 电子签名进行base64拼接
                if (StringUtils.isNotBlank(info.getLeaseSignUrl())) {
                    if (!info.getLeaseSignUrl().startsWith("http")) {
                        info.setLeaseSignUrl("data:image/png;base64," + info.getLeaseSignUrl());
                    }
                }
                /** 设置发料单位  防止代码冲突  **/

                leaseApplyRequestVo.setLeaseApplyInfo(info);
                // 获取领料单详情
                List<LeaseApplyDetails> details = leaseApplyInfoMapper.getDetailsLeaseList(bean);
                if (!CollectionUtils.isEmpty(details)) {
                    leaseApplyRequestVo.setLeaseApplyDetailsList(details);
                    for (LeaseApplyDetails detail : details) {
                        // 获取编码详情
                        List<MaCodeVo> maCodeVoList = leaseApplyDetailsMapper.getCodeList(bean.getId(), detail.getTypeId());
                        if (!CollectionUtils.isEmpty(maCodeVoList)) {
                            detail.setMaCodeVoList(maCodeVoList);
                        }
                    }
                    // 提取details中的signType和signUrl，单独作为一个集合，并去重
                    List<LeaseOutSign> approveSignList = details.stream()
                            .filter(detail -> detail.getSignUrl() != null)
                            .map(detail -> new LeaseOutSign(detail.getSignType(), detail.getSignUrl()))
                            .distinct()
                            .collect(Collectors.toList());
                    if (!CollectionUtils.isEmpty(approveSignList)) {
                        for (LeaseOutSign leaseOutSign : approveSignList) {
                            if (StringUtils.isNotBlank(leaseOutSign.getOutSignUrl())) {
                                if (!leaseOutSign.getOutSignUrl().startsWith("http")) {
                                    leaseOutSign.setOutSignUrl("data:image/png;base64," + leaseOutSign.getOutSignUrl());
                                }
                            }
                        }
                        leaseApplyRequestVo.setApproveSignList(approveSignList);
                    }
                }

                // 根据id查询领料出库情况，查询出库人电子签名详情
                List<LeaseOutSign> outSignList = leaseApplyInfoMapper.selectLeaseApplyOutList(bean.getId());
                if (!CollectionUtils.isEmpty(outSignList)) {
                    for (LeaseOutSign applyInfo : outSignList) {
                        if (StringUtils.isNotBlank(applyInfo.getOutSignUrl())) {
                            if (!applyInfo.getOutSignUrl().startsWith("http")) {
                                applyInfo.setOutSignUrl("data:image/png;base64," + applyInfo.getOutSignUrl());
                            }
                        }
                    }
                    leaseApplyRequestVo.setKgSignList(outSignList);
                }
                // 根据id查询领料出库情况，查询材料员电子签名详情
                if(details != null && !details.isEmpty()){
                    bean.setConfirmPerson(details.get(0).getConfirmPerson());
                    LeaseConfirmSign confirmSign = leaseApplyInfoMapper.getLeaseConfirmSign(bean);
                    if(confirmSign != null){
                        if (StringUtils.isNotBlank(confirmSign.getConfirmSignUrl())) {
                            if (!confirmSign.getConfirmSignUrl().startsWith("http")) {
                                confirmSign.setConfirmSignUrl("data:image/png;base64," + confirmSign.getConfirmSignUrl());
                            }
                        }
                        leaseApplyRequestVo.setConfirmSign(confirmSign);
                    }
                }

            // 根据id查询领料出库情况，查询出库人电子签名详情
            List<LeaseOutSign> signList = leaseApplyInfoMapper.selectOutList(bean.getId(), bean.getLeaseSignId());
            if (!CollectionUtils.isEmpty(signList)) {
                for (LeaseOutSign applyInfo : signList) {
                    if (StringUtils.isNotBlank(applyInfo.getOutSignUrl())) {
                        if (!applyInfo.getOutSignUrl().startsWith("http")) {
                            applyInfo.setOutSignUrl("data:image/png;base64," + applyInfo.getOutSignUrl());
                        }
                    }
                }
                leaseApplyRequestVo.setOutSignList(signList);
            }

            return leaseApplyRequestVo;
        } catch (Exception e) {
            // 记录异常日志
            throw new RuntimeException("Failed to select lease apply info", e);
        }
    }


    /**
     * 查询领料任务列表
     *
     * @param leaseApplyInfo 领料任务
     * @return 领料任务
     */
    @Override
    public List<LeaseApplyInfo> selectLeaseApplyInfoList(LeaseApplyInfo leaseApplyInfo) {
        try {
            Set<String> userRoles = SecurityUtils.getLoginUser().getRoles();
            // 检查用户是否具有特殊角色
            boolean hasSpecialRole = hasSpecialRole(userRoles);
            if (!hasSpecialRole) {
                leaseApplyInfo.setUserId(SecurityUtils.getLoginUser().getUserid());
            }
            //用leaseApplyInfo.getQueryType的值来区分是否是领用出库查询，如果是，时间筛选为发布时间
            List<LeaseApplyInfo> list = leaseApplyInfoMapper.selectLeaseApplyInfoList(leaseApplyInfo);
            // 如果statusList包含3、4、5，则为领料出库查询
            if (!CollectionUtils.isEmpty(leaseApplyInfo.getStatusList())) {
                if (((leaseApplyInfo.getStatusList().contains(3) || leaseApplyInfo.getStatusList().contains(4)) && !leaseApplyInfo.getStatusList().contains(1))
                        || leaseApplyInfo.getStatusList().containsAll(Arrays.asList(3, 4, 5))) {
                    extracted(leaseApplyInfo, list);
                }
            }
            // 电子签名列表查询
            if (leaseApplyInfo.getHasSign() != null && leaseApplyInfo.getHasSign() == 0) {
                // 领料数据查询
                list =  leaseApplyInfoMapper.selectNoSignList(leaseApplyInfo);
                // 领用数据查询
                List<LeaseApplyInfo> leaseOutList = leaseApplyInfoMapper.selectLeaseOutList(leaseApplyInfo);
                if (!CollectionUtils.isEmpty(leaseOutList)) {
                    list.addAll(leaseOutList);
                }
            }
            // 使用 Stream API 进行降序排序
            List<LeaseApplyInfo> sortedList = list.stream()
                        .sorted(Comparator.comparing(LeaseApplyInfo::getReleaseTime,
                                Comparator.nullsFirst(Comparator.naturalOrder())).reversed())
                        .collect(Collectors.toList());
            if (!CollectionUtils.isEmpty(sortedList)) {
                String keyWord = leaseApplyInfo.getKeyWord();
                List<?> statusList = leaseApplyInfo.getStatusList();

                // 转换为HashSet提高contains操作的效率（O(1)）
                Set<?> statusSet = CollectionUtils.isEmpty(statusList) ?
                        Collections.emptySet() :
                        new HashSet<>(statusList);

                sortedList = sortedList.stream()
                        .filter(item -> StringUtils.isBlank(keyWord) || containsKeyword(item, keyWord))
                        .filter(item -> statusSet.isEmpty() || statusSet.contains(item.getTaskStatus()))
                        .collect(Collectors.toList());
            }
            return sortedList;
        } catch (Exception e) {
            log.error("查询领料任务列表", e.getMessage());
            return new ArrayList<>();
        }
    }

    /**
     * 检查用户是否具有特殊角色
     * @param userRoles
     * @return
     */
    private boolean hasSpecialRole(Set<String> userRoles) {
        if (userRoles == null) {
            return false;
        }
        List<String> allowedRoles = GlobalConstants.allowedRoles;
        return allowedRoles.stream().anyMatch(userRoles::contains);
    }

    /**
     * 查询领用数据抽取
     * @param leaseApplyInfo
     * @param list
     */
    private void extracted(LeaseApplyInfo leaseApplyInfo, List<LeaseApplyInfo> list) {
        // 查询领用出库数据
        List<LeaseApplyInfo> leaseApplyOutList = leaseApplyInfoMapper.selectPublishList(leaseApplyInfo);
        if (!CollectionUtils.isEmpty(leaseApplyOutList)) {
            list.addAll(leaseApplyOutList);
        }
        for (LeaseApplyInfo applyInfo : list) {
            if (applyInfo.getTaskStatus() != null && applyInfo.getTaskStatus() == 1) {
                continue;
            }
            if (applyInfo.getPreCountNum().compareTo(applyInfo.getAlNum()) == 0) {
                applyInfo.setTaskStatus(LeaseTaskStatusEnum.LEASE_TASK_FINISHED.getStatus());
                applyInfo.setTaskStatusName(LeaseTaskStatusEnum.LEASE_TASK_FINISHED.getStatusName());
            } else {
                applyInfo.setTaskStatus(LeaseTaskStatusEnum.LEASE_TASK_IN_PROGRESS.getStatus());
                applyInfo.setTaskStatusName(LeaseTaskStatusEnum.LEASE_TASK_IN_PROGRESS.getStatusName());
            }
        }
    }

    /**
     * 材料员确认service
     *
     * @return
     */
    @Override
    public int confirmLeaseTask(LeaseApplyDetails details) {
        details.setConfirmPerson(String.valueOf(SecurityUtils.getLoginUser().getUserid()));
        details.setConfirmTime(new Date());
        //进行确认通过
        int count =  leaseApplyInfoMapper.confirmLeaseTask(details);
        return count;
//        if (count > 0) {
//            //查询是否都已确认
//            LeaseApplyInfo leaseApplyInfo = new LeaseApplyInfo();
//            leaseApplyInfo.setId(Long.valueOf(id));
//            List<LeaseApplyDetails> details = leaseApplyInfoMapper.selectOutDetailsList(leaseApplyInfo);
//            //查询details中是否有未确认的数据isConfirm==1
//            int flag = 0;
//            if (!CollectionUtils.isEmpty(details)) {
//                for (LeaseApplyDetails detail : details) {
//                    if (detail.getIsConfirm() == null || detail.getIsConfirm() == 1) {
//                        flag = 1;
//                    }
//                }
//            }
//            if (flag == 0) {
//                //leaseApplyInfo表全部确认
//                int countTwo = leaseApplyInfoMapper.updateLeaseApplyInfoConfirm(Long.valueOf(id));
//                if(countTwo ==0){
//                    throw new ServiceException("确认失败,lease_apply_info表更新失败");
//                }else{
//                    return countTwo;
//                }
//            }
//            return count;
//
//        }else{
//            throw new ServiceException("确认失败，lease_out_details表更新失败");
//        }
    }

    /**
     * 查询已完成出库任务
     *
     * @param leaseApplyInfo 领料任务
     * @return 领料任务集合
     */
    @Override
    public List<LeaseApplyInfo> getCompleteOutTaskList(LeaseApplyInfo leaseApplyInfo) {
        leaseApplyInfo.setUserId(SecurityUtils.getLoginUser().getUserid());
        // 领料数据
        List<LeaseApplyInfo> list = leaseApplyInfoMapper.selectCompleteOutList(leaseApplyInfo);
        // 领用数据
        List<LeaseApplyInfo> leaseApplyOutList = leaseApplyInfoMapper.selectPublish(leaseApplyInfo);
        if (!CollectionUtils.isEmpty(leaseApplyOutList)) {
            list.addAll(leaseApplyOutList);
        }
        if (!CollectionUtils.isEmpty(list)) {
            for (LeaseApplyInfo applyInfo : list) {
                // 根据id去查询总出库数量
                LeaseApplyInfo totalInfo = leaseApplyInfoMapper.getOutList(applyInfo);
                // 根据id去查询确认总出库数量
                LeaseApplyInfo info = leaseApplyInfoMapper.getInfoList(applyInfo);
                if (totalInfo != null) {
                    if (info != null) {
                        if (info.getAlNum().compareTo(totalInfo.getAlNum()) == 0) {
                            applyInfo.setIsConfirm(2);
                        } else {
                            applyInfo.setIsConfirm(1);
                        }
                    } else {
                        applyInfo.setIsConfirm(1);
                    }
                } else {
                    applyInfo.setIsConfirm(1);
                }
            }
        }
        //材料站权限过滤
        String username = SecurityUtils.getLoginUser().getUsername();
        if(!CollectionUtils.isEmpty(list)){
              list =  list.stream()
                    .filter(info -> {
                        // 调用 mapper 方法检查是否有符合条件的数据
                        int count = leaseApplyInfoMapper.checkPermission(info.getExternalId(), username);
                        return count > 0;
                    })
                    .collect(Collectors.toList());
        }

        if (leaseApplyInfo.getIsConfirm()!=null) {
            if (leaseApplyInfo.getIsConfirm() == 2) {
                // 已确认
                list = list.stream()
                        .filter(item -> item.getIsConfirm() == 2)
                        .collect(Collectors.toList());
            } else {
                // 未确认
                list = list.stream()
                        .filter(item -> item.getIsConfirm() == 1)
                        .collect(Collectors.toList());
            }

        }
        // 使用 Stream API 进行降序排序
        List<LeaseApplyInfo> sortedList = list.stream()
                .sorted(Comparator.comparing(LeaseApplyInfo::getCreateTime,
                        Comparator.nullsFirst(Comparator.naturalOrder())).reversed())
                .collect(Collectors.toList());
        if (!CollectionUtils.isEmpty(sortedList)) {
            String keyWord = leaseApplyInfo.getKeyWord();
            // 如果关键字不为空，进行过滤
            if (!StringUtils.isBlank(keyWord)) {
                sortedList = sortedList.stream()
                        .filter(item -> containsKeyword(item, keyWord))
                        .collect(Collectors.toList());
            }
        }
        return sortedList;
    }

    /**
     * 查询材料员确认
     *
     * @param leaseApplyInfo 领料任务
     * @return 领料任务集合
     */
    @Override
    public List<LeaseApplyInfo> getConfirmTaskList(LeaseApplyInfo leaseApplyInfo) {
        leaseApplyInfo.setUserId(SecurityUtils.getLoginUser().getUserid());
         // 领料数据
        List<LeaseApplyInfo> list = leaseApplyInfoMapper.selectCompleteOutList(leaseApplyInfo);
        // 领用数据
        List<LeaseApplyInfo> leaseApplyOutList = leaseApplyInfoMapper.selectPublish(leaseApplyInfo);
        if (!CollectionUtils.isEmpty(leaseApplyOutList)) {
            list.addAll(leaseApplyOutList);
        }
        // 使用Stream处理列表，避免显式for循环
        list.stream()
                .filter(Objects::nonNull) // 过滤null元素
                .forEach(applyInfo -> {
                    LeaseApplyInfo totalInfo = leaseApplyInfoMapper.getOutList(applyInfo);
                    LeaseApplyInfo info = leaseApplyInfoMapper.getInfoList(applyInfo);

                    // 简化判断逻辑
                    int isConfirm = (totalInfo != null && info != null
                            && info.getAlNum().compareTo(totalInfo.getAlNum()) == 0) ? 2 : 1;
                    applyInfo.setIsConfirm(isConfirm);
                });

        if (leaseApplyInfo.getIsConfirm()!=null) {
            if (leaseApplyInfo.getIsConfirm() == 2) {
                // 已确认
                list = list.stream()
                        .filter(item -> item.getIsConfirm() == 2)
                        .collect(Collectors.toList());
            } else {
                // 未确认
                list = list.stream()
                        .filter(item -> item.getIsConfirm() == 1)
                        .collect(Collectors.toList());
            }

        }
        // 使用 Stream API 进行降序排序
        List<LeaseApplyInfo> sortedList = list.stream()
                .sorted(Comparator.comparing(LeaseApplyInfo::getCreateTime,
                        Comparator.nullsFirst(Comparator.naturalOrder())).reversed())
                .collect(Collectors.toList());
        if (!CollectionUtils.isEmpty(sortedList)) {
            String keyWord = leaseApplyInfo.getKeyWord();
            // 如果关键字不为空，进行过滤
            if (!StringUtils.isBlank(keyWord)) {
                sortedList = sortedList.stream()
                        .filter(item -> containsKeyword(item, keyWord))
                        .collect(Collectors.toList());
            }
        }
        return sortedList;
    }

    /**
     * 统计时间段出库总数量
     * @param leaseApplyInfo
     * @return
     */
    @Override
    public LeaseApplyInfo getOutNum(LeaseApplyInfo leaseApplyInfo) {
        return leaseApplyInfoMapper.getOutNum(leaseApplyInfo);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public AjaxResult updateLeaseNum(LeaseApplyDetails leaseApplyDetails) {
        try {
            if (leaseApplyDetails.getNewTypeId()!= null){
                // 根据parentId查询发布数量
                LeaseApplyDetails applyDetails = leaseApplyInfoMapper.getPublishNum(leaseApplyDetails);
                // 根据传入的值判断少了多少发布数量
                if (applyDetails != null) {
                    BigDecimal num = leaseApplyDetails.getPublishNum().subtract(leaseApplyDetails.getPreNum());
                    leaseApplyDetails.setPublishNum(applyDetails.getPublishNum().subtract(num));
                }
                int res = leaseApplyInfoMapper.updateLeaseNum(leaseApplyDetails);
                if (res <= 0){
                    return AjaxResult.error("修改领用表失败");
                }
                res = leaseApplyInfoMapper.updateLeasePublish(leaseApplyDetails);
                if (res <= 0){
                    return AjaxResult.error("修改领料发布表失败");
                }
            } else {
                int res = leaseApplyInfoMapper.updateLeaseNumTwo(leaseApplyDetails);
                if (res <= 0){
                    return AjaxResult.error("修改领料表失败");
                }
            }
            return AjaxResult.success("修改成功");
        } catch (Exception e) {
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
            log.error(e.getMessage());
            return AjaxResult.error("修改失败");
        }
    }

    /**
     * 获取领料出库详细信息
     * @param bean
     * @return
     */
    @Override
    public List<LeaseApplyDetails> getOutInfo(LeaseApplyInfo bean) {
        // 性能监控开始
        long startTime = System.currentTimeMillis();
        Map<String, Long> stepTimes = new LinkedHashMap<>();
        String keyword = bean.getKeyWord();
        String publishTask = bean.getPublishTask();
        try {
            // 步骤1: 初始化查询对象和获取用户信息
            long step1Start = System.currentTimeMillis();
            LeaseApplyInfo leaseApplyInfo = new LeaseApplyInfo();
            leaseApplyInfo.setId(bean.getId());
            Long userId = SecurityUtils.getLoginUser().getUserid();
            stepTimes.put("初始化和获取用户信息", System.currentTimeMillis() - step1Start);

            // 步骤2: 查询用户绑定的物资类型
            long step2Start = System.currentTimeMillis();
            List<Long> typeIdList = leaseApplyInfoMapper.selectTypeIdList(userId);
            stepTimes.put("查询用户绑定物资类型", System.currentTimeMillis() - step2Start);

            // 步骤3: 设置查询参数
            if (!CollectionUtils.isEmpty(typeIdList)) {
                leaseApplyInfo.setTypeIdList(typeIdList);
            } else {
                leaseApplyInfo.setUserId(userId);
            }
            if (StringUtils.isNotBlank(keyword)) {
                leaseApplyInfo.setKeyWord(keyword);
            }
            if (StringUtils.isNotBlank(publishTask)) {
                leaseApplyInfo.setPublishTask(publishTask);
            }


            // 步骤8: 获取领料单详情
            long step8Start = System.currentTimeMillis();
            List<LeaseApplyDetails> details;
            if (!CollectionUtils.isEmpty(typeIdList)) {
                details = leaseApplyDetailsMapper.selectLeaseApplyDetailsList(new LeaseApplyDetails(bean.getId(), keyword, null, typeIdList));
            } else {
                details = leaseApplyDetailsMapper.selectLeaseApplyDetailsList(new LeaseApplyDetails(bean.getId(), keyword, userId, null));
            }
            stepTimes.put("获取领料单详情", System.currentTimeMillis() - step8Start);

            // 步骤81: 获取领料单详情
            long step81Start = System.currentTimeMillis();
            // 走单独的领用详情查询
            if (StringUtils.isNotBlank(publishTask)) {
                // 根据领用批次查询领用详情
                details = leaseApplyDetailsMapper.getDetailsPublish(leaseApplyInfo);
                if (!CollectionUtils.isEmpty(details)) {
                    for (LeaseApplyDetails detail : details) {
                        // 根据parent_id和type_id查询出库数量
                        BigDecimal outNum = leaseApplyDetailsMapper.getOutNum(detail);
                        detail.setAlNum(outNum);
                        detail.setOutNum(detail.getPreNum().subtract(outNum));
                        if (detail.getPreNum().compareTo(detail.getAlNum()) == 0) {
                            detail.setStatus("2");
                        } else {
                            detail.setStatus("1");
                        }
                    }
                }
            }
            if (details.size() > 0) {
                for (LeaseApplyDetails detail : details) {
                    //查询类型的库存和总待出库数量
                    LeaseApplyDetails pendingOutNum = mapper.selectPendingOutNum(detail);
                    detail.setPendingOutNum(pendingOutNum.getPendingOutNum());
                    detail.setStorageNum(pendingOutNum.getStorageNum());
                }
            }
            stepTimes.put("领用发布查询", System.currentTimeMillis() - step81Start);

            if (!CollectionUtils.isEmpty(details)) {
                // 收集所有typeId
                List<Long> typeIds = details.stream()
                        .map(LeaseApplyDetails::getTypeId)
                        .filter(Objects::nonNull)
                        .distinct()
                        .collect(Collectors.toList());

                if (!CollectionUtils.isEmpty(typeIds)) {
                    // 一次性批量查询所有编码详情
                    List<MaCodeVo> allMaCodeList = leaseApplyDetailsMapper.getCodeListBatch(bean.getId(), typeIds);
                    // 按typeId分组
                    Map<String, List<MaCodeVo>> maCodeMap = allMaCodeList.stream()
                            .filter(maCode -> maCode.getTypeId() != null)
                            .collect(Collectors.groupingBy(MaCodeVo::getTypeId));
                    // 分配给对应的detail
                    for (LeaseApplyDetails detail : details) {
                        if (detail.getTypeId() != null) {
                            List<MaCodeVo> maCodeVoList = maCodeMap.get(detail.getTypeId().toString());
                            if (!CollectionUtils.isEmpty(maCodeVoList)) {
                                detail.setMaCodeVoList(maCodeVoList);
                            }
                        }
                    }
                }
            }
            return details;
        } catch (Exception e) {
            // 记录异常日志和性能数据
            long totalTime = System.currentTimeMillis() - startTime;
            log.error("selectLeaseApplyInfoById执行异常，耗时: {}ms, id: {}, 错误: {}", totalTime, bean.getId(), e.getMessage());
            DateTimeHelper.logPerformanceAnalysis("selectLeaseApplyInfoById(异常)", totalTime, stepTimes);

            System.err.println("Error occurred while selecting lease apply info by ID: " + bean.getId() + e.getMessage());
            throw new RuntimeException("查询失败，请联系管理员");
        }
    }


    /**
     * 关键字搜索
     * @param item
     * @param keyWord
     * @return
     */
    private boolean containsKeyword(LeaseApplyInfo item, String keyWord) {
        return (item.getMaTypeNames() != null && item.getMaTypeNames().contains(keyWord)) ||
                (item.getLeaseUnit() != null && item.getLeaseUnit().contains(keyWord)) ||
                (item.getUnitName() != null && item.getUnitName().contains(keyWord)) ||
                (item.getLeaseProject() != null && item.getLeaseProject().contains(keyWord)) ||
                (item.getProjectName() != null && item.getProjectName().contains(keyWord)) ||
                (item.getCode() != null && item.getCode().contains(keyWord)) ||
                (item.getCreateBy() != null && item.getCreateBy().contains(keyWord)) ||
                (item.getLeasePerson() != null && item.getLeasePerson().contains(keyWord)) ||
                (item.getLeasePhone() != null && item.getLeasePhone().contains(keyWord)) ||
                (item.getContractPart() != null && item.getContractPart().contains(keyWord)) ||
                (item.getImpUnitName() != null && item.getImpUnitName().contains(keyWord))||
                (item.getBusinessCode() != null && item.getBusinessCode().contains(keyWord));
    }

    /**
     * 新增领料任务
     *
     * @param leaseApplyRequestVo 领料任务
     * @return 结果
     */
    @Override
    public AjaxResult insertLeaseApplyInfo(LeaseApplyRequestVo leaseApplyRequestVo) {
        /*int result = 0;
        if (null == leaseApplyRequestVo.getLeaseApplyInfo()) {
            return AjaxResult.error("请先填写领料任务信息");
        }
        if (CollectionUtil.isEmpty(leaseApplyRequestVo.getLeaseApplyDetailsList())) {
            return AjaxResult.error("请先添加领料任务物资明细");
        }
        leaseApplyRequestVo.getLeaseApplyInfo().setCreateTime(DateUtils.getNowDate());
        leaseApplyRequestVo.getLeaseApplyInfo().setCreateBy(SecurityUtils.getLoginUser().getSysUser().getNickName());
        try {
            // 获取 LeaseApplyDetails 列表
            List<LeaseApplyDetails> leaseApplyDetailsList = leaseApplyRequestVo.getLeaseApplyDetailsList();
            for (LeaseApplyDetails applyDetails : leaseApplyDetailsList) {
                if (applyDetails.getCompanyId() == null) {
                    throw new RuntimeException("未知所属公司领料任务，无法操作！");
                }
            }
            // 按 companyId 进行分组
            Map<Long, List<LeaseApplyDetails>> groupedByCompanyId = leaseApplyDetailsList.stream()
                    .collect(Collectors.groupingBy(LeaseApplyDetails::getCompanyId));
            for (Map.Entry<Long, List<LeaseApplyDetails>> entry : groupedByCompanyId.entrySet()) {
                Long key = entry.getKey();
                List<LeaseApplyDetails> details = entry.getValue();
                TmTaskTypeEnum splitType = null;
                String taskTypeLabel = null;
                // 机具领料任务
                if (key == 101) {
                    splitType = TmTaskTypeEnum.TM_TASK_JJ_LEASE;
                    taskTypeLabel = MaterialConstants.JJ_LEASE_TASK_TYPE_LABEL;
                    // 安全工器具领料任务
                } else if (key == 102) {
                    splitType = TmTaskTypeEnum.TM_TASK_SAFE_LEASE;
                    taskTypeLabel = MaterialConstants.AQ_LEASE_TASK_TYPE_LABEL;
                    // 宏源领料任务
                } else if (key == 309) {
                    splitType = TmTaskTypeEnum.TM_TASK_HY_LEASE;
                    taskTypeLabel = MaterialConstants.HY_LEASE_TASK_TYPE_LABEL;
                } else {
                    throw new RuntimeException("未知所属公司领料任务，无法操作！");
                }
                result += processLeaseTask(leaseApplyRequestVo, splitType, taskTypeLabel);
                if (result > 0) {
                    return insertPurchaseCheckDetails(details, leaseApplyRequestVo.getLeaseApplyInfo().getId());
                } else {
                    return AjaxResult.error("新增任务失败,lease_apply_info表插入0条");
                }
            }
        } catch (DataAccessException e) {
            throw new RuntimeException("数据库操作失败:" + e.getMessage());
        } catch (Exception e) {
            throw new RuntimeException("新增任务失败:" + e.getMessage());
        }
        return AjaxResult.error("新增任务失败");*/
        if (null == leaseApplyRequestVo.getLeaseApplyInfo()) {
            return AjaxResult.error("请先填写领料任务信息");
        }
        if (CollectionUtil.isEmpty(leaseApplyRequestVo.getLeaseApplyDetailsList())) {
            return AjaxResult.error("请先添加领料任务物资明细");
        }
        leaseApplyRequestVo.getLeaseApplyInfo().setCreateTime(DateUtils.getNowDate());
        leaseApplyRequestVo.getLeaseApplyInfo().setCreateBy(SecurityUtils.getLoginUser().getSysUser().getNickName());
        try {
            int thisMonthMaxOrder = tmTaskMapper.getMonthMaxOrderByDate(DateUtils.getCurrentYear(), DateUtils.getCurrentMonth(), TmTaskTypeEnum.TM_TASK_LEASE.getTaskTypeId());
            LeasePublishDetails publishDetails = mapper.selectPublishDetailsByCode();
            if (publishDetails != null && StringUtils.isNotBlank(publishDetails.getCode())) {
                String code = publishDetails.getCode();
                if (code.contains("-")) {
                    // 分割字符串，获取"-"后面的部分
                    String suffix = code.split("-")[1];
                    try {
                        // 转换为整数
                        int value = Integer.parseInt(suffix);
                        // 比较并更新最大值
                        if (value > thisMonthMaxOrder) {
                            thisMonthMaxOrder = value;
                        }
                    } catch (NumberFormatException e) {
                        throw new ServiceException("保存失败，请联系管理员");
                    }
                }
            }
            String taskCode = genderTaskCode(thisMonthMaxOrder);
            TmTask tmTask = new TmTask(null, TmTaskTypeEnum.TM_TASK_LEASE.getTaskTypeId(),
                    LeaseTaskStatusEnum.LEASE_TASK_TO_PUBLISHED.getStatus(),
                    leaseApplyRequestVo.getLeaseApplyInfo().getCompanyId(),thisMonthMaxOrder + 1, taskCode);
            tmTask.setCreateTime(DateUtils.getNowDate());
            tmTask.setCreateBy(SecurityUtils.getLoginUser().getSysUser().getNickName());
            tmTaskMapper.insertTmTask(tmTask);
            TmTaskAgreement tmTaskAgreement = new TmTaskAgreement(tmTask.getTaskId(), leaseApplyRequestVo.getLeaseApplyInfo().getAgreementId());
            tmTaskAgreement.setCreateTime(DateUtils.getNowDate());
            tmTaskAgreement.setCreateBy(SecurityUtils.getLoginUser().getSysUser().getNickName());
            tmTaskAgreementMapper.insertTmTaskAgreement(tmTaskAgreement);
            leaseApplyRequestVo.getLeaseApplyInfo().setTaskId(tmTask.getTaskId());
            leaseApplyRequestVo.getLeaseApplyInfo().setCode(taskCode);

            /** 设置审批人为默认的董班长 --防止代码冲突 **/
            Long peopleId = leaseApplyInfoMapper.getDirectAuditBy();
            leaseApplyRequestVo.getLeaseApplyInfo().setDirectAuditBy(peopleId);
            /** 设置审批人为默认的董班长 --防止代码冲突 **/

            int count = leaseApplyInfoMapper.insertLeaseApplyInfo(leaseApplyRequestVo.getLeaseApplyInfo());
            if (!CollectionUtils.isEmpty(leaseApplyRequestVo.getLeaseApplyInfo().getBmFileInfos())) {
                leaseApplyRequestVo.getLeaseApplyInfo().getBmFileInfos().forEach(bmFileInfo -> {
                    bmFileInfo.setTaskType(2);
                    bmFileInfo.setTaskId(tmTask.getTaskId());
                    bmFileInfo.setModelId(leaseApplyRequestVo.getLeaseApplyInfo().getId());
                    bmFileInfo.setFileType(5L);
                    bmFileInfo.setCreateBy(SecurityUtils.getLoginUser().getSysUser().getNickName());
                    bmFileInfo.setCreateTime(DateUtils.getNowDate());
                    bmFileInfoMapper.insertBmFileInfo(bmFileInfo);
                });
            }
            if (count > 0) {
                return insertPurchaseCheckDetails(leaseApplyRequestVo.getLeaseApplyDetailsList(), leaseApplyRequestVo.getLeaseApplyInfo().getId());
            } else {
                return AjaxResult.error("新增任务失败,lease_apply_info表插入0条");
            }
        } catch (DataAccessException e) {
            return AjaxResult.error("数据库操作失败:" + e.getMessage());
        } catch (Exception e) {
            return AjaxResult.error("新增任务失败:" + e.getMessage());
        }
    }

    /**
     * 处理任务
     * @param leaseApplyRequestVo
     * @param splitType
     * @param taskTypeLabel
     * @return
     */
    /*private int processLeaseTask(LeaseApplyRequestVo leaseApplyRequestVo, TmTaskTypeEnum splitType, String taskTypeLabel) {
        int thisMonthMaxOrder = tmTaskMapper.getMonthMaxOrderByDate(DateUtils.getCurrentYear(), DateUtils.getCurrentMonth(),
                TmTaskTypeEnum.TM_TASK_LEASE.getTaskTypeId());
        String taskCode = genderTaskCode(thisMonthMaxOrder, taskTypeLabel);

        TmTask tmTask = new TmTask(null, TmTaskTypeEnum.TM_TASK_LEASE.getTaskTypeId(),
                LeaseTaskStatusEnum.LEASE_TASK_TO_PUBLISHED.getStatus(),
                leaseApplyRequestVo.getLeaseApplyInfo().getCompanyId(), thisMonthMaxOrder + 1, taskCode);
        tmTask.setCreateTime(DateUtils.getNowDate());
        tmTask.setCreateBy(SecurityUtils.getLoginUser().getSysUser().getNickName());
        tmTask.setSplitType(splitType.getTaskTypeId());
        tmTaskMapper.insertTmTask(tmTask);

        TmTaskAgreement tmTaskAgreement = new TmTaskAgreement(tmTask.getTaskId(), leaseApplyRequestVo.getLeaseApplyInfo().getAgreementId());
        tmTaskAgreement.setCreateTime(DateUtils.getNowDate());
        tmTaskAgreement.setCreateBy(SecurityUtils.getLoginUser().getSysUser().getNickName());
        tmTaskAgreementMapper.insertTmTaskAgreement(tmTaskAgreement);

        leaseApplyRequestVo.getLeaseApplyInfo().setTaskId(tmTask.getTaskId());
        leaseApplyRequestVo.getLeaseApplyInfo().setCode(taskCode);

        // 设置审批人为默认的董班长 --防止代码冲突
        Long peopleId = leaseApplyInfoMapper.getDirectAuditBy();
        leaseApplyRequestVo.getLeaseApplyInfo().setDirectAuditBy(peopleId);

        int count = leaseApplyInfoMapper.insertLeaseApplyInfo(leaseApplyRequestVo.getLeaseApplyInfo());

        if (!CollectionUtils.isEmpty(leaseApplyRequestVo.getLeaseApplyInfo().getBmFileInfos())) {
            leaseApplyRequestVo.getLeaseApplyInfo().getBmFileInfos().forEach(bmFileInfo -> {
                bmFileInfo.setTaskType(2);
                bmFileInfo.setTaskId(tmTask.getTaskId());
                bmFileInfo.setModelId(leaseApplyRequestVo.getLeaseApplyInfo().getId());
                bmFileInfo.setFileType(5L);
                bmFileInfo.setCreateBy(SecurityUtils.getLoginUser().getSysUser().getNickName());
                bmFileInfo.setCreateTime(DateUtils.getNowDate());
                bmFileInfoMapper.insertBmFileInfo(bmFileInfo);
            });
        }
        return count;
    }*/

    /**
     * 发布任务
     *
     * @param leaseApplyInfo 领料任务info
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public AjaxResult publish(LeaseApplyInfo leaseApplyInfo) {
        if (leaseApplyInfo.getId() == null) {
            return AjaxResult.error("ID为空,请完善后重新发布!");
        }
        if (leaseApplyInfo.getTaskId() == null) {
            return AjaxResult.error("任务ID为空,请完善后重新发布!");
        }
        try {
            leaseApplyInfo.setReleaseTime(DateUtils.getTime());
            leaseApplyInfo.setPublisher(SecurityUtils.getLoginUser().getUserid());
            int result = leaseApplyInfoMapper.updateLeaseApplyInfo(leaseApplyInfo);
            if (result > GlobalConstants.INT_0) {
                // 同步修改tm_task任务状态, 如果不需要审核，改成 LEASE_TASK_IN_PROGRESS， 如果需要审核，改成 LEASE_TASK_TO_AUDIT
                TmTask tmTask = new TmTask();
                tmTask.setTaskType(TmTaskTypeEnum.TM_TASK_LEASE.getTaskTypeId());
                tmTask.setTaskId(leaseApplyInfo.getTaskId());
                tmTask.setTaskStatus(LeaseTaskStatusEnum.LEASE_TASK_IN_PROGRESS.getStatus());
                tmTaskMapper.updateTmTask(tmTask);
                return AjaxResult.success("发布成功");
            }
            return AjaxResult.error("发布失败");
        } catch (DataAccessException e) {
            // 抛出异常、回滚数据
            throw new RuntimeException();
        } catch (Exception e) {
            return AjaxResult.error("发布失败:" + e.getMessage());
        }
    }

    /**
     * 领用任务审核
     */
    @Override
    public AjaxResult useExamine(LeaseApplyInfo leaseApplyInfo) {
        if (leaseApplyInfo.getId() == null) {
            return AjaxResult.error("ID为空,请完善后重新发布!");
        }
        if (leaseApplyInfo.getTaskId() == null) {
            return AjaxResult.error("任务ID为空,请完善后重新发布!");
        }
        try {
            int result = leaseApplyInfoMapper.updateLeaseApplyInfo(leaseApplyInfo);
            if (result > GlobalConstants.INT_0) {
                // 同步修改tm_task任务状态, 如果不需要审核，改成 LEASE_TASK_IN_PROGRESS， 如果需要审核，改成 LEASE_TASK_TO_AUDIT
                TmTask tmTask = new TmTask();
                tmTask.setTaskType(TmTaskTypeEnum.TM_TASK_LEASE.getTaskTypeId());
                tmTask.setTaskId(leaseApplyInfo.getTaskId());
                tmTask.setTaskStatus(LeaseTaskStatusEnum.LEASE_TASK_TO_PUBLISHED.getStatus());
                tmTaskMapper.updateTmTask(tmTask);
                return AjaxResult.success("审核成功");
            }
            return AjaxResult.error("审核失败");
        } catch (DataAccessException e) {
            // 抛出异常、回滚数据
            throw new RuntimeException();
        } catch (Exception e) {
            return AjaxResult.error("审核失败:" + e.getMessage());
        }
    }

    /**
     * 信息采集领料出库
     * @param leaseOutRequestVo
     * @return
     */
    @Override
    public AjaxResult leaseOutByInfo(LeaseOutRequestVo leaseOutRequestVo) {
        for (LeaseOutDetails bean : leaseOutRequestVo.getLeaseOutDetailsList()) {
            AjaxResult ajaxResult = leaseOutDetailsService.leaseOutByInfo(bean);
            if (ajaxResult.isError()) {
                return ajaxResult;
            }
        }
        return AjaxResult.success();
    }


    /**
     * 插入领料任务详情数据
     * @param leaseApplyDetailsList
     * @param parentId
     * @return
     */
    private AjaxResult insertPurchaseCheckDetails(List<LeaseApplyDetails> leaseApplyDetailsList, Long parentId) {
        if (!CollectionUtils.isEmpty(leaseApplyDetailsList)) {
            for (LeaseApplyDetails details : leaseApplyDetailsList) {
                details.setParentId(parentId); // 设置info.parentId
                details.setCreateTime(DateUtils.getNowDate());
                details.setCreateBy(SecurityUtils.getLoginUser().getSysUser().getNickName());
            }
            // 批量插入详情数据
            int count = leaseApplyDetailsMapper.insertLeaseApplyDetailsList(leaseApplyDetailsList);
            if (count > 0) {
                return AjaxResult.success("新增任务成功");
            } else {
                return AjaxResult.error("新增任务失败,lease_apply_detail详情表插入0条");
            }
        } else {
            return AjaxResult.success("新增任务成功");
        }
    }

    /**
     * 生成任务编号并构造Tm_Task任务对象
     * @param thisMonthMaxOrder 当月最大单号
     * @return 任务对象
     */
    /*private static String genderTaskCode(Integer thisMonthMaxOrder, String taskType) {
        SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
        Date nowDate = DateUtils.getNowDate();
        String format = dateFormat.format(nowDate);
        String result = format.replace("-", "");
        return taskType + result + String.format("-%03d", thisMonthMaxOrder + 1);
    }*/
    private static String genderTaskCode(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("-%05d", thisMonthMaxOrder + 1);
    }

    /**
     * 修改领料任务
     *
     * @param leaseApplyRequestVo 领料任务
     * @return 结果
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean updateLeaseApplyInfo(LeaseApplyRequestVo leaseApplyRequestVo) {
        try {
            // 提取到局部变量中，减少重复代码
            LeaseApplyInfo leaseApplyInfo = leaseApplyRequestVo.getLeaseApplyInfo();
            if (leaseApplyInfo != null && leaseApplyInfo.getId() != null) {
                leaseApplyInfo.setUpdateTime(DateUtils.getNowDate());
                leaseApplyInfo.setUpdateBy(SecurityUtils.getLoginUser().getSysUser().getNickName());

                // 去除创建一个新的数组对象，直接复用
                Long[] ids = {leaseApplyInfo.getId()};
                if (CollectionUtil.isNotEmpty(leaseApplyInfo.getBmFileInfos())) {
                    // 删除原有数据
                    BmFileInfo bmFileInfo = new BmFileInfo();
                    bmFileInfo.setTaskId(leaseApplyInfo.getTaskId());
                    bmFileInfo.setModelId(leaseApplyInfo.getId());
                    bmFileInfo.setTaskType(2);
                    bmFileInfo.setFileType(5L);
                    bmFileInfoMapper.deleteBmFileInfoByBizInfo(bmFileInfo);
                    for (BmFileInfo fileInfo : leaseApplyInfo.getBmFileInfos()) {
                        fileInfo.setTaskId(leaseApplyInfo.getTaskId());
                        fileInfo.setModelId(leaseApplyInfo.getId());
                        fileInfo.setTaskType(2);
                        fileInfo.setFileType(5L);
                        fileInfo.setCreateBy(SecurityUtils.getLoginUser().getSysUser().getNickName());
                        fileInfo.setCreateTime(DateUtils.getNowDate());
                        bmFileInfoMapper.insertBmFileInfo(fileInfo);
                    }
                }
                if (CollectionUtil.isNotEmpty(leaseApplyRequestVo.getLeaseApplyDetailsList())) {
                    // 业务逻辑代码
                    leaseApplyDetailsMapper.deleteLeaseApplyDetailsByParentIds(ids);
                    insertPurchaseCheckDetails(leaseApplyRequestVo.getLeaseApplyDetailsList(), leaseApplyInfo.getId());
                }
                // 修改外层info
                leaseApplyInfoMapper.updateLeaseApplyInfo(leaseApplyInfo);
                // 进行状态判断
                List<LeaseApplyDetails> leaseApplyDetailsList = leaseApplyDetailsMapper.getByParentId(leaseApplyInfo.getId());
                int i = GlobalConstants.INT_0;
                for (LeaseApplyDetails bean : leaseApplyDetailsList) {
                    if (Objects.equals(bean.getPreNum(), bean.getAlNum())) {
                        i++;
                    }
                }
                if (i == leaseApplyDetailsList.size()) {
                    tmTaskMapper.updateTaskStatus(leaseApplyInfo.getTaskId().toString(), LeaseTaskStatusEnum.LEASE_TASK_FINISHED.getStatus());
                }
                return true;
            }
            return false;
        } catch (DataAccessException dae) {
            throw new ServiceException("数据访问异常: " + dae.getMessage());
        } catch (IllegalArgumentException iae) {
            throw new ServiceException("非法参数异常: " + iae.getMessage());
        } catch (Exception e) {
            throw new ServiceException("未知异常: " + e.getMessage());
        }
        /*try {
            int result = 0;
            // 提取到局部变量中，减少重复代码
            LeaseApplyInfo leaseApplyInfo = leaseApplyRequestVo.getLeaseApplyInfo();
            if (leaseApplyInfo != null && leaseApplyInfo.getId() != null) {
                // 去除创建一个新的数组对象，直接复用
                Long[] ids = {leaseApplyInfo.getId()};
                result = leaseApplyInfoMapper.deleteLeaseApplyInfoByIds(ids);
                if (result == 0) {
                    throw new RuntimeException("删除主要任务失败");
                }
                if (CollectionUtil.isNotEmpty(leaseApplyRequestVo.getLeaseApplyDetailsList())) {
                    // 业务逻辑代码
                    result = leaseApplyDetailsMapper.deleteLeaseApplyDetailsByParentIds(ids);
                    if (result == 0) {
                        throw new RuntimeException("删除详情任务失败");
                    }
                }
                // 查询是否存在文件
                BmFileInfo fileInfo = new BmFileInfo();
                fileInfo.setTaskId(leaseApplyInfo.getTaskId());
                fileInfo.setModelId(leaseApplyInfo.getId());
                fileInfo.setTaskType(2);
                fileInfo.setFileType(5L);
                List<BmFileInfo> bmFileInfos = bmFileInfoMapper.selectBmFileInfoList(fileInfo);
                // 删除原有数据
                if (!CollectionUtils.isEmpty(bmFileInfos)) {
                    result = bmFileInfoMapper.deleteBmFileInfoByBizInfo(fileInfo);
                    if (result == 0) {
                        throw new RuntimeException("删除文件失败");
                    }
                }
                // 重新走新增逻辑
                AjaxResult ajaxResult = insertLeaseApplyInfo(leaseApplyRequestVo);
                if (!ajaxResult.isSuccess()) {
                    System.err.println(ajaxResult.get("msg"));
                    throw new RuntimeException("修改新增数据异常");
                }
                return true;
            }
            return false;
        } catch (DataAccessException dae) {
            throw new ServiceException("数据访问异常: " + dae.getMessage());
        } catch (IllegalArgumentException iae) {
            throw new ServiceException("非法参数异常: " + iae.getMessage());
        } catch (Exception e) {
            throw new ServiceException("未知异常: " + e.getMessage());
        }*/
    }

    /**
     * 领料任务电子签名
     *
     * @param leaseApplyInfo
     */
    @Override
    public int updateLeaseApplyInfoSign(LeaseApplyInfo leaseApplyInfo) {
        int result = 0;
        Long userid = SecurityUtils.getLoginUser().getUserid();
        String nickName = SecurityUtils.getLoginUser().getSysUser().getNickName();
        leaseApplyInfo.setSignPerson(nickName);
        leaseApplyInfo.setCreateBy(userid.toString());
        leaseApplyInfo.setCreateTime(DateUtils.getNowDate());
        // 新增领料签字表lease_sign_info
        result = leaseApplyInfoMapper.insertLeaseSign(leaseApplyInfo);
        if (result == 0) {
            throw new RuntimeException("添加签名信息失败");
        }
        // 往lease_out_details表增加新增签字id字段
        if (StringUtils.isNotBlank(leaseApplyInfo.getIds())) {
            String[] ids = leaseApplyInfo.getIds().split(",");
            for (String id : ids) {
                leaseApplyInfo.setId(Long.parseLong(id));
                result = leaseOutDetailsMapper.updateLeaseOutSign(leaseApplyInfo);
                if (result == 0) {
                    throw new RuntimeException("修改领料签字信息失败");
                }
            }
        }

        List<LeaseApplyInfo> userList = leaseApplyInfoMapper.getUserList(leaseApplyInfo);
        // 省公司短信发送
        List<String> mobileList = new ArrayList();
        if(userList !=null && userList.size()>0){
            for (LeaseApplyInfo item : userList){
                LeaseApplyInfo item1 = leaseApplyInfoMapper.getUserPhoneById(item);
                mobileList.add(item1.getPhone());
            }
        }
        if (mobileList != null && mobileList.size() > 0){
            JSONObject sendResult = SmsTool.sendSms(new BatchSmsByContentParam(mobileList, "您有一条待确认的领料信息，请尽快登录机具系统进行确认！"), BmConfigItems.ANHUI_COMPANY_SMS_KEY);
            if (sendResult != null) {
                // 短信发送成功
                result =1;
            }
        }

        return result;
    }


    /**
     * 领料：出库
     *
     * @param leaseOutRequestVo 领料：出库
     * @return 结果
     */
    @Override
    public AjaxResult leaseOut(LeaseOutRequestVo leaseOutRequestVo) {
        // 判断库存是否充足
        if (!CollectionUtils.isEmpty(leaseOutRequestVo.getLeaseOutDetailsList())) {
            LeaseOutDetails leaseOutDetails = leaseOutRequestVo.getLeaseOutDetailsList().get(0);
            if (leaseOutDetails != null) {
                // 根据前端传入的keyId进行判断
                BigDecimal pendingNum = BigDecimal.ZERO;
                if (leaseOutDetails.getKeyId() != null) {
                    List<LeaseApplyDetails> list = leaseApplyDetailsMapper.getPendingCodeLeaseApplyDetails(leaseOutDetails);
                    if (!CollectionUtils.isEmpty(list)) {
                        return AjaxResult.error("该设备已出库，请勿重复操作");
                    }
                }
                if (leaseOutDetails.getManageType().equals(MaTypeManageTypeEnum.NUMBER_DEVICE.getTypeId())) {
                    if (leaseOutDetails.getInputNum().compareTo(BigDecimal.ZERO) <= 0) {
                        return AjaxResult.error("出库数量不能小于0");
                    }
                    // 查询待出库数量
                    LeaseApplyDetails info = new LeaseApplyDetails();
                    if (StringUtils.isNotBlank(leaseOutDetails.getPublishTask())) {
                       info = leaseApplyDetailsMapper.getPengNum(leaseOutDetails);
                    } else {
                        info = leaseApplyDetailsMapper.getPendLease(leaseOutDetails);
                    }
                    LeaseApplyDetails details = leaseApplyDetailsMapper.getPendingLeaseApplyDetails(leaseOutDetails);
                    if (details == null) {
                        pendingNum = info.getOutNum().subtract(BigDecimal.ZERO);
                    } else {
                        pendingNum = info.getOutNum().subtract(details.getOutNum());
                    }
                    if (leaseOutDetails.getInputNum().compareTo(pendingNum) > 0) {
                        return AjaxResult.error("该设备已出库，请勿重复操作");
                    }
                }
                if (leaseOutDetails.getManageType().equals(MaTypeManageTypeEnum.CODE_DEVICE.getTypeId())) {
                    if (leaseOutDetails.getParentId() != null) {
                        List<LeaseApplyDetails> detailsList = leaseApplyDetailsMapper.getLeaseMaCode(leaseOutDetails);
                        if (!CollectionUtils.isEmpty(detailsList)) {
                            return AjaxResult.error("该设备已出库，请勿重复操作");
                        }
                    }
                }
            }
        }
        for (LeaseOutDetails bean : leaseOutRequestVo.getLeaseOutDetailsList()) {
            if (Objects.isNull(bean)) {
                continue;
            }
            // 默认设置领料单位为非班组
            bean.setLeaseUnitIsTeam(false);
            // 根据现在的领料发布出库单位ID来判断类型是否是班组
            if (bean.getLeaseUnitId() != null) {
                // 查询单位类型
                Long leaseUnitTypeId = leaseApplyInfoMapper.selectUnitTypeByUnitId(Long.valueOf(bean.getLeaseUnitId()));
                if (leaseUnitTypeId != null && Objects.equals(leaseUnitTypeId, 1731L)) {
                    System.out.println("发布出库的领料单位是班组,Yes");
                    bean.setLeaseUnitIsTeam(true);
                } else {
                    System.out.println("发布出库的领料单位不是班组,No");
                }
            }
            AjaxResult ajaxResult = leaseOutDetailsService.leaseOut(bean);
            if (ajaxResult.isError()) {
                return ajaxResult;
            }
        }
        return AjaxResult.success();
    }



    /**
     * 批量删除领料任务
     *
     * @param ids 需要删除的领料任务主键
     * @return 结果
     */
    @Override
    public int deleteLeaseApplyInfoByIds(Long[] ids) {
        // 根据ids去查询该任务是否存在出库数据，存在则不能删除
        for (Long id : ids) {
            List<LeaseApplyDetails> list = leaseApplyInfoMapper.selectInfo(id);
            if (!CollectionUtils.isEmpty(list)) {
                throw new RuntimeException("该任务存在出库数据，不允许删除！");
            }
        }
        int result = leaseApplyInfoMapper.deleteLeaseApplyInfoByIds(ids);
        if (result > 0) {
            result = leaseApplyDetailsMapper.deleteLeaseApplyDetailsByParentIds(ids);
        }
        return result;
    }

    /**
     * 删除领料任务信息
     *
     * @param id 领料任务主键
     * @return 结果
     */
    @Override
    public int deleteLeaseApplyInfoById(Long id) {
        return leaseApplyInfoMapper.deleteLeaseApplyInfoById(id);
    }

    /**
     * 领料任务详情
     * @param leaseApplyInfo
     * @return
     */
    @Override
    public List<LeaseApplyDetails> selectLeaseApplyDetailsList(LeaseApplyInfo leaseApplyInfo) {
        return leaseApplyDetailsMapper.selectLeaseApplyDetailsList(new LeaseApplyDetails(leaseApplyInfo.getId(), leaseApplyInfo.getKeyWord(), leaseApplyInfo.getUserId(), null));
    }

    /**
     * 根据qrcode查询在库机具信息
     * @param bmQrcodeInfo
     * @return
     */
    @Override
    public AjaxResult getInfoByQrcode(BmQrcodeInfo bmQrcodeInfo) {
        if (StringUtils.isBlank(bmQrcodeInfo.getQrCode())) {
            return AjaxResult.error(HttpCodeEnum.FAIL.getCode(), "二维码code不能为空");
        }
        List<LeaseOutDetails> recordList = leaseApplyDetailsMapper.getInfoByQrcode(bmQrcodeInfo);
        String msg = "";
        if (CollectionUtil.isNotEmpty(recordList)) {
            recordList = recordList.stream().filter(item -> item.getMaStatus().equals(MaMachineStatusEnum.IN_STORE.getStatus().toString())).collect(Collectors.toList());
            if (recordList.size() > 0) {
                msg = "监测到当前设备符合出库条件,请确认是否出库!";
            }else{
                msg = "监测到当前设备不符合出库条件，无法出库!";
                recordList = new ArrayList<>();
            }
        } else {
            msg = "监测到当前设备不符合出库条件，无法出库!!";
            recordList = new ArrayList<>();
        }
        // 返回包含设备列表和消息的结果
        Map<String, Object> result = new HashMap<>(2);
        result.put("recordList", recordList);
        result.put("msg", msg);
        return AjaxResult.success(result);
    }

    @Override
    public LeaseApplyRequestVo getInfo(LeaseApplyInfo leaseApplyInfo) {
        try {
            Long userId = SecurityUtils.getLoginUser().getUserid();
            // 首先根据用户名去ma_type_manage表查询是否存在绑定物资信息
            List<Long> typeIdList = leaseApplyInfoMapper.selectTypeIdList(userId);
            if (!CollectionUtils.isEmpty(typeIdList)) {
                leaseApplyInfo.setTypeIdList(typeIdList);
            } else {
                leaseApplyInfo.setUserId(userId);
            }
            Optional<LeaseApplyInfo> optionalInfo = Optional.ofNullable(leaseApplyInfoMapper.selectLeaseApplyInfoById(leaseApplyInfo));
            if (StringUtils.isNotBlank(leaseApplyInfo.getPublishTask())) {
                optionalInfo = Optional.ofNullable(leaseApplyInfoMapper.selectLeaseApplyInfoPublishList(leaseApplyInfo));
            }
            LeaseApplyRequestVo leaseApplyRequestVo = new LeaseApplyRequestVo();

            optionalInfo.ifPresent(info -> {
                leaseApplyRequestVo.setLeaseApplyInfo(info);
                // 获取领料单详情
                List<LeaseOutVo> details = leaseApplyDetailsMapper.selectLeaseOutDetailsList(leaseApplyInfo);
                if (!CollectionUtils.isEmpty(details)) {
                    leaseApplyRequestVo.setLeaseOutVoList(details);
                }
            });
            return leaseApplyRequestVo;
        } catch (Exception e) {
            // 记录异常日志
            System.err.println("Error occurred while selecting lease apply info by ID: " + leaseApplyInfo.getId() + ", " + e.getMessage());
            throw new RuntimeException("Failed to select lease apply info", e);
        }
    }

    @Override
    public void exportInfo(LeaseApplyInfo leaseApplyInfo, LeaseApplyRequestVo leaseApplyRequestVo, HttpServletResponse response) {
        try {
            String fileName = "施工机具设备出库检验记录表";
            String projectName = "";
            String unit = "";
            List<LeaseOutVo> list = new ArrayList<>();
            if (leaseApplyRequestVo != null && leaseApplyRequestVo.getLeaseApplyInfo() != null) {
                projectName ="领用工程：" + leaseApplyRequestVo.getLeaseApplyInfo().getLeaseProject();
                unit ="使用单位：" + leaseApplyRequestVo.getLeaseApplyInfo().getLeaseUnit();
                list = leaseApplyRequestVo.getLeaseOutVoList();
                if (leaseApplyInfo.getMaId() != null) {
                    // 过滤出list中和leaseApplyInfo.getMaId()相等的元素
                    list = list.stream()
                            .filter(item -> item.getMaId().equals(leaseApplyInfo.getMaId()))
                            .collect(Collectors.toList());
                }
            }
            expOutExcel(response,list,fileName,projectName,unit);
        } catch (Exception e) {
            log.error(e.toString(), e);
        }
    }

    /**
     * 领料单详情
     * @param leaseApplyDetails
     * @return
     */
    @Override
    public LeaseApplyDetails getInnerById(LeaseApplyDetails leaseApplyDetails) {
        LeaseApplyDetails info =  leaseApplyDetailsMapper.getInnerById(leaseApplyDetails);
        // 根据领用批次查询领用详情
        if (StringUtils.isNotBlank(leaseApplyDetails.getPublishTask())) {
            info = leaseApplyDetailsMapper.selectInfo(leaseApplyDetails);
        }
        return info;
    }

    /**
     * 领料单详情
     * @param leaseApplyDetails
     * @return
     */
    @Override
    public List<LeaseApplyDetails> getDetailsById(LeaseApplyDetails leaseApplyDetails) {
        List<LeaseApplyDetails> list = leaseApplyDetailsMapper.getDetailsById(leaseApplyDetails);
        if (StringUtils.isNotBlank(leaseApplyDetails.getPublishTask())) {
            list = leaseApplyDetailsMapper.selectPublishDetails(leaseApplyDetails);
        }
        return list;
    }

    /**
     * app领料出库退回
     * @param leaseOutDetails
     * @return
     */
    @Override
    public AjaxResult leaseOutBack(LeaseOutDetails leaseOutDetails) {
        return leaseOutDetailsService.leaseOutBack(leaseOutDetails);
    }

    /**
     * 导出领料单
     * @param response
     * @param list
     * @param filename
     * @param projectName
     * @param unit
     * @throws Exception
     */
    private void expOutExcel(HttpServletResponse response, List<LeaseOutVo> list, String filename,String projectName,String unit)
            throws Exception {
        if (list != null) {
            List<Map<String, Object>> results = new ArrayList<Map<String, Object>>();
            int size = list.size();
            for (int i = 0; i < size; i++) {
                LeaseOutVo bean = list.get(i);
                Map<String, Object> maps = outReceiveDetailsBeanToMap(bean);
                results.add(maps);
            }
            List<String> headers = receiveDetailsHeader();
            HSSFWorkbook workbook = PoiOutPage.excelForcheck(results, headers, filename,projectName,unit);
            OutputStream out = null;
            response.setContentType("application/vnd.ms-excel;charset=UTF-8");
            response.addHeader("Content-Disposition",
                    "attachment;filename=" + URLEncoder.encode(filename, "UTF-8") + ".xls");
            response.setHeader("Pragma", "No-cache");
            out = response.getOutputStream();
            workbook.write(out);
            out.flush();
            out.close();
        }else{
            List<Map<String, Object>> results = new ArrayList<Map<String, Object>>();
            List<String> headers = receiveDetailsHeader();
            HSSFWorkbook workbook = PoiOutPage.excel(results, headers, filename);
            OutputStream out = null;
            response.setContentType("application/vnd.ms-excel;charset=UTF-8");
            response.addHeader("Content-Disposition",
                    "attachment;filename=" + URLEncoder.encode(filename, "UTF-8") + ".xls");
            response.setHeader("Pragma", "No-cache");
            out = response.getOutputStream();
            workbook.write(out);
            out.flush();
            out.close();
        }
    }

    /**
     * 领料单数据转换
     * @param bean
     * @return
     */
    private Map<String, Object> outReceiveDetailsBeanToMap(LeaseOutVo bean) {
        Map<String, Object> maps = new LinkedHashMap<String, Object>();
        maps.put("typeName", bean.getTypeName());
        maps.put("typeModelName", bean.getTypeModelName());
        maps.put("unit", bean.getUnit());
        maps.put("num", bean.getNum());
        maps.put("maCode", bean.getMaCode());
        maps.put("ratedLoad", bean.getRatedLoad());
        maps.put("testLoad", bean.getTestLoad());
        maps.put("holdingTime", bean.getHoldingTime());
        maps.put("testTime", bean.getTestTime());
        maps.put("nextTestTime", bean.getNextTestTime());
        maps.put("checkResult", bean.getCheckResult());
        maps.put("remark", bean.getRemark());
        return maps;
    }

    /**
     * 领料单表头
     * @return
     */
    private List<String> receiveDetailsHeader() {
        ArrayList<String> list = new ArrayList<String>();
        list.add("机具名称");
        list.add("规格型号");
        list.add("单位");
        list.add("数量");
        list.add("设备编码");
        list.add("额定载荷KN");
        list.add("试验载荷KN");
        list.add("持荷时间min");
        list.add("试验日期");
        list.add("下次试验日期");
        list.add("检验结论");
        list.add("备注");
        return list;
    }
}
