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

import cn.hutool.core.util.PhoneUtil;
import com.alibaba.nacos.common.utils.CollectionUtils;
import com.bonus.common.biz.constant.MaterialConstants;
import com.bonus.common.biz.domain.BmFileInfo;
import com.bonus.common.biz.domain.TypeTreeBuild;
import com.bonus.common.biz.domain.TypeTreeNode;
import com.bonus.common.biz.enums.BackTaskStatusEnum;
import com.bonus.common.biz.enums.HttpCodeEnum;
import com.bonus.common.biz.enums.MaMachineStatusEnum;
import com.bonus.common.biz.enums.TmTaskTypeEnum;
import com.bonus.common.core.exception.ServiceException;
import com.bonus.common.core.utils.DateUtils;
import com.bonus.common.core.utils.StringUtils;
import com.bonus.common.core.web.domain.AjaxResult;
import com.bonus.common.security.utils.SecurityUtils;
import com.bonus.material.back.domain.BackApplyInfo;
import com.bonus.material.back.domain.MaCodeDto;
import com.bonus.material.back.domain.vo.MaCodeVo;
import com.bonus.material.basic.mapper.BmFileInfoMapper;
import com.bonus.material.clz.domain.BmTeam;
import com.bonus.material.clz.domain.lease.MaterialLeaseApplyInfo;
import com.bonus.material.clz.mapper.IwsTeamUserMapper;
import com.bonus.material.clz.mapper.MaterialMachineMapper;
import com.bonus.material.common.mapper.SelectMapper;
import com.bonus.material.ma.mapper.MachineMapper;
import com.bonus.material.clz.domain.back.MaterialBackApplyDetails;
import com.bonus.material.clz.domain.back.MaterialBackApplyInfo;
import com.bonus.material.clz.domain.back.MaterialBackApplyTotalInfo;
import com.bonus.material.clz.domain.vo.back.MaterialBackApplyRequestVo;
import com.bonus.material.clz.domain.vo.back.MaterialBackMaCodeVo;
import com.bonus.material.clz.mapper.MaterialBackInfoMapper;
import com.bonus.material.clz.service.MaterialBackApplyInfoService;
import com.bonus.material.settlement.domain.SltAgreementInfo;
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 lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.math.RoundingMode;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.stream.Collectors;

/**
 * @Author ma_sh
 * @create 2025/6/25 9:30
 */
@Service
@Slf4j
public class MaterialBackApplyInfoServiceImpl implements MaterialBackApplyInfoService {

    @Resource
    private MaterialBackInfoMapper materialBackInfoMapper;

    @Resource
    private BmFileInfoMapper bmFileInfoMapper;

    @Resource
    private TmTaskMapper taskMapper;

    @Resource
    private TmTaskAgreementMapper taskAgreementMapper;

    @Resource
    private MachineMapper machineMapper;

    @Resource
    private SelectMapper mapper;

    @Resource
    private MaterialMachineMapper materialMachineMapper;

    @Resource
    private IwsTeamUserMapper iwsTeamUserMapper;
    /**
     * 查询退料申请列表
     * @param backApplyInfo
     * @return
     */
    @Override
    public List<MaterialBackApplyInfo> selectBackApplyInfoList(MaterialBackApplyInfo backApplyInfo) {
        String username = SecurityUtils.getLoginUser().getUsername();
        BmTeam teamData = null;
        Set<String> userRoles = SecurityUtils.getLoginUser().getRoles();
        // 检查用户是否具有特殊角色
        boolean hasSpecialRole = hasSpecialRole(userRoles);
        if (!hasSpecialRole) {
            // 根据用户名判断用户是否为班组长
             teamData = materialMachineMapper.getTeamData(username);
            if (teamData == null) {
                // 根据用户名查询项目部信息
                List<String> departId = mapper.getDepartId(username);
                // 根据项目部id查询工程信息
                List<String> projectIdList = mapper.getProjectId(departId);
                if (!org.springframework.util.CollectionUtils.isEmpty(projectIdList)) {
                    backApplyInfo.setProjectIdList(projectIdList);
                }
                backApplyInfo.setIdCard(null);
            }
        }
        List<MaterialBackApplyInfo> list = materialBackInfoMapper.selectBackApplyInfoList(backApplyInfo);
        // 如果列表为空，直接返回空列表
        if (CollectionUtils.isEmpty(list)) {
            return new ArrayList<>();
        }
        if (!hasSpecialRole) {
            Long deptId = SecurityUtils.getLoginUser().getSysUser().getDeptId();
            if (!org.springframework.util.CollectionUtils.isEmpty(list) && deptId != null) {
                // 删除元素
                list.removeIf(info -> !deptId.toString().equals(info.getImpUnit()));
            }
        }
        if (!org.springframework.util.CollectionUtils.isEmpty(list)) {
            // 班组长权限
            if (teamData != null) {
                // 将sortedList中班组身份证号与username相同的元素过滤处理
                list = list.stream()
                        .filter(item -> StringUtils.isBlank(item.getIdCard()) || username.equals(item.getIdCard()))
                        .collect(Collectors.toList());
            } /*else {
                // 材料员权限
                list = filterList(list, username);
            }*/
        }
        if (!CollectionUtils.isEmpty(list)) {
            for (MaterialBackApplyInfo materialRetainedEquipmentInfo : list) {
                // 根据班组名称查询分包单位
                String subUnitName = iwsTeamUserMapper.getTeamName(materialRetainedEquipmentInfo.getTeamName());
                materialRetainedEquipmentInfo.setSubUnitName(subUnitName);
            }
            if(backApplyInfo.getSubUnitName()!=null && !backApplyInfo.getSubUnitName().equals("") && !list.isEmpty()){
                // 根据传入的SubUnitName过滤列表
                list = list.stream()
                        .filter(item -> com.alibaba.nacos.common.utils.StringUtils.equals(item.getSubUnitName(), backApplyInfo.getSubUnitName()))
                        .collect(Collectors.toList());
            }
            if (!org.springframework.util.CollectionUtils.isEmpty(list) && !StringUtils.isBlank(backApplyInfo.getTypeName())) {
                list = list.stream()
                        .filter(item -> StringUtils.isNotBlank(item.getTypeName()) &&
                                item.getTypeName().contains(backApplyInfo.getTypeName()))
                        .collect(Collectors.toList());
            }
            // 如果需要导出
            if (backApplyInfo.getIsExport()) {
                for (MaterialBackApplyInfo applyInfo : list) {
                    applyInfo.setPrintStatus("0".equals(applyInfo.getPrintStatus()) ? "未打印" : "已打印");
                    switch (applyInfo.getStatus()) {
                        case "0":
                            applyInfo.setStatus("退料未完成");
                            break;
                        case "1":
                            applyInfo.setStatus("维修驳回");
                            break;
                        case "2":
                            applyInfo.setStatus("退料已完成");
                            break;
                        default:
                            break;
                    }
                }
            }
        }
        return list;
    }

    /**
     * 材料员权限
     * @param list
     * @param username
     * @return
     */
    private List<MaterialBackApplyInfo> filterList(List<MaterialBackApplyInfo> list, String username) {
        if (CollectionUtils.isEmpty(list)) {
            return Collections.emptyList();
        }
        List<MaterialBackApplyInfo> newList = new ArrayList<>();
        for (MaterialBackApplyInfo info : list) {
            if (StringUtils.isBlank(info.getExternalId())) {
                continue;
            }
            // 根据i8工程id查询项目部id
            MaterialLeaseApplyInfo i8ProjectInfo = mapper.selectI8ProjectInfo(info.getExternalId());
            if (i8ProjectInfo == null || i8ProjectInfo.getDepartId() == null) {
                continue;
            }
            List<String> userNameList = mapper.getUserNameList(i8ProjectInfo);
            if (!CollectionUtils.isEmpty(userNameList) && userNameList.contains(username)) {
                newList.add(info);
            }
        }
        if (!CollectionUtils.isEmpty(newList)) {
            return newList;
        }
        return list;
    }

    /**
     * 查询总站点退料记录数据
     * @param backApplyInfo
     * @return
     */
    @Override
    public List<MaterialBackApplyInfo> getTotalList(MaterialBackApplyInfo backApplyInfo) {
        Set<String> userRoles = SecurityUtils.getLoginUser().getRoles();
        String username = SecurityUtils.getLoginUser().getUsername();
        // 检查用户是否具有特殊角色
        boolean hasSpecialRole = hasSpecialRole(userRoles);
        BmTeam teamData = null;
        if (!hasSpecialRole) {
            // 根据用户名判断用户是否为班组长
            teamData = materialMachineMapper.getTeamData(username);
            if (teamData == null) {
                // 根据用户名查询项目部信息
                List<String> departId = mapper.getDepartId(username);
                // 根据项目部id查询工程信息
                List<String> projectIdList = mapper.getProjectId(departId);
                if (!org.springframework.util.CollectionUtils.isEmpty(projectIdList)) {
                    backApplyInfo.setProjectIdList(projectIdList);
                }
            }
        }
        List<MaterialBackApplyInfo> list = materialBackInfoMapper.getTotalList(backApplyInfo);
        if (!hasSpecialRole) {
            Long deptId = SecurityUtils.getLoginUser().getSysUser().getDeptId();
            if (!org.springframework.util.CollectionUtils.isEmpty(list) && deptId != null) {
                // 删除元素
                list.removeIf(info -> !deptId.toString().equals(info.getImpUnit()));
            }
        }
        if (!org.springframework.util.CollectionUtils.isEmpty(list)) {
            // 班组长权限
            if (teamData != null) {
                // 将sortedList中班组身份证号与username相同的元素过滤处理
                list = list.stream()
                        .filter(item -> StringUtils.isBlank(item.getIdCard()) || username.equals(item.getIdCard()))
                        .collect(Collectors.toList());
            } /*else {
                // 材料员权限
                list = filterList(list, username);
            }*/
        }
        // 新增typeName过滤条件
        if (!org.springframework.util.CollectionUtils.isEmpty(list) && !StringUtils.isBlank(backApplyInfo.getTypeName())) {
            list = list.stream()
                    .filter(item -> StringUtils.isNotBlank(item.getTypeName()) &&
                            item.getTypeName().contains(backApplyInfo.getTypeName()))
                    .collect(Collectors.toList());
        }
        if (!CollectionUtils.isEmpty(list)) {
            // 如果关键字不为空，进行过滤
            if (!StringUtils.isBlank(backApplyInfo.getKeyWord())) {
                list = list.stream()
                        .filter(item -> containsTotalKeyword(item, backApplyInfo.getKeyWord()))
                        .collect(Collectors.toList());
            }
        }
        return list;
    }

    /**
     * 检查用户是否具有特殊角色
     * @param userRoles
     * @return
     */
    private boolean hasSpecialRole(Set<String> userRoles) {
        if (userRoles == null) {
            return false;
        }
        List<String> allowedRoles = Collections.singletonList("clzcx");
        return allowedRoles.stream().anyMatch(userRoles::contains);
    }
    /**
     * 查询总站点退料详情数据
     * @param backApplyInfo
     * @return
     */
    @Override
    public List<MaterialBackApplyInfo> getDetailsList(MaterialBackApplyInfo backApplyInfo) {
        return materialBackInfoMapper.getDetailsList(backApplyInfo);
    }

    /**
     * 获取退料任务详细信息
     * @param id
     * @param keyWord
     * @return
     */
    @Override
    public AjaxResult selectBackApplyInfoById(Long id, String keyWord) {
        MaterialBackApplyRequestVo backApplyRequestVo = new MaterialBackApplyRequestVo();
        //先根据外层id查询上层信息
        MaterialBackApplyInfo backApplyInfo = materialBackInfoMapper.selectBackApplyInfoById(id);
        if (StringUtils.isNotBlank(backApplyInfo.getBackSignUrl())) {
            if (!backApplyInfo.getBackSignUrl().startsWith("http")) {
                backApplyInfo.setBackSignUrl("data:image/png;base64," + backApplyInfo.getBackSignUrl());
            }
        }
        backApplyRequestVo.setBackApplyInfo(backApplyInfo);
        //查询退料详情信息
        backApplyInfo.setKeyWord(keyWord);
        // 移出maCodeList集合中状态不为在用的数据
        List<MaCodeVo> newCodeList = new ArrayList<>();
        List<MaterialBackApplyDetails> backApplyDetailsList = materialBackInfoMapper.selectBackApplyDetailsListByTaskId(backApplyInfo);
        if (CollectionUtils.isNotEmpty(backApplyDetailsList)) {
            // 批量查询附件信息，减少数据库访问次数
            List<BmFileInfo> bmFileInfos = fetchBmFileInfos(id, backApplyDetailsList);
            // 查询编码设备信息
            List<MaCodeVo> maCodeList = fetchMaCodeList(id);
            if ("0".equals(backApplyInfo.getStatus())) {
                if (CollectionUtils.isNotEmpty(maCodeList)) {
                    // 根据id查询协议id
                    Long agreementId = materialBackInfoMapper.selectAgreementId(backApplyInfo);
                    for (MaCodeVo maCodeVo : maCodeList) {
                        if (maCodeVo.getMaId() != null) {
                            maCodeVo.setAgreementId(agreementId);
                            // 根据协议id以及typeId，maId查询设备是否还在用
                            MaterialBackApplyInfo info1 = materialBackInfoMapper.selectByAgreementIdAndTypeId(maCodeVo);
                            if (info1 == null) {
                                newCodeList.add(maCodeVo);
                            }
                        }
                    }
                }
                // 移除maCodeList中状态不为在用的数据
                if (CollectionUtils.isNotEmpty(newCodeList)) {
                    maCodeList.removeAll(newCodeList);
                }
            }
            // 根据协议id查询设备在用数
            // 先查第四层类型
            List<TypeTreeNode> listL4 = materialBackInfoMapper.getUseTypeTreeL4(backApplyInfo);
            for (MaterialBackApplyDetails details : backApplyDetailsList) {
                if (CollectionUtils.isNotEmpty(listL4)) {
                    for (TypeTreeNode node : listL4) {
                        if (node.getTypeId() == details.getTypeId()) {
                            details.setNum(node.getNum());
                            break;
                        }
                    }
                } else {
                    details.setNum(BigDecimal.ZERO);
                }
                // 为每个退料详情设置附件信息
                setBmFileInfosForDetails(details, bmFileInfos);
                // 如果是编码设备，查询并设置相关的编码信息和附件
                if ("0".equals(details.getManageType())) {
                    setMaCodeDetails(details, maCodeList);
                }
                if (CollectionUtils.isNotEmpty(newCodeList)) {
                    for (MaCodeVo maCodeVo : newCodeList) {
                        if (maCodeVo.getTypeId().equals(details.getTypeId().toString())) {
                            details.setPreNum(details.getPreNum().subtract(BigDecimal.valueOf(1)));
                        }
                        // 根据maId查询设备编码信息
                        BackApplyInfo dto = new BackApplyInfo();
                        dto.setId(id);
                        dto.setMaId(maCodeVo.getMaId());
                        MaCodeVo info = materialBackInfoMapper.selectDto(dto);
                        if (null != info) {
                            if (info.getMaId().equals(maCodeVo.getMaId())) {
                                if (info.getGoodNum() != null && info.getGoodNum().compareTo(BigDecimal.ZERO) > 0) {
                                    details.setGoodNum(details.getGoodNum().subtract(info.getGoodNum()));
                                } else if (info.getBadNum() != null && info.getBadNum().compareTo(BigDecimal.ZERO) > 0) {
                                    details.setBadNum(details.getBadNum().subtract(info.getBadNum()));
                                }
                            }
                        }
                    }
                }
            }
            backApplyRequestVo.setBackApplyDetailsList(backApplyDetailsList);
        }
        AjaxResult ajaxResult = AjaxResult.success();
        ajaxResult.put("data", backApplyRequestVo);
        if (CollectionUtils.isNotEmpty(newCodeList)) {
            // 拼接消息内容
            StringBuilder msgBuilder = new StringBuilder("您所选择的编码设备编号");
            for (int i = 0; i < newCodeList.size(); i++) {
                String code = newCodeList.get(i).getMaCode();
                msgBuilder.append(code);
                if (i < newCodeList.size() - 1) {
                    msgBuilder.append(", ");
                }
            }
            msgBuilder.append("已被他人完成退料，请注意查看！");
            String msg = msgBuilder.toString();
            msg = msg.replaceAll("\n","");
            ajaxResult.put("msg", msg);
        }
        return ajaxResult;
    }

    /**
     * 获取退料任务详细信息
     * @param backApplyDetails
     * @return
     */
    @Override
    public List<MaterialBackApplyDetails> getDetailsById(MaterialBackApplyDetails backApplyDetails) {
        return materialBackInfoMapper.getDetailsById(backApplyDetails);
    }

    /**
     * 新增退料任务
     * @param dto
     * @return
     */
    @Override
    public AjaxResult insertBackApplyInfo(MaterialBackApplyRequestVo dto) {
        if (dto == null || dto.getBackApplyInfo() == null || CollectionUtils.isEmpty(dto.getBackApplyDetailsList())) {
            return AjaxResult.error("参数为空，请重新选择后上传!");
        }
        String createBy = SecurityUtils.getLoginUser().getSysUser().getNickName();
        //对传入的手机号进行校验
        if (StringUtils.isNotBlank(dto.getBackApplyInfo().getPhone()) && !PhoneUtil.isMobile(dto.getBackApplyInfo().getPhone())) {
            return AjaxResult.error("手机号格式不正确，请重新填写!");
        }
        //对提交的退料详情数目进行校验
        for (MaterialBackApplyDetails backApplyDetails : dto.getBackApplyDetailsList()) {
            if (backApplyDetails.getNum() != null && backApplyDetails.getPreNum() != null) {
                if (backApplyDetails.getNum().compareTo( backApplyDetails.getPreNum())<0) {
                    return AjaxResult.error(backApplyDetails.getTypeName() + "退料数量不能大于预退数量，请重新填写!");
                }
            }
            if (backApplyDetails.getGoodNum() != null && backApplyDetails.getBadNum() != null && backApplyDetails.getPreNum() != null) {
                if (backApplyDetails.getGoodNum().add(backApplyDetails.getBadNum()).compareTo( backApplyDetails.getPreNum())>0) {
                    return AjaxResult.error(backApplyDetails.getTypeName() + "完好数量和损坏数量之和不能大于预退数量，请重新填写!");
                }
            }
            if (backApplyDetails.getGoodNum() != null && backApplyDetails.getBadNum() != null && CollectionUtils.isNotEmpty(backApplyDetails.getMaCodeList())) {
                if (backApplyDetails.getGoodNum().add(backApplyDetails.getBadNum()).compareTo( BigDecimal.valueOf(backApplyDetails.getMaCodeList().size()))>0) {
                    return AjaxResult.error(backApplyDetails.getTypeName() + "完好数量和损坏数量之和不能大于预退数量，请重新填写!");
                }
            }
        }
        int result = 0;
        try {
            int thisMonthMaxOrder = taskMapper.getMonthMaxOrderByDate(DateUtils.getCurrentYear(), DateUtils.getCurrentMonth(), TmTaskTypeEnum.TM_TASK_MATERIAL_BACK.getTaskTypeId());
            String code = genderTaskCode(thisMonthMaxOrder);
            TmTask tmTask;
            if (dto.getBackApplyInfo().getIsBack() == 1) {
                tmTask = new TmTask(null, TmTaskTypeEnum.TM_TASK_MATERIAL_BACK.getTaskTypeId(),
                        BackTaskStatusEnum.BACK_TASK_IN_FINISHED.getStatus(),
                        null, thisMonthMaxOrder + 1, code);
            } else {
                tmTask = new TmTask(null, TmTaskTypeEnum.TM_TASK_MATERIAL_BACK.getTaskTypeId(),
                        BackTaskStatusEnum.BACK_TASK_NO_FINISHED.getStatus(),
                        null, thisMonthMaxOrder + 1, code);
            }
            tmTask.setCreateTime(DateUtils.getNowDate());
            tmTask.setCreateBy(createBy);
            MaterialBackApplyInfo backApplyInfo = dto.getBackApplyInfo();
            backApplyInfo.setCode(code);
            backApplyInfo.setCreateBy(createBy);
            backApplyInfo.setCreateTime(DateUtils.getNowDate());
            // 保存退料信息到 tm_task 表中
            result += taskMapper.insertTmTask(tmTask);
            if (result > 0) {
                TmTaskAgreement tmTaskAgreement = new TmTaskAgreement(tmTask.getTaskId(), dto.getBackApplyInfo().getAgreementId());
                tmTaskAgreement.setCreateTime(DateUtils.getNowDate());
                tmTaskAgreement.setCreateBy(createBy);
                // 增加任务和协议关联表数据
                taskAgreementMapper.insertTmTaskAgreement(tmTaskAgreement);
                backApplyInfo.setTaskId(tmTask.getTaskId());
                backApplyInfo.setBackStyle("1");
                result += materialBackInfoMapper.insertBackApplyInfo(backApplyInfo);
            }
            // 保存退料详情
            result = saveBackApplyDetails(createBy, dto, backApplyInfo, result);
        } catch (Exception e) {
            log.error("保存退料信息时发生异常: ", e);
        }
        return result > 0 ? AjaxResult.success() : AjaxResult.error("保存失败，请重试!");
    }

    /**
     * 修改退料任务
     * @param dto
     * @return
     */
    @Override
    public AjaxResult updateBackApplyInfo(MaterialBackApplyRequestVo dto) {
        if (dto == null || dto.getBackApplyInfo() == null || dto.getBackApplyInfo().getId() == null || CollectionUtils.isEmpty(dto.getBackApplyDetailsList())) {
            return AjaxResult.error("参数为空，请重新选择后上传!");
        }
        String createBy = SecurityUtils.getLoginUser().getSysUser().getNickName();
        //对提交的退料详情数量进行校验
        for (MaterialBackApplyDetails backApplyDetails : dto.getBackApplyDetailsList()) {
            if (backApplyDetails.getNum() != null && backApplyDetails.getPreNum() != null) {
                if (backApplyDetails.getNum().compareTo(backApplyDetails.getPreNum()) < 0) {
                    return AjaxResult.error(backApplyDetails.getTypeName() + "退料数量不能大于预退数量，请重新填写!");
                }
            }
        }
        try {
            //针对修改，先删除，后添加
            //对传入的手机号进行校验
            if (StringUtils.isNotBlank(dto.getBackApplyInfo().getPhone()) && !PhoneUtil.isMobile(dto.getBackApplyInfo().getPhone())) {
                return AjaxResult.error("手机号格式不正确，请重新填写!");
            }
            // 查询信息
            Long id = dto.getBackApplyInfo().getId();
            MaterialBackApplyInfo backApplyInfo = materialBackInfoMapper.selectBackApplyInfoById(id);
            List<MaterialBackApplyDetails> backApplyDetailsList = materialBackInfoMapper.selectBackApplyDetailsListByTaskId(dto.getBackApplyInfo());
            List<MaCodeVo> maCodeList = materialBackInfoMapper.selectByCode(id);
            int result = 0;
            // 删除相关任务信息
            result += materialBackInfoMapper.deleteBackApplyDetails(id);
            result += materialBackInfoMapper.deleteCheckDetails(id);
            // 删除退料详情附件
            result += deleteFileInfoForDetails(backApplyDetailsList, id);
            // 删除编码设备附件
            result += deleteFileInfoForMaCodes(maCodeList, id);
            if (result > 0) {
                //执行新增操作
                MaterialBackApplyInfo info = dto.getBackApplyInfo();
                info.setUpdateTime(DateUtils.getNowDate());
                info.setUpdateBy(createBy);
                info.setCode(backApplyInfo.getCode());
                result += materialBackInfoMapper.updateBackApplyInfo(info);
                // 保存退料详情
                result = saveBackApplyDetails(createBy, dto, info, result);
                // 根据任务id修改任务状态
                if (dto.getBackApplyInfo().getIsBack() == 1) {
                    taskMapper.updateTaskStatus(dto.getBackApplyInfo().getTaskId().toString(), BackTaskStatusEnum.BACK_TASK_IN_FINISHED.getStatus());
                }
                return AjaxResult.success(result);
            }
        } catch (Exception e) {
            throw new ServiceException("修改失败，请联系管理员");
        }
        return AjaxResult.error(HttpCodeEnum.FAIL.getCode(), HttpCodeEnum.FAIL.getMsg());
    }

    /**
     * 修改退料任务电子签名
     * @param dto
     * @return
     */
    @Override
    public int updateSignById(MaterialBackApplyInfo dto) {
        return materialBackInfoMapper.updateSignById(dto);
    }

    /**
     * 删除退料任务
     * @param id
     * @return
     */
    @Override
    public AjaxResult deleteBackApplyInfoById(Long id) {
        try {
            // 查询信息
            MaterialBackApplyInfo backApplyInfo = materialBackInfoMapper.selectBackApplyInfoById(id);
            List<MaterialBackApplyDetails> backApplyDetailsList = materialBackInfoMapper.selectBackApplyDetailsListByTaskId(backApplyInfo);
            List<MaCodeVo> maCodeList = materialBackInfoMapper.selectByCode(id);
            // 删除相关任务信息
            int result = deleteTaskInfo(backApplyInfo);
            // 删除退料详情附件
            result += deleteFileInfoForDetails(backApplyDetailsList, id);
            // 删除编码设备附件
            result += deleteFileInfoForMaCodes(maCodeList, id);
            if (result > 0) {
                return AjaxResult.success(result);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return AjaxResult.error(HttpCodeEnum.FAIL.getCode(), HttpCodeEnum.FAIL.getMsg());
    }

    /**
     * 工器具退料记录
     * @param info
     * @return
     */
    @Override
    public List<MaterialBackApplyTotalInfo> getBackInfoDetails(MaterialBackApplyTotalInfo info) {
        String username = SecurityUtils.getLoginUser().getUsername();
        BmTeam teamData = null;
        Set<String> userRoles = SecurityUtils.getLoginUser().getRoles();
        // 检查用户是否具有特殊角色
        boolean hasSpecialRole = hasSpecialRole(userRoles);
        if (!hasSpecialRole) {
            // 根据用户名判断用户是否为班组长
             teamData = materialMachineMapper.getTeamData(username);
            if (teamData == null) {
                // 根据用户名查询项目部信息
                List<String> departId = mapper.getDepartId(username);
                // 根据项目部id查询工程信息
                List<String> projectIdList = mapper.getProjectId(departId);
                if (!org.springframework.util.CollectionUtils.isEmpty(projectIdList)) {
                    info.setProjectIdList(projectIdList);
                }
            }
        }
        BigDecimal backNum = BigDecimal.ZERO.setScale(3, RoundingMode.HALF_UP);
        List<MaterialBackApplyTotalInfo> list = materialBackInfoMapper.getBackInfoDetails(info);
        if (!hasSpecialRole) {
            Long deptId = SecurityUtils.getLoginUser().getSysUser().getDeptId();
            if (!CollectionUtils.isEmpty(list) && deptId != null) {
                // 删除元素
                list.removeIf(m -> !deptId.toString().equals(m.getImpUnit()));
            }
        }
        if (!org.springframework.util.CollectionUtils.isEmpty(list)) {
            // 班组长权限
            if (teamData != null) {
                // 将sortedList中班组身份证号与username相同的元素过滤处理
                list = list.stream()
                        .filter(item -> StringUtils.isBlank(item.getIdCard()) || username.equals(item.getIdCard()))
                        .collect(Collectors.toList());
            } /*else {
                // 材料员权限
                list = filterInfo(list, username);
            }*/
        }
        if (CollectionUtils.isNotEmpty(list)) {
            for (MaterialBackApplyTotalInfo materialRetainedEquipmentInfo : list) {
                // 根据班组名称查询分包单位
                String subUnitName = iwsTeamUserMapper.getTeamName(materialRetainedEquipmentInfo.getTeamName());
                materialRetainedEquipmentInfo.setSubUnitName(subUnitName);
            }
            if(info.getSubUnitName()!=null && !info.getSubUnitName().equals("") && !list.isEmpty()){
                // 根据传入的SubUnitName过滤列表
                list = list.stream()
                        .filter(item -> com.alibaba.nacos.common.utils.StringUtils.equals(item.getSubUnitName(), info.getSubUnitName()))
                        .collect(Collectors.toList());
            }
        }
        if (CollectionUtils.isNotEmpty(list)) {
            for (MaterialBackApplyTotalInfo backApplyTotalInfo : list) {
                backNum = backNum.add(backApplyTotalInfo.getBackNum());
            }
            if (info.getIsExport() == 0) {
                MaterialBackApplyTotalInfo info1 = new MaterialBackApplyTotalInfo();
                info1.setUnitName("合计");
                info1.setBackNum(backNum);
                list.add(0, info1);
            }
        }
        return list;
    }

    /**
     * 材料员权限
     * @param list
     * @param username
     * @return
     */
    private List<MaterialBackApplyTotalInfo> filterInfo(List<MaterialBackApplyTotalInfo> list, String username) {
        if (CollectionUtils.isEmpty(list)) {
            return Collections.emptyList();
        }
        List<MaterialBackApplyTotalInfo> newList = new ArrayList<>();
        for (MaterialBackApplyTotalInfo info : list) {
            if (StringUtils.isBlank(info.getExternalId())) {
                continue;
            }
            // 根据i8工程id查询项目部id
            MaterialLeaseApplyInfo i8ProjectInfo = mapper.selectI8ProjectInfo(info.getExternalId());
            if (i8ProjectInfo == null || i8ProjectInfo.getDepartId() == null) {
                continue;
            }
            List<String> userNameList = mapper.getUserNameList(i8ProjectInfo);
            if (!CollectionUtils.isEmpty(userNameList) && userNameList.contains(username)) {
                newList.add(info);
            }
        }
        if (!CollectionUtils.isEmpty(newList)) {
            return newList;
        }
        return list;
    }

    /**
     * 工器具退料二级页面记录
     * @param info
     * @return
     */
    @Override
    public List<MaterialBackMaCodeVo> getSecondBackInfo(MaterialBackApplyTotalInfo info) {
        return materialBackInfoMapper.getSecondBackInfo(info);
    }

    /**
     * 在用设备类型树
     * @param bean
     * @return
     */
    @Override
    public AjaxResult getUseTypeTree(MaterialBackApplyInfo bean) {
        List<TypeTreeNode> groupList = new ArrayList<>();
        List<TypeTreeNode> list = new ArrayList<>();
        List<TypeTreeNode> listL4 = new ArrayList<>();
        List<TypeTreeNode> listL3 = new ArrayList<>();
        List<TypeTreeNode> listL21 = new ArrayList<>();
        try {
            // 先查第四层类型
            listL4 = materialBackInfoMapper.getUseTypeTreeL4(bean);
            if (org.apache.commons.collections4.CollectionUtils.isNotEmpty(listL4)) {
                List<Long> list4ParentIds = listL4.stream().map(TypeTreeNode::getParentId).collect(Collectors.toList());
                // 根据第四层parentId 查第三层类型
                listL3 = mapper.getUseTypeTreeL3(list4ParentIds);
                List<Long> list3ParentIds = listL3.stream().map(TypeTreeNode::getParentId).collect(Collectors.toList());
                // 根据第三层parentId 查第1.2层类型
                listL21 = mapper.getUseTypeTreeL21(list3ParentIds);
                list.addAll(listL4);
                list.addAll(listL3);
                list.addAll(listL21);
            }
            if (org.apache.commons.collections4.CollectionUtils.isNotEmpty(list)) {
                // 创建树形结构（数据集合作为参数）
                TypeTreeBuild treeBuild = new TypeTreeBuild(list);
                // 原查询结果转换树形结构
                groupList = treeBuild.buildTree();
            }
        } catch (Exception e) {
            AjaxResult.error("类型树-查询失败", e);
        }
        return AjaxResult.success(groupList);
    }

    /**
     * 根据班组和工程id查询领料机具
     * @param dto
     * @return
     */
    @Override
    public AjaxResult getMachineById(MaterialBackApplyInfo dto) {
        return AjaxResult.success(materialBackInfoMapper.getMachineById(dto));
    }

    /**
     * 退料申请提交
     * @param backApplyInfo
     * @return
     */
    @Override
    public AjaxResult submitBackApply(MaterialBackApplyInfo backApplyInfo) {
        List<MaterialBackApplyInfo> codeList = new ArrayList<>();
        // 根据传入的id查询退料申请信息
        List<MaterialBackApplyInfo> applyInfoList = materialBackInfoMapper.selectBackDetails(backApplyInfo);
        // 将applyInfoList中状态不为在用的数据收集到新集合中
        if (CollectionUtils.isNotEmpty(applyInfoList)) {
            for (MaterialBackApplyInfo applyInfo : applyInfoList) {
                if (applyInfo.getMaId() != null) {
                    // 根据协议id以及typeId，maId查询设备是否还在用
                    MaterialBackApplyInfo info = materialBackInfoMapper.selectByAgreementIdAndTypeIdAndMaId(applyInfo);
                    if (info == null) {
                        codeList.add(applyInfo);
                    }
                }
            }
        }
        if (CollectionUtils.isNotEmpty(codeList)) {
            StringBuilder msgBuilder = new StringBuilder("您所选择的编码设备编号");
            for (int i = 0; i < codeList.size(); i++) {
                String maCode = codeList.get(i).getMaCode();
                msgBuilder.append(maCode);
                if (i < codeList.size() - 1) {
                    msgBuilder.append(", ");
                }
            }
            msgBuilder.append("已被他人完成退料，请编辑后重新提交！");
            String msg = msgBuilder.toString();
            msg = msg.replaceAll("\n", "");
            return AjaxResult.error(msg);
        }
        int result = 0;
        //先查询退料详情信息
        List<MaterialBackApplyDetails> applyDetails = materialBackInfoMapper.selectBackApplyDetailsListByTaskId(backApplyInfo);
        // 根据id查询协议id
        Long agreementId = materialBackInfoMapper.selectAgreementId(backApplyInfo);
        // 先查第四层类型
        backApplyInfo.setAgreementId(agreementId);
        List<TypeTreeNode> listL4 = materialBackInfoMapper.getUseTypeTreeL4(backApplyInfo);
        if (CollectionUtils.isNotEmpty(applyDetails)) {
            for (MaterialBackApplyDetails applyDetail : applyDetails) {
                if (CollectionUtils.isNotEmpty(listL4)) {
                    for (TypeTreeNode typeTreeNode : listL4) {
                        if (applyDetail.getTypeId().equals(typeTreeNode.getTypeId())) {
                            if (applyDetail.getPreNum().compareTo(typeTreeNode.getNum()) > 0) {
                                return AjaxResult.error(HttpCodeEnum.FAIL.getCode(), "退料数量不能大于在用数量");
                            }
                        }
                    }
                }
            }
        }
        // 设置更新信息
        backApplyInfo.setUpdateBy(SecurityUtils.getLoginUser().getSysUser().getNickName());
        backApplyInfo.setUpdateTime(DateUtils.getNowDate());
        backApplyInfo.setTaskStatus(BackTaskStatusEnum.BACK_TASK_IN_FINISHED.getStatus());
        // 更新任务表及退料申请表状态
        result += updateTaskAndBackInfo(backApplyInfo);
        if (result > 0 && CollectionUtils.isNotEmpty(applyInfoList)) {
            /*for (MaterialBackApplyInfo applyInfo : applyInfoList) {
                result += machineMapper.updateStatus(applyInfo.getMaId(), MaMachineStatusEnum.IN_STORE.getStatus());
            }*/
            // 获取applyInfoList的typeId并生成集合
            List<String> typeIdList = applyInfoList.stream()
                    .map(MaterialBackApplyInfo::getTypeId).distinct()
                    .collect(Collectors.toList());
            for (String typeId : typeIdList) {
                backApplyInfo.setTypeId(typeId);
                // 更新结算表
                List<MaterialBackApplyInfo> allList = materialBackInfoMapper.selectBackDetails(backApplyInfo);
                if (CollectionUtils.isNotEmpty(allList)) {
                    int res = updateSlt4Bean(backApplyInfo, allList);
                    // 检查机具是否领料
                    if (res == 0) {
                        throw new RuntimeException("该机具未被领料使用");
                    }
                }
                // 完成退料部分，更新 back_check_details
                finishBackCheckDetails(backApplyInfo);
            }
            // 如果所有操作都成功
            return AjaxResult.success();
        }
        // 操作失败，返回错误
        return AjaxResult.error(HttpCodeEnum.FAIL.getCode(), HttpCodeEnum.FAIL.getMsg());
    }

    /**
     * app编码检索
     * @param dto
     * @return
     */
    @Override
    public AjaxResult getMachine(MaterialBackApplyInfo dto) {
        //判断输入或者编码识别或者二维码识别是否为领料工程和单位对应
        List<MaCodeVo> list = new ArrayList<>();
        if (dto.getMaCode() != null ||dto.getQrCode() != null) {
            list = materialBackInfoMapper.getMachine(dto);
        }
        if (CollectionUtils.isNotEmpty(list)) {
            return AjaxResult.success(list);
        }
        return AjaxResult.error(HttpCodeEnum.SYSTEM_ERROR.getCode(), "该编码设备非该班组和工程所领");
    }

    /**
     * 完成退料
     * @param backApplyInfo
     */
    private void finishBackCheckDetails(MaterialBackApplyInfo backApplyInfo) {
        materialBackInfoMapper.updateCheckDetails(backApplyInfo);
    }

    /**
     *
     * @param backApplyInfo
     * @return
     */
    private int deleteTaskInfo(MaterialBackApplyInfo backApplyInfo) {
        // 删除任务、任务协议及相关信息
        int result = 0;
        result += taskMapper.deleteTmTaskByTaskId(backApplyInfo.getTaskId());
        result += taskAgreementMapper.deleteTmTaskAgreementByTaskId(backApplyInfo.getTaskId());
        result += materialBackInfoMapper.deleteBackApply(backApplyInfo.getId());
        result += materialBackInfoMapper.deleteBackApplyDetails(backApplyInfo.getId());
        result += materialBackInfoMapper.deleteCheckDetails(backApplyInfo.getId());
        return result;
    }

    /**
     * 删除编码设备附件
     * @param maCodeList
     * @param taskId
     * @return
     */
    private int deleteFileInfoForMaCodes(List<MaCodeVo> maCodeList, Long taskId) {
        // 删除编码设备相关附件
        int result = 0;
        if (CollectionUtils.isNotEmpty(maCodeList)) {
            for (MaCodeVo maCodeVo : maCodeList) {
                BmFileInfo bmFileInfo = new BmFileInfo();
                bmFileInfo.setModelId(maCodeVo.getMaId());
                bmFileInfo.setTaskId(taskId);
                bmFileInfo.setTaskType(3);
                result += bmFileInfoMapper.deleteBmFileInfoByBizInfo(bmFileInfo);
            }
        }
        return result;
    }

    /**
     * 删除退料详情相关附件
     * @param backApplyDetailsList
     * @param id
     * @return
     */
    private int deleteFileInfoForDetails(List<MaterialBackApplyDetails> backApplyDetailsList, Long id) {
        // 删除退料详情相关附件
        int result = 0;
        if (CollectionUtils.isNotEmpty(backApplyDetailsList)) {
            for (MaterialBackApplyDetails details : backApplyDetailsList) {
                BmFileInfo bmFileInfo = new BmFileInfo();
                bmFileInfo.setModelId(details.getId());
                bmFileInfo.setTaskId(id);
                bmFileInfo.setTaskType(3);
                result += bmFileInfoMapper.deleteBmFileInfoByBizInfo(bmFileInfo);
            }
        }
        return result;
    }

    /**
     * 保存退料详情
     * @param createBy
     * @param dto
     * @param backApplyInfo
     * @param result
     * @return
     */
    private int saveBackApplyDetails(String createBy, MaterialBackApplyRequestVo dto, MaterialBackApplyInfo backApplyInfo, int result) {
        // 循环退料详情
        for (MaterialBackApplyDetails details : dto.getBackApplyDetailsList()) {
            details.setCode(backApplyInfo.getCode());
            details.setParentId(backApplyInfo.getId());
            details.setAuditNum(details.getPreNum());
            details.setStatus(String.valueOf(BackTaskStatusEnum.BACK_TASK_NO_FINISHED.getStatus()));
            details.setCreateBy(createBy);
            details.setCreateTime(DateUtils.getNowDate());
            // 保存退料详情
            result += materialBackInfoMapper.insertBackApplyDetails(details);
            // 处理附件
            result = saveBmFileInfo(details, backApplyInfo.getId(), result);

            // 判断是否为编码设备并处理附件
            Integer isBack = dto.getBackApplyInfo().getIsBack();
            details.setIsFinished(isBack);
            result = saveMaCodeBmFileInfo(createBy, isBack, details, backApplyInfo.getId(), result);

            if (isBack == 1) {
                // 更新任务表及退料申请表状态
                result += updateTaskAndBackInfo(backApplyInfo);
                // 更新结算表
                backApplyInfo.setTypeId(details.getTypeId().toString());
                // 查询材料站的退料明细
                List<MaterialBackApplyInfo> allList = materialBackInfoMapper.selectBackDetails(backApplyInfo);
                if (CollectionUtils.isNotEmpty(allList)) {
                    List<MaterialBackApplyInfo> newList = new ArrayList<>();
                    if (CollectionUtils.isNotEmpty(details.getMaCodeList())) {
                        // 将allList和details.getMaCodeList()进行比较，如果allList中的typeId和maId与details.getMaCodeList()中的相同，
                        //则进行保留
                        for (MaterialBackApplyInfo applyInfo : allList) {
                            for (MaCodeDto maCodeDto : details.getMaCodeList()) {
                                if (applyInfo.getMaId().equals(maCodeDto.getMaId()) && applyInfo.getTypeId().equals(details.getTypeId().toString())) {
                                    newList.add(applyInfo);
                                }
                            }
                        }
                    } else {
                        for (MaterialBackApplyInfo applyInfo : allList) {
                            if (applyInfo.getTypeId().equals(details.getTypeId().toString())
                                    && applyInfo.getBackNum().compareTo(details.getPreNum()) == 0) {
                                newList.add(applyInfo);
                            }
                        }
                    }
                    // 更新材料站的结算协议表
                    int res = updateSlt4Bean(backApplyInfo, newList);
                    // 检查机具是否领料
                    if (res == 0) {
                        throw new RuntimeException("该机具未被领料使用");
                    }
                }
            }
        }
        return result;
    }

    /**
     * 更新协议表
     * @param record
     * @param allList
     * @return
     */
    private int updateSlt4Bean(MaterialBackApplyInfo record, List<MaterialBackApplyInfo> allList) {
        for (MaterialBackApplyInfo bean : allList) {
            List<SltAgreementInfo> infoList = materialBackInfoMapper.getStlInfo(bean);
            if (infoList.size() > 0) {
                BigDecimal backNum = bean.getBackNum();
                for (SltAgreementInfo info : infoList) {
                    BigDecimal num = info.getBackNum();
                    if (backNum.compareTo(num) == 0) {
                        materialBackInfoMapper.updateStlInfo(info, record);
                        break;
                    } else if (backNum.compareTo(num) > 0) {
                        backNum = backNum.subtract(num);
                        materialBackInfoMapper.updateStlInfo(info, record);
                    } else {
                        BigDecimal many = num.subtract(backNum);
                        materialBackInfoMapper.updateStlInfoTwo(info, record, backNum);
                        materialBackInfoMapper.insStlInfoTwo(info, many);
                        break;
                    }
                }
            } else {
                return 0;
            }
        }
        return 1;
    }

    /**
     * 更新任务表及退料申请表状态
     * @param backApplyInfo
     * @return
     */
    private int updateTaskAndBackInfo(MaterialBackApplyInfo backApplyInfo) {
        backApplyInfo.setTaskStatus(2);
        int result = materialBackInfoMapper.updateBack(backApplyInfo);
        result += materialBackInfoMapper.updateBackDetails(backApplyInfo);
        return result;
    }

    /**
     * 保存编码设备附件
     * @param createBy
     * @param isBack
     * @param details
     * @param id
     * @param result
     * @return
     */
    private int saveMaCodeBmFileInfo(String createBy, Integer isBack, MaterialBackApplyDetails details, Long id, int result) {
        // 设置公共字段
        setCommonFields(details, id);
        details.setCreateBy(createBy);
        if (CollectionUtils.isNotEmpty(details.getMaCodeList())) {
            for (MaCodeDto maCodeDto : details.getMaCodeList()) {
                // 设置每个 MaCodeDto 的独立属性
                details.setMaId(maCodeDto.getMaId());
                details.setPreNum(BigDecimal.valueOf(1));
                details.setApDetection(maCodeDto.getApDetection());
                // 插入 CheckDetails
                result += materialBackInfoMapper.insertCheckDetails(details);
                if (CollectionUtils.isNotEmpty(maCodeDto.getBmFileInfos())) {
                    for (BmFileInfo bmFileInfo : maCodeDto.getBmFileInfos()) {
                        bmFileInfo.setCreateBy(SecurityUtils.getLoginUser().getSysUser().getNickName());
                        bmFileInfo.setCreateTime(DateUtils.getNowDate());
                        bmFileInfo.setTaskId(details.getId());
                        bmFileInfo.setTaskType(3);
                        bmFileInfo.setModelId(maCodeDto.getMaId());
                        result += bmFileInfoMapper.insertBmFileInfo(bmFileInfo);
                    }
                }
            }
        } else {
            // 如果 MaCodeList 为空，只插入 CheckDetails
            result += materialBackInfoMapper.insertCheckDetails(details);
        }
        return result;
    }

    /**
     * 设置公共字段
     * @param details
     * @param id
     */
    private void setCommonFields(MaterialBackApplyDetails details, Long id) {
        details.setParentId(id);
        details.setCreateBy(SecurityUtils.getLoginUser().getSysUser().getNickName());
        details.setCreateTime(DateUtils.getNowDate());
        details.setStatus("0");
        // 默认返回状态 0
        details.setBackStatus("0");
    }

    /**
     * 保存编码设备附件
     * @param details
     * @param taskId
     * @param result
     * @return
     */
    private int saveBmFileInfo(MaterialBackApplyDetails details, Long taskId, int result) {
        if (CollectionUtils.isNotEmpty(details.getBmFileInfos())) {
            for (BmFileInfo bmFileInfo : details.getBmFileInfos()) {
                bmFileInfo.setCreateBy(SecurityUtils.getLoginUser().getSysUser().getNickName());
                bmFileInfo.setCreateTime(DateUtils.getNowDate());
                bmFileInfo.setTaskId(taskId);
                bmFileInfo.setTaskType(3);
                bmFileInfo.setModelId(details.getId());
                result += bmFileInfoMapper.insertBmFileInfo(bmFileInfo);
            }
        }
        return result;
    }

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

    /**
     * 查询编码设备信息
     * @param id
     * @return
     */
    private List<MaCodeVo> fetchMaCodeList(Long id) {
        return materialBackInfoMapper.selectByCode(id);
    }

    /**
     * 为编码设备详情设置编码信息和附件信息
     * @param details
     * @param maCodeList
     */
    private void setMaCodeDetails(MaterialBackApplyDetails details, List<MaCodeVo> maCodeList) {
        List<MaCodeVo> codeVos = maCodeList.stream()
                .filter(maCodeVo -> StringUtils.isNotBlank(maCodeVo.getMaCode())
                        && maCodeVo.getTypeId().equals(details.getTypeId().toString()))
                .collect(Collectors.toList());
        List<MaCodeDto> maCodeDtos = new ArrayList<>();
        for (MaCodeVo maCodeVo : codeVos) {
            MaCodeDto maCodeDto = new MaCodeDto();
            maCodeDto.setMaCode(maCodeVo.getMaCode());
            maCodeDto.setMaId(maCodeVo.getMaId());
            maCodeDto.setApDetection(maCodeVo.getApDetection());
            maCodeDto.setTypeName(maCodeVo.getTypeName());
            maCodeDto.setMaterialName(maCodeVo.getMaterialName());
            maCodeDto.setTypeId(maCodeVo.getTypeId());
            maCodeDto.setMaStatus(maCodeVo.getMaStatus());
            maCodeDto.setMaterialType(maCodeVo.getMaterialType());
            // 查询并设置编码附件
            List<BmFileInfo> bmFileInfoList = fetchBmFileInfo(details.getId(), maCodeVo.getMaId());
            if (CollectionUtils.isNotEmpty(bmFileInfoList)) {
                maCodeDto.setBmFileInfos(bmFileInfoList);
            }
            maCodeDtos.add(maCodeDto);
        }
        details.setMaCodeList(maCodeDtos);
    }

    /**
     * 批量查询附件信息
     * @param taskId
     * @param modelId
     * @return
     */
    private List<BmFileInfo> fetchBmFileInfo(Long taskId, Long modelId) {
        BmFileInfo fileInfo = new BmFileInfo();
        fileInfo.setTaskId(taskId);
        fileInfo.setTaskType(3);
        fileInfo.setModelId(modelId);
        return bmFileInfoMapper.selectBmFileInfoList(fileInfo);
    }

    /**
     * 为每个退料详情设置附件信息
     * @param details
     * @param bmFileInfos
     */
    private void setBmFileInfosForDetails(MaterialBackApplyDetails details, List<BmFileInfo> bmFileInfos) {
        // 为每个退料详情设置附件信息
        List<BmFileInfo> relatedFileInfos = bmFileInfos.stream()
                .filter(fileInfo -> fileInfo.getModelId().equals(details.getId()))
                .collect(Collectors.toList());
        if (CollectionUtils.isNotEmpty(relatedFileInfos)) {
            details.setBmFileInfos(relatedFileInfos);
        }
    }

    /**
     * 批量查询附件信息
     * @param id
     * @param backApplyDetailsList
     * @return
     */
    private List<BmFileInfo> fetchBmFileInfos(Long id, List<MaterialBackApplyDetails> backApplyDetailsList) {
        List<BmFileInfo> bmFileInfos = new ArrayList<>();
        for (MaterialBackApplyDetails details : backApplyDetailsList) {
            BmFileInfo bmFileInfo = new BmFileInfo();
            bmFileInfo.setTaskId(id);
            bmFileInfo.setTaskType(3);
            bmFileInfo.setModelId(details.getId());
            List<BmFileInfo> bmFileInfoList = bmFileInfoMapper.selectBmFileInfoList(bmFileInfo);
            // 合并所有附件信息
            bmFileInfos.addAll(bmFileInfoList);
        }
        return bmFileInfos;
    }


    /**
     * 关键字搜索
     * @param item
     * @param keyWord
     * @return
     */
    private boolean containsKeyword(MaterialBackApplyInfo item, String keyWord) {
        return (item.getTypeName() != null && item.getTypeName().contains(keyWord)) ||
                (item.getCode() != null && item.getCode().contains(keyWord)) ||
                (item.getBackPerson() != null && item.getBackPerson().contains(keyWord)) ||
                (item.getUnitName() != null && item.getUnitName().contains(keyWord)) ||
                (item.getProName() != null && item.getProName().contains(keyWord)) ||
                (item.getPhone() != null && item.getPhone().contains(keyWord));
    }

    /**
     * 总站点关键字搜索
     * @param item
     * @param keyWord
     * @return
     */
    private boolean containsTotalKeyword(MaterialBackApplyInfo item, String keyWord) {
        return (item.getTypeName() != null && item.getTypeName().contains(keyWord)) ||
                (item.getUnitName() != null && item.getUnitName().contains(keyWord)) ||
                (item.getProName() != null && item.getProName().contains(keyWord)) ||
                (item.getBackPerson() != null && item.getBackPerson().contains(keyWord)) ||
                (item.getCode() != null && item.getCode().contains(keyWord));
    }
}
