QisdaDeviceController.java 44.2 KB
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038
package com.myproject.webapp.controller.webService;

import com.myproject.bean.CodeBean;
import com.myproject.bean.qisda.*;
import com.myproject.bean.update.AlarmInfo;
import com.myproject.bean.update.Barcode;
import com.myproject.bean.update.DataLog;
import com.myproject.bean.update.Storage;
import com.myproject.bean.update.qisda.OutInfo;
import com.myproject.bean.update.qisda.OutItem;
import com.myproject.dao.mongo.IAlarmInfoDao;
import com.myproject.dao.mongo.IDataLogDao;
import com.myproject.dao.mongo.IStoragePosDao;
import com.myproject.dao.mongo.qisda.IOutInfoDao;
import com.myproject.dao.mongo.qisda.IOutItemDao;
import com.myproject.exception.ValidateException;
import com.myproject.manager.IBarcodeManager;
import com.myproject.manager.IComponentManager;
import com.myproject.util.QisdaApi;
import com.myproject.util.StorageConstants;
import com.myproject.webapp.controller.qisda.util.OutInfoCache;
import com.myproject.webapp.controller.storage.BaseController;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.apache.logging.log4j.util.Strings;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import java.util.*;
import java.util.concurrent.ConcurrentHashMap;


@Controller
@RequestMapping("/rest/api/qisda/device")
public class QisdaDeviceController extends BaseController {

    @Autowired
    protected ITaskService taskService;

    @Autowired
    protected IComponentManager componentManager;

    @Autowired
    private IBarcodeManager barcodeManager;

    @Autowired
    private DataCache dataCache;

    @Autowired
    private IDataLogDao dataLogDao;

    @Autowired
    private OutInfoCache outInfoCache;

    @Autowired
    private IAlarmInfoDao alarmInfoDao;

    protected final static Logger log = LogManager.getLogger(QisdaDeviceController.class);

    /**
     * 第一台机器人缓存位置信息(流水线扫码后获取尺寸时更新)
     */
    private DataLog firstRobotTask = null;

    private DataLog firstScanTask = null;
    /**
     * 第二台机器人缓存位置信息(流水线扫码后获取尺寸时更新)
     */
    private DataLog secondRobotTask = null;

    private DataLog secondScanTask = null;

    /**
     * 流水线根据条码及机器人工位获取尺寸信息,同时为料盘锁定架位
     */
    @RequestMapping(value = "/getSize")
    @ResponseBody
    public ResultBean getSize(HttpServletRequest request) {
        try{
            String robotIndex = request.getParameter("robotIndex");
            String barcodeStr = request.getParameter("barcode");
            log.info("料盘到达机器人["+robotIndex+"]扫码位置,开始获取["+ barcodeStr +"]的尺寸信息");
            if(robotIndex == null){
                return ResultBean.newErrorResult(-2, "参数错误:无robotIndex参数");
            }
            if(!robotIndex.equals("1") && !robotIndex.equals("2")){
                return ResultBean.newErrorResult(-2, "参数错误:robotIndex参数只能为1或2");
            }

            //清空扫码缓存信息
            updateScanTask(robotIndex, null);

            //Barcode barcode = dataCache.resolveOneValideBarcode(barcodeStr);

            Collection<CodeBean> codeBeans = dataCache.resolveCodeStr(barcodeStr);
            Barcode barcode = null;
            for (CodeBean codeBean : codeBeans) {
                if(codeBean.isValid()){
                    if(barcode != null){
                        String msg = "找到多个有效条码";
                        throw new ValidateException(msg);
                    }else{
                        barcode = codeBean.getBarcode();
                    }

                }
            }
            if(barcode == null){
                String msg = "未找到有效条码";
                throw new ValidateException(msg);
            }

            DataLog task = taskService.getFinishedTask(barcode.getBarcode());

            if(task == null){
                String msg = "未找到待分配位置的条码["+barcode.getBarcode()+"]尺寸信息";
                return ResultBean.newErrorResult(103, msg);
            }else{
                if(task.isFinished()){
                    String msg = "条码["+barcode.getBarcode()+"]的任务已完成,不返回尺寸信息";
                    return ResultBean.newErrorResult(104, msg);
                }else if(task.isStopSendToQisda()){
                    //被取消的出库任务,不可再放上料架
                    String msg = "条码["+barcode.getBarcode()+"]的任务已被取消,不返回尺寸信息";
                    return ResultBean.newErrorResult(107, msg);
                }else {
                    String hSerial = task.getAppendInfo().gethSerial();
                    String executingHSerial = QisdaCache.getCurrentOrderHSerial();
                    if(!executingHSerial.equals(hSerial)){
                        String msg = "料盘["+barcode.getBarcode()+"]任务的需求单号与当前正在执行的需求单号不一致,不返回尺寸信息";
                        return ResultBean.newErrorResult(106, msg);
                    }
                    boolean firstRobtoSame = isSameTask(barcode,firstRobotTask);
                    boolean secondRobtoSame = isSameTask(barcode,secondRobotTask);
                    if (firstRobtoSame || secondRobtoSame){
                        String msg = "机器人正在将料盘["+barcode.getBarcode()+"]的放上料架,不返回尺寸信息";
                        return ResultBean.newErrorResult(107, msg);
                    }
                }
            }

            updateScanTask(robotIndex, task);

            log.info("返回机器人["+robotIndex+"]barcode=["+task.getBarcode()+"]的尺寸:" + task.getW());
            return ResultBean.newOkResult(task.getW() + "");

        }catch(ValidateException e){
            log.warn("流水线获取尺寸信息出错:"+e.getMessage());
            return ResultBean.newErrorResult(105,"流水线获取尺寸信息错误:" + e.getMessage());
        }catch(Exception e){
            log.error("流水线获取尺寸信息出错",e);
            return ResultBean.newErrorResult(-1,"流水线获取尺寸信息内部错误:" + e.getMessage());
        }
    }

    /**
     * 更新相机扫码任务
     * @param robotIndex
     * @param task
     */
    private void updateScanTask(String robotIndex, DataLog task){
        if(robotIndex != null){
            if(robotIndex.equals("1")){
                //1号位机器人
                firstScanTask = task;
            }else if(robotIndex.equals("2")){
                secondScanTask = task;
            }
        }
    }

    /**
     * 判断条码是否与扫码和机器人工位的条码一致
     * @return
     */
    private boolean isSameTask(Barcode barcode, DataLog robotTask){
        if(barcode != null && robotTask != null){
            return barcode.getBarcode().equals(robotTask.getBarcode());
        }
        return false;
    }

    /**
     * 相机扫码获取完尺寸后,料盘到达机器人取料位置
     */
    @RequestMapping(value = "/arriveRobotLocation")
    @ResponseBody
    public Object arriveRobot(HttpServletRequest request){
        String robotIndex = request.getParameter("robotIndex");
        String barcode = request.getParameter("barcode");
        //更新位置任务,清空扫码任务
        log.info("料盘["+barcode+"]到达机器人["+robotIndex+"]取料位置,更新位置任务,清空扫码任务");
        if(robotIndex != null){
            try{
                if(robotIndex.equals("1")){
                    //1号位机器人
                    firstRobotTask = firstScanTask;
                    log.info("将扫码任务["+firstRobotTask.getBarcode()+"]设置到机器人["+robotIndex+"]取料任务");
                }else if(robotIndex.equals("2")){
                    secondRobotTask = secondScanTask;
                    log.info("将扫码任务["+secondRobotTask.getBarcode()+"]设置到机器人["+robotIndex+"]取料任务");
                }
                updateScanTask(robotIndex, null);
            }catch(Exception e){
                log.error("料盘到达机器人出错:",e);
                return "Error:" + e.getMessage();
            }

        }

        return "OK";
    }

    /**
     * 3号机器人获取摆放位置信息
     */
    @RequestMapping(value = "/getPackageLocation")
    @ResponseBody
    public Object getPackageLocation(HttpServletRequest request) {
        try{
            String bigRfid = request.getParameter("bigRfid");
            //包装料RFID
            String packageRfid = request.getParameter("packageRfid");
            String hSerial = QisdaCache.getCurrentOrderHSerial();
            if(hSerial.isEmpty()){
                return ResultBean.newErrorResult(-2, "未找到大料架["+bigRfid+"]");
            }
            List<DataLog> allTasks = taskService.getAllTasks();

            for (DataLog task : allTasks) {
                //如果还有小料任务未完成,说明换了需求单了,放行大料架
                if(task.isCheckOutTask() && task.isSmallReel() && !task.isPackageReel() && !task.isLessSendReel()){
                    AppendInfo appendInfo = task.getAppendInfo();
                    if(appendInfo.isFirstReelAction() || appendInfo.isTailAction()){
                        return ResultBean.newErrorResult(-3, "还有小料任务,需求单已更换,大料架["+bigRfid+"]放行");
                    }
                }
            }

            log.info("收到机器人[3]获取包装料摆放位置信息请求:[packageRfid=" + packageRfid + "]bigRfid=" + bigRfid + "当前工单料需求:["+hSerial+"]");
            ShelfInfo packageShelf = InquiryShelfBean.findPackageShelf(hSerial, packageRfid);

            ShelfInfo bigShelf = InquiryShelfBean.findSameShelf(hSerial,bigRfid);
            //未找到,说明是未绑定过的新料架,找相同类型的进行绑定
            //未找到已经有实际RFID的料架,查找库位最多的料架
            if(bigShelf == null){
                log.info("未找到实际绑定的["+bigRfid+"]料架,开始查找序号最小的C型料架");
                ShelfInfo maxLocShelf = InquiryShelfBean.findMaxUsedShelf(hSerial, StorageConstants.SHEFL_TYPE.C);
                if(maxLocShelf != null){
                    bigShelf = maxLocShelf;
                }else{
                    log.info(hSerial + "已没有C型料架");
                }
            }

            if(bigShelf != null){
                //剩余包装料任务
                int packageTask = 0;
                for (DataLog task : allTasks) {
                    if(!task.isFinished() && !task.isCancel() && task.isCheckOutTask()){
                        if(task.isPackageReel()){
                            if(!task.isCutReel()){
                                packageTask = packageTask + 1;
                            }
                        }
                    }
                }

                String barcode = "";
                int packageLoc = -1;
                int reelInPackage = 0;
                if(packageShelf == null){
                    log.info("机器人[3]获取包装料摆放位置信息,未找到包装料架["+packageRfid+"]的信息");
                }else{
                    //查找包装料架上的物料
                    Map<Integer, ShelfLoc> packageLocMap = packageShelf.getLocMap();
                    for (ShelfLoc shelfLoc : packageLocMap.values()) {
                        if(!shelfLoc.isEmpty()){
                            reelInPackage = reelInPackage + 1;
                            if(barcode.isEmpty()){
                                barcode = shelfLoc.getBarcode();
                                packageLoc = shelfLoc.getLoc();
                            }
                        }
                    }
                }

                AppendInfo taskAppendInfo = null;
                if(!barcode.isEmpty()){
                    //包装料架上有料,且大料架有空位,从大料架上查找空位
                    DataLog task = taskService.getFinishedTask(barcode);
                    if(task == null){
                        String msg = "机器人[3]获取包装料摆放位置信息,未找到条码["+barcode+"]的任务";
                        log.error(msg);
                        return ResultBean.newErrorResult(103, msg);
                    }
                    taskAppendInfo = task.getAppendInfo();
                }

                //当前大料架上空位数
                int emptyInBig = 0;
                int bigLoc = -1;

                Map<Integer, ShelfLoc> bigShelfLocMap = bigShelf.getLocMap();
                for (ShelfLoc shelfLoc : bigShelfLocMap.values()) {
                    //这里不能使用包装料的数量(补料盘的料架没有固定位置,不是包装料类型)
                    if(shelfLoc.isEmpty()){
                        emptyInBig = emptyInBig + 1;
                        if(taskAppendInfo != null){
                            //找到了包装料架上物料的任务才能查找位置
                            if(bigLoc <= 0){
                                if(taskAppendInfo.isFirstReelAction()){
                                    //首套料,需要固定位置
                                    if(shelfLoc.isInThisLoc(barcode)){
                                        bigLoc = shelfLoc.getLoc();
                                    }
                                }else{
                                    //尾料,不需要固定位置,返回机器人架位的同时,锁定此位置
                                    bigShelf.lockForPackage(shelfLoc,barcode);
                                    InquiryShelfBean.updateShelfInfo(bigShelf);
                                    bigLoc = shelfLoc.getLoc();
                                }
                            }
                        }
                    }
                }

                if(packageTask == 0){
                    //log.info("已无包装料任务,更改料架可放包装料数量"+ emptyInBig + "为0");
                    //emptyInBig = 0;
                }


                Map<String,Object> resultMap = new HashMap<>();
                resultMap.put("barcode", barcode);
                //大料架上可放包装料数量
                resultMap.put("emptyInBig", emptyInBig);
                //包装料架上剩余的包装料数量(包含当前获取的物料)
                resultMap.put("reelInPackage", reelInPackage);
                resultMap.put("packageTask", packageTask);
                resultMap.put("packageRfid", packageRfid);
                resultMap.put("packageLoc", packageLoc);
                resultMap.put("bigRfid", bigShelf.tempRfid());
                resultMap.put("realBigRfid",bigShelf.getRealRfid());
                resultMap.put("bigLoc", bigLoc);

                log.info("机器人[3]获取包装料摆放位置信息返回:"+resultMap);
                return ResultBean.newOkResult(resultMap);
            }else{
                return ResultBean.newErrorResult(-2, "未找到大料架["+bigRfid+"]");
            }


        }catch(Exception e){
            log.error("包装料摆放位置信息获取出错",e);
            return ResultBean.newErrorResult(-1,"包装料摆放位置信息获取出错:" + e.getMessage());
        }
    }


    /**
     * 1号2号机器人根据工位获取摆放位置信息
     */
    @RequestMapping(value = "/getLocation")
    @ResponseBody
    public Object getLocation(HttpServletRequest request) {
        try{
            String robotIndex = request.getParameter("robotIndex");
            String rfid = request.getParameter("rfid");
            log.info("收到机器人["+robotIndex+"]获取摆放位置信息请求:rfid=" + rfid);
            if(robotIndex == null){
                return ResultBean.newErrorResult(-2, "参数错误:无robotIndex参数");
            }
            if(!robotIndex.equals("1") && !robotIndex.equals("2")){
                return ResultBean.newErrorResult(-2, "参数错误:robotIndex参数只能为1或2");
            }
            if(rfid == null){
                return ResultBean.newErrorResult(-2, "参数错误:无rfid参数");
            }

            DataLog task = null;

            if(robotIndex != null){
                if(robotIndex.equals("1")){
                    //1号位机器人
                    task = firstRobotTask;
                }else if(robotIndex.equals("2")){
                    task = secondRobotTask;
                }
            }

            if(task == null){
                String msg = "机器人["+robotIndex+"]无缓存位置信息";
                log.info(msg);
                return ResultBean.newErrorResult(201,  msg);
            }

            AppendInfo appendInfo = task.getAppendInfo();
            ShelfLoc shelfLoc = null;
            if(appendInfo.isFirstReelAction()){
                //首盘料已经固定好库位了
                shelfLoc = InquiryShelfBean.getLimitLoc(task);
            }else{
                shelfLoc = InquiryShelfBean.lockShelfLoc(task, rfid, robotIndex);
            }
            if(shelfLoc == null){
                String msg = "机器人["+robotIndex+"]获取料架["+rfid+"]位置信息失败";
                log.info(msg);
                return ResultBean.newErrorResult(202,  msg);
            }

            String rfidToSave = shelfLoc.getRealRfid();
            if(rfidToSave == null || rfidToSave.isEmpty()){
                //料架上放的第一盘料,没绑定,使用tempRfid
                rfidToSave = shelfLoc.getTempRfid();
            }

            appendInfo.setRfid(rfidToSave);
            appendInfo.setRfidLoc(shelfLoc.getLoc());
            task.setAppendInfo(appendInfo);

            task.setStatus(StorageConstants.OP_STATUS.INROBOT.name());
            task.setLocInfo(robotIndex);

            task = dataLogDao.save(task);
            taskService.updateFinishedTask(task);


            String hSerial = appendInfo.gethSerial();
            List<String> usedRfidList = InquiryShelfBean.getUsedRfidList(hSerial);

            Map<String,Object> resultMap = new HashMap<>();
            resultMap.put("barcode", task.getBarcode());
            resultMap.put("w", task.getW()+ "");
            resultMap.put("h", task.getH() +"");
            resultMap.put("realRfid", shelfLoc.getRealRfid());
            resultMap.put("rfid", shelfLoc.getTempRfid());
            //已经使用过的RFID列表
            resultMap.put("usedRfidList",String.join(",",usedRfidList));
            resultMap.put("rfidLoc", shelfLoc.getLoc() + "");

            log.info("机器人["+robotIndex+"]位置信息返回:[realRfid="+shelfLoc.getRealRfid()+",rfid=[" + shelfLoc.getTempRfid() + "]["+shelfLoc.getLoc()+"] barcode=["+task.getBarcode()+"]尺寸"+task.getW()+"x"+task.getH());
            return ResultBean.newOkResult(resultMap);

        }catch(Exception e){
            log.error("{ \"code\":0,\"msg\":\"ok\",\"data\":{ \"bigLoc\":-1,\"packageLoc\":-1,\"packageTask\":3,\"packageRfid\":\"\",\"realBigRfid\":\"C24\",\"emptyInBig\":3,\"barcode\":\"\",\"bigRfid\":\"2106-1C\",\"reelInPackage\":0}",e);
            return ResultBean.newErrorResult(-1,"获取摆放位置信息出错:" + e.getMessage());
        }

    }



    /**
     * 查找已经完成的任务,如果不存在从数据库中查找,如果任务是未完成状态,执行出库完成指令,同时通知Qisda
     */
    private DataLog findFinishedTask(String barcode){
        if(Strings.isBlank(barcode)){
            return null;
        }
        DataLog task = taskService.getFinishedTask(barcode);
        if(task == null){
            log.info("未从缓存中找到条码["+barcode+"]的任务信息,从数据库中查询");
            task = dataLogDao.findLatestOutTask(barcode);
        }
        if(task == null){
            log.error("料盘["+barcode+"]的任务不存在");
            return null;
        }
        if(task.isExecuting() || task.isCancel()){
            log.error("料盘["+barcode+"]的任务未完成,补发出库通知到Qisda");
            try {
                taskService.checkoutFinished(task);
                task = taskService.getFinishedTask(barcode);
            } catch (ValidateException e) {
                log.error("补发通知出错",e);
            }
        }else if(task.isFinished()){
            log.error("料盘["+barcode+"]的任务已完成");
            return null;
        }
        return task;
    }

    /**
     * 查找包装料架的剩余任务数
     */
    @RequestMapping(value = "/packageShelfTask")
    @ResponseBody
    public ResultBean packageShelfTask(HttpServletRequest request) {
        String rfid = request.getParameter("rfid");
        if(rfid == null){
            rfid = "";
        }

        //InquiryShelfBean.findSameShelf()

        ShelfInfo shelfInfo = InquiryShelfBean.findSameShelf(InquiryShelfBean.URGENT_SHELF_MAP_KEY,rfid);
        if(shelfInfo == null){
            shelfInfo = InquiryShelfBean.findSameShelf(InquiryShelfBean.CUT_SHELF_MAP_KEY,rfid);
        }
        String tempRfid = "";
        if(shelfInfo != null){
            tempRfid = shelfInfo.tempRfid();
        }
        Map<String,Object> resultMap = new HashMap<>();
        resultMap.put("tempRfid", tempRfid);
        return ResultBean.newOkResult(resultMap);
    }


    /**
     * 查找料架的TempRfid,用于流水线重启时决定当前料串是否可用
     */
    @RequestMapping(value = "/findTempRfid")
    @ResponseBody
    public ResultBean findTempRfid(HttpServletRequest request) {
        String rfid = request.getParameter("rfid");
        if(rfid == null){
            rfid = "";
        }
        ShelfInfo shelfInfo = InquiryShelfBean.findSameShelf(InquiryShelfBean.URGENT_SHELF_MAP_KEY,rfid);
        if(shelfInfo == null){
            shelfInfo = InquiryShelfBean.findSameShelf(InquiryShelfBean.CUT_SHELF_MAP_KEY,rfid);
        }
        String tempRfid = "";
        if(shelfInfo != null){
            tempRfid = shelfInfo.tempRfid();
        }
        Map<String,Object> resultMap = new HashMap<>();
        resultMap.put("tempRfid", tempRfid);
        return ResultBean.newOkResult(resultMap);
    }

    /**
     * 分盘料/紧急料放上料串或料架流出时调用
     */
    @RequestMapping(value = "/clearRfid")
    @ResponseBody
    public ResultBean clearRfid(HttpServletRequest request) {
        String rfid = request.getParameter("rfid");
        if(rfid == null){
            rfid = "";
        }
        boolean clearResult = InquiryShelfBean.clearShelf(InquiryShelfBean.URGENT_SHELF_MAP_KEY,rfid);
        if(!clearResult){
            log.info("从分盘料料架中查找["+rfid+"]准备清除");
            clearResult = InquiryShelfBean.clearShelf(InquiryShelfBean.CUT_SHELF_MAP_KEY,rfid);
        }

        log.info("清除料架["+rfid+"]完成:" + clearResult);
        return ResultBean.newOkResult(clearResult);
    }

    /**
     * 取消入库任务
     */
    @RequestMapping(value = "/cancelPutInTask")
    @ResponseBody
    public ResultBean cancelPutInTask(HttpServletRequest request) {
        String codeStr = request.getParameter("barcode");
        try{
            Collection<DataLog> queueTasks = taskService.getQueueTasks();
            for (DataLog queueTask : queueTasks) {
                if(queueTask.isPutInTask() && codeStr.contains(queueTask.getBarcode())){
                    //只能取消入库任务
                    boolean cancelResult = taskService.cancelTask(queueTask.getId());
                    log.info("客户端取消["+codeStr+"]的入库任务结果:" + cancelResult);
                    return ResultBean.newOkResult(cancelResult);
                }
            }
        }catch (Exception e){
            return ResultBean.newErrorResult(2002, "客户端取消任务["+codeStr+"]失败:" + e.getMessage());
        }
        return ResultBean.newErrorResult(2003, "客户端取消任务["+codeStr+"]失败");
    }

    /**
     * 分盘料/紧急料放上料串或料架时调用
     */
    @RequestMapping(value = "/afterPutCut")
    @ResponseBody
    public ResultBean afterPutCut(HttpServletRequest request) {
        String cid = request.getParameter("cid");
        if(cid == null){
            cid = "";
        }
        String barcode = request.getParameter("barcode");
        String rfid = request.getParameter("rfid");
        String rfidLoc = request.getParameter("rfidLoc");
        log.debug("收到["+cid+"]紧急/分盘料[" + barcode + "]放入"+rfid+"[" + rfidLoc + "]指令");
        DataLog task = findFinishedTask(barcode);
        if(task != null){
            ShelfLoc shelfLoc = InquiryShelfBean.putInCutReel(task,rfid, Integer.valueOf(rfidLoc));
            if(shelfLoc != null){
                log.info("["+cid+"]紧急/分盘料[" + barcode + "]放入"+rfid+"[" + rfidLoc + "]成功");
                task.setStatus(StorageConstants.OP_STATUS.FINISHED.name());
                rfidLoc = shelfLoc.getLoc() + "";
            }else{
                if(task.isLessSendReel()){
                    task.setStatus(StorageConstants.OP_STATUS.FINISHED.toString());
                }else{
                    log.info(""+cid+"紧急/分盘料[" + barcode + "]放入"+rfid+"[" + rfidLoc + "]失败");
                    task.setStatus(StorageConstants.OP_STATUS.FINISHED.toString());
                }
            }

            AppendInfo appendInfo = task.getAppendInfo();

            //完成任务数量+1
            outInfoCache.incTaskFinishNum(appendInfo.gethSerial(), 0, 0);

            appendInfo.setRfid(rfid);
            int loc = task.resolveRfidLoc(rfidLoc);
            appendInfo.setRfidLoc(loc);
            task.setAppendInfo(appendInfo);
            task = dataLogDao.save(task);
            taskService.updateFinishedTask(task);


        }

        int cutPackageTask = 0;
        int urgentPackageTask = 0;
        int cutTask = 0;
        int urgentTask = 0;

        //总的分盘和紧急料数量
        int totalCutTask = 0;
        int totalUrgentTask = 0;
        List<DataLog> allTasks = taskService.getAllTasks();
        for (DataLog unFinishedTask : allTasks) {
            if(!unFinishedTask.isFinished() && !unFinishedTask.isCancel() && unFinishedTask.isCheckOutTask()){
                if(unFinishedTask.isCutReel()){
                    totalCutTask = totalCutTask + 1;
                    if(unFinishedTask.isPackageReel()){
                        if(unFinishedTask.getCid().equals(cid)){
                            //当前包装料仓的分盘任务
                            cutPackageTask = cutPackageTask + 1;
                        }
                    }else{
                        cutTask = cutTask + 1;
                    }

                }else if(unFinishedTask.isUrgentReel() || unFinishedTask.isLessSendReel()){
                    totalUrgentTask = totalUrgentTask + 1;
                    if(unFinishedTask.isPackageReel()) {
                        if (unFinishedTask.getCid().equals(cid)) {
                            urgentPackageTask = urgentPackageTask + 1;
                        }
                    }else{
                        urgentTask = urgentTask + 1;
                    }
                }
//                if(unFinishedTask.isPackageReel()){
//                    if(unFinishedTask.getCid().equals(cid)){
//                        if(unFinishedTask.isCutReel()){
//                            cutPackageTask = cutPackageTask + 1;
//                            totalCutTask = totalCutTask + 1;
//                        }else if(unFinishedTask.isUrgentReel()){
//                            urgentPackageTask = urgentPackageTask + 1;
//                            totalUrgentTask = totalUrgentTask + 1;
//                        }
//                    }
//                }else if(unFinishedTask.isCutReel()){
//                    cutTask = cutTask + 1;
//                    totalCutTask = totalCutTask + 1;
//                }else if(unFinishedTask.isUrgentReel()){
//                    urgentTask = urgentTask + 1;
//                    totalUrgentTask = totalUrgentTask + 1;
//                }
            }
        }

        Map<String,Object> resultMap = new HashMap<>();
        resultMap.put("cutPackageTask", cutPackageTask + "");
        resultMap.put("urgentPackageTask",urgentPackageTask + "");
        resultMap.put("cutTask", cutTask + "");
        resultMap.put("urgentTask", urgentTask + "");

        if(totalCutTask == 0){
            //log.info("已无分盘料任务,清空分盘料使用料架/料串");
            InquiryShelfBean.clearShelf(InquiryShelfBean.CUT_SHELF_MAP_KEY);
        }

        if(totalUrgentTask == 0){
            //log.info("已无紧急料任务,清空紧急料使用料架/料串");
            InquiryShelfBean.clearShelf(InquiryShelfBean.URGENT_SHELF_MAP_KEY);
        }

        return ResultBean.newOkResult(resultMap);
    }

    /**
     * 更新位置信息
     */
    @RequestMapping(value = "/updateLocInfo")
    @ResponseBody
    public ResultBean updateLocInfo(HttpServletRequest request) {
        String barcode = request.getParameter("barcode");
        String statusStr = request.getParameter("status");
        String locInfo = request.getParameter("locInfo");
        log.debug("收到料盘["+barcode+"]更新位置指令["+statusStr+"]=" + locInfo);

        DataLog task = findFinishedTask(barcode);
        if(task == null){
            return ResultBean.newErrorResult(301, "任务不存在");
        }

        if(task.isFinished()){
            return ResultBean.newErrorResult(302, "任务已完成");
        }

        if(task.isCancel()){
            return ResultBean.newErrorResult(303, "更新状态时"+task.getBarcode()+"的出库任务["+task.getId()+"]已被取消");
        }
        statusStr = statusStr.toUpperCase();
        log.info("更新料盘["+barcode+"]的任务状态["+task.getStatus()+"=" + task.getLocInfo() + "]为["+statusStr+"="+locInfo+"]");
        task.setStatus(statusStr);
        task.setLocInfo(locInfo);
        task = dataLogDao.save(task);
        taskService.updateFinishedTask(task);


        //包装料
        if(task.isPackageReel()){
            String[] infos = locInfo.split("@");
            String rfid = infos[0];
            String rfidLoc = infos[1];
            InquiryShelfBean.putInShelf(task,rfid, Integer.valueOf(rfidLoc));

            //剩余任务数
            String taskCid = task.getCid();
            Collection<DataLog> waitTasks = taskService.getQueueTasks();
            int taskCount = 0;
            //同一个料仓的出库任务(等待中和正在执行的)
            for (DataLog waitTask : waitTasks) {
                String waitCid = waitTask.getCid();
                if(waitTask.isCheckOutTask() && waitCid != null && waitCid.equals(taskCid)){
                    taskCount = taskCount + 1;
                }
            }
            Map<String,Object> resultMap = new HashMap<>();
            resultMap.put("taskCount",taskCount+"");
            return ResultBean.newOkResult(resultMap);
        }


        return ResultBean.newOkResult("");
    }

    /**
     * 料盘放入料架时,更新信息
     * @param cacheTask 条码任务
     * @param rfid 料架RFID
     * @param rfidLoc 料架位置
     */
    private synchronized boolean reelPutInFinished(DataLog cacheTask, String rfid, String rfidLoc){
        if(cacheTask != null){
            AppendInfo appendInfo = cacheTask.getAppendInfo();
            boolean putResult = InquiryShelfBean.putInShelf(cacheTask,rfid, Integer.valueOf(rfidLoc));
            //紧急料和分盘料放入失败不影响
            boolean isCutTask = cacheTask.isUrgentReel() || cacheTask.isCutReel() || cacheTask.isLessSendReel();
            if(!isCutTask && !putResult){
                //记录日志
                String errorMsg = "料盘["+cacheTask.getBarcode()+"]放入位置"+rfid+"["+rfidLoc+"]失败,原分配位置"+cacheTask.getTempRfid()+"["+appendInfo.getRfidLoc()+"],不更改状态,不进行发料";
                log.error(errorMsg);
                AlarmInfo alarmInfo = new AlarmInfo();
                alarmInfo.setBoxId("0");
                alarmInfo.setStorageName(cacheTask.getStorageName());
                alarmInfo.setInOutStatus("1");
                alarmInfo.setAlarmType("放料失败");
                Date date = new Date();
                alarmInfo.setStartTime(date);
                alarmInfo.setEndTime(date);
                alarmInfo.setAlarmMsg(errorMsg);
                alarmInfoDao.save(alarmInfo);
                return putResult;
            }else{
                log.info("料盘["+cacheTask.getBarcode()+"]放入位置"+rfid+"["+rfidLoc+"]成功");
                cacheTask.setStatus(StorageConstants.OP_STATUS.FINISHED.name());
                appendInfo.setRfid(rfid);

                int loc = cacheTask.resolveRfidLoc(rfidLoc);
                appendInfo.setRfidLoc(loc);
                cacheTask.setAppendInfo(appendInfo);
                cacheTask = dataLogDao.save(cacheTask);
                taskService.updateFinishedTask(cacheTask);

                String hSerial = appendInfo.gethSerial();
                if(Strings.isNotBlank(hSerial)){
                    int slotSeq = appendInfo.getSlotIndex();
                    int sendQty = cacheTask.getNum();
                    //发料完成,更新发料数量
                    OutInfo outInfo = outInfoCache.incTaskFinishNum(hSerial,slotSeq, sendQty);
                    if(outInfo != null){
                        if(cacheTask.isUrgentReel() || cacheTask.isCutReel()){
                            log.info("分盘料和紧急料不需要通知Qisda");
                        }else if(cacheTask.isLessSendReel()){
                            log.info("缺料补发料需要通知Qisda");
                            Barcode barcodeObj = barcodeManager.findByBarcode(cacheTask.getBarcode());
                            String latest = outInfo.getShelfLatest();
                            QisdaApi.VMIMateriaRecAss(cacheTask, barcodeObj,latest);

                        } else{
                            Barcode barcodeObj = barcodeManager.findByBarcode(cacheTask.getBarcode());
                            String latest = outInfo.getShelfLatest();
                            QisdaApi.VMIMateriaRecAss(cacheTask, barcodeObj,latest);

                        }
                    }
                }
            }

            return putResult;
        }
        return false;
    }
    /**
     * 包装线机器人从A包装料架放到C大料架上barcode
     */
    @RequestMapping(value = "/putPackageFinished")
    @ResponseBody
    public Object putPackageFinished(HttpServletRequest request) {
        //A料架肯定要存在
        String packageRfid = request.getParameter("packageRfid");
        String bigRfid = request.getParameter("bigRfid");
        String packageLoc = request.getParameter("packageLoc");
        String bigLoc = request.getParameter("bigLoc");
        String barcode = request.getParameter("barcode");
        String msg = "机器人[3]将包装料盘["+barcode+"]从"+packageRfid+"["+packageLoc+"]放入料架=>"+bigRfid+"["+bigLoc+"]";
        log.info(msg);
        if(Strings.isNotBlank(barcode)) {
            DataLog cacheTask = taskService.getFinishedTask(barcode);
            if (cacheTask == null) {
                return ResultBean.newErrorResult(501,msg+"失败, 料盘[" + barcode + "]的任务不存在");
            } else {
                boolean putInResult = reelPutInFinished(cacheTask,bigRfid, bigLoc);
                if(putInResult){
                    //清理包装料架的位置
                    ShelfInfo packageShelf = InquiryShelfBean.findPackageShelf(cacheTask.getAppendInfo().gethSerial(), packageRfid);
                    if(packageShelf != null){
                        log.info(msg + "成功,清空包装料架信息");
                        Map<Integer, ShelfLoc> packageLocMap = packageShelf.getLocMap();
                        for (ShelfLoc shelfLoc : packageLocMap.values()) {
                            if(shelfLoc.isInThisLoc(barcode)){
                                shelfLoc.setEmpty(true);
                                packageLocMap.put(shelfLoc.getLoc(), shelfLoc);
                                packageShelf.setLocMap(packageLocMap);
                                InquiryShelfBean.updateShelfInfo(packageShelf);
                                return ResultBean.newOkResult(null);
                            }
                        }
                    }else{
                        return ResultBean.newErrorResult(502,msg + "失败,未找到包装料架["+packageRfid+"]的缓存信息");
                    }
                }
            }
        }

        String errorMsg = "包装线机器人放置料盘["+barcode+"]从"+packageRfid+"["+packageLoc+"]=>"+bigRfid+"["+bigLoc+"]失败";
        return ResultBean.newErrorResult(501,errorMsg);
    }

    /**
     * 放置到料架动作完成,返回当前料架还可放置的数量,用任务总数
     */
    @RequestMapping(value = "/putShelfFinished")
    @ResponseBody
    public Object putShelfFinished(HttpServletRequest request) {
        String robotIndex = request.getParameter("robotIndex");
        String rfid = request.getParameter("rfid");
        String rfidLoc = request.getParameter("rfidLoc");
        String barcode = request.getParameter("barcode");

        try{

            DataLog cacheTask = null;
            if(Strings.isNotBlank(barcode)) {
                cacheTask = taskService.getFinishedTask(barcode);

                if (cacheTask == null) {
                    log.error("料盘[" + barcode + "]的任务不存在");
                } else {
                    if(Strings.isNotBlank(robotIndex)){
                        if(robotIndex.equals("1") && firstRobotTask != null){
                            if(firstRobotTask.getBarcode().equals(barcode)){
                                log.info("机器人["+robotIndex+"]将料盘["+barcode+"]放入料架["+rfid+"]["+rfidLoc+"]完成,任务一致,清空机器人任务");
                                //1号位机器人
                                firstRobotTask = null;
                            }else{
                                log.info("机器人["+robotIndex+"]将料盘["+barcode+"]放入料架["+rfid+"]["+rfidLoc+"]完成,与当前任务["+firstRobotTask.getBarcode()+"]不一致,不清空");
                            }
                        }else if(robotIndex.equals("2") && secondRobotTask != null){
                            if(secondRobotTask.getBarcode().equals(barcode)){
                                //1号位机器人
                                log.info("机器人["+robotIndex+"]将料盘["+barcode+"]放入料架["+rfid+"]["+rfidLoc+"]完成,任务一致,清空机器人任务");
                                secondRobotTask = null;
                            }else{
                                log.info("机器人["+robotIndex+"]将料盘["+barcode+"]放入料架["+rfid+"]["+rfidLoc+"]完成,与当前任务["+secondRobotTask.getBarcode()+"]不一致,不清空");
                            }
                        }
                    }
                    reelPutInFinished(cacheTask,rfid, rfidLoc);
                }
            }

            int packageTask = 0;
            int cutPackageTask = 0;
            int cutTask = 0;
            int smallTask = 0;
            int bigTask = 0;
            Collection<DataLog> queueTasks = taskService.getQueueTasks();
            List<DataLog> allTasks = taskService.getFinishedTasks();
            if(!queueTasks.isEmpty()){
                allTasks.addAll(queueTasks);
            }
            for (DataLog task : allTasks) {
                if(!task.isFinished() && !task.isCancel() && task.isCheckOutTask()){
                    if(task.isPackageReel()){
                        if(task.isCutReel() || task.isUrgentReel() || task.isLessSendReel()){
                            cutPackageTask = cutPackageTask + 1;
                        }else{
                            packageTask = packageTask + 1;
                        }
                    }else if(task.isCutReel() || task.isUrgentReel() || task.isLessSendReel()){
                        cutTask = cutTask + 1;
                    }else if(task.isSmallReel()){
                        smallTask = smallTask + 1;
                    }else{
                        bigTask = bigTask + 1;
                    }
                }
            }

            //当前料架还可放入的料盘数
            int smallEmpty = 0;
            int bigEmpty = 0;
            int packageEmpty = 0;

            String hSerial = QisdaCache.getCurrentOrderHSerial();
            if(cacheTask != null){
                hSerial = cacheTask.getAppendInfo().gethSerial();
            }
            ShelfInfo shelfInfo = InquiryShelfBean.findSameShelf(hSerial,rfid);
            if(shelfInfo != null){
                Map<Integer, ShelfLoc> locMap = shelfInfo.getLocMap();
                for (ShelfLoc shelfLoc : locMap.values()) {
                    if(shelfLoc.isEmpty()){
                        if(shelfLoc.isSmallLoc()){
                            smallEmpty = smallEmpty + 1;
                        }else if(shelfLoc.isBigLoc()){
                            bigEmpty = bigEmpty + 1;
                        }else if(shelfLoc.isPackageLoc()){
                            //包装料架
                            if(StorageConstants.SHEFL_TYPE.isAShelf(shelfInfo.getShelfType())){
                                packageEmpty = packageEmpty + 1;
                            }else{
                                //大料架,并且不是首套料
                                bigEmpty = bigEmpty + 1;
                            }
                        }
                    }
                }
            }else{
                //没找到料架,小料空位和大料空位都返回100
                smallEmpty = 100;
                bigEmpty = 100;
                packageEmpty = 100;
            }

            List<String> usedRfidList = InquiryShelfBean.getUsedRfidList(hSerial);

            //剩余的任务数
            Map<String,Object> resultMap = new HashMap<>();
            if(cacheTask == null){
                resultMap.put("barcode","");
            }else{
                resultMap.put("barcode",cacheTask.getBarcode());
            }
            resultMap.put("rfid", rfid);
            //已经使用过的RFID列表
            resultMap.put("usedRfidList",String.join(",",usedRfidList));
            resultMap.put("smallEmpty", smallEmpty + "");
            resultMap.put("bigEmpty", bigEmpty + "");
            resultMap.put("packageEmpty", packageEmpty + "");
            resultMap.put("cutPackageTask", cutPackageTask + "");
            resultMap.put("packageTask", packageTask + "");
            resultMap.put("cutTask", cutTask + "");
            resultMap.put("smallTask", smallTask + "");
            resultMap.put("bigTask", bigTask + "");

            int totalOrderTaskCount = packageTask + smallTask + bigTask;
            if(totalOrderTaskCount > 0){
                log.info("当前任务数:" + resultMap);
            }else{
//                if(!hSerial.isEmpty()){
//                    if(!usedRfidList.isEmpty()){
//                        log.info("工单总任务数为0,且工单有料架已经绑定,清空当前的工单序号["+hSerial+"]");
//                        outInfoCache.setCurrentOrderHSerial(null);
//                    }
//                }
            }
            return ResultBean.newOkResult(resultMap);

        }catch(Exception e){
            log.error("机器人放料完成信息出错robotIndex="+robotIndex+";rfid="+rfid+";rfidLoc="+rfidLoc+";barcode="+barcode,e);
        }

        return "";
    }

    /**
     * 包装料仓空闲仓位数量
     */
    @RequestMapping(value = "/emptyStoragePosCount")
    @ResponseBody
    public Object emptyStoragePosCount(HttpServletRequest request) {
        Map<String,Object> resultMap = new HashMap<>();
        try {
            Map<String, Storage> allStorage = dataCache.getAllStorage();
            for (Storage storage : allStorage.values()) {
                if(storage.isPackage()){
                    //包装料仓
                    resultMap.put(storage.getCid(), storage.getEmptySlots()+"");
                }
            }
        }catch (Exception e){
            log.error("获取包装料仓空闲仓位出错",e);
        }

        return ResultBean.newOkResult(resultMap);
    }

}