package com.sw.common.accessory.server.service.impl;


import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.sw.common.accessory.api.feignCilent.YbFeignClients;
import com.sw.common.accessory.api.model.AccessoryMaterialDto;
import com.sw.common.accessory.api.model.EquipmentDto;
import com.sw.common.accessory.api.model.MaterialModelDto;
import com.sw.common.accessory.server.EnumValuesAccy;
import com.sw.common.accessory.server.dto.*;
import com.sw.common.accessory.server.entity.*;
import com.sw.common.accessory.server.interfaces.out.AccyOutService;
import com.sw.common.accessory.server.mapper.AccessoryMapper;
import com.sw.common.accessory.server.service.*;
import com.sw.common.accessory.utils.CodeGenerator;
import com.sw.common.component.redis.server.RedisUtils;
import com.sw.common.core.context.BaseContextHandler;
import com.sw.common.core.exception.BusinessException;
import com.sw.common.core.response.Result;
import com.sw.common.core.response.ResultGenerator;
import com.sw.common.core.utils.StringUtils;
import com.sw.common.mybatisplus.base.BaseServiceImpl;
import org.apache.commons.collections4.CollectionUtils;
import org.checkerframework.checker.units.qual.C;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.Assert;
import org.springframework.util.ObjectUtils;
import org.springframework.validation.annotation.Validated;

import javax.validation.Valid;
import java.util.*;
import java.util.stream.Collectors;


/**
 * @Author
 * @Description：
 * @Date: Create in
 * @Modified By:
 */
@Validated
@Service
@Transactional
public class AccessoryServiceImpl extends BaseServiceImpl<AccessoryMapper, Accessory> implements AccessoryService {
    @Autowired
    private AccessoryMapper accessoryMapper;

    @Autowired
    private AccyOutService accyService;

    @Autowired
    private EquipmentAccessoryService equipmentAccessoryService;

    @Autowired
    private ReturnRecordService returnRecordService;

    @Autowired
    private ApplyRecordService applyRecordService;

    @Autowired
    private ReplacementRecordService replacementRecordService;

    @Autowired
    private LifeResumeService lifeResumeService;

    @Autowired
    private YbFeignClients ybFeignClients;

    @Autowired
    private AccessoryPartService accessoryPartService;

    @Autowired
    private AccessoryPartDetailsService accessoryPartDetailsService;

    @Autowired
    private DeterminationEchnologyService determinationEchnologyService;

    @Autowired
    private DeterminationQualityService determinationQualityService;

    @Override
    public List<AccessoryDetails> findByEquipmentAccessoryId(Long equipmentAccessoryId, Integer[] statuss, Integer warnStatus) {
        EquipmentAccessory equipmentAccessory = equipmentAccessoryService.get(equipmentAccessoryId);
        if (equipmentAccessory == null) {
            throw new BusinessException("该设备辅材id不存在");
        }
        List<AccessoryDetails> accessoryDetailss = accessoryMapper.findAccessoryDetailsByEquipmentAccessoryId(equipmentAccessoryId, statuss, warnStatus);
        accessoryDetailss.forEach(accessoryDetails -> {
            //上机时间
            if (!ObjectUtils.isEmpty(accessoryDetails.getUpperTime())) {
                Date upperTime = accessoryDetails.getUpperTime();
                Calendar calendar = Calendar.getInstance();
                calendar.setTime(upperTime);
                int upDay = calendar.get(Calendar.DAY_OF_MONTH);
                int upHour = calendar.get(Calendar.HOUR_OF_DAY);
                //下机时间
                Calendar instance = Calendar.getInstance();
                //下机状态
                if (!ObjectUtils.isEmpty(accessoryDetails.getDownTime()) && accessoryDetails.getStatus().equals(0)) {
                    instance.setTime(accessoryDetails.getDownTime());
                }
                int downDay = instance.get(Calendar.DAY_OF_MONTH);
                int downHour = instance.get(Calendar.HOUR_OF_DAY);
                //上机12点之前&&下机12点之后,上机12点之后||下机12点之前,上机12点之后&&下机12点之前
                int day;
                if (upHour < 12 && downHour >= 12) {
                    day = downDay - upDay + 1;
                } else if ((upHour >= 12 && downHour >= 12) || (upHour < 12 && downHour < 12)) {
                    day = downDay - upDay;
                } else {
                    day = downDay - upDay - 1;
                }
                accessoryDetails.setUsefulLife(day);
                Integer ratedLife = accessoryDetails.getRatedLife();
                accessoryDetails.setRemainingLife(ratedLife - day);
            }
        });
        if ((statuss == null || statuss.length == 0 || Arrays.asList(statuss).contains(4)) && (warnStatus == null || warnStatus == 0)) {
            // 添加待出库的数据，查询辅料申请记录
            LambdaQueryWrapper<ApplyRecord> applyRecordLambdaQueryWrapper = new LambdaQueryWrapper<ApplyRecord>().eq(ApplyRecord::getStatus, EnumValuesAccy.ApplyStatus.WAITING.getValue()).eq(ApplyRecord::getEquipmentCode, equipmentAccessory.getEquipmentCode());
            List<ApplyRecord> applyRecords = applyRecordService.list(applyRecordLambdaQueryWrapper);
            applyRecords.forEach(applyRecord -> {
                AccessoryDetails accessoryDetails = new AccessoryDetails();
                accessoryDetails.setId(applyRecord.getId());
                accessoryDetails.setEquipmentAccessoryId(equipmentAccessoryId);
                accessoryDetails.setMaterialId(applyRecord.getMaterialId());
                accessoryDetails.setMaterialType(applyRecord.getMaterialType());
                accessoryDetails.setMaterialName(applyRecord.getMaterialName());
                accessoryDetails.setMaterialCode(applyRecord.getMaterialCode());
                accessoryDetails.setNumber(applyRecord.getNumber());
                accessoryDetails.setStatus(4);
                accessoryDetails.setPartCode(applyRecord.getPartCode());
                accessoryDetails.setPartName(applyRecord.getPartName());
                accessoryDetailss.add(accessoryDetails);
            });
        }
        return accessoryDetailss;
    }

    @Override
    public List<AccessoryDetails> findByEquipmentAccessoryCode(String equipmentDeviceCode) {
        EquipmentAccessory equipmentAccessory = equipmentAccessoryService.findByEquipmentCode(equipmentDeviceCode);
        if (equipmentAccessory == null) {
            throw new BusinessException("该设备辅材不存在");
        }
        Integer[] statuss = null;
        Integer warnStatus = null;
        List<AccessoryDetails> accessoryDetailss = accessoryMapper.findAccessoryDetailsByEquipmentAccessoryId(equipmentAccessory.getId(), statuss, warnStatus);
        if ((statuss == null || statuss.length == 0 || Arrays.asList(statuss).contains(4)) && (warnStatus == null || warnStatus == 0)) {
            // 添加待出库的数据，查询辅料申请记录
            LambdaQueryWrapper<ApplyRecord> applyRecordLambdaQueryWrapper = new LambdaQueryWrapper<ApplyRecord>().eq(ApplyRecord::getStatus, EnumValuesAccy.ApplyStatus.WAITING.getValue()).eq(ApplyRecord::getEquipmentCode, equipmentAccessory.getEquipmentCode());
            List<ApplyRecord> applyRecords = applyRecordService.list(applyRecordLambdaQueryWrapper);
            applyRecords.forEach(applyRecord -> {
                AccessoryDetails accessoryDetails = new AccessoryDetails();
                accessoryDetails.setId(applyRecord.getId());
                accessoryDetails.setEquipmentAccessoryId(equipmentAccessory.getId());
                accessoryDetails.setMaterialId(applyRecord.getMaterialId());
                accessoryDetails.setMaterialType(applyRecord.getMaterialType());
                accessoryDetails.setMaterialName(applyRecord.getMaterialName());
                accessoryDetails.setMaterialCode(applyRecord.getMaterialCode());
                accessoryDetails.setNumber(applyRecord.getNumber());
                accessoryDetails.setStatus(4);
                accessoryDetails.setPartCode(applyRecord.getPartCode());
                accessoryDetails.setPartName(applyRecord.getPartName());
                accessoryDetails.setAccessoryStatus(applyRecord.getAccessoryStatus());
                accessoryDetailss.add(accessoryDetails);
            });
        }
        return accessoryDetailss;
    }

    @Override
    public Accessory findByUniqueCode(String uniqueCode) {
        LambdaQueryWrapper<Accessory> lambdaQueryWrapper = new LambdaQueryWrapper<>();
        lambdaQueryWrapper.eq(Accessory::getUniqueCode, uniqueCode).orderByDesc(Accessory::getId).last("LIMIT 1");
        return getOne(lambdaQueryWrapper);
    }

    @Override
    public void stockReturn(StockReturn stockReturn) {
        Accessory accessory = get(stockReturn.getId());
        if (accessory == null) {
            throw new BusinessException("辅材id不存在");
        }
        int accessoryStatus = accessory.getStatus();
        Assert.state(accessoryStatus == EnumValuesAccy.AccyUseStatus.上机中.getKey() || accessoryStatus == EnumValuesAccy.AccyUseStatus.待上机.getKey(), "当前为【" + EnumValuesAccy.AccyUseStatus.getText(accessoryStatus) + "】状态,不允许申请退库");
        EquipmentAccessory equipmentAccessory = equipmentAccessoryService.get(accessory.getEquipmentAccessoryId());
        Assert.notNull(equipmentAccessory, "辅材id不存在");
        if (accessoryStatus == EnumValuesAccy.AccyUseStatus.上机中.getKey()) {
            equipmentAccessoryService.updateBoardingCount(equipmentAccessory.getId(), equipmentAccessory.getBoardingCount(), -1);
        } else {
            equipmentAccessoryService.updateWaitingBoardingCount(equipmentAccessory.getId(), equipmentAccessory.getWaitingBoardingCount(), -1);
        }
        equipmentAccessoryService.updateStockReturnCount(equipmentAccessory.getId(), equipmentAccessory.getStockReturnCount(), 1);
        if (stockReturn.isExceptionAudit()) {
            accessory.setStatus(EnumValuesAccy.AccyUseStatus.异常判定中.getKey());
        }else {
            accessory.setStatus(EnumValuesAccy.AccyUseStatus.退库中.getKey());
        }
        accessory.setDownTime(new Date());
        accessory.setUserCreate(BaseContextHandler.getUsername());
        if (accessoryStatus == EnumValuesAccy.AccyUseStatus.上机中.getKey()) {
            // 修改退库状态
            boolean isUpdateTrue = update(accessory, new LambdaUpdateWrapper<Accessory>().
                    eq(Accessory::getId, accessory.getId()).eq(Accessory::getStatus, EnumValuesAccy.AccyUseStatus.上机中.getKey()));
            Assert.isTrue(isUpdateTrue, "退库失败，请重试");
            //退库下机，记录寿命追溯记录
            lifeResumeService.addLifeLog(EnumValuesAccy.AccOper.ApplyForStockReturn, accessory, null);
        } else {
            // 修改退库状态
            boolean isUpdateTrue = update(accessory, new LambdaUpdateWrapper<Accessory>().
                    eq(Accessory::getId, accessory.getId()).eq(Accessory::getStatus, EnumValuesAccy.AccyUseStatus.待上机.getKey()));
            Assert.isTrue(isUpdateTrue, "退库失败，请重试");
        }
        if(stockReturn.isExceptionAudit()){
            if (stockReturn.isMaterialAnomaly()) {
                DeterminationEchnology determinationEchnology = new DeterminationEchnology();
                determinationEchnology.setAccessoryId(accessory.getId());
                determinationEchnology.setDel(false);
                determinationEchnology.setMaterialCode(accessory.getMaterialCode());
                determinationEchnology.setStatus(0);
                determinationEchnology.setCreateBy(BaseContextHandler.getUsername());
                determinationEchnology.setCreateTime(new Date());
                determinationEchnology.setEquipmentCode(accessory.getEquipmentCode());
                determinationEchnology.setUniqueCode(accessory.getUniqueCode());
                determinationEchnology.setMaterialAnomaly(stockReturn.isMaterialAnomaly());
                determinationEchnology.setAuditPass(false);
                determinationEchnology.setResultDetermination(stockReturn.getDegreeDamage());
                determinationEchnology.setAbnormalCondition(stockReturn.getAbnormalDescription());
                determinationEchnology.setMaterialName(accessory.getMaterialName());
                determinationEchnologyService.saveOrUpdate(determinationEchnology);
            } else {
                DeterminationQuality determinationQuality = new DeterminationQuality();
                determinationQuality.setAccessoryId(accessory.getId());
                determinationQuality.setDel(false);
                determinationQuality.setMaterialCode(accessory.getMaterialCode());
                determinationQuality.setStatus(0);
                determinationQuality.setCreateBy(BaseContextHandler.getUsername());
                determinationQuality.setCreateTime(new Date());
                determinationQuality.setEquipmentCode(accessory.getEquipmentCode());
                determinationQuality.setUniqueCode(accessory.getUniqueCode());
                determinationQuality.setMaterialAnomaly(stockReturn.isMaterialAnomaly());
                determinationQuality.setResultDetermination(stockReturn.getDegreeDamage());
                determinationQuality.setAbnormalCondition(stockReturn.getAbnormalDescription());
                determinationQuality.setMaterialName(accessory.getMaterialName());
                determinationQualityService.saveOrUpdate(determinationQuality);
            }
        }else {
            updateStockReturn(stockReturn,accessory);
        }

    }

    public void updateStockReturn(StockReturn stockReturn, Accessory accessory) {
        //创建仓储系统的退库申请单
        String code = accyService.stockReturnApply(accessory, stockReturn.getReason());
        // 增加退库记录表
        ReturnRecord returnRecord = new ReturnRecord();
        returnRecord.setAccessoryId(accessory.getId());
        returnRecord.setCode(code);
        returnRecord.setAccessoryStatus(accessory.getAccessoryStatus());
        returnRecord.setEquipmentCode(accessory.getEquipmentCode());
        returnRecord.setMaterialType(accessory.getMaterialType());
        returnRecord.setMaterialName(accessory.getMaterialName());
        returnRecord.setMaterialCode(accessory.getMaterialCode());
        returnRecord.setBatchCode(accessory.getBatchCode());
        returnRecord.setUniqueCode(accessory.getUniqueCode());
        returnRecord.setNumber(stockReturn.getNumber());
        returnRecord.setSpecification(accessory.getSpecification());
        returnRecord.setUnit(accessory.getUnit());
        returnRecord.setSupplier(accessory.getSupplier());
        returnRecord.setRatedLife(accessory.getRatedLife());
        returnRecord.setUsefulLife(accessory.getUsefulLife());
        returnRecord.setRemainingLife(accessory.getRemainingLife());
        returnRecord.setReason(stockReturn.getReason());
        returnRecord.setUseStatus(accessory.getStatus());
        returnRecord.setStatus(EnumValuesAccy.ReturnStatus.WAIT_RECEIVE.getKey());
        returnRecord.setUserCreate(BaseContextHandler.getUsername());
        returnRecord.setGmtCreate(new Date());
        returnRecordService.saveOrUpdate(returnRecord);
        List<AccessoryDetails> accessoryDetails = accessoryMapper.findAccessoryDetailsByEquipmentAccessoryId(accessory.getEquipmentAccessoryId(), null, null);
        Optional<AccessoryDetails> accessoryDetail = accessoryDetails.stream().filter(entity -> entity.getId().equals(stockReturn.getId())).findFirst();
        //更新部位使用数量
        if (accessoryDetail.isPresent()) {
            Result<EquipmentDto> equipmentInfo = ybFeignClients.getByCodeDto(accessory.getEquipmentCode());
            String deviceCodes = new String();
            if (equipmentInfo.getCode().equals(200)) {
                Result<DeviceDto> result = ybFeignClients.getDeviceId(equipmentInfo.getData().getDeviceId());
                if (result.getCode().equals(200)) {
                    deviceCodes = result.getData().getCode();
                }
            }
            AccessoryPartDetails accessoryPart = accessoryPartDetailsService.getByCode(deviceCodes
                    , accessory.getEquipmentCode(), accessory.getMaterialCode(), accessoryDetail.get().getPartCode());
            if (!ObjectUtils.isEmpty(accessoryPart)) {
                accessoryPart.setUsableNumber(accessoryPart.getTotalNumber(), accessoryPart.getUsedNumber() - 1);
                if (accessoryPart.getTotalNumber() - accessoryPart.getUsedNumber() + 1 <= 0) {
                    accessoryPart.setUsedNumber(accessoryPart.getTotalNumber());
                } else {
                    accessoryPart.setUsedNumber(accessoryPart.getUsedNumber() - 1);
                }
                accessoryPartDetailsService.updateById(accessoryPart);
            }
        }
    }

    @Override
    public void down(Long id) {
        Accessory accessory = get(id);
        Assert.notNull(accessory, "辅材id不存在");
        down(accessory.getUniqueCode(), accessory.getEquipmentCode(), null, null);
    }

    @Override
    public List<AccessoryDetails> findAccessoryDetailsByEquipmentAccessoryId(Long id, Integer[] statuss, Integer status) {
        return accessoryMapper.findAccessoryDetailsByEquipmentAccessoryId(id, statuss, status);
    }

    @Override
    public void down(String uniqueCode, String equipmentCode, Integer life, Integer accessoryStatus) {
        if (life != null) {
            Assert.isTrue(life >= 0, "消耗寿命不能小于0");
        }
        Assert.notNull(uniqueCode, "辅材唯一码不能为空");
        Accessory accessory = findByUniqueCode(uniqueCode);
        Assert.notNull(accessory, "【" + uniqueCode + "】辅材唯一码不存在，请维护该辅材");
        int status = accessory.getStatus();
        Assert.state(status == EnumValuesAccy.AccyUseStatus.上机中.getKey(), "【" + uniqueCode + "】当前为【" + EnumValuesAccy.AccyUseStatus.getText(status) + "】状态，不允许下机");
        if (StringUtils.isNotBlank(equipmentCode)) {
            Assert.isTrue(equipmentCode.equals(accessory.getEquipmentCode()), "【" + uniqueCode + "】该辅材上机设备，不是【" + equipmentCode + "】，下机失败，请确认唯一码是否正确");
        }
        EquipmentAccessory equipmentAccessory = equipmentAccessoryService.get(accessory.getEquipmentAccessoryId());
        Assert.notNull(equipmentAccessory, "【" + uniqueCode + "】设备辅材id不存在");
        equipmentAccessoryService.updateBoardingCount(equipmentAccessory.getId(), equipmentAccessory.getBoardingCount(), -1);
        equipmentAccessoryService.updateWaitingBoardingCount(equipmentAccessory.getId(), equipmentAccessory.getWaitingBoardingCount(), 1);

        accessory.setStatus(EnumValuesAccy.AccyUseStatus.待上机.getKey());
        accessory.setDownTime(new Date());
        if (accessoryStatus != null) {
            accessory.setAccessoryStatus(accessoryStatus);
        }
        updateLife(accessory, life);
        //退库下机，记录寿命追溯记录
        lifeResumeService.addLifeLog(EnumValuesAccy.AccOper.ApplyForStockReturn, accessory, null);
        if (accessoryStatus != null && accessoryStatus == 3) {
            StockReturn stockReturn = new StockReturn();
            stockReturn.setId(accessory.getId());
            stockReturn.setReason("报废");
            stockReturn.setNumber(accessory.getNumber());
            stockReturn(stockReturn);
        }
        ReportSapGoodsmvtDto reportSapGoodsmvtDto = new ReportSapGoodsmvtDto();
        List<ReportSapChargItemDto> reportSapChargItemDtos = new ArrayList<>();
        ReportSapChargItemDto reportSapChargItemDto = new ReportSapChargItemDto();
        Result<EquipmentDto> equipmentInfo = ybFeignClients.getEquipmentInfo(accessory.getEquipmentCode());
        if (equipmentInfo.getCode().equals(200)) {
            Result<DictionaryItemDto> warehouseLocation = ybFeignClients.findByThemeValueAndNameAndValueAndEnable("WarehouseLocation"
                    , equipmentInfo.getData().getArea(), equipmentInfo.getData().getSeries(), true);
            if (warehouseLocation.getCode().equals(200)) {
                reportSapGoodsmvtDto.setLgort(warehouseLocation.getData().getExtendValue());
            }
        }
        String supplier = accessory.getSupplier();
        if (StringUtils.isNotEmpty(supplier)) {
            if (supplier.length() > 3) {
                String supplierUp = supplier.toUpperCase().substring(0, 3)
                        + CodeGenerator.buildYear()
                        + CodeGenerator.buildMonth()
                        + CodeGenerator.buildDay()
                        + new CodeGenerator().buildBatchNo();
                reportSapGoodsmvtDto.setCharg(supplierUp);
            } else {
                String supplierUp = supplier.toUpperCase()
                        + CodeGenerator.buildYear()
                        + CodeGenerator.buildMonth()
                        + CodeGenerator.buildDay()
                        + new CodeGenerator().buildBatchNo();
                reportSapGoodsmvtDto.setCharg(supplierUp);
            }

        }
        //上机时间
        Date upperTime = accessory.getUpperTime();
        Calendar calendar = Calendar.getInstance();
        calendar.setTime(upperTime);
        int upDay = calendar.get(Calendar.DAY_OF_MONTH);
        int upHour = calendar.get(Calendar.HOUR_OF_DAY);
        //下机时间
        Calendar instance = Calendar.getInstance();
        int downDay = instance.get(Calendar.DAY_OF_MONTH);
        int downHour = instance.get(Calendar.HOUR_OF_DAY);
        //上机12点之前&&下机12点之后,上机12点之后||下机12点之前,上机12点之后&&下机12点之前
        int day;
        if (upHour < 12 && downHour >= 12) {
            day = downDay - upDay + 1;
        } else if ((upHour >= 12 && downHour >= 12) || (upHour < 12 && downHour < 12)) {
            day = downDay - upDay;
        } else {
            day = downDay - upDay - 1;
        }
        reportSapChargItemDto.setAtnam("P01");
        reportSapChargItemDto.setAtwrt("JK1");
        reportSapChargItemDtos.add(reportSapChargItemDto);
        reportSapGoodsmvtDto.setChargItems(reportSapChargItemDtos);
        reportSapGoodsmvtDto.setBwart("201");
        reportSapGoodsmvtDto.setWerks("5041");
        reportSapGoodsmvtDto.setMenge(String.valueOf(day * 24));
        reportSapGoodsmvtDto.setMatnr(accessory.getMaterialCode());
        reportSapGoodsmvtDto.setMeins("H");
        reportSapGoodsmvtDto.setProcName("寿命监控下机");
//        ybFeignClients.sendSapGoodsmvt(reportSapGoodsmvtDto);
    }

    private void updateLife(Accessory accessory, Integer life) {
        accessory.setGmtCreate(new Date());
        accessory.setUserCreate(BaseContextHandler.getUsername());
        Integer oldLife = accessory.getUsefulLife();
        Integer oldWarnStatus = accessory.getWarnStatus();
        if (life != null && life > 0) {
            accessory.setUsefulLife(accessory.getUsefulLife() + life);
        }
        // 修改辅材状态以及寿命
        boolean isUpdateTrue = update(accessory, new LambdaUpdateWrapper<Accessory>().
                eq(Accessory::getId, accessory.getId()).eq(Accessory::getStatus, EnumValuesAccy.AccyUseStatus.上机中.getKey()).eq(Accessory::getUsefulLife, oldLife));
        Assert.isTrue(isUpdateTrue, "【" + accessory.getUniqueCode() + "】寿命更新失败，请重试");
        if (life != null && life > 0) {
            if (!oldWarnStatus.equals(accessory.getWarnStatus())) {
                EquipmentAccessory equipmentAccessory = equipmentAccessoryService.get(accessory.getEquipmentAccessoryId());
                equipmentAccessoryService.updateEarlyWarningCount(accessory.getEquipmentAccessoryId(), equipmentAccessory.getEarlyWarningCount(), accessory.getWarnStatus() == 1 ? 1 : -1);
            }
            //退库下机，记录寿命追溯记录
            lifeResumeService.addLifeLog(EnumValuesAccy.AccOper.LifeConsumption, accessory, null);
        }
    }

    @Override
    public void cancelStockReturn(Long id) {
        Accessory accessory = get(id);
        Assert.notNull(accessory, "辅材id不存在");
        Assert.isTrue(accessory.getStatus() == EnumValuesAccy.AccyUseStatus.退库中.getKey(), "辅材状态不是退库中");

        LambdaQueryWrapper<ReturnRecord> stockReturnLambdaQueryWrapper = new LambdaQueryWrapper<>();
        stockReturnLambdaQueryWrapper.eq(ReturnRecord::getAccessoryId, accessory.getId()).eq(ReturnRecord::getStatus, EnumValuesAccy.ReturnStatus.WAIT_RECEIVE.getKey());
        ReturnRecord returnRecord = returnRecordService.getOne(stockReturnLambdaQueryWrapper);
        Assert.notNull(returnRecord, "该辅材的退库单不存在");

        returnRecord.setStatus(EnumValuesAccy.ReturnStatus.HAS_CANCEL.getKey());
        cancelReturnRecordSave(accessory, returnRecord);

        //取消仓储信息的退库申请单
        accyService.cancelStockReturnApply(returnRecord.getCode());
        List<AccessoryDetails> accessoryDetails = accessoryMapper.findAccessoryDetailsByEquipmentAccessoryId(accessory.getEquipmentAccessoryId(), null, null);
        Optional<AccessoryDetails> accessoryDetail = accessoryDetails.stream().filter(entity -> entity.getId().equals(id)).findFirst();
        //更新部位使用数量
        if (accessoryDetail.isPresent()) {
            Result<EquipmentDto> equipmentInfo = ybFeignClients.getByCodeDto(accessory.getEquipmentCode());
            String deviceCodes = new String();
            if (equipmentInfo.getCode().equals(200)) {
                Result<DeviceDto> result = ybFeignClients.getDeviceId(equipmentInfo.getData().getDeviceId());
                if (result.getCode().equals(200)) {
                    deviceCodes = result.getData().getCode();
                }
            }
            AccessoryPartDetails accessoryPart = accessoryPartDetailsService.getByCode(deviceCodes
                    , accessory.getEquipmentCode(), accessory.getMaterialCode(), accessoryDetail.get().getPartCode());
            if (!ObjectUtils.isEmpty(accessoryPart)) {
                accessoryPart.setUsableNumber(accessoryPart.getTotalNumber(), accessoryPart.getUsedNumber() + 1);
                if (accessoryPart.getTotalNumber() - accessoryPart.getUsedNumber() - 1 <= 0) {
                    accessoryPart.setUsedNumber(accessoryPart.getTotalNumber());
                } else {
                    accessoryPart.setUsedNumber(accessoryPart.getUsedNumber() + 1);
                }
                accessoryPartDetailsService.updateById(accessoryPart);
            }
        }
    }


    @Override
    public void cancelReturnRecordSave(Accessory accessory, ReturnRecord returnRecord) {
        Assert.notNull(returnRecord, "退库记录不存在");
        Assert.notNull(accessory, "辅材信息不存在");
        boolean updateReturnRecordStatus = returnRecordService.update(returnRecord, new LambdaUpdateWrapper<ReturnRecord>().eq(ReturnRecord::getId, returnRecord.getId()).eq(ReturnRecord::getStatus, EnumValuesAccy.ReturnStatus.WAIT_RECEIVE.getKey()));
        Assert.isTrue(updateReturnRecordStatus, "失败，请重试，退库申请单状态修改失败");
        EquipmentAccessory equipmentAccessory = equipmentAccessoryService.get(accessory.getEquipmentAccessoryId());
        if (equipmentAccessory != null) {
            equipmentAccessoryService.updateWaitingBoardingCount(equipmentAccessory.getId(), equipmentAccessory.getWaitingBoardingCount(), 1);
            equipmentAccessoryService.updateStockReturnCount(equipmentAccessory.getId(), equipmentAccessory.getStockReturnCount(), -1);
        }
        accessory.setStatus(EnumValuesAccy.AccyUseStatus.待上机.getKey());
        saveOrUpdate(accessory);
    }


    @Override
    public void upper(Long id) {
        Accessory accessory = get(id);
        Assert.notNull(accessory, "辅材id不存在");
        execUpper(accessory, null, null);
    }

    @Override
    public void upper(String uniqueCode, String equipmentCode, Integer accessoryStatus) {
        Assert.notNull(uniqueCode, "辅材唯一码不能为空");
        Accessory accessory = findByUniqueCode(uniqueCode);
        Assert.notNull(accessory, "【" + uniqueCode + "】辅材唯一码不存在，请维护该辅材");
        execUpper(accessory, equipmentCode, accessoryStatus);
    }


    @Override
    public void upper(Long id, String equipmentCode, Integer accessoryStatus) {
        Accessory accessory = get(id);
        Assert.notNull(accessory, "辅材id不存在");
        execUpper(accessory, equipmentCode, accessoryStatus);
    }

    private void execUpper(Accessory accessory, String equipmentCode, Integer accessoryStatus) {
        Assert.state(accessory.getStatus() == EnumValuesAccy.AccyUseStatus.待上机.getKey(), accessory.getUniqueCode() + "【" + EnumValuesAccy.AccyUseStatus.getText(accessory.getStatus()) + "】状态，不可上机");
        EquipmentAccessory equipmentAccessory;
        if (StringUtils.isNotBlank(equipmentCode)) {
            equipmentAccessory = equipmentAccessoryService.findByEquipmentCode(equipmentCode);
            if (equipmentAccessory == null) {
                //判断设备是否存在
                EquipmentInfo equipmentInfo = accyService.getEquipmentInfo(equipmentCode);
                Assert.notNull(equipmentInfo, equipmentCode + "该设备号不存在，没有获取到设备信息");
                equipmentAccessory = equipmentAccessoryService.createNewEquipmentAccessory(equipmentInfo, 1);
            }
            if (accessory.getEquipmentAccessoryId() != null) {
                EquipmentAccessory equipmentAccessoryOld = equipmentAccessoryService.get(accessory.getEquipmentAccessoryId());
                if (equipmentAccessoryOld != null) {
                    equipmentAccessoryService.updateWaitingBoardingCount(equipmentAccessoryOld.getId(), equipmentAccessoryOld.getWaitingBoardingCount(), -1);
                }
            }
            accessory.setEquipmentAccessoryId(equipmentAccessory.getId());
        } else {
            Assert.notNull(accessory.getEquipmentAccessoryId(), "【" + accessory.getUniqueCode() + "】该辅材没有绑定上机设备，请指定设备编号");
            equipmentAccessory = equipmentAccessoryService.get(accessory.getEquipmentAccessoryId());
            Assert.notNull(equipmentAccessory, "设备辅材不存在，请指定设备编号");
            equipmentAccessoryService.updateWaitingBoardingCount(equipmentAccessory.getId(), equipmentAccessory.getWaitingBoardingCount(), -1);
        }
        equipmentAccessoryService.updateBoardingCount(equipmentAccessory.getId(), equipmentAccessory.getBoardingCount(), 1);
        accessory.setUpperTime(new Date());
        accessory.setStatus(EnumValuesAccy.AccyUseStatus.上机中.getKey());
        accessory.setEquipmentCode(equipmentAccessory.getEquipmentCode());
        accessory.setUserCreate(BaseContextHandler.getUsername());
        accessory.setGmtCreate(new Date());
        if (accessoryStatus != null) {
            accessory.setAccessoryStatus(accessoryStatus);
        }
        boolean updateStatus = update(accessory, new LambdaUpdateWrapper<Accessory>().eq(Accessory::getId, accessory.getId()).eq(Accessory::getStatus, EnumValuesAccy.AccyUseStatus.待上机.getKey()));
        Assert.isTrue(updateStatus, "【" + accessory.getUniqueCode() + "】上机失败，请重试，辅料状态修改失败");
        //上机，记录寿命追溯记录
        lifeResumeService.addLifeLog(EnumValuesAccy.AccOper.UpperDevice, accessory, null);
    }

    @Override
    public void batchSwitching(BatchSwitch batchSwitch) {
        Map<Long, Accessory> accessoryMap = new HashMap<>();
        Map<Long, Accessory> accessoryTargetMap = new HashMap<>();
        List<ReplacementRecord> replacementRecords = new ArrayList<>();
        batchSwitch.getSwitchDatas().forEach(switchData -> {
            Accessory accessory = get(switchData.getAccessory());
            Assert.notNull(accessory, "数据过期，请重新获取数据");
            Accessory accessoryTarget = get(switchData.getTargetAccessory());
            Assert.notNull(accessoryTarget, "数据过期，请重新获取数据");
            Assert.isTrue(accessory.getStatus() == EnumValuesAccy.AccyUseStatus.上机中.getKey() && accessoryTarget.getStatus() == EnumValuesAccy.AccyUseStatus.上机中.getKey(), accessoryTarget.getUniqueCode() + "与" + accessory.getUniqueCode() + "有一个不是上机中， 只有都为上机中状态才能进行切换");
            Assert.isTrue(accessory.getNumber().equals(accessoryTarget.getNumber()), accessoryTarget.getUniqueCode() + "与" + accessory.getUniqueCode() + "数量不一致，无法对调");
            Assert.isTrue(accessory.getMaterialCode().equals(accessoryTarget.getMaterialCode()), accessoryTarget.getUniqueCode() + "与" + accessory.getUniqueCode() + "的料号不一样，无法能对调");
            accessoryMap.put(switchData.getAccessory(), accessory);
            accessoryTargetMap.put(switchData.getTargetAccessory(), accessoryTarget);
        });
        try {
            batchSwitch.getSwitchDatas().forEach(switchData -> {
                Accessory accessory = accessoryMap.get(switchData.getAccessory());
                Accessory accessoryTarget = accessoryTargetMap.get(switchData.getTargetAccessory());
                long targetEquipmentAccessoryId = accessoryTarget.getEquipmentAccessoryId();
                String targetEquipmentCode = accessoryTarget.getEquipmentCode();
                accessoryTarget.setEquipmentAccessoryId(accessory.getEquipmentAccessoryId());
                accessoryTarget.setEquipmentCode(accessory.getEquipmentCode());
                accessoryTarget.setUpperTime(new Date());
                accessoryTarget.setGmtCreate(new Date());
                accessoryTarget.setUserCreate(BaseContextHandler.getUsername());
                accessory.setEquipmentAccessoryId(targetEquipmentAccessoryId);
                accessory.setEquipmentCode(targetEquipmentCode);
                accessory.setUpperTime(new Date());
                accessory.setGmtCreate(new Date());
                accessory.setUserCreate(BaseContextHandler.getUsername());
                List<Accessory> accessories = new ArrayList<>();
                accessories.add(accessory);
                accessories.add(accessoryTarget);
                updateBatchById(accessories);
                replacementRecords.add(setReplacementRecord(accessoryTarget, accessory));
                replacementRecords.add(setReplacementRecord(accessory, accessoryTarget));

                //下机
                lifeResumeService.addLifeLog(EnumValuesAccy.AccOper.Transfer, accessory, accessoryTarget);
            });
            if (replacementRecords.size() > 0) {
                replacementRecordService.saveOrUpdateBatch(replacementRecords);
            }
        } catch (Exception e) {
            throw new BusinessException("批量对调失败，请重试");
        }
    }

    private ReplacementRecord setReplacementRecord(Accessory accessory, Accessory accessoryTarget) {
        ReplacementRecord replacementRecord = new ReplacementRecord();
        replacementRecord.setEquipmentCode(accessoryTarget.getEquipmentCode());
        replacementRecord.setMaterialType(accessoryTarget.getMaterialType());
        replacementRecord.setMaterialName(accessoryTarget.getMaterialName());
        replacementRecord.setMaterialCode(accessoryTarget.getMaterialCode());
        replacementRecord.setBatchCode(accessoryTarget.getBatchCode());
        replacementRecord.setUniqueCode(accessoryTarget.getUniqueCode());
        replacementRecord.setNumber(accessoryTarget.getNumber());
        replacementRecord.setSpecification(accessoryTarget.getSpecification());
        replacementRecord.setSupplier(accessoryTarget.getSupplier());
        replacementRecord.setRatedLife(accessoryTarget.getRatedLife());
        replacementRecord.setUsefulLife(accessoryTarget.getUsefulLife());
        replacementRecord.setRemainingLife(accessoryTarget.getRemainingLife());
        replacementRecord.setWarnLife(accessoryTarget.getWarnLife());
        replacementRecord.setMaterialTypeOld(accessory.getMaterialType());
        replacementRecord.setMaterialNameOld(accessory.getMaterialName());
        replacementRecord.setMaterialCodeOld(accessory.getMaterialCode());
        replacementRecord.setBatchCodeOld(accessory.getBatchCode());
        replacementRecord.setUniqueCodeOld(accessory.getUniqueCode());
        replacementRecord.setNumberOld(accessory.getNumber());
        replacementRecord.setSpecificationOld(accessory.getSpecification());
        replacementRecord.setSupplierOld(accessory.getSupplier());
        replacementRecord.setRatedLifeOld(accessory.getRatedLife());
        replacementRecord.setUsefulLifeOld(accessory.getUsefulLife());
        replacementRecord.setRemainingLifeOld(accessory.getRemainingLife());
        replacementRecord.setWarnLifeOld(accessory.getWarnLife());
        replacementRecord.setReplaceTime(new Date());
        replacementRecord.setReplaceUser(BaseContextHandler.getUsername());
        replacementRecord.setChangeTime(new Date());
        replacementRecord.setChangeUser(BaseContextHandler.getUsername());
        replacementRecord.setRemark("【" + accessoryTarget.getEquipmentCode() + "->" + accessory.getEquipmentCode() + "】批量对调");
        replacementRecord.setReason("【" + accessoryTarget.getEquipmentCode() + "->" + accessory.getEquipmentCode() + "】批量对调");
        return replacementRecord;
    }

    @Override
    public List<AccessoryDto> findByEquipmentCode(String equipmentCode) {
        EquipmentAccessory equipmentAccessory = equipmentAccessoryService.findByEquipmentCode(equipmentCode);
        if (equipmentAccessory == null) {
            return new ArrayList<>();
        }
        return accessoryMapper.findByEquipmentAccessoryId(equipmentAccessory.getId());
    }

    @Override
    public AccessoryLife life(Long id) {
        Accessory accessory = get(id);
        if (accessory == null) {
            throw new BusinessException("辅材id不存在");
        }
        AccessoryDto accessoryDto = new AccessoryDto();
        BeanUtils.copyProperties(accessory, accessoryDto);
        AccessoryLife accessoryLife = new AccessoryLife();
        accessoryLife.setAccessoryDto(accessoryDto);
        List<LifeResume> lifeResumes = lifeResumeService.list(new LambdaUpdateWrapper<LifeResume>().eq(LifeResume::getAccessoryId, id).orderByDesc(LifeResume::getId));
        accessoryLife.setLifeResumes(lifeResumes);
        return accessoryLife;
    }

    @Override
    public List<AccessoryDto> findByEquipmentCodeAndStatus(String equipmentCode, int status) {
        LambdaQueryWrapper<Accessory> lambdaQueryWrapper = new LambdaQueryWrapper<Accessory>().eq(Accessory::getEquipmentCode, equipmentCode).eq(Accessory::getStatus, status);
        List<Accessory> accessories = list(lambdaQueryWrapper);
        return accessories.stream().map(accessory -> {
            AccessoryDto accessoryDto = new AccessoryDto();
            BeanUtils.copyProperties(accessory, accessoryDto);
            return accessoryDto;
        }).collect(Collectors.toList());
    }

    @Override
    public boolean save(Accessory accessory) {
        Assert.isNull(findByUniqueCode(accessory.getUniqueCode()), "唯一码【" + accessory.getUniqueCode() + "】已存在，请不要重复添加");
        if (accessory.getStatus() == EnumValuesAccy.AccyUseStatus.上机中.getKey()) {
            Assert.notNull(accessory.getEquipmentCode(), "【上机中】的辅材设备号不能为空");
        }
        EquipmentAccessory finalEquipmentAccessory = StringUtils.isBlank(accessory.getEquipmentCode()) ? null : getEquipmentAccessory(accessory.getEquipmentCode());
        setAccessory(finalEquipmentAccessory, new HashMap<>(), accessory);
        if (StringUtils.isEmpty(accessory.getMaterialType())) {
            Result<AccessoryMaterialDto> result = ybFeignClients.getByMaterialCode(accessory.getMaterialCode());
            if (result.getCode().equals(200)) {
                accessory.setMaterialType(result.getData().getModelName());
            } else {
                accessory.setMaterialType(new String());
            }
        }
        if (super.save(accessory)) {
            if (StringUtils.isNotBlank(accessory.getEquipmentCode())) {
                this.setCount(accessory.getEquipmentCode());
            }
            return true;
        }
        return false;
    }

    @Override
    public void canUpper(String uniqueCode) {
        Assert.notNull(uniqueCode, "辅材唯一码不能为空");
        Accessory accessory = findByUniqueCode(uniqueCode);
        Assert.notNull(accessory, "【" + uniqueCode + "】辅材唯一码不存在");
        Assert.isTrue(accessory.getStatus() == EnumValuesAccy.AccyUseStatus.待上机.getKey(), uniqueCode + "【" + EnumValuesAccy.AccyUseStatus.getText(accessory.getStatus()) + "】状态，不可上机");
    }

    @Override
    public void consumptionLife(String equipmentCode, Integer lifeType, Integer life) {
        Assert.notNull(equipmentCode, "设备编号不能为空");
        Assert.notNull(lifeType, "寿命类型不能为空");
        Assert.notNull(life, "寿命不能为空");
        EquipmentAccessory equipmentAccessory = equipmentAccessoryService.findByEquipmentCode(equipmentCode);
        Assert.notNull(equipmentAccessory, "设备辅材不存在");
        List<Accessory> accessories = list(new LambdaQueryWrapper<Accessory>().eq(Accessory::getEquipmentAccessoryId, equipmentAccessory.getId()).eq(Accessory::getLifeType, lifeType).eq(Accessory::getStatus, EnumValuesAccy.AccyUseStatus.上机中.getKey()));
        accessories.forEach(accessory -> {
            // 修改辅材状态以及寿命
            updateLife(accessory, life);
        });
    }

    @Override
    public void importAccessory(@Valid List<AccessoryImportDto> accessoryImportDtos) {
        Set<String> uniqueCodes = new HashSet<>();
        accessoryImportDtos.forEach(accessoryDto -> {
            Assert.isTrue(!uniqueCodes.contains(accessoryDto.getUniqueCode()), "唯一码【" + accessoryDto.getUniqueCode() + "】重复");
            uniqueCodes.add(accessoryDto.getUniqueCode());
            Assert.isNull(findByUniqueCode(accessoryDto.getUniqueCode()), "唯一码【" + accessoryDto.getUniqueCode() + "】已存在，请不要重复导入");
            if (accessoryDto.getStatus() == EnumValuesAccy.AccyUseStatus.上机中.getKey()) {
                Assert.notNull(accessoryDto.getEquipmentCode(), "【上机中】的辅材设备号不能为空");
            }
        });
        List<Accessory> accessorys = new ArrayList<>();
        Map<String, List<AccessoryImportDto>> accessoryImportDtoMap = accessoryImportDtos.stream().collect(Collectors.groupingBy(AccessoryImportDto::getEquipmentCode));
        accessoryImportDtoMap.forEach((equipmentCode, accessoryImportDtoList) -> {
            EquipmentAccessory finalEquipmentAccessory = StringUtils.isBlank(equipmentCode) ? null : getEquipmentAccessory(equipmentCode);
            Map<String, AccessoryMaterialInfo> accessoryMaterialInfoMap = new HashMap<>();
            accessoryImportDtoList.forEach(accessoryImportDto -> {
                Accessory accessory = new Accessory();
                BeanUtils.copyProperties(accessoryImportDto, accessory);
                setAccessory(finalEquipmentAccessory, accessoryMaterialInfoMap, accessory);
                accessorys.add(accessory);
            });
        });
        saveBatch(accessorys, 100);
        accessoryImportDtoMap.keySet().forEach(this::setCount);
    }

    private void setAccessory(EquipmentAccessory finalEquipmentAccessory, Map<String, AccessoryMaterialInfo> accessoryMaterialInfoMap, Accessory accessory) {
        AccessoryMaterialInfo accessoryMaterialInfo = accessoryMaterialInfoMap.get(accessory.getMaterialCode());
        if (accessoryMaterialInfo == null) {
            accessoryMaterialInfo = accyService.getByMaterialCode(accessory.getMaterialCode());
            accessoryMaterialInfoMap.put(accessory.getMaterialCode(), accessoryMaterialInfo);
        }
        Assert.notNull(accessoryMaterialInfo, "辅材信息不存在");
        accessory.setRatedLife(accessoryMaterialInfo.getUseLife().intValue());
        accessory.setWarnLife(accessoryMaterialInfo.getWarnTime().intValue());
        if (finalEquipmentAccessory != null) {
            accessory.setEquipmentAccessoryId(finalEquipmentAccessory.getId());
            accessory.setEquipmentCode(finalEquipmentAccessory.getEquipmentCode());
        }
        accessory.setMaterialId(accessoryMaterialInfo.getMaterialId());
        accessory.setMaterialType(accessoryMaterialInfo.getMaterialType());
        accessory.setMaterialName(accessoryMaterialInfo.getMaterialName());
        accessory.setMaterialCode(accessoryMaterialInfo.getMaterialCode());

        accessory.setNumber(1);

        accessory.setSupplier(accessoryMaterialInfo.getSupplier());
        accessory.setSpecification(accessoryMaterialInfo.getSpecification());
        accessory.setXh(accessoryMaterialInfo.getXh());
        accessory.setTh(accessoryMaterialInfo.getTh());
        accessory.setUnit(accessoryMaterialInfo.getUnit());
        accessory.setLifeType(accessoryMaterialInfo.getLifeType());
        accessory.setUserCreate(BaseContextHandler.getUsername());
        accessory.setGmtCreate(new Date());
    }

    private EquipmentAccessory getEquipmentAccessory(String equipmentCode) {
        EquipmentAccessory equipmentAccessory = equipmentAccessoryService.findByEquipmentCode(equipmentCode);
        if (equipmentAccessory == null) {
            EquipmentInfo equipmentInfo = accyService.getEquipmentInfo(equipmentCode);
            Assert.notNull(equipmentInfo, equipmentCode + "该设备号不存在，没有获取到设备信息");
            equipmentAccessory = new EquipmentAccessory();
            equipmentAccessory.setEarlyWarningCount(0);
            equipmentAccessory.setWaitingOutboundCount(0);
            equipmentAccessory.setWaitingBoardingCount(0);
            equipmentAccessory.setBoardingCount(0);
            equipmentAccessory.setStockReturnCount(0);
            equipmentAccessory.setGmtCreate(new Date());
            equipmentAccessory.setUserCreate(BaseContextHandler.getUsername());
            equipmentAccessory.setArea(equipmentInfo.getArea());
            equipmentAccessory.setSeries(equipmentInfo.getSeries());
            equipmentAccessory.setEquipmentCode(equipmentInfo.getEquipmentCode());
            equipmentAccessoryService.save(equipmentAccessory);
        }
        return equipmentAccessory;
    }

    private void setCount(String equipmentCode) {
        // 修改预警数量
        equipmentAccessoryService.update(new LambdaUpdateWrapper<EquipmentAccessory>().set(EquipmentAccessory::getEarlyWarningCount, count(new LambdaQueryWrapper<Accessory>().eq(Accessory::getWarnStatus, 1).eq(Accessory::getEquipmentCode, equipmentCode)))
                .eq(EquipmentAccessory::getEquipmentCode, equipmentCode));
        // 修改待上机数量
        equipmentAccessoryService.update(new LambdaUpdateWrapper<EquipmentAccessory>().set(EquipmentAccessory::getWaitingBoardingCount, count(new LambdaQueryWrapper<Accessory>().eq(Accessory::getStatus, 0).eq(Accessory::getEquipmentCode, equipmentCode)))
                .eq(EquipmentAccessory::getEquipmentCode, equipmentCode));
        // 修改上机中数量
        equipmentAccessoryService.update(new LambdaUpdateWrapper<EquipmentAccessory>().set(EquipmentAccessory::getBoardingCount, count(new LambdaQueryWrapper<Accessory>().eq(Accessory::getStatus, 1).eq(Accessory::getEquipmentCode, equipmentCode)))
                .eq(EquipmentAccessory::getEquipmentCode, equipmentCode));
    }

    @Override
    public Result<Void> batchUpper(List<String> eqpNos) {
        if (CollectionUtils.isEmpty(eqpNos)) {
            return ResultGenerator.fail("设备集合不能为空");
        }
        //根据设备号批量查询设备下的待上机的辅材信息
        List<Accessory> accessories = this.findByEquipmentCodeAndStatus(eqpNos, EnumValuesAccy.AccyUseStatus.待上机.getKey());
        if (CollectionUtils.isEmpty(accessories)) {
            return ResultGenerator.fail("根据设备查询到辅材信息为空");
        }
        for (Accessory accessory : accessories) {
            try {
                this.upper(accessory.getId());
            } catch (Exception e) {
                return ResultGenerator.fail("设备号：" + accessory.getEquipmentCode() + "上机失败，失败原因：" + e.getMessage());
            }
        }
        return ResultGenerator.success();
    }

    @Override
    public Result<Void> batchDown(List<String> eqpNos) {
        if (CollectionUtils.isEmpty(eqpNos)) {
            return ResultGenerator.fail("设备集合不能为空");
        }
        //根据设备号批量查询设备下的上机中的辅材信息
        List<Accessory> accessories = this.findByEquipmentCodeAndStatus(eqpNos, EnumValuesAccy.AccyUseStatus.上机中.getKey());
        if (CollectionUtils.isEmpty(accessories)) {
            return ResultGenerator.fail("根据设备查询到辅材信息为空");
        }
        for (Accessory accessory : accessories) {
            try {
                this.down(accessory.getId());
            } catch (Exception e) {
                return ResultGenerator.fail("设备号：" + accessory.getEquipmentCode() + "下机失败，失败原因：" + e.getMessage());
            }
        }
        return ResultGenerator.success();
    }

    @Override
    public List<Accessory> findByEquipmentCodeAndStatus(List<String> eqpNos, int status) {
        LambdaQueryWrapper<Accessory> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.in(Accessory::getEquipmentCode, eqpNos);
        queryWrapper.eq(Accessory::getStatus, status);
        return this.list(queryWrapper);
    }

    @Override
    public Accessory findByEquipmentCodeAndMaterialCode(String equipmentCode, String materialCode) {
        return accessoryMapper.findByEquipmentCodeAndMaterialCode(equipmentCode, materialCode);
    }
}