/*
 *  Copyright 2019-2020 Zheng Jie
 *
 *  Licensed under the Apache License, Version 2.0 (the "License");
 *  you may not use this file except in compliance with the License.
 *  You may obtain a copy of the License at
 *
 *  http://www.apache.org/licenses/LICENSE-2.0
 *
 *  Unless required by applicable law or agreed to in writing, software
 *  distributed under the License is distributed on an "AS IS" BASIS,
 *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 *  See the License for the specific language governing permissions and
 *  limitations under the License.
 */
package com.youchain.businessdata.service.impl;

import cn.hutool.core.bean.BeanUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.youchain.basicdata.domain.Item;
import com.youchain.basicdata.domain.Point;
import com.youchain.basicdata.domain.Stock;
import com.youchain.basicdata.repository.ItemRepository;
import com.youchain.basicdata.repository.PointRepository;
import com.youchain.basicdata.repository.StockRepository;
import com.youchain.basicdata.service.dto.StockSmallDto;
import com.youchain.businessdata.ReturnJson.RPTaskList;
import com.youchain.businessdata.domain.*;
import com.youchain.businessdata.inputJson.IPTask;
import com.youchain.businessdata.repository.*;
import com.youchain.businessdata.service.*;
import com.youchain.businessdata.service.dto.InventoryDto;
import com.youchain.exception.handler.ApiResult;
import com.youchain.modules.system.domain.Dept;
import com.youchain.utils.*;
import lombok.RequiredArgsConstructor;
import com.youchain.businessdata.service.dto.TaskDto;
import com.youchain.businessdata.service.dto.TaskQueryCriteria;
import com.youchain.businessdata.service.mapstruct.TaskMapper;
import lombok.extern.slf4j.Slf4j;
import org.checkerframework.checker.units.qual.A;
import org.hibernate.SQLQuery;
import org.hibernate.transform.AliasToEntityMapResultTransformer;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.transaction.interceptor.TransactionAspectSupport;

import java.security.PrivateKey;
import java.util.*;
import java.io.IOException;
import javax.persistence.EntityManager;
import javax.persistence.Query;
import javax.servlet.http.HttpServletResponse;

/**
 * @author houjianlan
 * @website https://eladmin.vip
 * @description 服务实现
 * @date 2023-08-16
 **/
@Service
@RequiredArgsConstructor
@Slf4j
@Transactional
public class TaskServiceImpl implements TaskService {

    private final TaskRepository taskRepository;
    private final TaskMapper taskMapper;
    private final AsnRepository asnRepository;
    private final InventoryRepository inventoryRepository;
    private final InventoryService inventoryService;
    private final PickDetailRepository pickDetailRepository;
    private final AsnDetailRepository asnDetailRepository;
    private final AsnDetailService asnDetailService;
    private final InventoryLogService inventoryLogService;
    private final EntityManager entityMapper;
    private  final StockRepository stockRepository;
    private  final PointRepository pointRepository;
    private  final ItemRepository itemRepository;
    private  final ItemKeyRepository itemKeyRepository;
    private  final ItemKeyService itemKeyService;
    @Override
    public Map<String, Object> queryAll(TaskQueryCriteria criteria, Pageable pageable) {
        Page<Task> page = taskRepository.findAll((root, criteriaQuery, criteriaBuilder) -> QueryHelp.getPredicate(root, criteria, criteriaBuilder), pageable);
        return PageUtil.toPage(page.map(taskMapper::toDto));
    }

    @Override
    public List<TaskDto> queryAll(TaskQueryCriteria criteria) {
        return taskMapper.toDto(taskRepository.findAll((root, criteriaQuery, criteriaBuilder) -> QueryHelp.getPredicate(root, criteria, criteriaBuilder)));
    }

    @Override
    @Transactional
    public TaskDto findById(Long id) {
        Task task = taskRepository.findById(id).orElseGet(Task::new);
        ValidationUtil.isNull(task.getId(), "Task", "id", id);
        return taskMapper.toDto(task);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public TaskDto create(Task resources) {
        return taskMapper.toDto(taskRepository.save(resources));
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void update(Task resources) {
        Task task = taskRepository.findById(resources.getId()).orElseGet(Task::new);
        ValidationUtil.isNull(task.getId(), "Task", "id", resources.getId());
        task.copy(resources);
        taskRepository.save(task);
    }

    @Override
    public void deleteAll(Long[] ids) {
        for (Long id : ids) {
            taskRepository.deleteById(id);
        }
    }

    @Override
    public void download(List<TaskDto> all, HttpServletResponse response) throws IOException {
        List<Map<String, Object>> list = new ArrayList<>();
        for (TaskDto task : all) {
            Map<String, Object> map = new LinkedHashMap<>();
            map.put("序号", task.getId());
            map.put("物料编码", task.getItemKey().getItem().getCode());
            map.put("物料名称", task.getItemKey().getItem().getName());
            map.put("容器编号", task.getSrcStock()==null?"":task.getSrcStock().getCode());
            map.put("原点位", task.getSrcPointCode());
            map.put("目标点位", task.getDstPointCode());
            map.put("任务状态", task.getTaskStatus());
            map.put("计划数量", task.getPlanQty());
            map.put("移位数量", task.getMoveQty());
            map.put("创建人", task.getCreateBy());
            map.put("创建时间", task.getCreateTime());
            list.add(map);
        }
        FileUtil.downloadExcel(list, response);
    }

    @Override
    public Task toEntity(TaskDto taskDto) {
        return taskMapper.toEntity(taskDto);
    }

    @Override
    public Task storeTask() {
        return null;
    }

    @Override
    public List<Task> getPickNotAllTask(Long id) {
        return taskRepository.getPickNotAllTask(id);
    }

    @Override
    public List<Task> getPickAllTask(Long id) {
        return taskRepository.getPickAllTask(id);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public synchronized void pickConfirm(long taskId, double pickedQuantity) throws Exception {
        if (taskId > 0) {
            TaskDto taskDto = findById(taskId);
            Task task = taskMapper.toEntity(taskDto);//Dto转实体
            if (task.getPlanQty() > task.getMoveQty()) {
                PickDetail pickDetail = task.getPickDetail();
                task.setMoveQty(pickedQuantity);
                task.setTaskStatus(BizStatus.FINISH);
                taskRepository.save(task);
                Inventory inv = inventoryRepository.findById(task.getInventory().getId()).get();
                if (inv != null) {
                    ItemKey itemKey = inv.getItemKey();
                    Item item = itemKey.getItem();
                    Dept dept = item.getDept();
                    double srcQty=inv.getQuantity();
                    inv.setQuantity(inv.getQuantity() - pickedQuantity);
                    inv.setQueuedQty(inv.getQueuedQty() - pickedQuantity);
                    inventoryRepository.save(inv);
                    if(inv.getQuantity()<=0){
                        inventoryRepository.delete(inv);
                    }
                    Stock stock=inv.getStock();
                    stock.setStatus(BaseStatus.FREE);
                    stockRepository.save(stock);
                    //添加库存日志
                    inventoryLogService.storeInventoryLog(BizStatus.PICK_DOWN,BizStatus.REDUCE,task.getPickDetail().getPo(),task.getItemKey(),task.getSrcPoint(),task.getDstPoint(),task.getSrcStock(),task.getDstStock(),srcQty,pickedQuantity, BizStatus.PICK,task.getId(),inv.getId(),"");

                    //刷新出库明细上的拣货数量
                    pickDetail.setPickedQty(pickDetail.getPickedQty() + pickedQuantity);
                    if (pickDetail.getOrderQty().equals(pickDetail.getPickedQty())) {
                        pickDetail.setStatus(BizStatus.PICK_ALL);
                    } else if (pickDetail.getAllocatedQty() > 0 && pickDetail.getOrderQty() - pickDetail.getPickedQty() > 0) {
                        pickDetail.setStatus(BizStatus.PICKUP);
                    }
                    pickDetailRepository.save(pickDetail);

                } else {
                    throw new RuntimeException("未找到库存相应记录！");
                }
            }

        } else {
            throw new RuntimeException("参数错误或为空");
        }
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public synchronized void pickBarBack(long taskId, double pickedQuantity) throws Exception {
        if (taskId > 0) {
            TaskDto taskDto = findById(taskId);
            Task task = taskMapper.toEntity(taskDto);//Dto转实体
            PickDetail pickDetail = task.getPickDetail();
            Inventory inv = inventoryRepository.findById(task.getInventory().getId()).get();
            if (inv != null) {
                //退回库存
                double srcQty=inv.getQueuedQty();
                inv.setQueuedQty(inv.getQueuedQty()+pickedQuantity);
                inv.setQuantity(inv.getQuantity()+pickedQuantity);
                inventoryRepository.save(inv);

                //添加库存日志
                inventoryLogService.storeInventoryLog(BizStatus.PICK_CANCEL,BizStatus.ADD,task.getPickDetail().getPo(),task.getItemKey(),task.getDstPoint(),task.getSrcPoint(),task.getSrcStock(),task.getDstStock(),srcQty,pickedQuantity, BizStatus.PICK,task.getId(),inv.getId(),"");


                //退回Task
                task.setMoveQty(task.getMoveQty() - pickedQuantity);
                taskRepository.save(task);

                //退回出库明细
                pickDetail.setPickedQty(pickDetail.getPickedQty() - pickedQuantity);
                if (pickDetail.getPickedQty() == 0) {
                    pickDetail.setStatus(BizStatus.ALLOCATE);
                }
                pickDetailRepository.save(pickDetail);
            } else {
                throw new RuntimeException("未找到库存相应记录！");
            }

        } else {
            throw new RuntimeException("参数错误或为空");
        }
    }

    @Transactional(readOnly = true)
    public  List<RPTaskList> queryTaskApp(IPTask t){
        String sql="SELECT t.pick_detail_id pickDetailId, it.code itemCode,it.`name` itemName,t.plan_qty qty,ik.prop_c1 pch,t.src_point_code srcPointCode,t.src_stock_code stockCode,t.dst_point_code dstPointCode\n" +
                " from data_task t\n" +
                "left join data_pick_detail d on t.pick_detail_id=d.id\n" +
                "left join data_item_key ik on ik.id=t.item_key_id\n" +
                "left join base_item it on it.id=ik.item_id\n" +
                "where d.`status`='ALLOCATE' \n" +
                "ORDER BY it.code";
        List ts= entityMapper.createNativeQuery(sql)
                .unwrap(SQLQuery.class)
                .setResultTransformer(
                        AliasToEntityMapResultTransformer.INSTANCE
                )
                .list();
        log.error(JSON.toJSONString(ts));
        List<RPTaskList> l = JSON.parseArray(JSON.toJSONString(ts),RPTaskList.class);
        return  l;
    }

    @Override
    public List<Task> findByPointCode(Long pointId) {
        String hql=" from Task t where t.dstPoint.id="+pointId+" and t.moveQty=0 ";
        Query query=entityMapper.createQuery(hql);
        List<Task> taskList=query.getResultList();
        return taskList;
    }

    @Override
    @Transactional
    public ApiResult readRfid(String rfid,String type) {
        String[] rfids=rfid.split("\\|");
        String itemCode=rfids[0]+"";
        String propC1=rfids[1]+"";
        String propC2=rfids[2]+"";
        String propC3=rfids[3]+"";// 系统单号
        String propC4=rfids[4]+"";
        String propC5=rfids[5]+"";//16进制 供货数量
        StringBuffer propC6 = new StringBuffer();//流水号
        StringBuffer propC7 = new StringBuffer();//成品物料码
        int xs = 0;//成品收货-箱数
        int xs_d = 0;//成品收货-单箱数量
        Double xs_start_d = 0d;//成品收货-起始箱码
        Double xs_end_d=0d;//成品收货-终止箱码
        String propC6Title=null;//成品收货-成品码抬头
        Long propC6_start_d = 0l;//成品收货-成品码起始码
        Long propC6_end_d=0l;//成品收货-成品码终止码
        Asn asn=asnRepository.findByRelatedBill1(propC3);
        if (asn==null){
            return ApiResult.result(201, "没有入库单", "");
        }else {
            if (!asn.getStatus().equals(BizStatus.RECEIVING)&&!asn.getStatus().equals(BizStatus.ACTIVE)){
                return ApiResult.result(500, "入库单未激活", "");
            }
        }
        if (asn.getBillType().getCode().equals(BizStatus.FC_RK)){
            propC6Title=rfids[7].substring(0, 6);
            propC6_start_d=Long.valueOf(rfids[7].substring(6, rfids[7].length()-1));//起始成品码
            propC6_end_d=Long.valueOf(rfids[8].substring(6, rfids[8].length()-1));//终止成品码
            propC6.append(propC6Title+propC6_start_d+"-"+propC6Title+propC6_end_d);
            /*for (Long i = propC6_start_d; i < propC6_end_d; i++) {
                if (propC6.length()<1){
                    propC6.append(propC6Title+i);
                }else {
                    propC6.append(","+propC6Title+i);
                }
            }*/
            xs = Integer.parseInt(rfids[9], 16);//箱数
            xs_start_d = Double.valueOf(rfids[10]);//料箱起始码
            xs_end_d = Double.valueOf(rfids[11]);//料箱终止码
            xs_d = Integer.parseInt(propC5, 16) / xs;//单箱数量
        }else {
            for (int i = 6; i < rfids.length; i++) {
                int decimalNumber = Integer.parseInt(rfids[i], 16);
                int decimalMin = Integer.parseInt("0001", 16);
                int decimalMax = Integer.parseInt("EA60", 16);
                if (decimalNumber >= decimalMin && decimalNumber <= decimalMax) {
                    if (propC6.length() < 1) {
                        propC6.append(rfids[i]);
                    } else {
                        propC6.append(",");
                        propC6.append(rfids[i]);
                    }
                } else {
                    System.out.println("无效RFID:" + rfids[i]);
                }
            }
        }

        Item item=itemRepository.findByCode(itemCode);
        if (item==null){
            return ApiResult.result(500, "没有物料", "");
        }
        if (itemKeyRepository.getByItemKey(item.getId(),propC1,propC2,propC3,propC4,propC5,propC6.toString())!=null){
            return ApiResult.result(500, "重复读取", "");
        };

        ItemKey itemKey=itemKeyService.getItemKey(item, propC1, propC2,propC3,propC4,propC5,propC6.toString(),rfid);
        //获取流水号
        String[] lsh=itemKey.getPropC6().split(",");
        int taskSum=0;// 生成task数量
        if (asn.getBillType().getCode().equals(BizStatus.FC_RK)){
            taskSum = xs;//按 料箱数量生成task
        }else {
            if (lsh.length!=itemKey.getIntPropC5()){
                TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
                return ApiResult.result(500, "流水号数量和供货数量不一致", "");
            }
            taskSum = lsh.length;//按 流水号数量生成task
        }
        for (int i = 0; i < taskSum; i++) {
            Task task = new Task();
            if (asn.getBillType().getCode().equals(BizStatus.FC_RK)){
                task.setPlanQty((double) xs_d);//单箱数量
                StringBuffer putCode=new StringBuffer();
                for (int j = 0; j < xs_d; j++) {
                    if (putCode.length()<1){
                        putCode.append(propC6Title+(propC6_start_d+j));
                    }else {
                        putCode.append(","+propC6Title+(propC6_start_d+j));
                    }
                }
                propC6_start_d=propC6_start_d+xs_d;
                task.setPutCode(putCode.toString());//箱内 流水号
                task.setSrcStockCode((xs_start_d+i)+"");
            }else {
                task.setPlanQty(1d);
                task.setPutCode(lsh[i]);
            }
            task.setItemKey(itemKey);
            task.setDept(UserUtils.getDept());
            task.setTaskStatus(BizStatus.RECEIVING);
            if (type.equals("AGV")) {
                task.setBeSkip(1);
            } else if (type.equals("RG")) {
                task.setBeSkip(0);
            }
            task.setBillCode(propC3);
            task.setTaskType(asn.getBillType().getCode());
            Point startPoint = pointRepository.findByTypeAndArea(BaseStatus.PLATFORM, item.getGoodType());
            task.setSrcPoint(startPoint);
            taskRepository.save(task);
        }
        return ApiResult.result(200, "操作成功", asn.getBillType().getCode());
    }

    @Override
    public ApiResult manualReceiving(JSONObject request) {
        String rfid=request.getString("RFID");
        Point point= pointRepository.getById(request.getLong("pointId"));
        // 读取RFID生成Task
        String billTypeCode="";//单据类型
        ApiResult apiResult = readRfid(rfid, "RG");
        if (apiResult.getStatus()!=200){
            return apiResult;
        }else {
            if (apiResult.getStatus()==200){
                billTypeCode=apiResult.getData()+"";
            }
        }
        // 分配Task库位
        List<Task> taskList=taskRepository.findByItemType(BizStatus.RECEIVING,0,billTypeCode);
        for (int i = 0; i < taskList.size(); i++) {
            Task task=taskList.get(i);
            ApiResult api = getAsnTask(point, task);
            taskRepository.save(task);
        }
        // 生成库存
        List<Map<String,Object>> taskMapList=taskRepository.findByAgvTask(null,billTypeCode,0l);
        Inventory inventory = inventoryService.asnAddInventory(taskMapList);
        // 更新当前点位 存储容器状态 ###
        point.setStorageType(inventory.getItemKey().getItem().getGoodType());
        if (point.getStatus().equals(BaseStatus.USED)){
            point.setStatus(BaseStatus.FREE);
        }else {
            // 人工入库没有选中推荐库位，清除一个库位的占用状态
            List<Point> pointList=pointRepository.findByAreaCodeCp(inventory.getItemKey().getItem().getGoodType(),BaseStatus.USED);
            for (int i = 0; i < pointList.size(); i++) {
                Point pointUsed =pointList.get(0);
                if (point.getHeat()==null||point.getHeat()==1){
                    //浅位 直接取消
                    pointUsed.setStatus(BaseStatus.FREE);
                }else {
                    // 深位，查询浅位是否空闲
                    List<Point> pointListQ=pointRepository.findByBeatCode(point.getBeatCode(),point.getHeat());
                    if (pointListQ.size()>0){
                        // 浅位空闲
                        continue;
                    }else {
                        pointUsed.setStatus(BaseStatus.FREE);
                    }
                }
                pointRepository.save(pointUsed);
                break;
            }
        }
        pointRepository.save(point);
        return ApiResult.result(200, "操作成功", "");
    }

    public List<Object[]> queryAreaMonth(String type) {
        List<Object[]> taskList=null;
        String hql = "";
        if(type.equals("IN")){
            hql += " select t.dstPoint.area.name,count(t.id) from Task t where  t.dstPoint.area.name in ('"+AreaNameDic.QHTL+"','"+AreaNameDic.QHTK+"','"+AreaNameDic.ZCK+"','"+AreaNameDic.ZCM+"')";
            hql+=" and t.asnDetail.id is not null ";
            hql+=" group by  t.dstPoint.area.name";
        }else if(type.equals("OUT")){
            hql += " select t.srcPoint.area.name,count(t.id) from Task t where  t.srcPoint.area.name in ('"+AreaNameDic.QHTL+"','"+AreaNameDic.QHTK+"','"+AreaNameDic.ZCK+"','"+AreaNameDic.ZCM+"')";
            hql+=" and t.pickDetail.id is not null ";
            hql+=" group by  t.srcPoint.area.name";
        }
        Query query = entityMapper.createQuery(hql);
        taskList = query.getResultList();
        return taskList;
    }

    public List<Object[]> queryAreaDay(String type,String zoneType) {
        List<Object[]> taskList=null;
        String hql = "select count(t.id),CAST(sum(t.moveQty) as integer )from Task t where 1=1";
        if(type.equals("IN")){
            if(zoneType.equals("ZC")) {
                hql += " and t.dstPoint.area.name in ('" + AreaNameDic.ZCM + "')";
            }
            hql+=" and t.asnDetail.id is not null ";
        }else if(type.equals("OUT")){
            if(zoneType.equals("ZC")) {
                hql += " and t.srcPoint.area.name in ('" + AreaNameDic.ZCM + "')";
            }
            hql+=" and t.pickDetail.id is not null ";
        }
        hql += " and DATE_FORMAT(t.createTime,'%Y-%m-%d')=DATE_FORMAT(now(),'%Y-%m-%d')";
        Query query = entityMapper.createQuery(hql);
        taskList = query.getResultList();
        return taskList;
    }

    public ApiResult getAsnTask(Point point, Task task) {
        task.setDstPoint(point);
        task.setMoveQty(task.getPlanQty());
        List<AsnDetail> asnDetailList=asnDetailRepository.findByAsnAndItem(task.getBillCode(), task.getItemKey().getItem().getCode());
        if (asnDetailList.size()>0){
            AsnDetail asnDetail=asnDetailList.get(0);
            asnDetailService.receivingAsnDetail(asnDetail, task.getMoveQty());
        }else {
            return ApiResult.success(500, "收货单异常！！", "");
        }
        return null;
    }

    @Override
    public ApiResult picking(Long[] ids) {
        List<Task> taskList=new ArrayList<>();
        for (int i = 0; i < ids.length; i++) {
            Long id=ids[i];
            Task task=taskRepository.getById(id);
            taskList.add(task);
        }
        inventoryService.pickDelInventory(taskList);
        return ApiResult.fail(200,"操作成功","");
    }

    @Override
    public ApiResult devanRfidAsn(String rfid) {
        String[] rfids=rfid.split("\\|");
        JSONObject data=new JSONObject();
        if (rfids.length>4){
            String sku=rfids[0]+"";//sku
            String propC1=rfids[1]+"";
            String propC2=rfids[2]+"";
            String propC3=rfids[3]+"";// 系统单号
            String propC5=rfids[5]+"";// 收货数量（16禁止）

            Asn asn=asnRepository.findByRelatedBill1(propC3);
            if (asn!=null){
                if (asn.getBillType().getCode().equals(BizStatus.FC_RK)){
                    // 成品入库
                    if (rfids.length==13){
                        data.put("relatedBill1",asn.getRelatedBill1());
                        data.put("relatedBill2",asn.getRelatedBill2());
                        data.put("billType",asn.getBillType());
                        data.put("sku",sku);
                        List<AsnDetail> asnDetailList = asnDetailRepository.findByAsnAndItem(asn.getRelatedBill1(),sku);
                        double orderQty=0;
                        for (int i = 0; i < asnDetailList.size(); i++) {
                            orderQty=orderQty+asnDetailList.get(i).getOrderQty();
                        }
                        data.put("lineNos",asnDetailList.size());
                        data.put("RFID",rfid);
                        data.put("orderQty",orderQty);
                        data.put("billCode",BizStatus.CP);
                        data.put("receivedQty",Integer.parseInt(propC5, 16));
                    }else {
                        return ApiResult.fail(400,"rfid长度不为13","");
                    }
                }
            }else {
                return ApiResult.fail(400,"未查询到系统单号","");
            }
        }
        return ApiResult.fail(200,"操作成功",data);
    }

    @Override
    public ApiResult devanRfidPT(String rfid) {
        String[] rfids=rfid.split("\\|");
        JSONObject data=new JSONObject();
        if (rfids.length>4) {
            String sku = rfids[0] + "";//sku
            String propC1 = rfids[1] + "";
            String propC2 = rfids[2] + "";
            String propC3 = rfids[3] + "";// 系统单号
            String propC4 = rfids[4] + "";// 厂家代码
            String propC5 = rfids[5] + "";// 收货数量（16禁止）
            Item item=itemRepository.findByCode(sku);
            if (item==null){
                return ApiResult.fail(400,"没有找到物料",null);
            }
            if (item.getGoodType().equals(BizStatus.CP)){
                String propC7=rfids[7].substring(0, rfids[7].length()-1);//起始成品码
                String propC8=rfids[8].substring(0, rfids[8].length()-1);//终止成品码
                // 成品解析
                ItemKey itemKey=itemKeyRepository.getByItemKey(item.getId(),propC1,propC2,propC3,propC4,propC5,propC7+"-"+propC8);
                if (itemKey==null){
                    return ApiResult.fail(400,"没有找到RFID码对应的库存",null);
                }
                Inventory inventory=inventoryRepository.findByItemKey(itemKey.getId());
                if (inventory==null){
                    return ApiResult.fail(500,"库存异常",null);
                }
                List<Task> taskList=taskRepository.findByItemKey(itemKey.getId(), BizStatus.ALLOCATE);
                if (taskList.size()!=1){
                    return ApiResult.fail(500,"Task异常",null);
                }
                Task task=taskList.get(0);
                PickDetail pickDetail=task.getPickDetail();
                Pick pick=pickDetail.getPick();
                if (inventory.getQueuedQty()<=0){
                    // 未占用库存 询问是否更改出库库存
                }else {
                    // 已占用库存 推荐库存
                    data.put("relatedBill1",pick.getRelatedBill1());
                    data.put("relatedBill2",pick.getRelatedBill2());
                    data.put("billType",pick.getBillType());
                    data.put("sku",sku);
                    data.put("lineNo",pickDetail.getLineNo());
                    data.put("RFID",rfid);
                    data.put("taskId",task.getId());
                    data.put("orderQty",pickDetail.getOrderQty());
                    data.put("receivedQty",inventory.getQueuedQty());
                }
            }else if (item.getGoodType().equals(BizStatus.BCP)){

            }else if (item.getGoodType().equals(BizStatus.LX)){
                // 料箱解析
            }else {
                return ApiResult.fail(400,"请维护物料类型，无法识别解析方式",null);
            }
        }
        return ApiResult.fail(200, "操作成功", data);
    }
}
