package digital.laboratory.platform.imr.service.impl;

import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.IdWorker;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import digital.laboratory.platform.common.core.util.R;
import digital.laboratory.platform.common.mybatis.security.service.DLPUser;
import digital.laboratory.platform.imr.dto.DepositToDTO;
import digital.laboratory.platform.imr.dto.SampleInfo;
import digital.laboratory.platform.imr.dto.UseOutboundDTO;
import digital.laboratory.platform.imr.entity.*;
import digital.laboratory.platform.imr.enums.OutApplyStatus;
import digital.laboratory.platform.imr.enums.OutboundType;
import digital.laboratory.platform.imr.feign.TransferFeignService;
import digital.laboratory.platform.imr.feign.dto.UpdateHolderDTO;
import digital.laboratory.platform.imr.mapper.*;
import digital.laboratory.platform.imr.service.CabinetOpeningRecordService;
import digital.laboratory.platform.imr.vo.CabinetSampleVO;
import digital.laboratory.platform.imr.vo.OutSampleVO;
import digital.laboratory.platform.sys.entity.CellAndStoreSupplyData;
import digital.laboratory.platform.sys.feign.RemoteCabinetService;
import io.seata.spring.annotation.GlobalTransactional;
import lombok.AllArgsConstructor;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;


@Service
@AllArgsConstructor
public class CabinetOpeningRecordServiceImpl extends ServiceImpl<CabinetOpeningRecordMapper, CabinetOpeningRecord> implements CabinetOpeningRecordService {


    public final CabinetOpeningRecordMapper openingRecordMapper;

    public final SampleStorageMapper storageMapper;

    private final SampleOutboundRecordMapper outboundRecordMapper;

    public final OutWarehouseDetailedMapper outWarehouseDetailedMapper;


    public final SampleOutWarehouseApplyMapper outWarehouseApplyMapper;


    private final SampleInboundAndOutboundTableMapper tableMapper;


    private final RemoteCabinetService cabinetService;

    private final TransferFeignService transferFeignService;

    private static final PasswordEncoder ENCODER = new org.springframework.security.crypto.password.MessageDigestPasswordEncoder("MD5");


    private final SampleInboundRecordMapper recordMapper;

    //扫码查询
    @Override
    public List<CabinetSampleVO> scanCode(String number) {

        List<CabinetSampleVO> vo = openingRecordMapper.scanCode(number);

        if (vo == null || vo.size() == 0) {
            throw new RuntimeException("当前物品未查询出入库信息,请检查是否已入库");
        }
        String eventName = "";

        switch (vo.get(0).getSource()) {
            case "entrustment":
                //委托
                if (vo.get(0).getQuality() == 0.0) {
                    //没查询到就赋值现有质量
                    vo.get(0).setQuality(storageMapper.getQuality(vo.get(0).getSampleId()));
                }
                eventName = storageMapper.getEntrustmentName(vo.get(0).getSampleId());
                break;
            case "hairJob":
                //毛发
                eventName = storageMapper.getHairJobName(vo.get(0).getSampleId());
                break;
            case "sewageJob":
                //污水
                eventName = storageMapper.getSewageJobName(vo.get(0).getSampleId());
                break;
            case "internal":
                //内部录入
                eventName = storageMapper.getEventName(vo.get(0).getSampleId());
                break;
            default:
                //特征分析
                eventName = storageMapper.getFeatureName(vo.get(0).getSampleId());
                break;
        }
        //其他来源
        for (CabinetSampleVO cabinetSampleVO : vo) {
            cabinetSampleVO.setEventName(eventName);
        }
        
        
    /*    //判断当前是否存储
        QueryWrapper<SampleStorage> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("sample_id",vo.getSampleId());

        SampleStorage storage = storageMapper.selectOne(queryWrapper);
        if(storage==null || storage.getStatus()==3){
            //未入库
          vo.setIdentifying(false);
        } else {
            vo.setIdentifying(true);
            //为了返显库存位置
            vo.setStorageLocation(storage.getStorageLocation());
            vo.setCabinetName(storage.getCabinetName());
            vo.setStorageCellId(storage.getStorageCellId());
            vo.setBuildingLv(storage.getBuildingLv());
            vo.setBoxId(storage.getBoxId());
            vo.setRoomNo(storage.getRoomNo());
        }
*/
        return vo;
    }


    /*
    推荐入库
     */
    @Override
    @GlobalTransactional
    public void scanCodePromptInbound(DepositToDTO dto, DLPUser dlpUser) {
        List<SampleInfo> sampleInfo = dto.getSampleInfo();

        ArrayList<String> list = new ArrayList<>();

        String applyPerson = "无";

        for (SampleInfo sample : sampleInfo) {

            OutSampleVO sampleDetailInfo = storageMapper.getSampleById(sample.getSampleId());

            applyPerson = storageMapper.getUserName(sampleDetailInfo.getHolder());
            //先查询判断是不是第一次存储
            QueryWrapper<SampleStorage> queryWrapper = new QueryWrapper<>();
            queryWrapper.eq("sample_id", sample.getSampleId());
            SampleStorage storage = storageMapper.selectOne(queryWrapper);
            if (storage == null) {
                SampleStorage sampleStorage = new SampleStorage();
                sampleStorage.setId(IdWorker.get32UUID().toUpperCase());
                sampleStorage.setName(sample.getSampleName());
                sampleStorage.setSampleId(sample.getSampleId());
                sampleStorage.setStorageDate(LocalDateTime.now().plusYears(10));
                sampleStorage.setEarlyWarning(0);//暂时不销毁
                sampleStorage.setStatus(2);//已经入库
                sampleStorage.setDepositorId(dlpUser.getId());//存放人id
                sampleStorage.setInRepositoryDate(LocalDateTime.now());//入库时间
                sampleStorage.setSampleType(sampleDetailInfo.getSampleType());//A/B

                sampleStorage.setBuildingLv(dto.getBuildingLv());
                sampleStorage.setRoomNo(dto.getRoomNo());
                sampleStorage.setStorageCellId(dto.getCellId());
                sampleStorage.setCabinetName(dto.getCabinetName());
                sampleStorage.setBoxId(dto.getBoxId());
                sampleStorage.setStorageLocation(dto.getStorageLocation());

                //数据添加
                storageMapper.insert(sampleStorage);
            } else {
                if (storage.getStatus() == 2) {
                    throw new RuntimeException("当前:" + storage.getName() + "的样本已经入库,切勿重复入库");
                }
                storage.setStorageDate(LocalDateTime.now().plusYears(10));
                storage.setEarlyWarning(0);//暂时不销毁
                storage.setStatus(2);//已经入库
                storage.setDepositorId(dlpUser.getId());//存放人id
                storage.setInRepositoryDate(LocalDateTime.now());//入库时间

                storage.setBuildingLv(dto.getBuildingLv());
                storage.setRoomNo(dto.getRoomNo());
                storage.setStorageCellId(dto.getCellId());
                storage.setCabinetName(dto.getCabinetName());
                storage.setBoxId(dto.getBoxId());
                storage.setStorageLocation(dto.getStorageLocation());

                //数据修改
                storageMapper.updateById(storage);
            }

            //流转表
            transferFeignService.addTransferByInbound(sample.getSampleId(), dlpUser.getId());

            //持有人
            UpdateHolderDTO updateHolderDTO = new UpdateHolderDTO();
            updateHolderDTO.setHolder(dlpUser.getId());
            updateHolderDTO.setSampleId(sample.getSampleId());
            transferFeignService.updateSampleHolder(updateHolderDTO);


            //更新出入库登记表(这里因为只有入库,所以就创建部分数据;入库一定是添加数据)
            List<SampleInboundAndOutboundTable> tables = tableMapper.selectList(Wrappers.<SampleInboundAndOutboundTable>lambdaQuery().eq(SampleInboundAndOutboundTable::getSampleId, sample.getSampleId()).orderByDesc(SampleInboundAndOutboundTable::getCreateTime));
            //证明之前已经入库过了，我们将这个入库时间赋值到新增的出入库登记表中
            if (tables != null && tables.size() > 0) {
                SampleInboundAndOutboundTable sampleInboundAndOutboundTable = tables.get(0);
                if (sampleInboundAndOutboundTable.getReturnTime() == null) {
                    sampleInboundAndOutboundTable.setReturnTime(LocalDateTime.now());
                }
                tableMapper.updateById(sampleInboundAndOutboundTable);
                SampleInboundAndOutboundTable table = new SampleInboundAndOutboundTable();
                table.setWarehousingDate(LocalDateTime.now());//入库时间
                table.setId(IdWorker.get32UUID().toUpperCase());
                table.setImAdministrators(dto.getSupervisorId());
                table.setRecipient(sampleDetailInfo.getHolder());//持有人变入库人
                table.setRemarks("检材入库");
                table.setSampleId(sample.getSampleId());
                table.setInboundSupervisor(dto.getSupervisorId());//入库监督人
                tableMapper.insert(table);
            }
//                table.setWarehousingDate(sampleInboundAndOutboundTable.getWarehousingDate());//入库时间
            else {
                SampleInboundAndOutboundTable table = new SampleInboundAndOutboundTable();
                table.setWarehousingDate(LocalDateTime.now());//入库时间
                table.setId(IdWorker.get32UUID().toUpperCase());
                table.setImAdministrators(dto.getSupervisorId());
                table.setRecipient(sampleDetailInfo.getHolder());//持有人变入库人
                table.setRemarks("检材入库");
                table.setSampleId(sample.getSampleId());
                table.setInboundSupervisor(dto.getSupervisorId());//入库监督人
                tableMapper.insert(table);
            }


            //入库记录
            SampleInboundRecord record = new SampleInboundRecord();
            record.setId(IdWorker.get32UUID().toUpperCase());
            record.setWarehousingPersonId(dlpUser.getId());//入库人id
            record.setWarehousingDate(LocalDateTime.now());
            record.setImAdministrators(dlpUser.getId());
            record.setSampleId(sample.getSampleId());
            record.setName(sample.getSampleName());
            record.setRemarks("检材入库");
            recordMapper.insert(record);

            //3.b_sample样本状态为已入库
            transferFeignService.updateStatus(sample.getSampleId(), 2);

            list.add(sample.getSampleId());


            //修改质量
            openingRecordMapper.updateSampleQuality(sample.getSampleId()
                    , sample.getQuality());
        }


    /*
     柜子新接口
    */
        CellAndStoreSupplyData cellAndStoreSupplyData = new CellAndStoreSupplyData();
        cellAndStoreSupplyData.setCellId(dto.getCellId());//格子id
        cellAndStoreSupplyData.setCellStatus(dto.getCellStatus());//格子状态
        cellAndStoreSupplyData.setStoreSupplyList(list);//样本id

        //cabinetService.updateCabinet(dto.getCellId(),str,"1");
        ArrayList<CellAndStoreSupplyData> supplyData = new ArrayList<>();
        supplyData.add(cellAndStoreSupplyData);
        cabinetService.takeOrSaveGoodsFromCabinet(supplyData, 1);


    /*
    柜子开锁
     */
        ArrayList<String> cellIds = new ArrayList<>();
        cellIds.add(dto.getCellId());
        cabinetService.openCabinetCellByIds(cellIds);


    /*
    开箱记录
     */
        String userName = storageMapper.getUserName(dto.getSupervisorId());

        CabinetOpeningRecord record = new CabinetOpeningRecord();
        record.setId(IdWorker.get32UUID().

                toUpperCase());
        record.setOpenPurpose("检材入库");
        record.setApplyPerson(applyPerson);//申请人
        record.setOpenPerson(dlpUser.getName());
        record.setSupervisor(userName);
        record.setStorageLocation(dto.getStorageLocation());
        record.setOpenTime(LocalDateTime.now());
        record.setOpenType("扫码开箱");
        record.setWarehouse(dto.getRoomNo());//这里先赋值房间号
        openingRecordMapper.insert(record);

        /*
        开箱记录关联表
         */

    }


    //推荐出库(单个)
    @Override
    @GlobalTransactional
    public void scanCodePromptOutbound(UseOutboundDTO dto, DLPUser dlpUser) {


        QueryWrapper<SampleStorage> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("sample_id", dto.getSampleId());
        SampleStorage storage = storageMapper.selectOne(queryWrapper);

        OutSampleVO sampleDetailInfo = storageMapper.getSampleById(storage.getSampleId());

        //修改样本存储
        storage.setStatus(3);
        storage.setRecipientId(dlpUser.getId());//
        storage.setOutRepositoryDate(LocalDateTime.now());//出库时间
        storage.setIsReturn(-1);//不需要归还

        storageMapper.updateById(storage);

        //流转表
        transferFeignService.addTransferByOut(dto.getSampleId(), dlpUser.getId());

        //持有人
        UpdateHolderDTO updateHolderDTO = new UpdateHolderDTO();
        updateHolderDTO.setHolder(dlpUser.getId());
        updateHolderDTO.setSampleId(dto.getSampleId());
        transferFeignService.updateSampleHolder(updateHolderDTO);


        //2.修改样本出入库登记表--出库是修改操作先查询出sample对应的出入库登记表
        //程序文件中说明:检验时才填写出入库登记表
        QueryWrapper<SampleInboundAndOutboundTable> wrapper = new QueryWrapper<>();
        wrapper.eq("sample_id", dto.getSampleId());
        wrapper.isNull("out_warehouse_date");//出库日期的数据
        SampleInboundAndOutboundTable table = tableMapper.selectOne(wrapper);
        if (table != null) {
            table.setOutboundSupervisor(dto.getSupervisorId());//出库监督人
            table.setOutWarehouseDate(LocalDateTime.now());//出库时间
            tableMapper.updateById(table);
        }

        //2.出库记录
        SampleOutboundRecord sampleOutboundRecord = new SampleOutboundRecord();
        sampleOutboundRecord.setId(IdWorker.get32UUID().toUpperCase());
        sampleOutboundRecord.setOutboundType(OutboundType.SCANCODE);//扫码出库
        sampleOutboundRecord.setName(storage.getName());//样本名称--方便搜索
        sampleOutboundRecord.setRecipientId(dlpUser.getId());//领取人id
        sampleOutboundRecord.setSampleId(dto.getSampleId());


        //后面的备注--当前样本已经销毁"+"销毁单位:"+xxx
        sampleOutboundRecord.setReason("扫码单个出库");//把出库原因设置为备注
        sampleOutboundRecord.setOutboundDate(LocalDateTime.now());//出库时间
        outboundRecordMapper.insert(sampleOutboundRecord);

        //3.b_sample样本状态为出库
        transferFeignService.updateStatus(dto.getSampleId(), 1);


        ArrayList<String> list = new ArrayList<>();
        list.add(dto.getSampleId());

    /*
     柜子存储数据新接口
    */
        CellAndStoreSupplyData cellAndStoreSupplyData = new CellAndStoreSupplyData();
        cellAndStoreSupplyData.setCellId(storage.getStorageCellId());//格子id
        cellAndStoreSupplyData.setCellStatus("1");//格子状态
        cellAndStoreSupplyData.setStoreSupplyList(list);//样本id

        //cabinetService.updateCabinet(dto.getCellId(),str,"1");
        ArrayList<CellAndStoreSupplyData> supplyData = new ArrayList<>();
        supplyData.add(cellAndStoreSupplyData);
        cabinetService.takeOrSaveGoodsFromCabinet(supplyData, -1);


    /*
    柜子开锁
     */
        ArrayList<String> cellIds = new ArrayList<>();
        cellIds.add(storage.getStorageCellId());
        cabinetService.openCabinetCellByIds(cellIds);


    /*
    开箱记录
     */

        String userName = storageMapper.getUserName(dto.getSupervisorId());

        CabinetOpeningRecord record1 = new CabinetOpeningRecord();
        record1.setId(IdWorker.get32UUID().toUpperCase());
        record1.setOpenPurpose("检材出库");
        record1.setApplyPerson(dlpUser.getName());
        record1.setOpenPerson(dlpUser.getName());
        record1.setSupervisor(userName);
        record1.setStorageLocation(storage.getStorageLocation());
        record1.setOpenTime(LocalDateTime.now());
        record1.setOpenType("扫码开箱");
        record1.setWarehouse(storage.getRoomNo());//这里先赋值房间号
        openingRecordMapper.insert(record1);
        /*
        开箱记录关联表
         */
    }

    /*
    强制开箱
     */
    @Override
    @GlobalTransactional
    public void forceOpen(UseOutboundDTO dto, DLPUser dlpUser) {


     /*
    开箱记录
     */
        String userName = storageMapper.getUserName(dto.getSupervisorId());


        CabinetOpeningRecord record1 = new CabinetOpeningRecord();
        record1.setId(IdWorker.get32UUID().toUpperCase());
        record1.setOpenPurpose("检材出库");
        record1.setApplyPerson("无");
        record1.setOpenPerson(dlpUser.getName());
        record1.setSupervisor(userName);
        record1.setStorageLocation(dto.getLocation());
        record1.setOpenTime(LocalDateTime.now());
        record1.setOpenType("强制开箱");
        record1.setWarehouse(dto.getRoomNo());//这里先赋值房间号
        openingRecordMapper.insert(record1);

        ArrayList<String> cellIds = new ArrayList<>();

        //说明要开的柜子是改造柜，因为改造柜的柜子没有ID,所以我们要去获得柜子中某一个盒子的ID，用于开箱
        if (dto.getType() != null && dto.getType() == 3 && StrUtil.isNotBlank(dto.getCabinetId()) && dto.getNumber() != null) {

            try {
                R<String> data = cabinetService.getCellId(dto.getCabinetId(), dto.getNumber());
                String id = data.getData();
                cellIds.add(id);
                R r = cabinetService.openCabinetCellByIds(cellIds);
                boolean ret = (boolean) r.getData();
                if (!ret) {
                    throw new RuntimeException(String.format("开箱失败"));
                }
            } catch (Exception e) {
                e.printStackTrace();
                throw new RuntimeException(String.format("开箱失败"));
            }
        }
        //说明只想开柜子
        else {
            cellIds.add(dto.getCellId());
            R r = cabinetService.openCabinetCellByIds(cellIds);
            boolean ret = (boolean) r.getData();
            if (!ret) {
                throw new RuntimeException(String.format("开箱失败"));
            }
        }

    }


    //取检码查询
    @Override
    public List<CabinetSampleVO> querySampleByCode(String code, String roomNo) {
        //先通过取检码查询数据
        QueryWrapper<SampleOutWarehouseApply> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("sample_code_number", code);
        SampleOutWarehouseApply apply = outWarehouseApplyMapper.selectOne(queryWrapper);

        if (apply == null || apply.getStatus() != OutApplyStatus.SUCCESS) {
            throw new RuntimeException("当前取检码无效");
        }

        QueryWrapper<OutWarehouseDetailed> wrapper = new QueryWrapper<>();
        wrapper.eq("apply_id", apply.getId());
        List<OutWarehouseDetailed> detailedList = outWarehouseDetailedMapper.selectList(wrapper);

        List<CabinetSampleVO> sampleVOS = new ArrayList<>();
        for (OutWarehouseDetailed detailed : detailedList) {
            CabinetSampleVO vo = openingRecordMapper.getSampleById(detailed.getSampleId());
            if (!vo.getRoomNo().equals(roomNo)) {
                throw new RuntimeException("当前取检码只在:" + vo.getRoomNo() + "房间生效");
            }
            String eventName = "";
            switch (vo.getSource()) {
                case "entrustment":
                    //委托
                    eventName = storageMapper.getEntrustmentName(vo.getSampleId());
                    break;
                case "hairJob":
                    //毛发
                    eventName = storageMapper.getHairJobName(vo.getSampleId());
                    break;
                case "sewageJob":
                    //污水
                    eventName = storageMapper.getSewageJobName(vo.getSampleId());
                    break;
                case "internal":
                    //内部录入
                    eventName = storageMapper.getEventName(vo.getSampleId());
                    break;
                default:
                    //特征分析
                    eventName = storageMapper.getFeatureName(vo.getSampleId());
                    break;
            }
            //其他来源
            vo.setEventName(eventName);

            sampleVOS.add(vo);
            Collections.sort(sampleVOS, new Comparator<CabinetSampleVO>() {
                @Override
                public int compare(CabinetSampleVO o1, CabinetSampleVO o2) {
                    String[] split1 = o1.getSampleNo().split("-");
                    String[] split2 = o2.getSampleNo().split("-");
                    // 先比较年份
                    int yearComparison = split2[0].compareTo(split1[0]);
                    if (yearComparison != 0) {
                        return yearComparison;
                    }
                    // 再比较序号
                    int num1 = Integer.parseInt(split2[1]);
                    int num2 = Integer.parseInt(split1[1]);
                    if (num1 - num2 != 0) {
                        return num1 - num2;
                    }
                    // 再比较尾号
                    int num3 = Integer.parseInt(split1[2]);
                    int num4 = Integer.parseInt(split2[2]);
                    return num3 - num4;
                }
            });
        }

        return sampleVOS;
    }


    /*
    领用出库
     */
    @Override
    @GlobalTransactional
    public void useOutbound(UseOutboundDTO dto, DLPUser dlpUser) {
        //通过取检码查询数据
        //先通过取检码查询数据
        QueryWrapper<SampleOutWarehouseApply> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("sample_code_number", dto.getCode());
        SampleOutWarehouseApply apply = outWarehouseApplyMapper.selectOne(queryWrapper);

        //0.修改当前领用出库申请状态为已使用
        apply.setStatus(OutApplyStatus.ALREADY_USED);
        apply.setSampleCodeNumber(apply.getSampleCodeNumber() + "(已使用)");
        outWarehouseApplyMapper.updateById(apply);
        ArrayList<SampleStorage> storages = new ArrayList<>();

        //通过样本id循环查询并修改和改变其他逻辑

        ArrayList<String> cellIds = new ArrayList<>();

        for (String sampleId : dto.getSampleIds()) {

            QueryWrapper<SampleStorage> wrapper = new QueryWrapper<>();
            wrapper.eq("sample_id", sampleId);
            SampleStorage sample = storageMapper.selectOne(wrapper);
            storages.add(sample);

            if (!cellIds.contains(sample.getStorageCellId())) {

                cellIds.add(sample.getStorageCellId());
            }

            //修改样本存储
            sample.setStatus(3);
            sample.setRecipientId(dlpUser.getId());//领取人
            sample.setOutRepositoryDate(LocalDateTime.now());//出库时间
            sample.setIsReturn(1);//需要归还
            sample.setReturnTime(apply.getReturnDate());//归还时间
            sample.setPurpose(apply.getPurpose());//出库用途
            storageMapper.updateById(sample);


            //流转表
            transferFeignService.addTransferByInbound(sample.getSampleId(), dlpUser.getId());

            //持有人
            UpdateHolderDTO updateHolderDTO = new UpdateHolderDTO();
            updateHolderDTO.setHolder(dlpUser.getId());
            updateHolderDTO.setSampleId(sample.getSampleId());
            transferFeignService.updateSampleHolder(updateHolderDTO);


            //2.修改样本出入库登记表--出库是修改操作先查询出sample对应的出入库登记表
            //程序文件中说明:检验时才填写出入库登记表
            QueryWrapper<SampleInboundAndOutboundTable> wrapper1 = new QueryWrapper<>();
            wrapper1.eq("sample_id", sample.getSampleId());
            wrapper1.isNull("out_warehouse_date");//出库日期的数据
            SampleInboundAndOutboundTable table = tableMapper.selectOne(wrapper1);
            if (table != null) {
                table.setOutboundSupervisor(dto.getSupervisorId());//出库监督人
                table.setOutWarehouseDate(LocalDateTime.now());//出库时间
                table.setAppraiserId(dlpUser.getId());
                tableMapper.updateById(table);
            }

            //2.出库记录
            SampleOutboundRecord sampleOutboundRecord = new SampleOutboundRecord();
            sampleOutboundRecord.setId(IdWorker.get32UUID().toUpperCase());
            sampleOutboundRecord.setOutboundType(OutboundType.USE);//领用出库
            sampleOutboundRecord.setName(sample.getName());//样本名称--方便搜索
            sampleOutboundRecord.setRecipientId(dlpUser.getId());//领取人id
            sampleOutboundRecord.setSampleId(sample.getSampleId());

            //3.b_sample样本状态为已经出库
            transferFeignService.updateStatus(sample.getSampleId(), 1);

    /*
     柜子存储数据新接口
    */


        }
        ArrayList<CellAndStoreSupplyData> supplyData = new ArrayList<>();
        for (SampleStorage storage : storages) {
            ArrayList<String> strings = new ArrayList<>();
            CellAndStoreSupplyData cellAndStoreSupplyData = new CellAndStoreSupplyData();
            cellAndStoreSupplyData.setCellId(storage.getStorageCellId());//格子id
            cellAndStoreSupplyData.setCellStatus("1");//格子状态
            strings.add(storage.getSampleId());
            cellAndStoreSupplyData.setStoreSupplyList(strings);//样本id
            //cabinetService.updateCabinet(dto.getCellId(),str,"1");
            supplyData.add(cellAndStoreSupplyData);
        }
        cabinetService.takeOrSaveGoodsFromCabinet(supplyData, -1);

    /*
    柜子开锁
    这里要做cell的去重
     */
        cabinetService.openCabinetCellByIds(cellIds);

        String applyPerson = storageMapper.getUserName(apply.getApplicantId());

        for (String cellId : cellIds) {
            QueryWrapper<SampleStorage> wrapper = new QueryWrapper<>();
            wrapper.eq("storage_cell_id", cellId);
            List<SampleStorage> sampleStorages = storageMapper.selectList(wrapper);

   /*
    开箱记录
     */
            String userName = storageMapper.getUserName(dto.getSupervisorId());
            CabinetOpeningRecord record1 = new CabinetOpeningRecord();
            record1.setId(IdWorker.get32UUID().toUpperCase());
            record1.setOpenPurpose("检材出库");
            record1.setApplyPerson(applyPerson);
            record1.setOpenPerson(dlpUser.getName());
            record1.setSupervisor(userName);//监督人姓名
            record1.setStorageLocation(sampleStorages.get(0).getStorageLocation());
            record1.setOpenTime(LocalDateTime.now());
            record1.setOpenType("取检码开柜");
            record1.setWarehouse(sampleStorages.get(0).getRoomNo());//这里先赋值房间号
            openingRecordMapper.insert(record1);
        }

    }

    //批量入库查询接口
    @Override
    public List<CabinetSampleVO> batchScanCode(String number) {


        List<CabinetSampleVO> sampleVOS = openingRecordMapper.batchScanCode(number);


        if (sampleVOS == null || sampleVOS.size() == 0) {
            throw new RuntimeException("请检查当前样本是否为入库状态");
        }

        for (CabinetSampleVO vo : sampleVOS) {
            String eventName = "";
            switch (vo.getSource()) {
                case "entrustment":
                    //委
                    eventName = storageMapper.getEntrustmentName(vo.getSampleId());
                    if (vo.getQuality() == 0.0) {
                        //没查询到就赋值现有质量
                        vo.setQuality(storageMapper.getQuality(vo.getSampleId()));
                    }
                    break;
                case "hairJob":
                    //毛发
                    eventName = storageMapper.getHairJobName(vo.getSampleId());
                    break;
                case "sewageJob":
                    //污水
                    eventName = storageMapper.getSewageJobName(vo.getSampleId());
                    break;
                case "internal":
                    //内部录入
                    eventName = storageMapper.getEventName(vo.getSampleId());
                    break;
                default:
                    //特征分析
                    eventName = storageMapper.getFeatureName(vo.getSampleId());
                    break;
            }
            //其他来源
            vo.setEventName(eventName);
        }
        boolean isE = true;
        for (CabinetSampleVO sampleVO : sampleVOS) {
            if (!sampleVO.getSource().equals("entrustment")) {
                isE = false;
            }
        }
        if (isE) {
            Collections.sort(sampleVOS, new Comparator<CabinetSampleVO>() {
                @Override
                public int compare(CabinetSampleVO o1, CabinetSampleVO o2) {
                    String[] split1 = o1.getSampleNo().split("-");
                    String[] split2 = o2.getSampleNo().split("-");
                    // 先比较年份
                    int yearComparison = split2[0].compareTo(split1[0]);
                    if (yearComparison != 0) {
                        return yearComparison;
                    }
                    // 再比较序号
                    int num1 = Integer.parseInt(split2[1]);
                    int num2 = Integer.parseInt(split1[1]);
                    if (num1 - num2 != 0) {
                        return num1 - num2;
                    }
                    // 再比较尾号
                    int num3 = Integer.parseInt(split1[2]);
                    int num4 = Integer.parseInt(split2[2]);
                    return num3 - num4;
                }
            });
        }

        return sampleVOS;
    }

    //修改样本质量
    @Override
    public void updateSampleQuality(String sampleId, double sampleQuality) {
        openingRecordMapper.updateSampleQuality(sampleId, sampleQuality);
    }
}
