QisdaDeviceController.java 41.3 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
package com.myproject.webapp.controller.webService;

import com.myproject.bean.CodeBean;
import com.myproject.bean.qisda.*;
import com.myproject.bean.update.*;
import com.myproject.bean.update.qisda.OutInfo;
import com.myproject.bean.utils.BoxStatusBean;
import com.myproject.bean.utils.StatusBean;
import com.myproject.dao.mongo.IAlarmInfoDao;
import com.myproject.dao.mongo.IDataLogDao;
import com.myproject.exception.ValidateException;
import com.myproject.manager.IBarcodeManager;
import com.myproject.manager.IComponentManager;
import com.myproject.manager.IStoragePosManager;
import com.myproject.util.JsonUtil;
import com.myproject.util.QisdaApi;
import com.myproject.util.StorageConstants;
import com.myproject.webapp.controller.qisda.StockCheckController;
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
    protected IStoragePosManager storagePosManager;

    @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);

    /**
     * 流水线根据条码及机器人工位获取尺寸信息,同时为料盘锁定架位
     */
    @RequestMapping(value = "/getSize")
    @ResponseBody
    public ResultBean getSize(HttpServletRequest request) {
        try{
            String barcodeStr = request.getParameter("barcode");
            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);
                    }
                }
            }

            log.info("返回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());
        }
    }



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


    /**
     * 3楼料盘到达机器人取料位置
     */
    @RequestMapping(value = "/arrive3fRobotLocation")
    @ResponseBody
    public Object arrive3fRobotLocation(HttpServletRequest request){
        String codeStr = request.getParameter("barcode");
        //更新位置任务,清空扫码任务
        log.info("料盘["+codeStr+"]到达取料位置");

        return ResultBean.newOkResult("OK");
    }

    /**
     * 相机扫码获取完尺寸后,料盘到达机器人取料位置
     */
    @RequestMapping(value = "/arriveRobotLocation")
    @ResponseBody
    public Object arriveRobot(HttpServletRequest request){
        String codeStr = request.getParameter("barcode");
        //更新位置任务,清空扫码任务
        log.info("料盘["+codeStr+"]到达取料位置");

        return "OK";
    }

    /**
     * 1号2号机器人根据工位获取摆放位置信息
     */
    @RequestMapping(value = "/getLocation")
    @ResponseBody
    public Object getLocation(HttpServletRequest request) {
        try{

            String rfid = request.getParameter("rfid");
            String codeStr = request.getParameter("barcode");
            Barcode barcode = dataCache.resolveOneValideBarcode(codeStr);
            DataLog task = taskService.getFinishedTask(barcode.getBarcode());
            if(task == null){
                String msg = "未找到待分配位置的条码["+barcode.getBarcode()+"]任务信息";
                return ResultBean.newErrorResult(203, msg);
            }else {
                if (task.isFinished()) {
                    String msg = "条码[" + barcode.getBarcode() + "]的任务已完成";
                    return ResultBean.newErrorResult(204, msg);
                } else if (task.isStopSendToQisda()) {
                    //被取消的出库任务,不可再放上料架
                    String msg = "条码[" + barcode.getBarcode() + "]的任务已被取消";
                    return ResultBean.newErrorResult(207, msg);
                } else {
//                    String hSerial = task.getAppendInfo().gethSerial();
//                    String executingHSerial = QisdaCache.getCurrentOrderHSerial();
//                    if (!executingHSerial.equals(hSerial)) {
//                        String msg = "料盘[" + barcode.getBarcode() + "]任务的需求单号与当前正在执行的需求单号不一致";
//                        return ResultBean.newErrorResult(206, msg);
//                    }
                }
            }


            AppendInfo appendInfo = task.getAppendInfo();
            ShelfLoc shelfLoc = InquiryShelfBean.lockShelfLoc(task, rfid);
            if(shelfLoc == null){
                String msg = "获取料架["+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("");

            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("位置信息返回:[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+"]的任务未完成,清空库位信息");
            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;
    }




    /**
     * 查找料架的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);
    }

    /**
     * 根据虚拟RFID查找料架的真实的Rfid
     */
    @RequestMapping(value = "/findRealRfid")
    @ResponseBody
    public ResultBean findRealRfid(HttpServletRequest request) {
        String tempRfid = request.getParameter("tempRfid");
        if(tempRfid == null){
            tempRfid = "";
        }
        String realRfid = "";
        ShelfInfo shelfInfo = InquiryShelfBean.findShelfByTempRfid(tempRfid);

        if(shelfInfo != null){
            realRfid = shelfInfo.getRealRfid();
        }
        Map<String,Object> resultMap = new HashMap<>();
        resultMap.put("tempRfid", tempRfid);
        resultMap.put("realRfid", realRfid);
        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("");
    }

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

    /**
     * 取消出库任务
     */
    @RequestMapping(value = "/cancelOutTask")
    @ResponseBody
    public ResultBean cancelOutTask(HttpServletRequest request) {
        String codeStr = request.getParameter("barcode");
        try{
            Collection<DataLog> tasks = taskService.getAllTasks();
            for (DataLog task : tasks) {
                if(codeStr.contains(task.getBarcode())){
                    if(task.isCheckOutTask()){
                        if(task.isWait() || task.isExecuting()){
                            //未执行完成的,理论上不会从客户端取消
                            boolean cancelResult = taskService.cancelTask(task.getId());
                            log.info("客户端取消["+codeStr+"]的未执行完成的出库任务结果:" + cancelResult);
                            return ResultBean.newOkResult(cancelResult);
                        }else{
                            //禁用库位
                            boolean prohibitePos = true;
                            boolean hideResult = taskService.hideTask(task.getId(),prohibitePos);
                            log.info("客户端取消["+codeStr+"]已完成的出库任务结果:" + hideResult);
                            return ResultBean.newOkResult(hideResult);
                        }
                    }
                }
            }
        }catch (Exception e){
            return ResultBean.newErrorResult(2004, "客户端取消任务["+codeStr+"]失败:" + e.getMessage());
        }
        return ResultBean.newErrorResult(2005, "客户端取消任务["+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);
        String tempRfid = "";
        if(task != null && !task.isCancel()){
            boolean putResult = InquiryShelfBean.putInShelf(task,rfid, Integer.valueOf(rfidLoc));
            if(putResult){
                log.info("["+cid+"]紧急/分盘料[" + barcode + "]放入"+rfid+"[" + rfidLoc + "]成功");
                task.setStatus(StorageConstants.OP_STATUS.FINISHED.name());
            }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
            if(!task.isLessSendReel()){
                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);
            tempRfid = task.getTempRfid();

        }

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

        //总的分盘和紧急料数量
        int totalCutTask = 0;
        int totalUrgentTask = 0;

        int totalPackageCutTask = 0;
        int totalPackageUrgentTask = 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()){
                        totalPackageCutTask = totalPackageCutTask + 1;
                        if(unFinishedTask.getCid().equals(cid)){
                            //当前包装料仓中当前料架的分盘任务
                            if(tempRfid.equals(unFinishedTask.getTempRfid())){
                                cutPackageTask = cutPackageTask + 1;
                            }
                        }
                    }else{
                        cutTask = cutTask + 1;
                    }

                }else if(unFinishedTask.isUrgentReel() || unFinishedTask.isLessSendReel() || unFinishedTask.getAppendInfo().isCheckAction()){
                    totalUrgentTask = totalUrgentTask + 1;
                    if(unFinishedTask.isPackageReel()) {
                        totalPackageUrgentTask = totalPackageUrgentTask + 1;
                        if (unFinishedTask.getCid().equals(cid)) {
                            if(tempRfid.equals(unFinishedTask.getTempRfid())){
                                urgentPackageTask = urgentPackageTask + 1;
                            }
                        }
                    }else{
                        urgentTask = urgentTask + 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);

//        if(task.isInBelt() || task.isPackageReel()){
//            //已经放上皮带线
//            AppendInfo appendInfo =  task.getAppendInfo();
//            if(Strings.isBlank(appendInfo.gethSerial())){
//                //log.info("手动出库料盘["+barcode+"]放上皮带线或包装料架,结束任务");
//                //task.setStatus(StorageConstants.OP_STATUS.FINISHED.name());
//            }else if(appendInfo.isCheckAction()){
//                log.info("盘点料盘["+barcode+"]放上皮带线或包装料架,结束任务");
//                task.setStatus(StorageConstants.OP_STATUS.FINISHED.name());
//                //盘点料,出到皮带线上即算完成
//                int slotSeq = appendInfo.getSlotIndex();
//                int sendQty = task.getNum();
//                outInfoCache.incTaskFinishNum(appendInfo.gethSerial(),slotSeq, sendQty);
//            }
//        }

        task = dataLogDao.save(task);

        if(!task.isStopSendToQisda()){
            //未关闭
            taskService.updateFinishedTask(task);
        }

        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+"]成功 outOrder="+cacheTask.getOutOrder());
                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;
    }

    /**
     * 放置到料架动作完成,返回当前料架还可放置的数量,用任务总数
     */
    @RequestMapping(value = "/putShelfFinished")
    @ResponseBody
    public Object putShelfFinished(HttpServletRequest request) {
        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 {
                    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() || task.getAppendInfo().isCheckAction()){
                            cutPackageTask = cutPackageTask + 1;
                        }else{
                            packageTask = packageTask + 1;
                        }
                    }else if(task.isCutReel() || task.isUrgentReel() || task.isLessSendReel() || task.getAppendInfo().isCheckAction()){
                        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();
            }
            List<String> usedRfidList = InquiryShelfBean.getUsedRfidList(hSerial);

            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{
                //料架上一个工单使用过,直接放行,其他情况继续使用
                boolean lastHSerialUsed = QisdaCache.isLastHSerialUsedRfid(rfid);
                if(!lastHSerialUsed){
                    //没有使用过
                    smallEmpty = 100;
                    bigEmpty = 100;
                    packageEmpty = 100;
                }else{
                    //为了料架能重用,如果当前执行的需求单料已经放上料架,则清空上一个需求单使用过的料架
                    if(!usedRfidList.isEmpty()){
                        log.info("料架["+rfid+"]上一个需求单已使用,当前需求单["+hSerial+"]物料已放上料架,清理上一个需求单使用过的料架");
                        QisdaCache.updateUsedRfid(null);
                        smallEmpty = 100;
                        bigEmpty = 100;
                        packageEmpty = 100;
                    }
                }
            }



            //剩余的任务数
            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("机器人放料完成信息出错rfid="+rfid+";rfidLoc="+rfidLoc+";barcode="+barcode,e);
        }

        return "";
    }

    /**
     * 获取当前料架中锁定库位的料盘信息
     */
    @RequestMapping(value = "/getShelfLockInfo")
    @ResponseBody
    public ResultBean getShelfLockInfo(HttpServletRequest request){
        String rfid = request.getParameter("rfid");
        List<ReelLockPosInfo> shelfLockInfoList = QisdaCache.getShelfLockPosInfo(rfid);
        return ResultBean.newOkResult(shelfLockInfoList);
    }

    /**
     * 清理料架中锁定库位的料盘绑定信息
     */
    @RequestMapping(value = "/clearLockLoc")
    @ResponseBody
    public ResultBean clearLockLoc(HttpServletRequest request){
        String rfid = request.getParameter("rfid");
        String rfidLoc = request.getParameter("rfidLoc");
        ReelLockPosInfo lockInfo = QisdaCache.getLockPosInfoByRfidLoc(rfid, rfidLoc);
        if(lockInfo != null){
            log.info("客户端清理料架锁定信息:"+ lockInfo);
            QisdaCache.removeReelLockPosInfo(lockInfo.getBarcode());
            return ResultBean.newOkResult("");
        }else{
            return ResultBean.newErrorResult(201,"未找到"+rfid+"["+rfidLoc+"]的锁定信息");
        }

    }



    /**
     * 库位物料检测接口
     */
    @RequestMapping(value = "/posReelCheck")
    @ResponseBody
    public ResultBean posReelCheck(HttpServletRequest request){
        String cid = request.getParameter("cid");
        String posName = request.getParameter("pos");
        String hasReelStr = request.getParameter("hasReel");
        log.info("收到客户端["+cid+"]对库位["+posName+"]的盘点结果:" + hasReelStr);
        StoragePos pos = storagePosManager.getByPosName(posName);
        if(pos != null){
            Boolean hasReel = Boolean.valueOf(hasReelStr);
            StockCheckController.updateStockCheckItem(pos,hasReel);
        }
        return ResultBean.newOkResult("");
    }

    private Map<String,DeviceAlarmMsgBean> deviceAlarmMap = new ConcurrentHashMap<>();

    @RequestMapping(value = "/updateDeviceAlarmMsg")
    @ResponseBody
    public ResultBean updateDeviceAlarmMsg(HttpServletRequest request){
        String alarmListStr = request.getParameter("deviceAlarmList");
        if(Strings.isNotBlank(alarmListStr)){
            List<DeviceAlarmMsgBean> alarmList = JsonUtil.toList(alarmListStr, DeviceAlarmMsgBean.class);
            for (DeviceAlarmMsgBean deviceAlarmMsgBean : alarmList) {
                String msgKey = deviceAlarmMsgBean.getMsgKey();
                DeviceAlarmMsgBean oldBean = deviceAlarmMap.get(msgKey);
                if(oldBean != null){
                    oldBean.updateMsg(deviceAlarmMsgBean);
                    if(oldBean.getMsgValue().isEmpty()){
                        deviceAlarmMap.remove(msgKey);
                        continue;
                    }
                }else{
                    log.info("收到新的设备报警信息:" + alarmListStr);
                    deviceAlarmMsgBean.setStartTime(new Date());
                    oldBean = deviceAlarmMsgBean;
                }
                deviceAlarmMap.put(msgKey,oldBean);
            }
        }
        return ResultBean.newOkResult("");
    }

    @RequestMapping(value = "/deviceMsgList")
    @ResponseBody
    public Collection<DeviceAlarmMsgBean> updateAlarmList(HttpServletRequest request){
        List<DeviceAlarmMsgBean> alarmList = new ArrayList<>();
        for (DeviceAlarmMsgBean deviceAlarmMsgBean : deviceAlarmMap.values()) {
            if(deviceAlarmMsgBean.isTimeout()){
                deviceAlarmMap.remove(deviceAlarmMsgBean);
            }else{
                alarmList.add(deviceAlarmMsgBean);
            }
        }

        for (Storage storage : dataCache.getAllStorage().values()) {
            StatusBean statusBean = taskService.getStatus(storage.getCid());
            Map<Integer, BoxStatusBean> boxStatusMap = statusBean.getBoxStatus();
            if(statusBean.getStatus() == StorageConstants.STATUS.OFFLINE){
                String msgKey = "box." + storage.getCid()+ ".offline";
                DeviceAlarmMsgBean alarmMsgBean = new DeviceAlarmMsgBean(storage.getName(),msgKey,"设备离线");
                alarmList.add(alarmMsgBean);
            }
            if(!boxStatusMap.isEmpty()){
                BoxStatusBean boxStatusBean = boxStatusMap.values().iterator().next();
                String boxMsg = boxStatusBean.getMsg();
                if(Strings.isNotBlank(boxMsg)){
                    String msgKey = "box." + storage.getCid();
                    DeviceAlarmMsgBean alarmMsgBean = new DeviceAlarmMsgBean(storage.getName(),msgKey,boxMsg);
                    alarmList.add(alarmMsgBean);
                }
            }
        }

        return alarmList;
    }

    /**
     * 查询当前正在出的工单的线别信息
     */
    @RequestMapping(value = "/currentOutLine")
    @ResponseBody
    public ResultBean currentOutLine(HttpServletRequest request){
        OutInfo currentOutInfo = outInfoCache.getCurrentExeOutInfo();
        if(currentOutInfo != null){
            Map<String,Object> resultMap = new HashMap<>();
            resultMap.put("hSerial", currentOutInfo.gethSerial());
            resultMap.put("so", currentOutInfo.getSo());
            resultMap.put("line", currentOutInfo.getLine());
            return ResultBean.newOkResult(resultMap);
        }
        return ResultBean.newOkResult("");
    }

    /**
     * 料架放上AGV时,根据RFID清理料架的缓存信息,使料架可以重复使用
     */
    @RequestMapping(value = "/agvRemoveRfid")
    @ResponseBody
    public ResultBean agvRemoveRfid(HttpServletRequest request){
        String realRfid = request.getParameter("rfid");
        log.info("料架放上AGV时,清理["+realRfid+"]的缓存信息");
        if(Strings.isNotBlank(realRfid)){
            InquiryShelfBean.agvRemoveRfid(realRfid);
        }
        return ResultBean.newOkResult("料架放上AGV时,清理["+realRfid+"]的缓存信息成功");
    }

    /**
     * 客户端进出轴报警时禁用库位
     */
    @RequestMapping("/disablePos")
    @ResponseBody
    public ResultBean enablePos(HttpServletRequest request) {
        String posName = request.getParameter("posName");
        try {
            StoragePos pos = storagePosManager.getByPosName(posName);
            if(pos != null){
                log.info("客户端禁用库位["+posName+"]");
                if(pos.isEnabled()){
                    pos.setEnabled(false);
                    storagePosManager.save(pos);
                    Storage storage = dataCache.getStorageById(pos.getStorageId());
                    dataCache.reloadStorage(storage);
                    return ResultBean.newOkResult("库位["+posName+"]禁用成功","");
                }else{
                    return ResultBean.newErrorResult(4003,"库位["+posName+"]已被禁用");
                }
            }else{
                return ResultBean.newErrorResult(4004,"未到到库位["+posName+"]");
            }
        }catch (Exception e){
            log.error("禁用库位出错",e);
            return ResultBean.newErrorResult(4005,"禁用库位出错:" + e.getMessage());
        }
    }



    /**
     * 点料机解析条码,用于获取料盘尺寸
     */
    @RequestMapping("/resolveCode")
    @ResponseBody
    public ResultBean resolveCode(HttpServletRequest request) {
        try {
            String code = request.getParameter("code");
            log.info("点料机解析获取条码["+code+"]尺寸");
            if(Strings.isNotBlank(code)){
                Collection<CodeBean> codeBeans = dataCache.resolveCodeStr(code);
                Barcode barcode = null;
                for (CodeBean codeBean : codeBeans) {
                    if(codeBean.isValid()){
                        if(barcode != null){
                            String msg = "找到多个有效条码";
                            return ResultBean.newErrorResult(5100,msg);
                        }else{
                            barcode = codeBean.getBarcode();
                        }
                    }
                }

                if(barcode == null){
                    String msg = "未找到有效条码";
                    return ResultBean.newErrorResult(5101,msg);
                }
                Map<String,Object> resultMap = new HashMap<>();
                resultMap.put("barcode", barcode.getBarcode());
                resultMap.put("pn",barcode.getPartNumber());
                resultMap.put("qty",barcode.getAmount());
                resultMap.put("w",barcode.getPlateSize());
                resultMap.put("h",barcode.getHeight());
                return ResultBean.newOkResult(resultMap);
            }

            return ResultBean.newErrorResult(5102,"未找到code参数");
        }catch (Exception e){
            log.error("点料机获取料盘尺寸出错",e);
            return ResultBean.newErrorResult(5103,"点料机获取料盘尺寸出错:" + e.getMessage());
        }
    }
}