package com.youchain.appupdate.rest;

import cn.hutool.core.date.DateUtil;
import cn.hutool.json.JSONUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.youchain.annotation.AnonymousAccess;
import com.youchain.annotation.Log;
import com.youchain.appupdate.inputJson.*;
import com.youchain.appupdate.service.ContainerService;
import com.youchain.basicdata.domain.*;
import com.youchain.basicdata.repository.*;
import com.youchain.basicdata.service.ItemService;
import com.youchain.basicdata.service.PointService;
import com.youchain.basicdata.service.StockService;
import com.youchain.basicdata.service.dto.ItemDto;
import com.youchain.basicdata.service.dto.ItemQueryCriteria;
import com.youchain.businessdata.domain.*;
import com.youchain.businessdata.repository.AgvTaskRepository;
import com.youchain.businessdata.repository.InventoryRepository;
import com.youchain.businessdata.repository.TaskRepository;
import com.youchain.businessdata.service.*;
import com.youchain.businessdata.service.dto.InventoryDto;
import com.youchain.businessdata.service.mapstruct.InventoryMapper;
import com.youchain.exception.handler.ApiResult;
import com.youchain.modules.system.service.DictService;
import com.youchain.modules.system.service.dto.DictDto;
import com.youchain.modules.system.service.dto.DictQueryCriteria;
import com.youchain.utils.*;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.security.access.method.P;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.transaction.interceptor.TransactionAspectSupport;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.Arrays;
import java.util.Date;
import java.util.List;
import java.util.Map;

import static org.springframework.http.HttpStatus.BAD_REQUEST;
import static org.springframework.http.HttpStatus.OK;

@RestController
@RequiredArgsConstructor
@Api(tags = "app接口管理")
@RequestMapping("/api/appScene")
@Slf4j
public class SceneAppController {

    private final ItemService itemService;

    private final PointService pointService;
    private final TaskRepository taskRepository;
    private final BillTypeRepository billTypeRepository;
    private final InventoryLogService inventoryLogService;
    private final PointRepository pointRepository;
    private final StockService stockService;
    private final StockTypeRepository stockTypeRepository;
    private final BoxRepository boxRepository;

    private final DictService dictService;
    private final InventoryMapper inventoryMapper;
    private final AsnDetailService asnDetailService;
    private final PickDetailService pickDetailService;
    private final ItemKeyService itemKeyService;
    private final AgvTaskService agvTaskService;
    private final AgvTaskRepository agvTaskRepository;
    private final TaskService taskService;
    private final InventoryService inventoryService;
    private final ItemRepository itemRepository;
    private final InventoryRepository inventoryRepository;
    //容器出场和入场
    private final ContainerService containerService;
    private final ZcjxbRepository zcjxbRepository;
    @PostMapping("/pointStockBack")
    @Log("App接口》 容器出入场")
    @ApiOperation("容器出入场")
    @AnonymousAccess
    public ResponseEntity<Object> pointStockBack(@RequestBody JSONObject jsonObject) {
        String type = jsonObject.getString("type");
        String storageType = jsonObject.getString("code");
        String pointCode = jsonObject.getString("pointCode");
        Point point=pointRepository.findByCode(pointCode);
        ApiResult apiResult=ApiResult.success(OK.value(), "操作成功", "");
        if (type.equals("asn")) {
            apiResult = agvTaskService.pointStockRk(storageType, point.getId());
        }else if (type.equals("pick")){
            apiResult = agvTaskService.pointStockCk(storageType, point.getId());
        }
        return new ResponseEntity<>(apiResult, HttpStatus.valueOf(apiResult.getStatus()));
    }
    @PostMapping("/asn/rkReadRFID")
    @Log("app接口》成品/料箱 人工入库-读取RFID")
    @ApiOperation("成品/料箱 人工入库-读取RFID")
    @AnonymousAccess
    public ResponseEntity<Object> rkReadRFID(@RequestBody String data) {
        JSONObject jsonObject=JSONObject.parseObject(data);
        String rfid=jsonObject.getString("rfid");
        String type=jsonObject.getString("type");
        String pointType=jsonObject.getString("pointType");
        ApiResult apiResult;
        if (type.equals("ASN")){
            apiResult = taskService.devanRfidAsn(rfid,pointType);
        }else {
            apiResult = taskService.devanRfidPT(rfid);
        }
        return new ResponseEntity<>(apiResult, HttpStatus.valueOf(apiResult.getStatus()));
    }

    @PostMapping("/asn/rqRkSub")
    @Log("app接口》半成品/料箱 AGV入库-RFID容器入场")
    @ApiOperation("半成品/料箱 AGV入库-RFID容器入场")
    @AnonymousAccess
    public ResponseEntity<Object> rqRkSub(@RequestBody String data) {
        JSONObject jsonObject=JSONObject.parseObject(data);
        Long taskId=jsonObject.getLong("id");
        Box box=boxRepository.getById(taskId);
        // 根据点位 获取容器类型
        String stockType = BizStatus.getBillToAgv(box.getLampStatus());
        ApiResult apiResult;
        apiResult = agvTaskService.pointStockRk(stockType,box.getPoint().getId());
        Point pointEndCode=pointRepository.findByTypeAndArea(BaseStatus.PLATFORM,"TAGM");
        if (apiResult.getStatus()==200){
            apiResult = agvTaskService.addAgvTask(box.getPoint().getId(),pointEndCode.getCode());
        }
        return new ResponseEntity<>(apiResult, HttpStatus.valueOf(apiResult.getStatus()));
    }
    @PostMapping("/asn/RkSub")
    @Log("app接口》成品/料箱 人工入库-确定收货")
    @ApiOperation("成品/料箱 人工入库-确定收货")
    @AnonymousAccess
    public ResponseEntity<Object> rkSub(@RequestBody JSONObject request) {
        String rfid=request.getString("rfid");
        int agvFlag=request.getIntValue("agvFlag");
        Point point= pointRepository.findByName(request.getString("pointCode"));
        // 人工入库 直接生成库存
        ApiResult apiResult = taskService.manualReceiving(rfid,point,agvFlag);
        if (point.getType().equals(BaseStatus.BOX)){
            if (apiResult.getStatus()==200){
                // AGV入库 生成搬运任务（目标库区，单据任务类型）
                apiResult = agvTaskService.addAgvAsn(apiResult.getData().toString());
            }
        }

        return new ResponseEntity<>(apiResult, HttpStatus.valueOf(apiResult.getStatus()));
    }
    @PostMapping("/asn/sjTaskList")
    @Log("app接口》人工入库-料箱上架 查询待上架Task任务")
    @ApiOperation("人工入库-料箱上架 查询待上架Task任务")
    @AnonymousAccess
    public ResponseEntity<Object> sjTaskList(@RequestBody(required=false) String request) {
        List<Map<String, Object>> taskList;
        JSONObject requestJson=JSONObject.parseObject(request);
        String rfid=requestJson.getString("rfid");
        if (rfid.length()<1) {
            taskList = taskRepository.findBySjTask();
        }else {

            taskList = taskRepository.findBySjTask(rfid);
            // 人工入库 直接生成库存
            if (taskList==null||taskList.size()<1){
                ApiResult apiResult = ApiResult.fail(500,"为查询到数据",taskList);
                return new ResponseEntity<>(apiResult, HttpStatus.valueOf(apiResult.getStatus()));
            }
        }
        ApiResult apiResult = ApiResult.fail(200,"查询成功",taskList);
        return new ResponseEntity<>(apiResult, HttpStatus.valueOf(apiResult.getStatus()));
    }
    @PostMapping("/asn/rqRkList")
    @Log("app接口》半成品/料箱 AGV入库-人工入场点位配置")
    @ApiOperation("半成品/料箱 AGV入库-人工入场点位配置")
    public ResponseEntity<Object> rqRkList() {
        JSONArray jsonArray=new JSONArray();
        List<Box> boxList=boxRepository.getByEnabled(true);
        for (int i = 0; i < boxList.size(); i++) {
            JSONObject jsonObject=new JSONObject();
            Box box=boxList.get(i);
            BillType billType=billTypeRepository.findByCode(box.getLampStatus());
            if (billType!=null){
                jsonObject.put("stockTypeName", billType.getName());
            }
            jsonObject.put("pointName", box.getPoint().getCode());
            jsonObject.put("boxCode", box.getCode());
            if (box.getPoint().getStorageType()==null||box.getPoint().getStorageType().length()<1){
                jsonObject.put("status", "");
            }else {
                jsonObject.put("status", "占用");
            }
            jsonObject.put("id", box.getId());
            jsonArray.add(jsonObject);
        }

        ApiResult apiResult=ApiResult.fail(200,"查询成功",jsonArray);
        return new ResponseEntity<>(apiResult, HttpStatus.valueOf(apiResult.getStatus()));
    }
    @PostMapping("/asn/sjSub")
    @Log("app接口》AGV入库-料箱上架")
    @ApiOperation("AGV入库-料箱上架")
    @AnonymousAccess
    @Transactional
    public ResponseEntity<Object> sjSub(@RequestBody JSONObject request) {
        Long taskId=request.getLong("id");
        String pointCode=request.getString("endPointCode");
        Point point=pointRepository.findByCode(pointCode);
        ApiResult apiResult = taskService.butSTputaway(taskId,point.getId());
        return new ResponseEntity<>(apiResult, HttpStatus.valueOf(apiResult.getStatus()));
    }
    @PostMapping("/asn/bcpRgRkSub")
    @Log("半成品 人工入库-确定收货")
    @ApiOperation("半成品 人工入库-确定收货")
    @AnonymousAccess
    @Transactional
    public ResponseEntity<Object> bcpRgRkSub(@RequestBody JSONObject request) {
        Point point= pointRepository.findByCode(request.getString("pointCode"));
        if (point==null){
            ApiResult apiResult=ApiResult.fail(500,"点位错误","");
            return new ResponseEntity<>(apiResult, HttpStatus.valueOf(apiResult.getStatus()));
        }
        int agvFlag=request.getIntValue("agvFlag");
        JSONArray tableList=request.getJSONArray("tableList");
        int apiCode=200;
        JSONArray apiData=new JSONArray();
        for (int i = 0; i < tableList.size(); i++) {
            JSONObject tableSize=tableList.getJSONObject(i);
            String rfid=tableSize.getString("rfid");
            //如果物料不是半成品
            String itemCode=rfid.substring(0, 9);
            Item item=itemRepository.findByCode(itemCode);

            String id = tableSize.getString("id");
            String status = tableSize.getString("status");
            ApiResult apiResult;
            JSONObject data = new JSONObject();
            data.put("id", id);
            data.put("rfid", rfid);
            if (!item.getGoodType().equals(BizStatus.BCP)){
                apiResult=ApiResult.fail(500,"非半成品",null);
                System.out.println();
            }else {
                apiResult = taskService.manualReceiving(rfid, point, agvFlag);
            }
            data.put("status", apiResult.getMessage());
            if (apiResult.getStatus()!=200){
                apiCode=500;
            }
            apiData.add(data);
        }
        String msg="解析完成-操作成功";
        if (apiCode!=200){
            msg="解析完成-操作失败";
            //回滚
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
//            apiCode=200;
        }
        ApiResult apiResult=ApiResult.fail(apiCode,msg,apiData);
        return new ResponseEntity<>(apiResult, HttpStatus.valueOf(apiResult.getStatus()));
    }
    @PostMapping("/asn/bcpRgRkTjPoint")
    @Log("半成品人工入库-推荐库位")
    @ApiOperation("半成品人工入库-推荐库位")
    @AnonymousAccess
    @Transactional
    public ResponseEntity<Object> bcpRgRkTjPoint(@RequestBody JSONObject request) {
        String type=request.getString("type");
        ApiResult apiResult;
        JSONObject data = new JSONObject();
        if (type.equals(BizStatus.BCP)) {
            List<Point> pointEndList = pointRepository.findByAreaCode(BizStatus.BCP);
            if (pointEndList.size() < 1) {
                data.put("pointCode", "");
                apiResult = ApiResult.fail(200, "没有推荐库位", data);
            } else {
                data.put("pointCode", pointEndList.get(0).getCode());
                apiResult = ApiResult.fail(200, "操作成功", data);
            }
        }else {
            apiResult=ApiResult.fail(500,"参数错误",null);
        }
        return new ResponseEntity<>(apiResult, HttpStatus.valueOf(apiResult.getStatus()));
    }
    @PostMapping("/pick/rfJhTaskList")
    @Log("app接口》人工拣货 查询已分配Task任务")
    @ApiOperation("人工拣货 查询已分配Task任务")
    @AnonymousAccess
    public ResponseEntity<Object> rfJhTaskList(@RequestBody(required=false) String request) {
        List<Map<String, Object>> taskList;
        JSONObject requestJson=JSONObject.parseObject(request);
        String rfid=requestJson.getString("rfid");
        if (rfid.length()<1) {
            taskList = taskRepository.findByRgJhTask(null);
        }else {
            taskList = taskRepository.findByRgJhTask(rfid);
            // 人工入库 直接生成库存
            if (taskList==null||taskList.size()<1){
                ApiResult apiResult = ApiResult.fail(500,"未查询到数据",taskList);
                return new ResponseEntity<>(apiResult, HttpStatus.valueOf(apiResult.getStatus()));
            }
        }
        ApiResult apiResult = ApiResult.fail(200,"查询成功",taskList);
        return new ResponseEntity<>(apiResult, HttpStatus.valueOf(apiResult.getStatus()));
    }
    @PostMapping("/pick/lxJhTaskList")
    @Log("app接口》料箱拣货 查询料箱拣货Task任务")
    @ApiOperation("人工拣货 查询已分配Task任务")
    @AnonymousAccess
    public ResponseEntity<Object> lxJhTaskList(@RequestBody(required=false) String requestText) {
        JSONObject request=JSONObject.parseObject(requestText);
        String rfid=request.getString("rfid")+"";
        List<Map<String, Object>> taskList;
        if (rfid.length()<1) {
            taskList = taskRepository.findByLxJhTask(null);
        }else {
            taskList = taskRepository.findByLxJhTask(rfid);
            if (taskList==null||taskList.size()<1){
                ApiResult apiResult = ApiResult.fail(500,"未查询到数据",taskList);
                return new ResponseEntity<>(apiResult, HttpStatus.valueOf(apiResult.getStatus()));
            }
        }
        ApiResult apiResult = ApiResult.fail(200,"查询成功",taskList);
        return new ResponseEntity<>(apiResult, HttpStatus.valueOf(apiResult.getStatus()));
    }
    @PostMapping("/pick/rfJhSub")
    @Log("app接口》人工拣货-拣货确认")
    @ApiOperation("人工拣货-拣货确认")
    @AnonymousAccess
    public ResponseEntity<Object> rfJhSub(@RequestBody(required=false) JSONObject request) {
        JSONArray jsonArray=request.getJSONArray("ids");
        Long[] taskId = new Long[jsonArray.size()];
        for (int i = 0; i < jsonArray.size(); i++) {
            taskId[i]=jsonArray.getLong(i);
        }
        ApiResult apiResult=taskService.picking(taskId);
        return new ResponseEntity<>(apiResult, HttpStatus.valueOf(apiResult.getStatus()));
    }
    @PostMapping("/inv/subInvPoint")
    @Log("app接口》库存-更新点位")
    @ApiOperation("库存-库存查询")
    @AnonymousAccess
    public ResponseEntity<Object> subInvPoint(@RequestBody(required=false) String requestText) {
        JSONObject request=JSONObject.parseObject(requestText);
        Long invId=request.getLong("id");
        String pointCode=request.getJSONObject("point").getString("code");
        Point point=pointRepository.findByCode(pointCode);
        ApiResult apiResult;
        if (point.getStorageType()==null){
            apiResult = ApiResult.fail(500, "请先做容器入场", "");
        }else {
            Inventory inventory = inventoryService.editInvPoint(invId,point);
            if (inventory.getQueuedQty()<1){
                apiResult = ApiResult.fail(200, "修改成功", "");
            }else {
                apiResult = ApiResult.fail(500, "库存被占用", "");
            }
        }
        return new ResponseEntity<>(apiResult, HttpStatus.valueOf(apiResult.getStatus()));
    }
    @PostMapping("/inv/thInvList")
    @Log("app接口》库存查询")
    @ApiOperation("拣货-库存查询")
    @AnonymousAccess
    public ResponseEntity<Object> thInvList(@RequestBody(required=false) JSONObject request) {
        String msg="";
        List<Inventory> inventoryList;
        if (request==null) {
            inventoryList = inventoryRepository.findAll();
            msg="全部库存";
        }else {
            String type=request.getString("type");
            String rfid=request.getString("rfid");
//            String param=request.getString("param");
            if (type.equals("query")){
                inventoryList=inventoryRepository.findByParam(rfid);
                msg="查询成功";
            }else {
                inventoryList = inventoryRepository.findByItemKeyC7(rfid);
                // 人工入库 直接生成库存
                if (inventoryList == null || inventoryList.size() < 1) {
                    ApiResult apiResult = ApiResult.fail(500, "未查询到数据", inventoryList);
                    return new ResponseEntity<>(apiResult, HttpStatus.valueOf(apiResult.getStatus()));
                }
                Inventory inventory = inventoryList.get(0);
                if (type.equals("startInv")) {
                    if (inventory.getQueuedQty() < 1) {
                        ApiResult apiResult = ApiResult.fail(500, "未分配", null);
                        return new ResponseEntity<>(apiResult, HttpStatus.valueOf(apiResult.getStatus()));
                    } else if (inventory.getPoint().getStatus().equals(BaseStatus.USED)) {
                        ApiResult apiResult = ApiResult.fail(500, "搬运中", null);
                        return new ResponseEntity<>(apiResult, HttpStatus.valueOf(apiResult.getStatus()));
                    }
                    msg = "被替换库存";
                } else if (type.equals("endInv")) {
                    if (inventory.getQueuedQty() > 0 || inventory.getPoint().getStatus().equals(BaseStatus.USED)) {
                        ApiResult apiResult = ApiResult.fail(500, "库存已被占用或搬运任务未完成", null);
                        return new ResponseEntity<>(apiResult, HttpStatus.valueOf(apiResult.getStatus()));
                    }
                    msg = "替换库存";
                }
            }
        }
        ApiResult apiResult=ApiResult.fail(200,msg,inventoryList);
        return new ResponseEntity<>(apiResult, HttpStatus.valueOf(apiResult.getStatus()));
    }
    @PostMapping("/inv/ctInv")
    @Log("app接口》拆托")
    @ApiOperation("拣货-拆托")
    @AnonymousAccess
    @Transactional
    public ResponseEntity<Object> ctInv(@RequestBody(required=false) JSONObject request) {
        JSONArray invIds=request.getJSONArray("invIds");//invIds
        String rfid1=request.getString("rfid1");//
        String rfid2=request.getString("rfid2");//
        if (rfid1.equals(rfid2)){
            ApiResult apiResult=ApiResult.fail(500,"拆托后两个RFID信息重复",null);
            return new ResponseEntity<>(apiResult, HttpStatus.valueOf(apiResult.getStatus()));
        }

        Point point = null;
        for (int i = 0; i < invIds.size(); i++) {
            long invId=invIds.getLong(i);
            Inventory startInventory=inventoryRepository.getById(invId);
            if (point==null){
                point=startInventory.getPoint();
            }
            InventoryDto inventoryDto= inventoryMapper.toDto(startInventory);
            inventoryRepository.delete(startInventory);
            // 添加删除 日志
            inventoryLogService.storeInventoryLog(BizStatus.MODIFY_LOT,BizStatus.REDUCE,inventoryDto.getItemKey().getPropC3(),inventoryDto.getItemKey(),point,null,null,null,inventoryDto.getQuantity(),inventoryDto.getQuantity(), inventoryDto.getItemKey().getPropC6(),null,inventoryDto.getId(),inventoryDto.getDescription());
            // 库存调整反馈
            UrlApi.invBackSap(inventoryDto.getOwner(), inventoryDto.getItemKey().getItem().getCode(),0+""
                    , inventoryDto.getQuantity()+"",inventoryDto.getZtBid(),inventoryDto.getProdMtrl(),inventoryDto.getDescription());
        }
        // 解析RFID信息
        if (rfid1!=null&&!rfid1.equals("null")) {
            Inventory inventory1 = getApiResult(rfid1);
            inventory1.setPoint(point);
            inventoryRepository.save(inventory1);
            // 库存调整反馈
            UrlApi.invBackSap(inventory1.getOwner(), inventory1.getItemKey().getItem().getCode(),inventory1.getQuantity()+""
                    , 0+"",inventory1.getZtBid(),inventory1.getProdMtrl(),inventory1.getDescription());
        }
        if (rfid2!=null&&!rfid2.equals("null")) {
            Inventory inventory2 = getApiResult(rfid2);
            // 库存调整反馈
            UrlApi.invBackSap(inventory2.getOwner(), inventory2.getItemKey().getItem().getCode(),inventory2.getQuantity()+""
                    , 0+"",inventory2.getZtBid(),inventory2.getProdMtrl(),inventory2.getDescription());
        }
        ApiResult apiResult=ApiResult.fail(200,"操作成功",null);
        return new ResponseEntity<>(apiResult, HttpStatus.valueOf(apiResult.getStatus()));
    }
    private Inventory getApiResult(String rfid1) {
        String itemCode=rfid1.substring(0, 9);
        Item item=itemRepository.findByCode(itemCode);

        String propC1=rfid1.substring(9, 11);
        String propC2=rfid1.substring(11, 13);
        String propC3=rfid1.substring(13, 19);// 系统单号
        String propC4=rfid1.substring(19, 20);//供货商
        String propC5=rfid1.substring(20, 24);//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;//成品收货-成品码终止码
        // 更新当前点位 存储容器状态
        String storageType=item.getGoodType();
        if (item.getGoodType().equals(BizStatus.CP)) {
            String tzm=rfid1.substring(24,28);//特征码
            String sm=rfid1.substring(28,50);//始码
            String zm=rfid1.substring(50,72);//止码
            xs = Integer.parseInt(rfid1.substring(72, 74));//箱数
            xs_start_d = Double.valueOf(rfid1.substring(74,78));//成品包装箱起始码
            xs_end_d = Double.valueOf(rfid1.substring(78,82));//成品包装箱终止码
            xs_d = Integer.parseInt(propC5, 16) / xs;//单箱数量
            propC6Title= sm.substring(0, 6);
            propC6_start_d=Long.valueOf(sm.substring(6, sm.length()-1));//起始成品码
            propC6_end_d=Long.valueOf(zm.substring(6, zm.length()-1));//终止成品码
            propC6.append(propC6Title+propC6_start_d+"-"+propC6Title+propC6_end_d);
            String endm = rfid1.substring(82,86);//结束吗
            //成品容器类型 入库
            storageType=BizStatus.CTP_STO;
        } else {
            String lshBf=rfid1.substring(24,rfid1.length());
            int decimalMin = Integer.parseInt("0001", 16);//流水号范围
            int decimalMax = Integer.parseInt("EA60", 16);//流水号范围
            for (int i = 0; i < lshBf.length(); i++) {
                String lsh=lshBf.substring(i,i+4);
                int decimalNumber = Integer.parseInt(lsh, 16);
                if (decimalNumber >= decimalMin && decimalNumber <= decimalMax) {
                    if (propC6.length() < 1) {
                        propC6.append(lsh);
                    } else {
                        propC6.append(",");
                        propC6.append(lsh);
                    }
                } else {
                    System.out.println("无效RFID:" + lsh);
                }
                i=i+4;
            }
            //半成品 入库
            storageType=BizStatus.TP_STO;
        }

        ItemKey itemKeyRfid1 = itemKeyService.getItemKey(item, propC1, propC2, propC3, propC4, propC5, propC6.toString(), rfid1);
        int qty = Integer.parseInt(propC5, 16);//单箱数量
        Inventory inventoryRfid1 = inventoryService.getInventory(Double.valueOf(qty), itemKeyRfid1.getId(), null,BizStatus.MODIFY_LOT);
        return inventoryRfid1;
    }
    @PostMapping("/sto/getStockType")
    @AnonymousAccess
    public ResponseEntity<Object> getStockType() {
        List<StockType> stockTypeList=stockTypeRepository.findAll();
        ApiResult apiResult = ApiResult.fail(200,"加载完成",stockTypeList);
        return new ResponseEntity<>(apiResult, HttpStatus.valueOf(apiResult.getStatus()));
    }

    @PostMapping("/pick/thInvSub")
    @Log("app接口》拣货-确认替换分配库存")
    @ApiOperation("拣货-确认替换分配库存")
    @AnonymousAccess
    public ResponseEntity<Object> thInvSub(@RequestBody(required=false) String text) {
        JSONArray request=JSONObject.parseObject(text).getJSONArray("datas");
        Long startId=null;
        Long endId=null;
        for (int i = 0; i < request.size(); i++) {
            String type=request.getJSONObject(i).getString("type");
            if (type.equals("startInv")){
                startId=request.getJSONObject(i).getLong("id");
            }else {
                endId=request.getJSONObject(i).getLong("id");
            }
        }
        List<Task> task=taskRepository.findByInv(startId);
        ApiResult apiResult;
        /** 取消分配库存 */
        apiResult = pickDetailService.cancelAllocate(task.get(0).getPickDetail().getId(),task.get(0).getInventory().getQuantity());
        if (apiResult.getStatus()!=200){
            return new ResponseEntity<>(apiResult, HttpStatus.valueOf(apiResult.getStatus()));
        }
        /** 重新分配 */
        Inventory inventory=inventoryRepository.getById(endId);
        Point point=pointRepository.findByCode(task.get(0).getPickDetail().getPropC5());
        List<Inventory> inventoryList= Arrays.asList(inventory);
        int agvFlag=0;
        if (task.get(0).getPickDetail().getPropC4().equals("AGV_PT")){
            agvFlag=1;
        }
        apiResult = pickDetailService.allocate(task.get(0).getPickDetail(), UserUtils.getDept(), inventory.getQuantity(),agvFlag,point,inventoryList);
        if (apiResult==null){
            apiResult=ApiResult.fail(200,"替换成功",null);
        }
        return new ResponseEntity<>(apiResult, HttpStatus.valueOf(apiResult.getStatus()));
    }
    @PostMapping("/pick/lxJhSub")
    @Log("app接口》出库-料箱拣货")
    @ApiOperation("出库-料箱拣货")
    @AnonymousAccess
    public ResponseEntity<Object> lxJhSub(@RequestBody(required=false) JSONObject request) {
        JSONArray taskIds=request.getJSONArray("ids");
        /** AGV料箱出库生成AgvTask*/
        ApiResult apiResult = taskService.rmCkPickUp(taskIds);
        return new ResponseEntity<>(apiResult, HttpStatus.valueOf(apiResult.getStatus()));
    }









    @PostMapping("/zCBindingItem")
    @Log("轴承座机械臂换邦物料")
    @ApiOperation("轴承座机械臂换邦物料")
    @AnonymousAccess
    public ResponseEntity<Object> zCBindingItem(@RequestBody ZCBindingMaterial zcBindingMaterial){
        //查询该物料是否存在
        ItemQueryCriteria itemQueryCriteria = new ItemQueryCriteria();
        itemQueryCriteria.setName("轴承座");
        itemQueryCriteria.setCode(zcBindingMaterial.getModbusTcpItem());
        List<ItemDto> itemDtos = itemService.queryAll(itemQueryCriteria);
        if (itemDtos.isEmpty()){
            return new ResponseEntity<>(ApiResult.fail(BAD_REQUEST.value(), "物料号输入错误", ""), HttpStatus.BAD_REQUEST);
        }
        //修改物料
        zcjxbRepository.updateZCJItem(zcBindingMaterial.getModbusTcpItem(),zcBindingMaterial.getCode());
        return new ResponseEntity<>(ApiResult.success(OK.value(), "物料更换成功!", ""), HttpStatus.OK);
    }
    @PostMapping("/fullStockIn")
    @Log("满车入库")
    @ApiOperation("满车入库")
    @AnonymousAccess
    public ResponseEntity<Object> fullStockIn(@RequestBody FullStockIn bi) {
        String agvScene = bi.getAgvScene();
        String itemCode = bi.getItemCode();//物料编号
        String pointCode = bi.getPointCode();
        String stockCode = bi.getStockCode();
        int checkCode = bi.getCheckCode();
        String endArea = "";
        String srcArea = "";
        String agv_on_off = "OFF";
        //判断满车入库是否全填完   判断是不是轴承卓空车点直接入的
        if (agvScene.equals("ZC") && itemCode != null && (pointCode != null && pointCode.length() > 0)) {//判断是否是轴承座的满车入库
            Point point = pointService.getPoint(pointCode, null, null, srcArea);
            //判断是人拉过去的还是呼叫空车过去的
            if (point.getStatus().equals(BaseStatus.FREE)) {
                Boolean b = this.stockOutIn(stockCode, pointCode);
                if (!b) {
                    return new ResponseEntity<>(ApiResult.fail(BAD_REQUEST.value(), "容器出场再入场失败", ""), HttpStatus.BAD_REQUEST);
                }
            }
        }
        agv_on_off = dictService.getDictDescription("agv_on_off") == null ? "OFF" : dictService.getDictDescription("agv_on_off").getDescription();
        Item item = itemService.existItem(itemCode);
        if (item == null) {
            return new ResponseEntity<>(ApiResult.fail(BAD_REQUEST.value(), "物料不存在!", ""), HttpStatus.BAD_REQUEST);
        } else if (checkCode == 1) {
            return new ResponseEntity<>(ApiResult.success(OK.value(), "校验成功!", ""), HttpStatus.OK);
        }
        if (agvScene.equals("ZC")) {
            if (!item.getGoodType().equals("ZC")) {
                return new ResponseEntity<>(ApiResult.fail(BAD_REQUEST.value(), "物料不属于轴承座!", ""), HttpStatus.BAD_REQUEST);
            }
            srcArea = AreaNameDic.ZCFB;
            endArea = AreaNameDic.ZCM;
        } else if (agvScene.equals("MF")) {
            if (!item.getGoodType().equals("MF")) {
                return new ResponseEntity<>(ApiResult.fail(BAD_REQUEST.value(), "物料不属于门封!", ""), HttpStatus.BAD_REQUEST);
            }
            srcArea = AreaNameDic.MFJB;
            endArea = AreaNameDic.MFM;
        }

        Stock stock = stockService.findByCode(stockCode, null);
        if (stock == null) {
            return new ResponseEntity<>(ApiResult.fail(BAD_REQUEST.value(), "容器不存在!", ""), HttpStatus.BAD_REQUEST);
        } else if (stock.getPoint() == null) {
            return new ResponseEntity<>(ApiResult.fail(BAD_REQUEST.value(), "容器未入场!", ""), HttpStatus.BAD_REQUEST);
        } else if (checkCode == 2) {
            return new ResponseEntity<>(ApiResult.success(OK.value(), "校验成功!", ""), HttpStatus.OK);
        }
        Point srcPoint = pointService.getPoint(pointCode, null, null, srcArea);
        if (srcPoint == null) {
            return new ResponseEntity<>(ApiResult.fail(BAD_REQUEST.value(), pointCode + "没有料车!", ""), HttpStatus.BAD_REQUEST);
        } else if (!stock.getPoint().getCode().equals(pointCode)) {
            return new ResponseEntity<>(ApiResult.fail(BAD_REQUEST.value(), "点位和容器不匹配!", ""), HttpStatus.BAD_REQUEST);
        }
        Point endPoint = pointService.getPoint(null, BaseStatus.FREE, null, endArea);
        if (endPoint == null) {
            return new ResponseEntity<>(ApiResult.fail(BAD_REQUEST.value(), endArea + "无空闲点位!", ""), HttpStatus.BAD_REQUEST);
        }
        //生成搬运任务
        AgvTask agvTask = new AgvTask(BizStatus.ASN, stock.getCode(), pointCode, endPoint.getCode(), BizStatus.OPEN, "RACK_MOVE");
        agvTaskService.create(agvTask);
        String code = "0";
        String message = null;
        if (agv_on_off.equals("ON")) {
            String resultJson = agvTaskService.sendAgvTaskImpl(agvTask);//发送任务
//            String resultJson =  "{\n" +
//                    "  \"data\": null,\n" +
//                    "  \"code\": 0,\n" +
//                    "  \"message\": null,\n" +
//                    "  \"success\": true\n" +
//                    "}";//发送任务
            JSONObject resulObject = JSON.parseObject(resultJson);
            code = resulObject.getString("code") == null ? "" : resulObject.getString("code");
            message = resulObject.getString("message") == null ? "" : resulObject.getString("message");
        }
        if (code.equals("0")) {
           /* //终点占用
            endPoint.setStatus(BaseStatus.USED);
            pointService.update(endPoint);
            //生成入库任务
            Date date = cn.hutool.core.date.DateUtil.date();
            String propC1 = DateUtil.format(date, "yyyyMMdd");
            AsnDetail asnDetail = asnDetailService.createAsnDetail(item, stock, srcPoint, propC1, null);
            //生成Itemkey
            ItemKey itemKey = itemKeyService.getItemKey(item, asnDetail.getPropC1(), asnDetail.getOrderNumber());
            //生成入库记录
            Task task = new Task(item, itemKey, asnDetail.getOrderNumber(), BizStatus.ASN, asnDetail, null, null, null, stock, stock, srcPoint, endPoint, stock.getCode(), stock.getCode(), srcPoint.getCode(), endPoint.getCode(), null, BizStatus.OPEN, asnDetail.getOrderQty(), null, null, item.getDept(), agvTask);
            taskService.create(task);*/
        } else {
            return new ResponseEntity<>(ApiResult.fail(BAD_REQUEST.value(), message, ""), HttpStatus.BAD_REQUEST);
        }
        return new ResponseEntity<>(ApiResult.success(OK.value(), "入库成功!", ""), HttpStatus.OK);
    }

    @PostMapping("/fullStockOut")
    @Log("满车出库")
    @ApiOperation("满车出库")
    @AnonymousAccess
    public ResponseEntity<Object> fullStockOut(@RequestBody FullStockOut bi) {
        String itemCode = bi.getItemCode();
        String pointCode = bi.getPointCode();
        String agvScene = bi.getAgvScene();
        int checkCode = bi.getCheckCode();
        String agv_on_off = "OFF";
        agv_on_off = dictService.getDictDescription("agv_on_off") == null ? "OFF" : dictService.getDictDescription("agv_on_off").getDescription();
        String endArea = "";
        String srcArea = "";
        Item item = itemService.existItem(itemCode);
        if (item == null) {
            return new ResponseEntity<>(ApiResult.fail(BAD_REQUEST.value(), "物料不存在!", ""), HttpStatus.BAD_REQUEST);
        } else if (checkCode == 1) {
            return new ResponseEntity<>(ApiResult.success(OK.value(), "校验成功!", ""), HttpStatus.OK);
        }
        if (agvScene.equals(BizStatus.ZC)) {
            if (!item.getGoodType().equals(BizStatus.ZC)) {
                return new ResponseEntity<>(ApiResult.fail(BAD_REQUEST.value(), "物料不属于轴承座!", ""), HttpStatus.BAD_REQUEST);
            }
            endArea = AreaNameDic.ZCJXB;
            srcArea = AreaNameDic.ZCM;
        } else if (agvScene.equals("MF")) {
            if (!item.getGoodType().equals("MF")) {
                return new ResponseEntity<>(ApiResult.fail(BAD_REQUEST.value(), "物料不属于门封!", ""), HttpStatus.BAD_REQUEST);
            }
            endArea = "门封出库缓存区";
            srcArea = "门封满车区";
        }
        Point endPoint = pointService.getPoint(pointCode, null, null, endArea);
        if (endPoint == null) {
            return new ResponseEntity<>(ApiResult.fail(BAD_REQUEST.value(), pointCode + "点位错误!", ""), HttpStatus.BAD_REQUEST);
        } else if (endPoint.getStatus().equals(BaseStatus.USED)) {
            return new ResponseEntity<>(ApiResult.fail(BAD_REQUEST.value(), pointCode + "点位被占用!", ""), HttpStatus.BAD_REQUEST);
        }
        List<Inventory> inventoryList = inventoryService.queryInventory(item.getId());
        if (inventoryList.size() == 0) {
            return new ResponseEntity<>(ApiResult.fail(BAD_REQUEST.value(), itemCode + "无库存!", ""), HttpStatus.BAD_REQUEST);
        } else {
            PickDetail pickDetail = pickDetailService.createPickDetail(item, null);
            try {
                pickDetailService.allocateAll(pickDetail.getId(), endPoint);
            } catch (Exception e) {
                return new ResponseEntity<>(ApiResult.fail(BAD_REQUEST.value(), e.getMessage(), ""), HttpStatus.BAD_REQUEST);
            }
            List<Task> taskList = taskService.getPickNotAllTask(pickDetail.getId());
            AgvTask agvTask = taskList.get(0).getAgvTask();
            String code = "0";
            String message = null;
            if (agv_on_off.equals("ON")) {
                String resultJson = agvTaskService.sendAgvTaskImpl(agvTask);//发送任务
                JSONObject resulObject = JSON.parseObject(resultJson);
                code = resulObject.getString("code") == null ? "" : resulObject.getString("code");
                message = resulObject.getString("message") == null ? "" : resulObject.getString("message");
            }
            if (code.equals("0")) {
                endPoint.setStatus(BaseStatus.USED);
                pointService.update(endPoint);
            } else {
                throw new RuntimeException(message);
            }
        }
        return new ResponseEntity<>(ApiResult.success(OK.value(), "出库成功!", ""), HttpStatus.OK);
    }


    @PostMapping("/pointCallStock")
    @Log("容器搬运")
    @AnonymousAccess
    public ResponseEntity<Object> pointCallStock(@RequestBody JSONObject jsonObject) {
        System.out.println("容器搬运"+jsonObject);
        String pointEndCode = jsonObject.getString("pointCode");
        JSONArray ids=jsonObject.getJSONArray("ids");
        ApiResult apiResult = null;
        for (int i = 0; i < ids.size(); i++) {
            Long id=ids.getLong(i);
            apiResult = agvTaskService.addAgvTask(id,pointEndCode);
        }
        return new ResponseEntity<>(apiResult, HttpStatus.valueOf(apiResult.getStatus()));
    }


    public Boolean stockOutIn(String stockCode, String pointCode) {//容器出场再入场
        Stock stock = stockService.findByCode(stockCode, null);
        //容器出场
        ContainerIn containerIn = new ContainerIn();
        containerIn.setContainerCode(stockCode);
        containerIn.setPosition(stock.getPoint().getCode());
        //xyjAppController.containerOut(containerIn);
        if (!containerService.ContainerOut(containerIn)){
            log.error("容器出场失败");
            return false;
        }
        //容器容器入场
        ContainerIn containerIn1 = new ContainerIn();
        containerIn1.setContainerCode(stockCode);
        containerIn1.setPosition(pointCode);
        //xyjAppController.containerIn(containerIn1);
        if (!containerService.ContainerIn(containerIn1)){
            log.error("容器入场失败");
            return false;
        }
        Point point = pointService.getPoint(pointCode, null, null, null);
        point.setStatus(BaseStatus.USED);
        pointService.update(point);
        return true;
    }
}
