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

import cn.hutool.core.collection.CollectionUtil;
import com.alibaba.nacos.common.utils.CollectionUtils;
import com.alibaba.nacos.common.utils.StringUtils;
import com.bonus.common.core.web.domain.AjaxResult;
import com.bonus.common.security.utils.SecurityUtils;
import com.bonus.material.basic.domain.BmProject;
import com.bonus.material.clz.domain.TeamVo;
import com.bonus.material.clz.domain.lease.MaterialLeaseApplyInfo;
import com.bonus.material.clz.domain.machine.MaterialUseStorageInfo;
import com.bonus.material.clz.domain.vo.*;
import com.bonus.material.clz.mapper.IwsTeamUserMapper;
import com.bonus.material.common.domain.dto.SelectDto;
import com.bonus.material.common.domain.vo.AgreementVo;
import com.bonus.material.common.mapper.SelectMapper;
import com.bonus.material.ma.domain.Machine;
import com.bonus.material.clz.domain.BmTeam;
import com.bonus.material.clz.domain.machine.MaterialStorageInfo;
import com.bonus.material.clz.mapper.MaterialMachineMapper;
import com.bonus.material.clz.service.MaterialMachineService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

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

/**
 * @Author ma_sh
 * @create 2025/6/25 13:27
 */
@Service
@Slf4j
public class MaterialMachineServiceImpl implements MaterialMachineService {

    @Resource
    private MaterialMachineMapper materialMachineMapper;

    @Resource
    private SelectMapper mapper;

    @Resource
    private IwsTeamUserMapper iwsTeamUserMapper;

    /**
     * 获取机具追溯管理数据
     * @param machine
     * @return
     */
    @Override
    public List<Machine> getMachineInfo(Machine machine) {
        Set<String> userRoles = SecurityUtils.getLoginUser().getRoles();
        String username = SecurityUtils.getLoginUser().getUsername();
        BmTeam teamData = new BmTeam();
        // 检查用户是否具有特殊角色
        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)) {
                    machine.setProjectIdList(projectIdList);
                }
            }
            // 查询slt_agreement_info数据
            machine.setImpUnit(SecurityUtils.getLoginUser().getSysUser().getDeptId().toString());
        }
        List<Machine> mergedList = materialMachineMapper.getMachineInfo(machine);
        if (!CollectionUtils.isEmpty(mergedList)) {
            // 班组权限
            if (teamData != null) {
                // 将sortedList中班组身份证号与username相同的元素过滤处理
                mergedList = mergedList.stream()
                        .filter(item -> StringUtils.isBlank(item.getIdCard()) || username.equals(item.getIdCard()))
                        .collect(Collectors.toList());
            }
        }
        if (!StringUtils.isBlank(machine.getKeyWord())) {
            mergedList = mergedList.stream()
                    .filter(item -> containsKeywordMachine(item, machine.getKeyWord()))
                    .collect(Collectors.toList());
        }
        return mergedList;
    }

    /**
     * 判断机具追溯管理数据中是否包含关键字
     * @param item
     * @param keyWord
     * @return
     */
    private boolean containsKeywordMachine(Machine item, String keyWord) {
        return (item.getMaterialName() != null && item.getMaterialName().contains(keyWord)) ||
                (item.getTypeName() != null && item.getTypeName().contains(keyWord)) ||
                (item.getMaModel() != null && item.getMaModel().contains(keyWord)) ||
                (item.getMaCode() != null && item.getMaCode().contains(keyWord)) ||
                (item.getQrCode() != null && item.getQrCode().contains(keyWord)) ||
                (item.getCheckMan() != null && item.getCheckMan().contains(keyWord));
    }

    /**
     * 获取机具追溯管理数据
     * @param list
     * @param username
     * @return
     */
    private List<Machine> filterInfoMachine(List<Machine> list, String username) {
        if (CollectionUtils.isEmpty(list)) {
            return Collections.emptyList();
        }
        List<Machine> newList = new ArrayList<>();
        for (Machine 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 bean
     * @return
     */
    @Override
    public List<MaterialRetainedEquipmentInfo> getRetainedEquipmentList(MaterialRetainedEquipmentInfo bean) {
        String username = SecurityUtils.getLoginUser().getUsername();
        // 根据用户名判断用户是否为班组长
        BmTeam teamData = materialMachineMapper.getTeamData(username);
        Set<String> userRoles = SecurityUtils.getLoginUser().getRoles();
        // 检查用户是否具有特殊角色
        boolean hasSpecialRole = hasSpecialRole(userRoles);
        if (!hasSpecialRole) {
            if (teamData == null) {
                // 根据用户名查询项目部信息
                List<String> departId = mapper.getDepartId(username);
                // 根据项目部id查询工程信息
                List<String> projectIdList = mapper.getProjectId(departId);
                if (!org.springframework.util.CollectionUtils.isEmpty(projectIdList)) {
                    bean.setProjectIdList(projectIdList);
                }
            }
            Long deptId = SecurityUtils.getLoginUser().getSysUser().getDeptId();
            if (deptId != null) {
                bean.setImpUnit(deptId.toString());
            }
        }
        // 查询目前在用的设备信息
        List<MaterialRetainedEquipmentInfo> usList = materialMachineMapper.getUsInfoList(bean);
        //查询目前还有库存的设备
        List<MaterialRetainedEquipmentInfo> recordList = materialMachineMapper.getRetainInfoList(bean);
        if (!CollectionUtils.isEmpty(usList)) {
            for (MaterialRetainedEquipmentInfo materialRetainedEquipmentInfo : usList) {
                // 根据班组名称查询分包单位
                String subUnitName = iwsTeamUserMapper.getTeamName(materialRetainedEquipmentInfo.getTeamName());
                materialRetainedEquipmentInfo.setSubUnitName(subUnitName);
            }
            // 数据合并
            if (!CollectionUtils.isEmpty(recordList)) {
                usList.addAll(recordList);
            }
            if (teamData != null) {
                // 将sortedList中班组身份证号与username相同的元素过滤处理
                usList = usList.stream()
                        .filter(item -> StringUtils.isBlank(item.getIdCard()) || username.equals(item.getIdCard()))
                        .collect(Collectors.toList());
            }
        }
        return usList;
    }

    /**
     * 保有设备总量查询材料员权限
     * @param list
     * @param username
     * @return
     */
    private List<MaterialRetainedEquipmentInfo> filterInfo(List<MaterialRetainedEquipmentInfo> list, String username) {
        if (CollectionUtils.isEmpty(list)) {
            return Collections.emptyList();
        }
        List<MaterialRetainedEquipmentInfo> newList = new ArrayList<>();
        for (MaterialRetainedEquipmentInfo info : list) {
            if (com.bonus.common.core.utils.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 bean
     * @return
     */
    @Override
    public List<MaterialStorageInfo> getMaCodeList(MaterialStorageInfo bean) {
        try {
            // 查询库管员
            List<MaterialStorageInfo> list = materialMachineMapper.getMaCodeList(bean);
            MaterialUseStorageInfo materialUseStorageInfo = new MaterialUseStorageInfo();
            materialUseStorageInfo.setProId(StringUtils.isNotBlank(bean.getProId()) ? bean.getProId() : null);
            materialUseStorageInfo.setTypeId(bean.getTypeId() != null ? bean.getTypeId() : null);
            List<MaterialUseStorageInfo> userList = materialMachineMapper.getUserRecords(materialUseStorageInfo);
            if (CollectionUtils.isNotEmpty(list)) {
                if (CollectionUtils.isNotEmpty(userList)) {
                    list.removeIf(info -> {
                        for (MaterialUseStorageInfo useStorageInfo : userList) {
                            if (info.getMaId().equals(useStorageInfo.getMaId())) {
                                return true;
                            }
                        }
                        return false;
                    });
                }
            }
            if (CollectionUtils.isNotEmpty(list)) {
                for (MaterialStorageInfo useStorageInfo : list) {
                    // 查询出库信息
                    if (useStorageInfo.getLeaseId() != null) {
                        MaterialStorageInfo dto = materialMachineMapper.selectInFo(useStorageInfo);
                        if (dto != null) {
                            useStorageInfo.setInputUser(dto.getInputUser());
                            useStorageInfo.setInputTime(dto.getInputTime());
                        }
                    }
                }
                String keyWord = bean.getKeyWord();
                // 如果关键字不为空，进行过滤
                if (!com.bonus.common.core.utils.StringUtils.isBlank(keyWord)) {
                    list = list.stream()
                            .filter(item -> containsKeyword(item, keyWord))
                            .collect(Collectors.toList());
                }
            }
            return list;
        } catch (Exception e) {
            log.error("查询在用设备详情失败", e);
            throw new RuntimeException("查询在用设备详情失败");
        }
    }

    /**
     * 班组库存查询
     * @param bean
     * @return
     */
    @Override
    public List<MaterialRetainedEquipmentInfo> getTeamUseNumList(MaterialRetainedEquipmentInfo bean) {
        String username = SecurityUtils.getLoginUser().getUsername();
        // 根据用户名判断用户是否为班组长
        BmTeam 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)) {
                bean.setProjectIdList(projectIdList);
            }
        }
        List<MaterialRetainedEquipmentInfo> list = materialMachineMapper.getTeamUseNumList(bean);
        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 (MaterialRetainedEquipmentInfo retainedEquipmentInfo : list) {
                MaterialRetainedEquipmentInfo info = new MaterialRetainedEquipmentInfo();
                info.setTypeId(retainedEquipmentInfo.getTypeId());
                info.setTeamId(bean.getTeamId());
                List<MaterialRetainedEquipmentInfo> teamUseNumDetailsList = materialMachineMapper.getTeamUseNumDetailsList(info);
                if (CollectionUtils.isNotEmpty(teamUseNumDetailsList)) {
                    retainedEquipmentInfo.setModelList(teamUseNumDetailsList);
                }
            }
        }
        return list;
    }

    /**
     * 班组预警详情查询
     * @param bean
     * @return
     */
    @Override
    public List<MaterialRetainedEquipmentInfo> getTeamWarnDetailsList(MaterialRetainedEquipmentInfo bean) {
        List<MaterialRetainedEquipmentInfo> list = materialMachineMapper.getTeamUseNumDetailsList(bean);
        Long deptId = SecurityUtils.getLoginUser().getSysUser().getDeptId();
        if (!CollectionUtils.isEmpty(list) && deptId != null) {
            // 删除元素
            list.removeIf(m -> !deptId.toString().equals(m.getImpUnit()));
        }
        if (CollectionUtils.isEmpty(list)) {
            return new ArrayList<>();
        }
        if (!CollectionUtil.isEmpty(list)) {
            if (StringUtils.isNotBlank(bean.getStatus())) {
                return list.stream().filter(item -> {
                    return item.getStatus().equals(bean.getStatus());
                }).collect(Collectors.toList());
            }
        }
        return list;
    }

    /**
     * 工器具台账查询
     * @param bean
     * @return
     */
    @Override
    public List<MaterialRetainedEquipmentInfo> getToolsLedgerList(MaterialRetainedEquipmentInfo bean) {
        String username = SecurityUtils.getLoginUser().getUsername();
        // 根据用户名判断用户是否为班组长
        BmTeam 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)) {
                bean.setProjectIdList(projectIdList);
            }
        }
        List<MaterialRetainedEquipmentInfo> list1 = new ArrayList<>();
        try {
            //List<MaterialRetainedEquipmentInfo> totalList = materialMachineMapper.getToolsLedgerList(bean);
            List<MaterialRetainedEquipmentInfo> list = materialMachineMapper.getRetainedEquipmentList(bean);
            Long deptId = SecurityUtils.getLoginUser().getSysUser().getDeptId();
            /*if (!CollectionUtils.isEmpty(totalList) && deptId != null) {
                // 删除元素
                totalList.removeIf(m -> !deptId.toString().equals(m.getImpUnit()));
            }
            if (CollectionUtils.isEmpty(totalList)) {
                return new ArrayList<>();
            }*/
            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 = filterInfoTools(list, username);
                }*/
            }
            // 根据用户名判断用户是否为班组长
            if (CollectionUtils.isNotEmpty(list)) {
                list1 = groupByThirdTypeId(list);
            } /*else if (CollectionUtils.isNotEmpty(totalList)) {
                list1 = groupByThirdTypeId(totalList);
            }*/
            return list1;
        } catch (Exception e){
            log.error("获取设备台账列表失败，参数：{}", bean, e);
            return new ArrayList<>();
        }
    }

    /**
     * 材料员工器具台账查询
     * @param list
     * @param username
     * @return
     */
    private List<MaterialRetainedEquipmentInfo> filterInfoTools(List<MaterialRetainedEquipmentInfo> list, String username) {
        if (CollectionUtils.isEmpty(list)) {
            return Collections.emptyList();
        }
        List<MaterialRetainedEquipmentInfo> newList = new ArrayList<>();
        for (MaterialRetainedEquipmentInfo info : list) {
            if (com.bonus.common.core.utils.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);
            }
        }
        return newList;
    }

    /**
     * 工器具预警设备数量查询
     * @param bean
     * @return
     */
    @Override
    public MaterialRetainedEquipmentInfo getToolsLedgerDetailsList(MaterialRetainedEquipmentInfo bean) {
        String username = SecurityUtils.getLoginUser().getUsername();
        try {
            // 根据用户名判断用户是否为班组长
            BmTeam teamData = materialMachineMapper.getTeamData(username);
            if (teamData == null) {
                // 根据用户名查询项目部信息
                List<String> departId = mapper.getDepartId(username);
                if (CollectionUtils.isEmpty(departId)) {
                    return new MaterialRetainedEquipmentInfo();
                }
                // 根据项目部id查询工程信息
                List<String> projectIdList = mapper.getProjectId(departId);
                if (!org.springframework.util.CollectionUtils.isEmpty(projectIdList)) {
                    bean.setProjectIdList(projectIdList);
                }
            }
            // 查询slt_agreement_info数据
            List<MaterialRetainedEquipmentInfo> primaryList = materialMachineMapper.getToolsLedgerDetailsList(bean);
            // 查询clz_slt_agreement_info数据
            List<MaterialRetainedEquipmentInfo> list = materialMachineMapper.getTeamUseNumDetailsList(bean);
            Long deptId = SecurityUtils.getLoginUser().getSysUser().getDeptId();
            if (!CollectionUtils.isEmpty(primaryList) && deptId != null) {
                // 删除元素
                primaryList.removeIf(m -> !deptId.toString().equals(m.getImpUnit()));
            }
            if (CollectionUtils.isEmpty(primaryList)) {
                return new MaterialRetainedEquipmentInfo();
            }
            if (!CollectionUtils.isEmpty(list)) {
                if (teamData != null) {
                    // 将sortedList中班组身份证号与username相同的元素过滤处理
                    list = list.stream()
                            .filter(item -> StringUtils.isBlank(item.getIdCard()) || username.equals(item.getIdCard()))
                            .collect(Collectors.toList());
                    if (CollectionUtils.isNotEmpty(list)) {
                        return getMaterialRetainedEquipmentInfo(list);
                    }
                }
            }
           if (!CollectionUtil.isEmpty(primaryList)) {
                return getMaterialRetainedEquipmentInfo(primaryList);
            }
        } catch (Exception e){
            log.error("获取设备详情列表失败，参数：{}", bean, e);
        }
        return new MaterialRetainedEquipmentInfo();
    }

    /**
     * 工器具详情查询数量处理
     * @param list
     * @return
     */
    private MaterialRetainedEquipmentInfo getMaterialRetainedEquipmentInfo(List<MaterialRetainedEquipmentInfo> list) {
        // 获取list集合中状态的元素的总数
        MaterialRetainedEquipmentInfo retainedEquipmentInfo = new MaterialRetainedEquipmentInfo();
        long normalNum = list.stream().filter(item -> "0".equals(item.getStatus())).count();
        retainedEquipmentInfo.setNormalNum(normalNum);
        long threeMonthNum = list.stream().filter(item -> "1".equals(item.getStatus())).count();
        retainedEquipmentInfo.setThreeMonthNum(threeMonthNum);
        long oneMonthNum = list.stream().filter(item -> "2".equals(item.getStatus())).count();
        retainedEquipmentInfo.setOneMonthNum(oneMonthNum);
        long expiredNum = list.stream().filter(item -> "3".equals(item.getStatus())).count();
        retainedEquipmentInfo.setExpiredNum(expiredNum);
        return retainedEquipmentInfo;
    }

    /**
     * 工器具详情查询
     * @param bean
     * @return
     */
    @Override
    public List<MaterialRetainedEquipmentInfo> getToolsDetailsList(MaterialRetainedEquipmentInfo bean) {
        try {
            //没有班组，则查全部
            List<MaterialRetainedEquipmentInfo> list = materialMachineMapper.getToolsDetailsList(bean);
            if (!CollectionUtil.isEmpty(list)) {
                if (StringUtils.isNotBlank(bean.getStatus())) {
                    return list.stream().filter(item -> {
                        return StringUtils.isNotBlank(item.getStatus()) && item.getStatus().equals(bean.getStatus());
                    }).collect(Collectors.toList());
                }
            }
            return list;
        } catch (Exception e){
            log.error("工器具台账详情查询失败", e);
            return new ArrayList<>();
        }
    }

    /**
     * 查询在用设备详情
     * @param bean
     * @return
     */
    @Override
    public List<MaterialUseStorageInfo> getUserRecords(MaterialUseStorageInfo bean) {
        try {
            // 查询库管员
            List<MaterialUseStorageInfo> list = materialMachineMapper.getUserRecords(bean);
            if (CollectionUtils.isNotEmpty(list)) {
                for (MaterialUseStorageInfo useStorageInfo : list) {
                    // 查询出库信息
                    if (useStorageInfo.getLeaseId() != null) {
                        MaterialUseStorageInfo dto = materialMachineMapper.selectUseInFo(useStorageInfo);
                        if (dto != null) {
                            useStorageInfo.setCreator(dto.getCreator());
                            useStorageInfo.setOutTime(dto.getOutTime());
                        }
                    }
                }
                String keyWord = bean.getKeyWord();
                // 如果关键字不为空，进行过滤
                if (StringUtils.isNotBlank(keyWord)) {
                    list = list.stream()
                            .filter(item -> containsUseKeyword(item, keyWord))
                            .collect(Collectors.toList());
                }
            }
            return list;
        } catch (Exception e) {
            log.error("查询在用设备详情失败", e);
            throw new RuntimeException("查询在用设备详情失败");
        }
    }

    /**
     * 安全工器具预警页面查询
     * @param bean
     * @return
     */
    @Override
    public List<MaterialRetainedEquipmentInfo> getSafeDetailsList(MaterialRetainedEquipmentInfo bean) {
        bean.setDeptId(SecurityUtils.getLoginUser().getSysUser().getDeptId());
        List<MaterialRetainedEquipmentInfo> usList = materialMachineMapper.getTotalList(bean);
        for (MaterialRetainedEquipmentInfo materialRetainedEquipmentInfo : usList) {
            // 根据班组名称查询分包单位
            String subUnitName = iwsTeamUserMapper.getTeamName(materialRetainedEquipmentInfo.getTeamName());
            materialRetainedEquipmentInfo.setSubUnitName(subUnitName);
        }
        if(bean.getSubUnitName()!=null && !bean.getSubUnitName().equals("") && !usList.isEmpty()){
            // 根据传入的SubUnitName过滤列表
            usList = usList.stream()
                    .filter(item -> StringUtils.equals(item.getSubUnitName(), bean.getSubUnitName()))
                    .collect(Collectors.toList());
        }
        return usList;
    }

    /**
     * 模糊匹配查询
     * @param item
     * @param keyWord
     * @return
     */
    private boolean containsNumKeyword(MaterialRetainedEquipmentInfo item, String keyWord) {
        return (item.getTypeName() != null && item.getTypeName().contains(keyWord)) ||
                (item.getTypeModelName() != null && item.getTypeModelName().contains(keyWord)) ||
                (item.getProName() != null && item.getProName().contains(keyWord)) ||
                (item.getMaCode() != null && item.getMaCode().contains(keyWord)) ||
                (item.getTeamName() != null && item.getTeamName().contains(keyWord));
    }

    /**
     * 后台班组在用库存查询
     * @param bean
     * @return
     */
    @Override
    public List<MaterialRetainedTeamTotalVo> getTeamNumList(MaterialRetainedEquipmentInfo bean) {
        String username = SecurityUtils.getLoginUser().getUsername();
        // 根据用户名查询项目部信息
        List<String> departId = mapper.getDepartId(username);
        // 根据项目部id查询工程信息
        List<MaterialRetainedTeamTotalVo> teamNumList = materialMachineMapper.getTeamNumList(bean);

        for (MaterialRetainedTeamTotalVo materialRetainedEquipmentInfo : teamNumList) {
            // 根据班组名称查询分包单位
            String subUnitName = iwsTeamUserMapper.getTeamName(materialRetainedEquipmentInfo.getTeamName());
            materialRetainedEquipmentInfo.setSubUnitName(subUnitName);
        }
        if(bean.getSubUnitName()!=null && !bean.getSubUnitName().equals("") && !teamNumList.isEmpty()){
            // 根据传入的SubUnitName过滤列表
            teamNumList = teamNumList.stream()
                    .filter(item -> StringUtils.equals(item.getSubUnitName(), bean.getSubUnitName()))
                    .collect(Collectors.toList());
        }
        if (CollectionUtils.isEmpty(departId)) {
            List<String> projectIdList = mapper.getProjectId(departId);
            List<BmProject> list = mapper.getProjectInfo(new BmProject());
            if (CollectionUtils.isNotEmpty(list) && CollectionUtils.isNotEmpty(projectIdList)) {
                // 找出list中projectId与projectIdList中相同的数据
                list = list.stream().filter(info -> projectIdList.contains(info.getProjectId())).collect(Collectors.toList());
                if (CollectionUtils.isNotEmpty(list)) {
                    // 获取list中的projectId
                    List<String> collect = list.stream().map(BmProject::getProjectId).distinct().collect(Collectors.toList());
                    // 根据i8工程id查询班组信息
                    List<IwsTeamUserVo> iwsTeamUserVos = iwsTeamUserMapper.selectProjectTeamInfoByProjectIds(collect);
                    if (CollectionUtil.isNotEmpty(iwsTeamUserVos)) {
                        if (CollectionUtil.isNotEmpty(teamNumList)) {
                            // 筛选出teamNumList中班组名称和iwsTeamUserVos中班组名称相同的数据
                            teamNumList = teamNumList.stream().filter(item -> iwsTeamUserVos.stream().anyMatch(info -> info.getTeamName().equals(item.getTeamName()))).collect(Collectors.toList());
                        }
                    }
                }
            }
        }
        // 根据用户名判断用户是否为班组长
        BmTeam teamData = materialMachineMapper.getTeamData(username);
        Long deptId = SecurityUtils.getLoginUser().getSysUser().getDeptId();
        if (CollectionUtils.isNotEmpty(teamNumList)) {
            if (deptId != null) {
                // 删除元素
                teamNumList.removeIf(m -> !deptId.toString().equals(m.getImpUnit()));
            }
            if (teamData != null) {
                return teamNumList.stream().filter(item -> {
                    return StringUtils.isNotBlank(item.getIdCard()) && item.getIdCard().equals(username);
                }).collect(Collectors.toList());
            }
        }
        return teamNumList;
    }

    /**
     * 后台班组在用库存查询二级页面
     * @param bean
     * @return
     */
    @Override
    public List<MaterialRetainedTeamVo> getTeamNumSecondList(MaterialRetainedEquipmentInfo bean) {
        return materialMachineMapper.getTeamNumSecondList(bean);
    }

    /**
     * 后台班组在用库存查询三级页面
     * @param bean
     * @return
     */
    @Override
    public List<MaterialRetainedEquipmentInfo> getTeamNumThirdList(MaterialRetainedEquipmentInfo bean) {
        return materialMachineMapper.getTeamNumThirdList(bean);
    }

    /**
     * 安全工器具预警数量查询
     * @param bean
     * @return
     */
    @Override
    public MaterialRetainedEquipmentInfo getSafeNumList(MaterialRetainedEquipmentInfo bean) {
        MaterialRetainedEquipmentInfo retainedEquipmentInfo = new MaterialRetainedEquipmentInfo();
        bean.setDeptId(SecurityUtils.getLoginUser().getSysUser().getDeptId());
        List<MaterialRetainedEquipmentInfo> totalList = materialMachineMapper.getTotalList(bean);
        if (!CollectionUtil.isEmpty(totalList)) {
            if (StringUtils.isNotBlank(bean.getStatus())) {
                totalList = totalList.stream().filter(item -> StringUtils.isNotBlank(item.getStatus()) && item.getStatus().equals(bean.getStatus())).collect(Collectors.toList());
            }
            // 如果关键字不为空，进行过滤
            if (StringUtils.isNotBlank(bean.getKeyWord())) {
                totalList = totalList.stream()
                        .filter(item -> containsNumKeyword(item, bean.getKeyWord()))
                        .collect(Collectors.toList());
            }
            if (CollectionUtils.isNotEmpty(totalList)) {
                // 收集totalList中各种状态的总数量
                long normalNum = totalList.stream().filter(item -> "0".equals(item.getStatus())).count();
                retainedEquipmentInfo.setNormalNum(normalNum);
                long threeMonthNum = totalList.stream().filter(item -> "1".equals(item.getStatus())).count();
                retainedEquipmentInfo.setThreeMonthNum(threeMonthNum);
                long oneMonthNum = totalList.stream().filter(item -> "2".equals(item.getStatus())).count();
                retainedEquipmentInfo.setOneMonthNum(oneMonthNum);
                long expiredNum = totalList.stream().filter(item -> "3".equals(item.getStatus())).count();
                retainedEquipmentInfo.setExpiredNum(expiredNum);
            }
        }
        return retainedEquipmentInfo;
    }

    /**
     * 安全工器具预警页面查询获取协议id
     * @param bean
     * @return
     */
    @Override
    public AjaxResult getAgreementId(MaterialRetainedEquipmentInfo bean) {
        String username = SecurityUtils.getLoginUser().getUsername();
        // 根据用户名查询项目部信息
        List<String> departId = mapper.getDepartId(username);
        if (CollectionUtils.isEmpty(departId)) {
            return AjaxResult.success();
        }
        // 根据项目部id查询工程信息
        List<String> projectIdList = mapper.getInProject(departId);
        List<BmProject> list = mapper.getProjectInfo(new BmProject());
        Set<Integer> agreementIdList = new HashSet<>();
        if (CollectionUtils.isNotEmpty(list)) {
            if (CollectionUtils.isNotEmpty(projectIdList)) {
                // 找出list中projectId与projectIdList中相同的数据
                list = list.stream().filter(info -> projectIdList.contains(info.getProjectId())).collect(Collectors.toList());
            }
            if (CollectionUtils.isNotEmpty(list)) {
                for (BmProject project : list) {
                    SelectDto selectDto = new SelectDto();
                    selectDto.setProId(project.getProId());
                    List<AgreementVo> agreementList = mapper.getAgreementInfoBy(selectDto);
                    if (CollectionUtils.isNotEmpty(agreementList)) {
                        for (AgreementVo agreement : agreementList) {
                            agreementIdList.add(agreement.getAgreementId());
                        }
                    }
                }
            }
        }
        return AjaxResult.success(agreementIdList);
    }

    /**
     * 工器具台账查询
     * @param bean
     * @return
     */
    @Override
    public MaterialTotalMentInfo getTotalList(MaterialRetainedEquipmentInfo bean) {
        MaterialTotalMentInfo info = new MaterialTotalMentInfo();
        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查询工程信息
                if (!CollectionUtils.isEmpty(departId)) {
                    List<String> projectIdList = mapper.getProjectId(departId);
                    if (!CollectionUtils.isEmpty(projectIdList)) {
                        bean.setProjectIdList(projectIdList);
                    }
                }
            }
            Long deptId = SecurityUtils.getLoginUser().getSysUser().getDeptId();
            if (deptId != null) {
                bean.setImpUnit(deptId.toString());
            }
        }
        // 获取项目部总数
        Integer departNum = materialMachineMapper.selectDepartNum(bean);
        // 获取工程总数
        Integer projectNum = materialMachineMapper.selectProjectNum(bean);
        // 获取班组总数
        Integer teamNum = materialMachineMapper.selectTeamNum(bean);
        // 获取在用量
        MaterialRetainedEquipmentInfo useInfo = materialMachineMapper.getRetainTotalInfo(bean);
        BigDecimal useNum = (useInfo != null && useInfo.getUsNum() != null) ?
                useInfo.getUsNum() : BigDecimal.ZERO;

        // 库存量
        MaterialRetainedEquipmentInfo storeInfo = materialMachineMapper.getRetainStoreInfo(bean);
        BigDecimal storeNum = (storeInfo != null && storeInfo.getStoreNum() != null) ?
                storeInfo.getStoreNum() : BigDecimal.ZERO;
        BigDecimal storeUseNum = (storeInfo != null && storeInfo.getUsNum() != null) ?
                storeInfo.getUsNum() : BigDecimal.ZERO;

         // 站内库存量 = 库存量 - 库存中已使用量，不能为负数
        BigDecimal inNum = storeNum.subtract(storeUseNum);
        if (inNum.compareTo(BigDecimal.ZERO) < 0) {
            inNum = BigDecimal.ZERO;
        }
        // 设置结果
        info.setInNum(inNum);
        info.setUseNum(useNum);
        info.setDepartNum(departNum);
        info.setProNum(projectNum);
        info.setTeamNum(teamNum);
        info.setAllNum(inNum.add(useNum));
        return info;
    }

    /**
     * 班组进出场记录
     * @param bean
     * @return
     */
    @Override
    public List<TeamVo> getTeamInOrOutInfo(TeamVo bean) {
        return materialMachineMapper.getTeamInOrOutInfo(bean);
    }

    /**
     * 检查用户是否具有特殊角色
     * @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 item
     * @param keyWord
     * @return
     */
    private boolean containsTotalKeyword(MaterialTotalMentInfo item, String keyWord) {
        return (item.getProCenter() != null && item.getProCenter().contains(keyWord)) ||
                (item.getProName() != null && item.getProName().contains(keyWord));
    }

    /**
     * 在用设备模糊匹配
     * @param item
     * @param keyWord
     * @return
     */
    private boolean containsUseKeyword(MaterialUseStorageInfo item, String keyWord) {
        return (item.getTypeName() != null && item.getTypeName().contains(keyWord)) ||
                (item.getTypeModelName() != null && item.getTypeModelName().contains(keyWord)) ||
                (item.getCreator() != null && item.getCreator().contains(keyWord)) ||
                (item.getMaCode() != null && item.getMaCode().contains(keyWord)) ||
                (item.getTeamName() != null && item.getTeamName().contains(keyWord)) ||
                (item.getCode() != null && item.getCode().contains(keyWord));
    }

    /**
     * 工器具台账分组
     * @param dbList
     * @return
     */
    private List<MaterialRetainedEquipmentInfo> groupByThirdTypeId(List<MaterialRetainedEquipmentInfo> dbList) {
        // 按thirdTypeId分组，同时保留typeName
        Map<Integer, List<MaterialRetainedEquipmentInfo>> groupedMap = dbList.stream()
                .collect(Collectors.groupingBy(
                        MaterialRetainedEquipmentInfo::getThirdTypeId,
                        Collectors.toList()
                ));

        // 转换为目标格式
        List<MaterialRetainedEquipmentInfo> result = new ArrayList<>();

        groupedMap.forEach((thirdTypeId, items) -> {
            if (!items.isEmpty()) {
                MaterialRetainedEquipmentInfo category = new MaterialRetainedEquipmentInfo();
                category.setThirdTypeId(thirdTypeId);
                // 取第一个元素的typeName
                category.setTypeName(items.get(0).getTypeName());

                List<MaterialRetainedEquipmentInfo> specs = items.stream()
                        .map(item -> {
                            MaterialRetainedEquipmentInfo spec = new MaterialRetainedEquipmentInfo();
                            spec.setTypeModelName(item.getTypeModelName());
                            spec.setUnit(item.getUnit());
                            spec.setBuyPrice(item.getBuyPrice());
                            spec.setStoreNum(item.getStoreNum());
                            spec.setManageType(item.getManageType());
                            spec.setTypeId(item.getTypeId());
                            return spec;
                        })
                        .collect(Collectors.toList());

                category.setModelList(specs);
                result.add(category);
            }
        });

        return result;
    }

    /**
     * 判断item是否包含关键字
     * @param item
     * @param keyWord
     * @return
     */
    private boolean containsKeyword(MaterialStorageInfo item, String keyWord) {
        return (item.getTypeName() != null && item.getTypeName().contains(keyWord)) ||
                (item.getTypeModelName() != null && item.getTypeModelName().contains(keyWord)) ||
                (item.getInputUser() != null && item.getInputUser().contains(keyWord)) ||
                (item.getMaCode() != null && item.getMaCode().contains(keyWord)) ||
                (item.getTeamName() != null && item.getTeamName().contains(keyWord)) ||
                (item.getCode() != null && item.getCode().contains(keyWord)) ;
    }
}
