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

import java.math.BigDecimal;
import java.math.RoundingMode;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.concurrent.atomic.AtomicReference;
import java.util.function.Function;
import java.util.stream.Collectors;

import com.bonus.common.biz.constant.BmConfigItems;
import com.bonus.common.biz.enums.MaTypeManageTypeEnum;
import com.bonus.common.biz.enums.PurchaseTaskStageEnum;
import com.bonus.common.biz.enums.PurchaseTaskStatusEnum;
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.common.biz.domain.BmFileInfo;
import com.bonus.material.basic.mapper.BmFileInfoMapper;
import com.bonus.material.basic.service.IBmConfigService;
import com.bonus.material.countersign.domain.SignProcessVo;
import com.bonus.material.countersign.mapper.SignProcessMapper;
import com.bonus.material.ma.domain.Type;
import com.bonus.material.ma.mapper.TypeMapper;
import com.bonus.material.purchase.domain.PurchaseCheckDetails;
import com.bonus.material.purchase.domain.PurchaseSignRecord;
import com.bonus.material.purchase.domain.dto.PurchaseCheckDto;
import com.bonus.material.purchase.domain.dto.PurchaseQueryDto;
import com.bonus.material.purchase.domain.vo.PurchaseVerifyVo;
import com.bonus.material.purchase.mapper.PurchaseCheckDetailsMapper;
import com.bonus.material.purchase.domain.vo.PurchaseCheckFormVo;
import com.bonus.material.purchase.mapper.PurchaseMacodeInfoMapper;
import com.bonus.material.task.domain.TmTask;
import com.bonus.material.task.mapper.TmTaskMapper;
import com.bonus.system.api.model.LoginUser;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.BooleanUtils;
import org.springframework.dao.DataAccessException;
import org.springframework.stereotype.Service;
import com.bonus.material.purchase.mapper.PurchaseCheckInfoMapper;
import com.bonus.material.purchase.domain.PurchaseCheckInfo;
import com.bonus.material.purchase.service.IPurchaseCheckInfoService;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;
import javax.annotation.Resource;

import static com.bonus.common.biz.constant.MaterialConstants.PURCHASE_TASK_TYPE_LABEL;

/**
 * 新购验收任务Service业务层处理
 *
 * @author syruan
 */
@Service
@Slf4j
public class PurchaseCheckInfoServiceImpl implements IPurchaseCheckInfoService {

    @Resource
    private IBmConfigService bmConfigService;

    @Resource
    private PurchaseCheckInfoMapper purchaseCheckInfoMapper;

    @Resource
    private PurchaseCheckDetailsMapper purchaseCheckDetailsMapper;

    @Resource
    private PurchaseMacodeInfoMapper purchaseMacodeInfoMapper;

    @Resource
    private TmTaskMapper tmTaskMapper;

    @Resource
    private BmFileInfoMapper bmFileInfoMapper;

    @Resource
    private TypeMapper typeMapper;

    @Resource
    private SignProcessMapper signProcessMapper;

    // 引入新购任务阶段常量
    private static final int PURCHASE_TASK_STAGE_MANAGE = 1;
    private static final int PURCHASE_TASK_STAGE_CHECK = 2;
    private static final int PURCHASE_TASK_STAGE_BIND = 3;
    private static final int PURCHASE_TASK_STAGE_STORE = 4;

    /**
     * 查询新购验收任务
     *
     * @param purchaseQueryDto 新购验收任务请求参数封装dto
     * @return 新购验收任务
     */
    @Override
    public PurchaseCheckDto selectPurchaseCheckInfoById(PurchaseQueryDto purchaseQueryDto) {
        purchaseQueryDto.setUserId(SecurityUtils.getLoginUser().getUserid());
        PurchaseCheckDto purchaseCheckDtoResult = new PurchaseCheckDto();
        PurchaseCheckInfo purchaseCheckInfo = purchaseCheckInfoMapper.selectPurchaseCheckInfoById(purchaseQueryDto.getId());
        if (null != purchaseCheckInfo) {
            purchaseCheckDtoResult.setPurchaseCheckInfo(purchaseCheckInfo);
//            boolean isAllowPartTransfer = bmConfigService.isBmConfigEnabledWithDefaultFalse(BmConfigItems.BOOLEAN_ALLOW_PURCHASE_PART_TRANSFER);
            List<PurchaseCheckDetails> purchaseCheckDetailsList = purchaseCheckDetailsMapper.selectPurchaseCheckDetailsListByQueryDto(purchaseQueryDto);
            if (null != purchaseQueryDto.getTaskStage()) {
                // 根据阶段来过滤详情数据
                switch (purchaseQueryDto.getTaskStage()) {
                    case PURCHASE_TASK_STAGE_MANAGE:
                        // 新购管理阶段展示全部任务、不进行过滤
                        break;
                    case PURCHASE_TASK_STAGE_CHECK:
                        purchaseCheckDetailsList = purchaseCheckDetailsList.stream().filter(o -> !PurchaseTaskStatusEnum.TO_NOTICE.getStatus().equals(o.getStatus())).collect(Collectors.toList());
                        //purchaseCheckDetailsList = purchaseCheckDetailsList.stream().filter(o -> !PurchaseTaskStatusEnum.TO_CHECK_AFTER_REJECT.getStatus().equals(o.getStatus())).collect(Collectors.toList());
                        break;
                    case PURCHASE_TASK_STAGE_BIND:
                        purchaseCheckDetailsList = purchaseCheckDetailsList.stream().filter(o ->
                                !PurchaseTaskStatusEnum.TO_NOTICE.getStatus().equals(o.getStatus()) && !PurchaseTaskStatusEnum.TO_CHECK_AFTER_REJECT.getStatus().equals(o.getStatus()) &&
                                !PurchaseTaskStatusEnum.TO_CHECK.getStatus().equals(o.getStatus()) && !PurchaseTaskStatusEnum.TO_BIND_AFTER_REJECT.getStatus().equals(o.getStatus())
                        ).collect(Collectors.toList());
                        break;
                    case PURCHASE_TASK_STAGE_STORE:
                        purchaseCheckDetailsList = purchaseCheckDetailsList.stream().filter(o ->
                                PurchaseTaskStatusEnum.IN_STORE.getStatus().equals(o.getStatus()) ||
                                PurchaseTaskStatusEnum.TO_STORE.getStatus().equals(o.getStatus()) ||
                                PurchaseTaskStatusEnum.TASK_FINISHED.getStatus().equals(o.getStatus()) ||
                                (PurchaseTaskStatusEnum.TO_BIND.getStatus().equals(o.getStatus()) && null != o.getBindNum() && 0 < o.getBindNum().compareTo(BigDecimal.ZERO)) ||
                                (PurchaseTaskStatusEnum.TO_STORE_AFTER_REJECT.getStatus().equals(o.getStatus()) && null != o.getBindNum() && 0 < o.getBindNum().compareTo(BigDecimal.ZERO))
                        ).collect(Collectors.toList());
                        break;
                    default:
                        System.err.println("未知的新购任务阶段：" + purchaseQueryDto.getTaskStage());
                }
            }
            //查询是否存在附件，给前端用于文件颜色判断
            extractedExitFile(purchaseCheckDetailsList);
            //针对于app查询可能存在的验收图片
            extractedFile(purchaseCheckDetailsList);
            purchaseCheckDtoResult.setPurchaseCheckDetailsList(purchaseCheckDetailsList);
        }
        return purchaseCheckDtoResult;
    }

    /**
     * 查询是否存在附件，给前端用于文件颜色判断
     * @param purchaseCheckDetailsList 新购验收明细列表
     */
    private void extractedExitFile(List<PurchaseCheckDetails> purchaseCheckDetailsList) {
        if (!CollectionUtils.isEmpty(purchaseCheckDetailsList)) {
            for (PurchaseCheckDetails purchaseCheckDetails : purchaseCheckDetailsList) {
                final BmFileInfo fileInfo = new BmFileInfo();
                fileInfo.setTaskType(0);
                fileInfo.setModelId(purchaseCheckDetails.getTypeId());
                fileInfo.setTaskId(purchaseCheckDetails.getTaskId());
                final List<BmFileInfo> bmFileInfoList = bmFileInfoMapper.selectBmFileInfoList(fileInfo);
                if (!CollectionUtils.isEmpty(bmFileInfoList)) {
                    purchaseCheckDetails.setIsExitFile(0);
                    purchaseCheckDetails.setBmFileInfos(bmFileInfoList);
                }else {
                    purchaseCheckDetails.setIsExitFile(1);
                }
            }
        }
    }

    /**
     * 提取app新购验收文件信息
     * @param purchaseCheckDetailsList 新购验收明细列表
     */
    private void extractedFile(List<PurchaseCheckDetails> purchaseCheckDetailsList) {
        if (!CollectionUtils.isEmpty(purchaseCheckDetailsList)) {
            for (PurchaseCheckDetails purchaseCheckDetails : purchaseCheckDetailsList) {
                final BmFileInfo fileInfo = new BmFileInfo();
                fileInfo.setTaskType(10);
                fileInfo.setModelId(purchaseCheckDetails.getId());
                fileInfo.setTaskId(purchaseCheckDetails.getTaskId());
                final List<BmFileInfo> bmFileInfoList = bmFileInfoMapper.selectBmFileInfoList(fileInfo);
                if (!CollectionUtils.isEmpty(bmFileInfoList)) {
                    purchaseCheckDetails.setBmFileInfos(bmFileInfoList);
                }
            }
        }
    }

    private int getPurchaseMaCodeCount(Long taskId, Long typeId) {
        return purchaseMacodeInfoMapper.getPurchaseMaCodeCount(taskId, typeId);
    }

    /**
     * 查询新购验收任务列表 - 性能优化版本
     *
     * @param purchaseQueryDto 新购验收任务请求参数
     * @return 新购验收任务
     */
    @Override
    public List<PurchaseCheckInfo> selectPurchaseCheckInfoList(PurchaseQueryDto purchaseQueryDto) {
        log.info("=== MaterialLeaseInfoServiceImpl.selectPurchaseCheckInfoList开始执行，purchaseQueryDto: {}", purchaseQueryDto);

        final List<PurchaseCheckInfo> purchaseCheckInfos = purchaseCheckInfoMapper.selectPurchaseCheckInfoJoinList(purchaseQueryDto);
        if (CollectionUtils.isEmpty(purchaseCheckInfos)) {
            return Collections.emptyList();
        }

        // 检查 SecurityUtils.getLoginUser() 是否为 null
        LoginUser loginUser = SecurityUtils.getLoginUser();
        if (loginUser == null) {
            log.error("当前用户未登录或登录信息丢失，无法获取用户ID");
            return Collections.emptyList();
        }

        final Long loginUserId = loginUser.getUserid();
        if (Objects.isNull(loginUserId) || Objects.isNull(purchaseQueryDto.getTaskStage())) {
            return Collections.emptyList();
        }

        // 提取所有任务ID，用于批量查询
        List<Long> taskIds = purchaseCheckInfos.stream()
                .map(PurchaseCheckInfo::getTaskId)
                .collect(Collectors.toList());

        // 批量查询所有任务的明细信息
        List<PurchaseCheckDetails> allDetails = purchaseCheckDetailsMapper.selectPurchaseCheckDetailsListByTaskIdsBatch(taskIds, loginUserId);
        Map<Long, List<PurchaseCheckDetails>> detailsMap = allDetails.stream()
                .filter(detail -> detail.getTaskId() != null)
                .collect(Collectors.groupingBy(PurchaseCheckDetails::getTaskId));

        // 批量查询任务状态信息
        List<TmTask> tmTasks = tmTaskMapper.selectTmTaskByTaskIdsBatch(taskIds);
        Map<Long, TmTask> taskMap = tmTasks.stream()
                .filter(task -> task.getTaskId() != null)
                .collect(Collectors.toMap(TmTask::getTaskId, Function.identity()));

        // 批量查询物资类型名称
        final boolean isAllowPartTransfer = bmConfigService.isBmConfigEnabledWithDefaultFalse(BmConfigItems.BOOLEAN_ALLOW_PURCHASE_PART_TRANSFER);
        List<PurchaseCheckInfo> maTypeNames;
        if (isAllowPartTransfer) {
            maTypeNames = purchaseCheckDetailsMapper.selectMaTypeNameByTaskIdsBatch(taskIds, purchaseQueryDto.getStatusList());
        } else {
            maTypeNames = purchaseCheckDetailsMapper.selectMaTypeNameByTaskIdsBatch(taskIds, Collections.emptyList());
        }
        Map<Long, String> maTypeNameMap = maTypeNames.stream()
                .filter(info -> info.getTaskId() != null)
                .collect(Collectors.toMap(PurchaseCheckInfo::getTaskId, 
                    info -> info.getPurchaseMaTypeName() != null ? info.getPurchaseMaTypeName() : ""));

        // 批量查询会签记录
        List<PurchaseSignRecord> allSignRecords = signProcessMapper.getPurchaseSignRecordByTasksBatch(taskIds);
        Map<Long, List<PurchaseSignRecord>> signRecordsMap = allSignRecords.stream()
                .filter(record -> record.getTaskId() != null)
                .collect(Collectors.groupingBy(PurchaseSignRecord::getTaskId));

        // 查询会签配置（这个查询量小，可以保持原样）
        List<SignProcessVo> signProcessVoList = signProcessMapper.getList(new SignProcessVo());

        List<PurchaseCheckInfo> purchaseCheckInfoResult = new ArrayList<>();

        for (final PurchaseCheckInfo purchaseInfo : purchaseCheckInfos) {
            Long taskId = purchaseInfo.getTaskId();
            
            // 获取采购物资明细
            List<PurchaseCheckDetails> purchaseCheckDetails = detailsMap.getOrDefault(taskId, Collections.emptyList());
            if (CollectionUtils.isEmpty(purchaseCheckDetails)) {
                continue;
            }

            // 过滤掉数量管理并且是待绑定状态或者驳回后待绑定状态的物资
            purchaseCheckDetails = purchaseCheckDetails.stream().filter(o -> 
                !(MaTypeManageTypeEnum.NUMBER_DEVICE.getTypeId().equals(o.getManageType()) &&
                    (o.getStatus().equals(PurchaseTaskStatusEnum.TO_BIND.getStatus()) || 
                     o.getStatus().equals(PurchaseTaskStatusEnum.TO_BIND_AFTER_REJECT.getStatus())))).collect(Collectors.toList());

            if (isAllowPartTransfer) {
                // 根据任务阶段过滤
                switch (purchaseQueryDto.getTaskStage()) {
                    case PURCHASE_TASK_STAGE_MANAGE:
                        // 新购管理阶段展示全部任务、不进行过滤
                        break;
                    case PURCHASE_TASK_STAGE_CHECK:
                        purchaseCheckDetails = purchaseCheckDetails.stream().filter(o -> 
                            !PurchaseTaskStatusEnum.TO_NOTICE.getStatus().equals(o.getStatus()) &&
                            !PurchaseTaskStatusEnum.TO_CHECK_AFTER_REJECT.getStatus().equals(o.getStatus())).collect(Collectors.toList());
                        break;
                    case PURCHASE_TASK_STAGE_BIND:
                        purchaseCheckDetails = purchaseCheckDetails.stream().filter(o ->
                                !PurchaseTaskStatusEnum.TO_NOTICE.getStatus().equals(o.getStatus()) &&
                                !PurchaseTaskStatusEnum.TO_CHECK_AFTER_REJECT.getStatus().equals(o.getStatus()) &&
                                !PurchaseTaskStatusEnum.TO_CHECK.getStatus().equals(o.getStatus()) &&
                                !PurchaseTaskStatusEnum.TO_BIND_AFTER_REJECT.getStatus().equals(o.getStatus())
                        ).collect(Collectors.toList());
                        break;
                    case PURCHASE_TASK_STAGE_STORE:
                        purchaseCheckDetails = purchaseCheckDetails.stream().filter(o ->
                                PurchaseTaskStatusEnum.IN_STORE.getStatus().equals(o.getStatus()) ||
                                PurchaseTaskStatusEnum.TO_STORE.getStatus().equals(o.getStatus()) ||
                                PurchaseTaskStatusEnum.TASK_FINISHED.getStatus().equals(o.getStatus()) ||
                                (PurchaseTaskStatusEnum.TO_BIND.getStatus().equals(o.getStatus()) && null != o.getBindNum() && 0 < o.getBindNum().compareTo(BigDecimal.ZERO)) ||
                                (PurchaseTaskStatusEnum.TO_STORE_AFTER_REJECT.getStatus().equals(o.getStatus()) && null != o.getBindNum() && 0 < o.getBindNum().compareTo(BigDecimal.ZERO))
                        ).collect(Collectors.toList());
                        break;
                    default:
                        System.err.println("未知的新购任务阶段：" + purchaseQueryDto.getTaskStage());
                        return Collections.emptyList();
                }
            }

            // 设置物资类型名称
            purchaseInfo.setPurchaseMaTypeName(maTypeNameMap.get(taskId));

            if (!CollectionUtils.isEmpty(purchaseCheckDetails)) {
                // 计算数量和金额
                BigDecimal purchaseMaTotalNumber = BigDecimal.ZERO;
                BigDecimal checkMaTotalNumber = BigDecimal.ZERO;
                BigDecimal bindMaTotalNumber = BigDecimal.ZERO;
                BigDecimal inputMaTotalNumber = BigDecimal.ZERO;
                BigDecimal purchaseMaTotalPrice = BigDecimal.ZERO;
                BigDecimal purchaseTaxPriceTotal = BigDecimal.ZERO;

                boolean isIncludeStage = false;
                for (final PurchaseCheckDetails detail : purchaseCheckDetails) {
                    if (null == detail.getPurchaseNum() || null == detail.getPurchasePrice()) {
                        continue;
                    }
                    if (0 > detail.getPurchaseNum().compareTo(BigDecimal.ZERO) || 0 > detail.getPurchasePrice().compareTo(BigDecimal.ZERO)) {
                        throw new IllegalArgumentException("采购数量和价格必须为非负数");
                    }
                    if (!isIncludeStage) {
                        isIncludeStage = PurchaseTaskStatusEnum.isStatusOfStage(detail.getStatus(), PurchaseTaskStageEnum.getByCode(purchaseQueryDto.getTaskStage()), detail.getManageType());
                    }

                    purchaseMaTotalNumber = purchaseMaTotalNumber.add(Optional.of(detail.getPurchaseNum()).orElse(BigDecimal.ZERO));
                    checkMaTotalNumber = checkMaTotalNumber.add(Optional.ofNullable(detail.getCheckNum()).orElse(BigDecimal.ZERO));
                    bindMaTotalNumber = bindMaTotalNumber.add(Optional.ofNullable(detail.getBindNum()).orElse(BigDecimal.ZERO));
                    inputMaTotalNumber = inputMaTotalNumber.add(Optional.ofNullable(detail.getInputNum()).orElse(BigDecimal.ZERO));
                    purchaseMaTotalPrice = purchaseMaTotalPrice.add(detail.getPurchaseNum().multiply(detail.getPurchasePrice()).setScale(10, RoundingMode.HALF_DOWN));
                    purchaseTaxPriceTotal = purchaseTaxPriceTotal.add(detail.getPurchaseNum().multiply(detail.getPurchaseTaxPrice()).setScale(10, RoundingMode.HALF_DOWN));
                }

                purchaseInfo.setPurchaseMaNumber(purchaseMaTotalNumber);
                purchaseInfo.setPurchasePrice(purchaseMaTotalPrice);
                purchaseInfo.setPurchaseTaxPrice(purchaseTaxPriceTotal);
                purchaseInfo.setBindMaNumber(bindMaTotalNumber);
                purchaseInfo.setCheckMaNumber(checkMaTotalNumber);
                purchaseInfo.setInputMaNumber(inputMaTotalNumber);
                purchaseInfo.setWaitInputNumber(purchaseMaTotalNumber.subtract(inputMaTotalNumber));

                // 设置任务状态
                final TmTask tmTask = taskMap.get(taskId);
                purchaseInfo.setTaskStatusName(isIncludeStage ? "未完成" : "已完成");
                if (null != purchaseQueryDto.getIsFinish()) {
                    if (1 == purchaseQueryDto.getIsFinish()) {
                        if (isIncludeStage) {continue;}
                    } else {
                        if (!isIncludeStage) {continue;}
                    }
                }

                // 设置采购状态
                List<Integer> statusList = purchaseCheckDetails.stream()
                        .map(PurchaseCheckDetails::getStatus)
                        .collect(Collectors.toList());
                
                if (!CollectionUtils.isEmpty(statusList)) {
                    if (statusList.contains(PurchaseTaskStatusEnum.TO_BIND.getStatus()) ||
                        statusList.contains(PurchaseTaskStatusEnum.TO_STORE.getStatus()) ||
                        statusList.contains(PurchaseTaskStatusEnum.TO_BIND_AFTER_REJECT.getStatus()) ||
                        statusList.contains(PurchaseTaskStatusEnum.TO_STORE_AFTER_REJECT.getStatus())) {
                        purchaseInfo.setPurchaseStatus(PurchaseTaskStatusEnum.TO_BIND.getStatus());
                    } else if (statusList.contains(PurchaseTaskStatusEnum.IN_STORE.getStatus()) ||
                               statusList.contains(PurchaseTaskStatusEnum.TASK_IN_PROGRESS.getStatus()) ||
                               statusList.contains(PurchaseTaskStatusEnum.TASK_FINISHED.getStatus())) {
                        purchaseInfo.setPurchaseStatus(PurchaseTaskStatusEnum.IN_STORE.getStatus());
                    } else {
                        purchaseInfo.setPurchaseStatus(0);
                    }
                }
                
                if (tmTask != null) {
                    purchaseInfo.setTaskStatus(tmTask.getTaskStatus());
                }

                // 检查是否应该加入结果列表
                if (isAllowPartTransfer) {
                    purchaseCheckInfoResult.add(purchaseInfo);
                } else {
                    final OptionalInt minStatus = purchaseCheckDetails.stream().mapToInt(PurchaseCheckDetails::getStatus).min();
                    if (minStatus.isPresent() && purchaseQueryDto.getStatusList().contains(minStatus.getAsInt())) {
                        purchaseCheckInfoResult.add(purchaseInfo);
                    }
                }
            }
        }

        if (!CollectionUtils.isEmpty(purchaseCheckInfoResult)) {
            // 设置会签级别
            for (PurchaseCheckInfo purchaseCheckInfo : purchaseCheckInfoResult) {
                List<PurchaseSignRecord> purchaseSignRecordList = signRecordsMap.getOrDefault(purchaseCheckInfo.getTaskId(), Collections.emptyList());
                
                if (!CollectionUtils.isEmpty(purchaseSignRecordList) && !CollectionUtils.isEmpty(signProcessVoList)) {
                    Set<Long> configSignOrgSet = signProcessVoList.stream().map(SignProcessVo::getOrgId).collect(Collectors.toSet());
                    Set<Long> signedOrgSet = purchaseSignRecordList.stream().map(PurchaseSignRecord::getOrgId).collect(Collectors.toSet());
                    configSignOrgSet.removeAll(signedOrgSet);
                    
                    if (signedOrgSet.size() == 1) {
                        purchaseCheckInfo.setSignLevel("2");
                    } else {
                        // 获取purchaseSignRecordList中是否存在auditStatus为2，即被驳回的数据
                        boolean isRejected = purchaseSignRecordList.stream().anyMatch(item -> "2".equals(item.getAuditStatus()));
                        if (!isRejected) {
                            purchaseCheckInfo.setSignLevel("3");
                        }
                    }
                }
            }

            // 关键字过滤
            String keyWord = purchaseQueryDto.getKeyWord();
            if (!StringUtils.isBlank(keyWord)) {
                purchaseCheckInfoResult = purchaseCheckInfoResult.stream()
                        .filter(item -> containsKeyword(item, keyWord))
                        .collect(Collectors.toList());
            }
        }
        
        return purchaseCheckInfoResult;
    }

    /**
     * 查询新购验收任务列表 - 原始版本（保留作为备份）
     *
     * @param purchaseQueryDto 新购验收任务请求参数
     * @return 新购验收任务
     */
    public List<PurchaseCheckInfo> selectPurchaseCheckInfoListOriginal(PurchaseQueryDto purchaseQueryDto) {
        log.info("=== MaterialLeaseInfoServiceImpl.selectPurchaseCheckInfoList开始执行，purchaseQueryDto: {}", purchaseQueryDto);

        final List<PurchaseCheckInfo> purchaseCheckInfos = purchaseCheckInfoMapper.selectPurchaseCheckInfoJoinList(purchaseQueryDto);
        if (CollectionUtils.isEmpty(purchaseCheckInfos)) {
            return Collections.emptyList();
        }

        // 检查 SecurityUtils.getLoginUser() 是否为 null
        LoginUser loginUser = SecurityUtils.getLoginUser();
        if (loginUser == null) {
            log.error("当前用户未登录或登录信息丢失，无法获取用户ID");
            return Collections.emptyList();
        }

        final AtomicReference<Long> loginUserId = new AtomicReference<>(loginUser.getUserid());
        if (Objects.isNull(loginUserId.get()) || Objects.isNull(purchaseQueryDto.getTaskStage())) {
            return Collections.emptyList();
        }

        List<PurchaseCheckInfo> purchaseCheckInfoResult = new ArrayList<>();
        final boolean isAllowPartTransfer = bmConfigService.isBmConfigEnabledWithDefaultFalse(BmConfigItems.BOOLEAN_ALLOW_PURCHASE_PART_TRANSFER);

        for (final PurchaseCheckInfo purchaseInfo : purchaseCheckInfos) {
            // 获取采购物资明细、2024-12-23日修改by阮世耀 根据当前库管员绑定物资来查询 不展示非本角色管理的物资类型
            List<PurchaseCheckDetails> purchaseCheckDetails = purchaseCheckDetailsMapper.selectPurchaseCheckDetailsListByTaskId(purchaseInfo.getTaskId(), null, loginUserId.get());
            if (CollectionUtils.isEmpty(purchaseCheckDetails)) {continue;}

            // 过滤掉数量管理并且是待绑定状态或者驳回后待绑定状态的物资
            purchaseCheckDetails = purchaseCheckDetails.stream().filter(o -> !(MaTypeManageTypeEnum.NUMBER_DEVICE.getTypeId().equals(o.getManageType()) &&
                    (o.getStatus().equals(PurchaseTaskStatusEnum.TO_BIND.getStatus()) || o.getStatus().equals(PurchaseTaskStatusEnum.TO_BIND_AFTER_REJECT.getStatus())))).collect(Collectors.toList());

            final OptionalInt minStatus = purchaseCheckDetails.stream().mapToInt(PurchaseCheckDetails::getStatus).min();

            if (isAllowPartTransfer) {
                // 2024-12-23日  取消状态过滤，修改由任务阶段来过滤  --- by 阮世耀
                switch (purchaseQueryDto.getTaskStage()) {
                    case PURCHASE_TASK_STAGE_MANAGE:
                        // 新购管理阶段展示全部任务、不进行过滤
                        break;
                    case PURCHASE_TASK_STAGE_CHECK:
                        purchaseCheckDetails = purchaseCheckDetails.stream().filter(o -> !PurchaseTaskStatusEnum.TO_NOTICE.getStatus().equals(o.getStatus())).collect(Collectors.toList());
                        purchaseCheckDetails = purchaseCheckDetails.stream().filter(o -> !PurchaseTaskStatusEnum.TO_CHECK_AFTER_REJECT.getStatus().equals(o.getStatus())).collect(Collectors.toList());
                        break;
                    case PURCHASE_TASK_STAGE_BIND:
                        purchaseCheckDetails = purchaseCheckDetails.stream().filter(o ->
                                !PurchaseTaskStatusEnum.TO_NOTICE.getStatus().equals(o.getStatus()) &&
                                !PurchaseTaskStatusEnum.TO_CHECK_AFTER_REJECT.getStatus().equals(o.getStatus()) &&
                                !PurchaseTaskStatusEnum.TO_CHECK.getStatus().equals(o.getStatus()) &&
                                !PurchaseTaskStatusEnum.TO_BIND_AFTER_REJECT.getStatus().equals(o.getStatus())
                        ).collect(Collectors.toList());
                        break;
                    case PURCHASE_TASK_STAGE_STORE:
                        purchaseCheckDetails = purchaseCheckDetails.stream().filter(o ->
                                PurchaseTaskStatusEnum.IN_STORE.getStatus().equals(o.getStatus()) ||
                                PurchaseTaskStatusEnum.TO_STORE.getStatus().equals(o.getStatus()) ||
                                PurchaseTaskStatusEnum.TASK_FINISHED.getStatus().equals(o.getStatus()) ||
                                (PurchaseTaskStatusEnum.TO_BIND.getStatus().equals(o.getStatus()) && null != o.getBindNum() && 0 < o.getBindNum().compareTo(BigDecimal.ZERO)) ||
                                (PurchaseTaskStatusEnum.TO_STORE_AFTER_REJECT.getStatus().equals(o.getStatus()) && null != o.getBindNum() && 0 < o.getBindNum().compareTo(BigDecimal.ZERO))
                        ).collect(Collectors.toList());
                        break;
                    default:
                        System.err.println("未知的新购任务阶段：" + purchaseQueryDto.getTaskStage());
                        return Collections.emptyList();
                }
                purchaseInfo.setPurchaseMaTypeName(purchaseCheckDetailsMapper.selectMaTypeNameByTaskAndStatusList(purchaseInfo.getTaskId(), purchaseQueryDto.getStatusList()));
            } else {
                purchaseInfo.setPurchaseMaTypeName(purchaseCheckDetailsMapper.selectMaTypeNameByTaskAndStatusList(purchaseInfo.getTaskId(), new ArrayList<>()));
            }
            if (!CollectionUtils.isEmpty(purchaseCheckDetails)) {
                BigDecimal purchaseMaTotalNumber = BigDecimal.ZERO, checkMaTotalNumber = BigDecimal.ZERO, bindMaTotalNumber = BigDecimal.ZERO, inputMaTotalNumber = BigDecimal.ZERO;
                final AtomicReference<BigDecimal> purchaseMaTotalPrice = new AtomicReference<>(BigDecimal.ZERO);
                final AtomicReference<BigDecimal> purchaseTaxPriceTotal = new AtomicReference<>(BigDecimal.ZERO);

                boolean isIncludeStage = false;
                for (final PurchaseCheckDetails detail : purchaseCheckDetails) {
                    if (null == detail.getPurchaseNum() || null == detail.getPurchasePrice()) {continue;}
                    if (0 > detail.getPurchaseNum().compareTo(BigDecimal.ZERO) || 0 > detail.getPurchasePrice().compareTo(BigDecimal.ZERO)) {
                        throw new IllegalArgumentException("采购数量和价格必须为非负数");
                    }
                    if (!isIncludeStage) {
                        isIncludeStage = PurchaseTaskStatusEnum.isStatusOfStage(detail.getStatus(), PurchaseTaskStageEnum.getByCode(purchaseQueryDto.getTaskStage()), detail.getManageType());
                    }

                    // 更新 purchaseMaTotalNumber
                    purchaseMaTotalNumber = purchaseMaTotalNumber.add(Optional.of(detail.getPurchaseNum()).orElse(BigDecimal.ZERO));
                    checkMaTotalNumber = checkMaTotalNumber.add(Optional.ofNullable(detail.getCheckNum()).orElse(BigDecimal.ZERO));
                    bindMaTotalNumber = bindMaTotalNumber.add(Optional.ofNullable(detail.getBindNum()).orElse(BigDecimal.ZERO));
                    inputMaTotalNumber = inputMaTotalNumber.add(Optional.ofNullable(detail.getInputNum()).orElse(BigDecimal.ZERO));
                    purchaseMaTotalPrice.updateAndGet(v -> v.add(detail.getPurchaseNum().multiply(detail.getPurchasePrice()).setScale(10, RoundingMode.HALF_DOWN)));
                    purchaseTaxPriceTotal.updateAndGet(v -> v.add(detail.getPurchaseNum().multiply(detail.getPurchaseTaxPrice()).setScale(10, RoundingMode.HALF_DOWN)));
                }
                purchaseInfo.setPurchaseMaNumber(purchaseMaTotalNumber);
                purchaseInfo.setPurchasePrice(purchaseMaTotalPrice.get());
                purchaseInfo.setPurchaseTaxPrice(purchaseTaxPriceTotal.get());
                purchaseInfo.setBindMaNumber(bindMaTotalNumber);
                purchaseInfo.setCheckMaNumber(checkMaTotalNumber);
                purchaseInfo.setInputMaNumber(inputMaTotalNumber);
                purchaseInfo.setWaitInputNumber(Optional.of(purchaseMaTotalNumber).orElse(BigDecimal.ZERO).subtract(Optional.of(inputMaTotalNumber).orElse(BigDecimal.ZERO)));

                // 设置外层任务状态：入库待开始、入库进行中、入库已完成
                final TmTask tmTask = tmTaskMapper.selectTmTaskByTaskId(purchaseInfo.getTaskId());
                purchaseInfo.setTaskStatusName(isIncludeStage ? "未完成" : "已完成");
                if (null != purchaseQueryDto.getIsFinish()) {
                    if (1 == purchaseQueryDto.getIsFinish()) {
                        if (isIncludeStage) {continue;}
                    } else {
                        if (!isIncludeStage) {continue;}
                    }
                }
                // 判断purchaseCheckDetails集合里面status状态，对purchaseStatus进行赋值，用于前端展示验收单和入库单
                if (!CollectionUtils.isEmpty(purchaseCheckDetails)) {
                    // 将purchaseCheckDetails中的status取出来
                    List<Integer> statusList = purchaseCheckDetails.stream().map(PurchaseCheckDetails::getStatus).collect(Collectors.toList());
                    if (!CollectionUtils.isEmpty(statusList)) {
                        if (statusList.contains(PurchaseTaskStatusEnum.TO_BIND.getStatus())
                                || statusList.contains(PurchaseTaskStatusEnum.TO_STORE.getStatus())
                        || statusList.contains(PurchaseTaskStatusEnum.TO_BIND_AFTER_REJECT.getStatus())
                        || statusList.contains(PurchaseTaskStatusEnum.TO_STORE_AFTER_REJECT.getStatus())) {
                            purchaseInfo.setPurchaseStatus(PurchaseTaskStatusEnum.TO_BIND.getStatus());
                        } else if (statusList.contains(PurchaseTaskStatusEnum.IN_STORE.getStatus())
                        || statusList.contains(PurchaseTaskStatusEnum.TASK_IN_PROGRESS.getStatus())
                        ||  statusList.contains(PurchaseTaskStatusEnum.TASK_FINISHED.getStatus())) {
                            purchaseInfo.setPurchaseStatus(PurchaseTaskStatusEnum.IN_STORE.getStatus());
                        } else {
                            purchaseInfo.setPurchaseStatus(0);
                        }
                    }
                }
                purchaseInfo.setTaskStatus(tmTask.getTaskStatus());

                // 设置外层任务列表
                if (isAllowPartTransfer) {
                    purchaseCheckInfoResult.add(purchaseInfo);
                } else if (minStatus.isPresent() && purchaseQueryDto.getStatusList().contains(minStatus.getAsInt())) {
                    // 当不允许部分物资状态流转时，例如内部状态含(2,12,3,13)，其中最小的状态值(2),当等于传入的状态值(2,12)时，才显示外面的列表
                    purchaseCheckInfoResult.add(purchaseInfo);
                }

            }
        }
        if (!CollectionUtils.isEmpty(purchaseCheckInfoResult)) {
            // 根据taskId查询验收任务层级，返回前端，用于验收按钮显示
            for (PurchaseCheckInfo purchaseCheckInfo : purchaseCheckInfoResult) {
                // 查询已进行会签的org_id集合
                List<PurchaseSignRecord> purchaseSignRecordList = signProcessMapper.getPurchaseSignRecordByTask(purchaseCheckInfo.getTaskId());
                // 查询需要进行会签的org_id集合
                List<SignProcessVo> signProcessVoList = signProcessMapper.getList(new SignProcessVo());
                if (!CollectionUtils.isEmpty(purchaseSignRecordList) && !CollectionUtils.isEmpty(signProcessVoList)) {
                    // 查询出配置需要会签的org_id集合
                    Set<Long> configSignOrgSet = signProcessVoList.stream().map(SignProcessVo::getOrgId).collect(Collectors.toSet());
                    // 获取已进行会签的org_id集合
                    Set<Long> signedOrgSet = purchaseSignRecordList.stream().map(PurchaseSignRecord::getOrgId).collect(Collectors.toSet());
                    // 移除已会签的org_id
                    configSignOrgSet.removeAll(signedOrgSet);
                    if (signedOrgSet.size() == 1) {
                        purchaseCheckInfo.setSignLevel("2");
                    } else {
                        purchaseCheckInfo.setSignLevel("3");
                    }
                }
            }
            String keyWord = purchaseQueryDto.getKeyWord();
            // 如果关键字不为空，进行过滤
            if (!StringUtils.isBlank(keyWord)) {
                purchaseCheckInfoResult = purchaseCheckInfoResult.stream()
                        .filter(item -> containsKeyword(item, keyWord))
                        .collect(Collectors.toList());
            }
        }
        return purchaseCheckInfoResult;
    }

    /**
     * 关键字搜索
     * @param item
     * @param keyWord
     * @return
     */
    private boolean containsKeyword(PurchaseCheckInfo item, String keyWord) {
        return (item.getPurchaseMaTypeName() != null && item.getPurchaseMaTypeName().contains(keyWord)) ||
                (item.getCode() != null && item.getCode().contains(keyWord)) ||
                (item.getSupplier() != null && item.getSupplier().contains(keyWord)) ||
                (item.getCreateBy() != null && item.getCreateBy().contains(keyWord));
    }

    /**
     * 查询新购验收任务详细列表
     *
     * @param purchaseCheckInfo 新购验收任务详细
     * @return 新购验收任务详细
     */
    @Override
    public List<PurchaseCheckDetails> selectPurchaseCheckDetailsList(PurchaseCheckInfo purchaseCheckInfo) {
        return purchaseCheckDetailsMapper.selectPurchaseCheckDetailsListFromInfo(purchaseCheckInfo);
    }

    /**
     * 含税价格计算
     * @param purchaseNoTaxPrice 不含税价格
     * @param taxRate 税率：0~100  例如13%税率 值应该是整形:13
     * @return 不含税价格100 税率为13%，结果为 113.00
     */
    public static BigDecimal calculateTaxPrice(BigDecimal purchaseNoTaxPrice, BigDecimal taxRate) {
        if (null == taxRate || 0 > taxRate.compareTo(BigDecimal.ZERO) || 0 < taxRate.compareTo(BigDecimal.valueOf(100))) {
            throw new IllegalArgumentException("税率必须在0到100之间");
        }
        // 计算税率
        final BigDecimal rate = taxRate.divide(BigDecimal.valueOf(100), 3, RoundingMode.HALF_UP);
        // 税后价格计算
        final BigDecimal taxIncludedPrice = purchaseNoTaxPrice.multiply(BigDecimal.ONE.add(rate));
        // 保留10位小数
        return taxIncludedPrice.setScale(10, RoundingMode.HALF_UP);
    }

    /**
     * 新增新购验收任务
     *
     * @param purchaseCheckInfo 新购验收任务
     * @return 结果
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public AjaxResult insertPurchaseCheckInfo(PurchaseCheckDto purchaseCheckInfo) {
        purchaseCheckInfo.getPurchaseCheckInfo().setCreateTime(DateUtils.getNowDate());
        purchaseCheckInfo.getPurchaseCheckInfo().setPurchaseTime(DateUtils.getNowDate());
        purchaseCheckInfo.getPurchaseCheckInfo().setCreateBy(SecurityUtils.getLoginUser().getSysUser().getNickName());
        try {
            final int thisMonthMaxOrder = tmTaskMapper.getMonthMaxOrderByDate(DateUtils.getCurrentYear(), DateUtils.getCurrentMonth(), TmTaskTypeEnum.TM_TASK_PURCHASE.getTaskTypeId());
            String taskCode = genderTaskCode(thisMonthMaxOrder);
            final TmTask tmTask = new TmTask(null, TmTaskTypeEnum.TM_TASK_PURCHASE.getTaskTypeId(),
                    PurchaseTaskStatusEnum.TO_NOTICE.getStatus(),
                    purchaseCheckInfo.getPurchaseCheckInfo().getCompanyId(), thisMonthMaxOrder + 1, taskCode);
            tmTask.setCreateTime(DateUtils.getNowDate());
            tmTaskMapper.insertTmTask(tmTask);
            Long taskId = tmTask.getTaskId();
            purchaseCheckInfo.getPurchaseCheckInfo().setTaskId(taskId);
            final int count = purchaseCheckInfoMapper.insertPurchaseCheckInfo(purchaseCheckInfo.getPurchaseCheckInfo());
            if (0 < count) {
                return insertPurchaseCheckDetails(purchaseCheckInfo.getPurchaseCheckDetailsList(), taskId);
            } else {
                return AjaxResult.error("新增任务失败,新购任务信息表插入0条");
            }
        } catch (final DataAccessException dae) {
            throw new ServiceException("数据库错误:" + dae.getMessage());
        } catch (final Exception e) {
            throw new ServiceException("新增任务失败:" + e.getMessage());
        }
    }

    /**
     * 插入新购验收任务详情
     * @param purchaseCheckDetailsList 新购验收物资明细
     * @param taskId 任务id
     * @return 结果
     */
    private AjaxResult insertPurchaseCheckDetails(List<PurchaseCheckDetails> purchaseCheckDetailsList, Long taskId) {
        if (!CollectionUtils.isEmpty(purchaseCheckDetailsList)) {
            for (PurchaseCheckDetails details : purchaseCheckDetailsList) {
                details.setTaskId(taskId);
                details.setStatus(Objects.equals(PurchaseTaskStatusEnum.TO_CHECK_AFTER_REJECT.getStatus(), details.getStatus()) ?
                        PurchaseTaskStatusEnum.TO_CHECK.getStatus() :
                        PurchaseTaskStatusEnum.TO_NOTICE.getStatus());
                details.setInputStatus("0");
                final List<BmFileInfo> bmFileInfos = details.getBmFileInfos();
                if (!CollectionUtils.isEmpty(bmFileInfos)) {
                    bmFileInfos.forEach(o -> {
                        o.setTaskId(taskId);
                        o.setModelId(details.getTypeId());
                        o.setCreateBy(SecurityUtils.getLoginUser().getUserid().toString());
                        o.setCreateTime(DateUtils.getNowDate());
                    });
                    bmFileInfoMapper.insertBmFileInfos(bmFileInfos);
                }
                Type type = new Type();
                type.setTypeId(details.getTypeId());
                type.setUpdateTime(DateUtils.getNowDate());
                type.setUpdateBy(SecurityUtils.getLoginUser().getUserid().toString());
                type.setBuyPrice(details.getPurchaseTaxPrice());
                type.setNotTaxPrice(details.getPurchasePrice());
                Type maType = typeMapper.getMaType(details.getTypeId());
                if (maType != null && (maType.getRentPrice() == null || maType.getRentPrice().compareTo(BigDecimal.ZERO) == 0)) {
                    type.setRentPrice(details.getRentPrice());
                }
                typeMapper.updateType(type);
            }
            // 批量插入详情数据
            final int count = purchaseCheckDetailsMapper.insertPurchaseCheckDetailsList(purchaseCheckDetailsList);
            if (0 < count) {
                return AjaxResult.success("新增任务成功");
            } else {
                return AjaxResult.error("新增任务失败,purchase_check_detail详情表插入0条");
            }
        } else {
            return AjaxResult.success("新增任务成功");
        }
    }

    @Override
    @Transactional
    public AjaxResult outVerify(PurchaseVerifyVo purchaseVerifyVo) {
        try {
            purchaseVerifyVo.getTaskIds().removeIf(Objects::isNull);
            int updateCount = 0;
            for (Long taskId : purchaseVerifyVo.getTaskIds()) {
                PurchaseQueryDto purchaseQueryDto = new PurchaseQueryDto();
                purchaseQueryDto.setTaskId(taskId);
                List<PurchaseCheckDetails> purchaseCheckDetails = purchaseCheckDetailsMapper.selectPurchaseCheckDetailsListByQueryDto(purchaseQueryDto);
                List<PurchaseCheckDetails> codeList = purchaseCheckDetails.stream().filter(o -> MaTypeManageTypeEnum.CODE_DEVICE.getTypeId().equals(o.getManageType())).collect(Collectors.toList());
                List<PurchaseCheckDetails> numList = purchaseCheckDetails.stream().filter(o -> MaTypeManageTypeEnum.NUMBER_DEVICE.getTypeId().equals(o.getManageType())).collect(Collectors.toList());
                if (!CollectionUtils.isEmpty(codeList)) {
                    for (PurchaseCheckDetails details : codeList) {
                        details.setStatus(PurchaseTaskStatusEnum.TO_BIND.getStatus());
                        details.setCheckUser(SecurityUtils.getLoginUser().getUserid());
                        updateCount += purchaseCheckDetailsMapper.updatePurchaseDetails4Check(details);
                    }

                }
                if (!CollectionUtils.isEmpty(numList)) {
                    for (PurchaseCheckDetails details : numList) {
                        details.setStatus(PurchaseTaskStatusEnum.TO_STORE.getStatus());
                        details.setCheckUser(SecurityUtils.getLoginUser().getUserid());
                        updateCount += purchaseCheckDetailsMapper.updatePurchaseDetails4Check(details);
                    }
                }
            }
            return 0 < updateCount ? AjaxResult.success("验证成功") : AjaxResult.error("无验证信息");
        } catch (final Exception e) {
            return AjaxResult.error("验收状态更改失败,异常报错:" + e.getMessage());
        }
    }

    @Override
    @Transactional
    public AjaxResult innerVerify(PurchaseVerifyVo purchaseVerifyVo) {
        try {
            AjaxResult result = new AjaxResult();
            if (!CollectionUtils.isEmpty(purchaseVerifyVo.getPurchaseCheckDetailsList())) {
                Long loginUserDeptId = SecurityUtils.getLoginUser().getSysUser().getDeptId();
                if (BooleanUtils.isTrue(purchaseVerifyVo.getVerifyPass())) {
                    // 验收通过处理流程
                    for (PurchaseCheckDetails details : purchaseVerifyVo.getPurchaseCheckDetailsList()) {
                        // 前端选择验收通过操作，进入会签校验流程
                        if (null != details && null != details.getTaskId()) {
                            // 查询已进行会签的org_id集合
                            List<PurchaseSignRecord> purchaseSignRecordList = signProcessMapper.getPurchaseSignRecordByTask(details.getTaskId());
                            if (null == loginUserDeptId || 0 == loginUserDeptId) {
                                return AjaxResult.error("会签失败!，请检查用户部门信息");
                            }
                            if (CollectionUtils.isEmpty(purchaseSignRecordList)) {
                                // 如果该任务没有进行过会签，则无需校验 直接进行会签流程
                                int addPurchaseSignResult = signProcessMapper.insertPurchaseSignRecord(new PurchaseSignRecord(details.getTaskId(), SecurityUtils.getLoginUser().getUserid(), loginUserDeptId, details.getCheckResult()));
                                if (0 < addPurchaseSignResult) {
                                    return AjaxResult.success("会签成功");
                                } else {
                                    return AjaxResult.error("会签失败!，插入0条数据");
                                }
                            } else {

                                // 查询需要进行会签的org_id集合
                                List<SignProcessVo> signProcessVoList = signProcessMapper.getList(new SignProcessVo());
                                if (CollectionUtils.isEmpty(signProcessVoList)) {
                                    return AjaxResult.error("会签失败!，未查询到会签配置流程!");
                                } else {
                                    // 查询出配置需要会签的org_id集合
                                    Set<Long> configSignOrgSet = signProcessVoList.stream().map(SignProcessVo::getOrgId).collect(Collectors.toSet());
                                    // 获取已进行会签的org_id集合
                                    Set<Long> signedOrgSet = purchaseSignRecordList.stream().map(PurchaseSignRecord::getOrgId).collect(Collectors.toSet());
                                    // 移除已会签的org_id
                                    configSignOrgSet.removeAll(signedOrgSet);
                                    if (!CollectionUtils.isEmpty(configSignOrgSet)) {
                                        // 如果还有需要进行会签的数据，那么进行本次会签
                                        PurchaseSignRecord purchaseSignRecord = new PurchaseSignRecord();
                                        purchaseSignRecord.setTaskId(details.getTaskId());
                                        purchaseSignRecord.setUserId(SecurityUtils.getLoginUser().getUserid());
                                        purchaseSignRecord.setOrgId(loginUserDeptId);
                                        // 审核通过
                                        purchaseSignRecord.setAuditStatus("1");
                                        purchaseSignRecord.setCreateTime(DateUtils.getNowDate());
                                        purchaseSignRecord.setAuditRemark(details.getCheckResult());
                                        int addPurchaseSignResult = signProcessMapper.insertPurchaseSignRecord(purchaseSignRecord);
                                        if (0 < addPurchaseSignResult) {
                                            // 会签成功，对配置的流程进行处理
                                            configSignOrgSet.remove(loginUserDeptId);
                                            // 如果loginUserDeptId包含库管一班、库管二班或者库管三班的任意一个组织id，那么库管班就算审核通过
                                            if (loginUserDeptId == 106L || loginUserDeptId == 334L || loginUserDeptId == 335L) {
                                                // 库管班审核通过，放行进行验收流程
                                                System.out.println("ONE会签成功,放行进行验收流程!");
                                            } else {
                                                // 如果本次会签完成后还有需要进行会签的，那么本次会签完成，返回前端
                                                return AjaxResult.success("会签成功!");
                                            }
                                        } else {
                                            return AjaxResult.error("会签失败!，插入0条数据");
                                        }
                                    } else {
                                        System.out.println("TWO会签成功,已全部进行会签,放行进行验收流程!");
                                    }
                                }
                            }

                        } else {
                            return AjaxResult.error("detail数据异常,任务ID为空");
                        }


                        if (MaTypeManageTypeEnum.CODE_DEVICE.getTypeId().equals(details.getManageType())) {
                            details.setStatus(PurchaseTaskStatusEnum.TO_BIND.getStatus());
                        } else if (MaTypeManageTypeEnum.NUMBER_DEVICE.getTypeId().equals(details.getManageType())) {
                            details.setStatus(PurchaseTaskStatusEnum.TO_STORE.getStatus());
                        }
                        details.setCheckUser(SecurityUtils.getLoginUser().getUserid());
                        result = 0 < purchaseCheckDetailsMapper.updatePurchaseDetails4Check(details) ? AjaxResult.success("验收成功") : AjaxResult.error("details无验证信息");
                        extractedFile(details);
                    }
                } else {
                    if (!CollectionUtils.isEmpty(purchaseVerifyVo.getPurchaseCheckDetailsList())) {
                        // 验收驳回处理流程
                        for (PurchaseCheckDetails details : purchaseVerifyVo.getPurchaseCheckDetailsList()) {
                            details.setStatus(PurchaseTaskStatusEnum.TO_CHECK_AFTER_REJECT.getStatus());
                            int res = purchaseCheckDetailsMapper.updatePurchaseDetails4Check(details);
                            if (res < 1) {
                                return AjaxResult.error("验收驳回失败,请联系管理员");
                            }
                            extractedFile(details);
                        }
                        PurchaseCheckDetails purchaseCheckDetails = purchaseVerifyVo.getPurchaseCheckDetailsList().get(0);
                        PurchaseSignRecord purchaseSignRecord = new PurchaseSignRecord();
                        purchaseSignRecord.setTaskId(purchaseCheckDetails.getTaskId());
                        purchaseSignRecord.setUserId(SecurityUtils.getLoginUser().getUserid());
                        purchaseSignRecord.setOrgId(loginUserDeptId);
                        // 审核驳回
                        purchaseSignRecord.setAuditStatus("2");
                        purchaseSignRecord.setCreateTime(DateUtils.getNowDate());
                        purchaseSignRecord.setAuditRemark(purchaseCheckDetails.getCheckResult());
                        int addPurchaseSignResult = signProcessMapper.insertPurchaseSignRecord(purchaseSignRecord);
                        if (addPurchaseSignResult < 1) {
                            return AjaxResult.error("会签失败，purchase_audit_record表插入0条数据");
                        } else {
                            return AjaxResult.success("验收驳回成功");
                        }
                    }
                }
            }
            return result;
        } catch (final Exception e) {
            return AjaxResult.error("验收状态更改失败,异常报错:" + e.getMessage());
        }
    }

    /**
     * app新购验收图片上传方法抽取
     * @param details 详情
     */
    private void extractedFile(PurchaseCheckDetails details) {
        if (!CollectionUtils.isEmpty(details.getBmFileInfos())) {
            for (final BmFileInfo bmFileInfo : details.getBmFileInfos()) {
                if (null != bmFileInfo.getTaskType() && Objects.equals(TmTaskTypeEnum.TM_TASK_AGREEMENT_MANAGEMENT.getTaskTypeId(), bmFileInfo.getTaskType())) {
                    bmFileInfo.setTaskId(details.getTaskId());
                    bmFileInfo.setModelId(details.getId());
                    bmFileInfo.setCreateBy(SecurityUtils.getLoginUser().getSysUser().getNickName());
                    bmFileInfo.setCreateTime(DateUtils.getNowDate());
                    bmFileInfoMapper.insertBmFileInfo(bmFileInfo);
                }
            }
        }
    }

    /**
     * 根据任务id查询验收单
     *
     * @param taskId 任务id
     */
    @Override
    public PurchaseCheckFormVo selectPurchaseCheckFormVoByTaskId(Long taskId) {
        // 执行SQL查询外层信息
        final PurchaseCheckFormVo result = purchaseCheckInfoMapper.selectPurchaseCheckFormVoByTaskId(taskId);
        if (null != result) {
            PurchaseCheckInfo purchaseCheckInfo = new PurchaseCheckInfo();
            purchaseCheckInfo.setTaskId(taskId);
            List<PurchaseCheckDetails> list = purchaseCheckDetailsMapper.selectPurchaseCheckDetailsListFromInfo(purchaseCheckInfo);
            if (!CollectionUtils.isEmpty(list)) {
                List<PurchaseSignRecord> purchaseSignRecordUserSignList = new ArrayList<>();
                HashMap<String, PurchaseSignRecord> purchaseSignRecordMap = new HashMap<>();
                for (PurchaseCheckDetails purchaseCheckDetails : list) {
                    // 查询已签名的记录
                    if (purchaseSignRecordUserSignList.isEmpty()) {
                        purchaseSignRecordUserSignList  = signProcessMapper.getPurchaseSignUrlListByTaskId(purchaseCheckDetails.getTaskId());
                        for (PurchaseSignRecord purchaseSignRecord : purchaseSignRecordUserSignList) {
                            if (StringUtils.isNotBlank(purchaseSignRecord.getSignUrl())) {
                                if (!purchaseSignRecord.getSignUrl().startsWith("http")) {
                                    purchaseSignRecord.setSignUrl("data:image/png;base64," + purchaseSignRecord.getSignUrl());
                                }
                            }
                            purchaseSignRecordMap.put(purchaseSignRecord.getSignUrl(), purchaseSignRecord);
                        }
                    }
                    result.setSignUrl(null != purchaseCheckDetails.getSignUrl() ? purchaseCheckDetails.getSignUrl() : "");
                    result.setSignType(null != purchaseCheckDetails.getSignType() ? purchaseCheckDetails.getSignType() : "");
                }
                // 分流存入集合,利用Map去重
                purchaseSignRecordMap.forEach((k, v) -> {
                    if (null != v.getUserId()) {
                        if (v.getOrgId() == 105) {result.getGySignUrl().add(v);}
                        if (v.getOrgId() == 103) {result.getScSignUrl().add(v);}
                        if (v.getOrgId() == 106 || v.getOrgId() == 334 || v.getOrgId() == 335) {result.getKgSignUrl().add(v);}
                    }
                });
            }
            // 执行SQL查询内层信息
            List<PurchaseCheckDetails> purchaseCheckDetails = purchaseCheckDetailsMapper.selectPurchaseCheckDetailsListByTaskId(taskId, null, SecurityUtils.getLoginUser().getUserid());
            // 过滤掉空数据
            purchaseCheckDetails.removeIf(Objects::isNull);
            if (!CollectionUtils.isEmpty(purchaseCheckDetails)) {
                for (PurchaseCheckDetails purchaseCheckDetail : purchaseCheckDetails) {
                    BmFileInfo fileInfo = new BmFileInfo();
                    fileInfo.setTaskId(taskId);
                    fileInfo.setModelId(purchaseCheckDetail.getTypeId());
                    fileInfo.setTaskType(0);
                    List<BmFileInfo> bmFileInfos = bmFileInfoMapper.selectBmFileInfoList(fileInfo);
                    if (!CollectionUtils.isEmpty(bmFileInfos)) {
                        purchaseCheckDetail.setFileReceiveNum(bmFileInfos.size());
                    } else {
                        purchaseCheckDetail.setFileReceiveNum(0);
                    }
                }
            }
            result.setMaterialList(purchaseCheckDetails);
            return result;
        } else {
            return new PurchaseCheckFormVo();
        }
    }

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

    /**
     * 修改新购验收任务
     *
     * @param purchaseCheckDto 新购验收任务
     * @return 结果
     */
    @Override
    @Transactional
    public boolean updatePurchaseCheckInfo(PurchaseCheckDto purchaseCheckDto) {
        purchaseCheckDto.getPurchaseCheckInfo().setUpdateTime(DateUtils.getNowDate());
        purchaseCheckDto.getPurchaseCheckInfo().setUpdateBy(SecurityUtils.getLoginUser().getSysUser().getNickName());
        // 先去查是否存在文件信息，存在就删除
        BmFileInfo fileInfo = new BmFileInfo();
        fileInfo.setTaskType(0);
        fileInfo.setTaskId(purchaseCheckDto.getPurchaseCheckInfo().getTaskId());
        List<BmFileInfo> bmFileInfoList = bmFileInfoMapper.selectBmFileInfoList(fileInfo);
        if (!CollectionUtils.isEmpty(bmFileInfoList)) {
            bmFileInfoMapper.deleteBmFileList(purchaseCheckDto.getPurchaseCheckInfo().getTaskId());
        }
        if (!CollectionUtils.isEmpty(purchaseCheckDto.getPurchaseCheckDetailsList())) {
            purchaseCheckDto.getPurchaseCheckDetailsList().removeIf(Objects::isNull);
            purchaseCheckDto.getPurchaseCheckDetailsList().removeIf(o -> Objects.isNull(o.getStatus()));
            purchaseCheckDto.getPurchaseCheckDetailsList().removeIf(o ->
                    !Objects.equals(o.getStatus(), PurchaseTaskStatusEnum.TO_NOTICE.getStatus()) &&
                    !Objects.equals(o.getStatus(), PurchaseTaskStatusEnum.TO_CHECK_AFTER_REJECT.getStatus())
            );
        }
        try {
            final Long[] ids = {purchaseCheckDto.getPurchaseCheckInfo().getId()};
            purchaseCheckDetailsMapper.deletePurchaseCheckDetailsByParentIds(ids);
            insertPurchaseCheckDetails(purchaseCheckDto.getPurchaseCheckDetailsList(), purchaseCheckDto.getPurchaseCheckInfo().getTaskId());
            purchaseCheckInfoMapper.updatePurchaseCheckInfo(purchaseCheckDto.getPurchaseCheckInfo());
            return true;
        } catch (final Exception e) {
            throw new ServiceException("错误信息描述");
        }
    }

    /**
     * 批量删除新购验收任务
     *
     * @param ids 需要删除的新购验收任务主键
     * @return 结果
     */
    @Override
    @Transactional
    public int deletePurchaseCheckInfoByIds(Long[] ids) {
        tmTaskMapper.deleteTmTaskByPurchaseIds(ids);
        purchaseCheckDetailsMapper.deletePurchaseCheckDetailsByParentIds(ids);
        return purchaseCheckInfoMapper.deletePurchaseCheckInfoByIds(ids);
    }

    /**
     * 删除新购验收任务信息
     *
     * @param id 新购验收任务主键
     * @return 结果
     */
    @Override
    public int deletePurchaseCheckInfoById(Long id) {
        return purchaseCheckInfoMapper.deletePurchaseCheckInfoById(id);
    }

    @Override
    public List<PurchaseCheckInfo> selectPurchaseCheckUserById(PurchaseQueryDto purchaseQueryDto) {
        return purchaseCheckInfoMapper.selectPurchaseCheckUserById(purchaseQueryDto);
    }

    /**
     * 获取签名列表
     * @param purchaseSignRecord
     * @return
     */
    @Override
    public List<PurchaseSignRecord> getSignList(PurchaseSignRecord purchaseSignRecord) {
        List<PurchaseSignRecord> list = signProcessMapper.getPurchaseSignRecordByTask(purchaseSignRecord.getTaskId());
        if (!CollectionUtils.isEmpty(list)) {
            Set<String> deptNameSet = new HashSet<>();
            List<PurchaseSignRecord> signList = new ArrayList<>();
            for (PurchaseSignRecord signRecord : list) {
                // 如果部门名称不在集合中，则添加到结果列表和部门名称集合
                if (!deptNameSet.contains(signRecord.getDeptName())) {
                    signList.add(signRecord);
                    deptNameSet.add(signRecord.getDeptName());
                }
            }
            if (!CollectionUtils.isEmpty(signList)) {
                for (PurchaseSignRecord signRecord : signList) {
                    if ("1".equals(signRecord.getAuditStatus())) {
                        signRecord.setAuditStatusName("审核通过");
                    } else if ("2".equals(signRecord.getAuditStatus())) {
                        signRecord.setAuditStatusName("审核驳回");
                    }
                }
            }
            return signList;
        }
        return list;
    }

    /**
     * 修改新购验收任务
     * @param purchaseCheckDto
     * @return
     */
    @Override
    public int update(PurchaseCheckDto purchaseCheckDto) {
        purchaseCheckDto.getPurchaseCheckInfo().setUpdateTime(DateUtils.getNowDate());
        purchaseCheckDto.getPurchaseCheckInfo().setUpdateBy(SecurityUtils.getLoginUser().getSysUser().getNickName());
        // 先去查是否存在文件信息，存在就删除
        BmFileInfo fileInfo = new BmFileInfo();
        fileInfo.setTaskType(0);
        fileInfo.setTaskId(purchaseCheckDto.getPurchaseCheckInfo().getTaskId());
        List<BmFileInfo> bmFileInfoList = bmFileInfoMapper.selectBmFileInfoList(fileInfo);
        if (!CollectionUtils.isEmpty(bmFileInfoList)) {
            bmFileInfoMapper.deleteBmFileList(purchaseCheckDto.getPurchaseCheckInfo().getTaskId());
        }
        try {
            final Long[] ids = {purchaseCheckDto.getPurchaseCheckInfo().getId()};
            purchaseCheckDetailsMapper.deleteDetails(ids);
            insertPurchaseCheckDetailsInfo(purchaseCheckDto.getPurchaseCheckDetailsList(), purchaseCheckDto.getPurchaseCheckInfo().getTaskId());
            return purchaseCheckInfoMapper.updatePurchaseCheckInfo(purchaseCheckDto.getPurchaseCheckInfo());
        } catch (final Exception e) {
            throw new ServiceException("错误信息描述");
        }
    }

    /**
     * 批量插入新购验收任务详情
     * @param purchaseCheckDetailsList
     * @param taskId
     * @return
     */
    private int insertPurchaseCheckDetailsInfo(List<PurchaseCheckDetails> purchaseCheckDetailsList, Long taskId) {
        int count = 0;
        if (!CollectionUtils.isEmpty(purchaseCheckDetailsList)) {
            for (PurchaseCheckDetails details : purchaseCheckDetailsList) {
                details.setTaskId(taskId);
                details.setStatus(Objects.equals(PurchaseTaskStatusEnum.TO_CHECK_AFTER_REJECT.getStatus(), details.getStatus()) ?
                        PurchaseTaskStatusEnum.TO_CHECK.getStatus() :
                        PurchaseTaskStatusEnum.TO_NOTICE.getStatus());
                details.setInputStatus("0");
                final List<BmFileInfo> bmFileInfos = details.getBmFileInfos();
                if (!CollectionUtils.isEmpty(bmFileInfos)) {
                    bmFileInfos.forEach(o -> {
                        o.setTaskId(taskId);
                        o.setModelId(details.getTypeId());
                        o.setCreateBy(SecurityUtils.getLoginUser().getUserid().toString());
                        o.setCreateTime(DateUtils.getNowDate());
                    });
                    bmFileInfoMapper.insertBmFileInfos(bmFileInfos);
                }
                Type type = new Type();
                type.setTypeId(details.getTypeId());
                type.setUpdateTime(DateUtils.getNowDate());
                type.setUpdateBy(SecurityUtils.getLoginUser().getUserid().toString());
                type.setBuyPrice(details.getPurchaseTaxPrice());
                type.setNotTaxPrice(details.getPurchasePrice());
                Type maType = typeMapper.getMaType(details.getTypeId());
                if (maType != null && (maType.getRentPrice() == null || maType.getRentPrice().compareTo(BigDecimal.ZERO) == 0)) {
                    type.setRentPrice(details.getRentPrice());
                }
                typeMapper.updateType(type);
            }
            // 批量插入详情数据
            // 将purchaseCheckDetailsList的status全部设置为2
            purchaseCheckDetailsList.forEach(o -> o.setStatus(PurchaseTaskStatusEnum.TO_CHECK.getStatus()));
            count = purchaseCheckDetailsMapper.insertPurchaseCheckDetailsList(purchaseCheckDetailsList);
        }
        return count;
    }
}
