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

import com.google.common.base.Strings;
import com.google.common.collect.Lists;
import com.google.common.collect.Sets;
import com.myproject.bean.json.ChartItem;
import com.myproject.bean.qisda.*;
import com.myproject.bean.update.*;
import com.myproject.bean.update.qisda.DNInfo;
import com.myproject.bean.update.qisda.OutInfo;
import com.myproject.bean.update.qisda.OutItem;
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.IStoragePosManager;
import com.myproject.util.*;
import com.myproject.webapp.controller.qisda.util.OutInfoCache;
import com.myproject.webapp.controller.qisda.util.SoseqCache;
import com.myproject.webapp.controller.storage.BaseController;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
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.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import java.io.IOException;
import java.util.*;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.stream.Collectors;


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

    @Autowired
    protected ITaskService taskService;

    @Autowired
    private IStoragePosDao storagePosDao;

    @Autowired
    private IOutItemDao outItemDao;

    @Autowired
    private IOutInfoDao outInfoDao;

    @Autowired
    private OutInfoCache outInfoCache;

    @Autowired
    private SoseqCache soseqCache;

    @Autowired
    private QisdaBindService qisdaBindService;

    @Autowired
    private IStoragePosManager storagePosManager;

    @Autowired
    private IBarcodeManager barcodeManager;
    @Autowired
    private DataCache dataCache;

    @Autowired
    private IDataLogDao dataLogDao;

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

    private static ExecutorService threadPool = Executors.newCachedThreadPool();
    /**
     * 基础数据同步
     */
    @RequestMapping(value = "/availableInventory")
    @ResponseBody
    public Object availableInventory(HttpServletRequest request) {
        try{
            String paramInfo = request.getParameter("paramInfo");
            if(Strings.isNullOrEmpty(paramInfo)){
                //从body里面再获取一次
                Map<String, String> bodyParamMap = getParamMapFromBody(request);
                paramInfo = bodyParamMap.get("paramInfo");
            }
            log.info("收到获取库存数量接口paramInfo="+paramInfo);
            if(Strings.isNullOrEmpty(paramInfo)){
                Map<String,String> resultMap = new HashMap<>();
                resultMap.put("errorcode","参数错误,参数paramInfo为空");
                return resultMap;
            }
            List<AvailableInventoryBean> results = new ArrayList<>();
            if(!Strings.isNullOrEmpty(paramInfo)){
                List<AvailableInventoryBean> items = JsonUtil.toList(paramInfo, AvailableInventoryBean.class);
                Map<String, Integer> availableMap = storagePosDao.availableInventory();
                for (AvailableInventoryBean item : items) {
                    String key = item.toMapKey();
                    Integer availableQty = availableMap.get(key);
                    if(availableQty != null && availableQty > 0){
                        //只有那些有可用库存的才返回,没有可用库存的不需要添加到返回结果中
                        item.setQty(availableQty);
                        results.add(item);
                    }
                }
            }

            if(results.isEmpty()){
                Map<String,String> resultMap = new HashMap<>();
                resultMap.put("msg","没有数据");
                return resultMap;
            }
            return results;
        }catch(Exception e){
            Map<String,String> resultMap = new HashMap<>();
            log.error("获取可用数量接口出错",e);
            resultMap.put("errorcode","系统错误," + e.getMessage());
            return resultMap;
        }

    }



    @RequestMapping("/executeOut")
    @ResponseBody
    public String executeOut(HttpServletRequest request){
        String hSerial = request.getParameter("hSerial");
        //OutInfo outInfo = outInfoCache.getOutInfoFromCache(hSerial);
        //qisdaBindService.realBindOutInfo(outInfo);
        log.info("手动执行需求单["+hSerial+"]出库");
        ResultBean resultBean = outInfoCache.checkOutOutItems(hSerial);
        return resultBean.getMsg();
    }

    /**
     * 判断条码是否可以入库
     */
    public static Barcode CISInCheck(DNInfo dnInfo, Barcode barcode) throws ValidateException{
        //纯入库
        if(barcode.getAppendInfo().isCISIn()){
            return QisdaApi.VMILocationInCheck(barcode);
        }else{
            QisdaApi.VMIMateriaReceiveJudge(dnInfo, barcode);
        }
        return null;
    }

    /**
     * 入库完成通知
     * @param barcode
     * @param task
     */
    public static void PutInFinished(Barcode barcode, DataLog task){
        //纯入库
        if(barcode.getAppendInfo().isCISIn()){
            String fullCode = barcode.getFullCodeStr();
            QisdaApi.VMILocationIn(barcode.getBarcode(),task.getPosName(),fullCode);
        }else{
            //DN单收料或Facility收料
            QisdaApi.VMIMateriaReceive(barcode, task);
        }
    }
    /**
     * 获取工单的绑定情况
     */
    @RequestMapping(value = "/soSeqLockInfo")
    @ResponseBody
    public ResultBean getSoSeqLockInfo(HttpServletRequest request){
        String soseqStr = receiveParamInfo(request,"soseq");
        String soStr = receiveParamInfo(request,"so");
        log.info("收到工单绑定查询请求so="+ soStr + " soseq="+soseqStr);
        Set<String> soseqSet = Sets.newHashSet();
        if(!Strings.isNullOrEmpty(soseqStr)){
            String[] soseqArr = soseqStr.split(",");
            for (String soseq : soseqArr) {
                soseqSet.add(soseq);
            }
        }

        if(!Strings.isNullOrEmpty(soStr)){
            String[] soArr = soStr.split(",");
            for (String so : soArr) {
                List<OutInfo> outInfos = outInfoDao.listBySo(so);
                for (OutInfo outInfo : outInfos) {
                    soseqSet.add(outInfo.getSoseq());
                }
            }
        }

        List<SoseqLockInfo> lockInfos = new ArrayList<>();
        for (String soseq : soseqSet) {
            SoseqLockInfo lockInfo = getLockInfo(soseq);
            lockInfos.add(lockInfo);
        }
        return ResultBean.newOkResult(lockInfos);
    }

    /**
     * 获取工单的实时绑定情况
     * 要求:
     * 1、传参:工单序号序号
     * 2、返回参数:
     * {"code":0,"msg":"ok","data":[{"soseq":"21266250","so":"1001011793","lockItems":[{"soseq":"21266
     * 250",
     * "slotlocation":112,"partNum":"EM.3DBH0.00M","qty":3900,realLockQty":3900},{"soseq":"2126625
     * 0",
     * "slotlocation":72,"partNum":"EM.7HBH0.006","qty":6650,"realLockQty":9784}]}]}
     */
    @RequestMapping(value = "/soSeqCurrentLockInfo")
    @ResponseBody
    public ResultBean soSeqCurrentLockInfo(HttpServletRequest request){
        String soseqStr = receiveParamInfo(request,"soseq");
        log.info("收到工单实时绑定查询请求soseq="+soseqStr);
        if(Strings.isNullOrEmpty(soseqStr)){
            return ResultBean.newErrorResult(-1,"参数错误:必须有参数soseq");
        }
        String[] soseqList = soseqStr.split(",");
        List<SoseqLockInfo> lockInfos = new ArrayList<>();
        for (String soseq : soseqList) {
            SoseqLockInfo soseqLockInfo = new SoseqLockInfo();
            soseqLockInfo.setSoseq(soseq);
            OutInfo cutActionInfoFromCache = soseqCache.getCutActionInfoFromCache(soseq);
            if(cutActionInfoFromCache != null){
                soseqLockInfo.setSo(cutActionInfoFromCache.getSo());
            }
            List<StoragePos> bindPosList = storagePosDao.listSoSeqBindPos(soseq);
            Map<String,LockItemInfo> lockItemMap = new HashMap<>();
            for (StoragePos storagePos : bindPosList) {
                Barcode reel = storagePos.getBarcode();
                AppendInfo appendInfo = reel.getAppendInfo();
                String bindSlot = appendInfo.getBindSlot();
                if(!Strings.isNullOrEmpty(bindSlot)){
                    LockItemInfo lockItemInfo = lockItemMap.get(bindSlot);
                    if(lockItemInfo == null){
                        lockItemInfo = new LockItemInfo();
                        lockItemInfo.setSoseq(appendInfo.getSoseq());
                        lockItemInfo.setSlotlocation(Integer.valueOf(bindSlot));
                        lockItemInfo.setPartNum(reel.getPartNumber());
                    }
                    int reelLockQty = lockItemInfo.getRealLockQty() + reel.getAmount();
                    lockItemInfo.setQty(reelLockQty);
                    lockItemInfo.setRealLockQty(reelLockQty);
                    lockItemMap.put(bindSlot,lockItemInfo);
                }
            }
            soseqLockInfo.setLockItems(new ArrayList<LockItemInfo>(lockItemMap.values()));
            lockInfos.add(soseqLockInfo);
        }

        return ResultBean.newOkResult(lockInfos);
    }

    private SoseqLockInfo getLockInfo(String soseq){
        SoseqLockInfo soseqLockInfo = new SoseqLockInfo();
        soseqLockInfo.setSoseq(soseq);
        OutInfo cutOutInfo = soseqCache.getCutActionInfoFromCache(soseq);
        if(cutOutInfo != null){
            soseqLockInfo.setSo(cutOutInfo.getSo());
            for (OutItem outItem : cutOutInfo.getOutItems()) {
                LockItemInfo lockItemInfo = new LockItemInfo();
                lockItemInfo.setSoseq(outItem.getSoseq());
                lockItemInfo.setSlotlocation(outItem.getSlotlocation());
                lockItemInfo.setPartNum(outItem.getPn());
                lockItemInfo.setQty(outItem.getQty());
                lockItemInfo.setPreLockQty(outItem.getLockQty());
                lockItemInfo.setRealLockQty(outItem.getRealLockQty());
                lockItemInfo.setTotalSendQty(outItem.getSendQty());
                lockItemInfo.setFirstSendQty(outItem.getOutQty());
                soseqLockInfo.addLockItem(lockItemInfo);
            }
        }
        return soseqLockInfo;
    }

    /**
     * 获取工单的小料盘绑定数量
     */
    @RequestMapping(value = "/getSmallBindCount")
    @ResponseBody
    public ResultBean smallBindCount(HttpServletRequest request){
        String soseqListStr = receiveParamInfo(request,"soseqList");
        log.info("收到获取工单的小料盘绑定数量 soseqList="+soseqListStr);
        String[] soseqList = soseqListStr.split(",");
        List<Map<String,String>> resultList = new ArrayList<>();
        for (String soseq : soseqList) {
            int smallBindCount = 0;
            List<StoragePos> bindPosList = storagePosDao.listSoSeqBindPos(soseq);
            for (StoragePos storagePos : bindPosList) {
                Barcode reel = storagePos.getBarcode();
                if(reel.isSmallReel()){
                    smallBindCount++;
                }
            }
            Map<String,String> itemMap = new HashMap<>();
            itemMap.put("soseq", soseq);
            itemMap.put("smallCount", "" + smallBindCount);
            log.info("soseq=["+soseq+"]小料盘绑定数量:" + smallBindCount);
            resultList.add(itemMap);
        }

        return ResultBean.newOkResult(resultList);
    }

    /**
     * 查询需求单是否存在
     */
    @RequestMapping(value = "/existHSerial")
    @ResponseBody
    public ResultBean existHSerial(HttpServletRequest request){
        String hSerialistStr = receiveParamInfo(request,"hSerialList");
        log.info("收到查询需求单是否存在 hSerialList="+hSerialistStr);
        String[] hSerialList = hSerialistStr.split(",");
        List<Map<String,String>> resultList = new ArrayList<>();
        for (String hSerial : hSerialList) {
            OutInfo outInfo = outInfoDao.findByHSerial(hSerial);
            boolean exist = false;
            if(outInfo != null){
                exist = true;
            }
            Map<String,String> itemMap = new HashMap<>();
            itemMap.put("hSerial", hSerial);
            itemMap.put("exist", exist + "");
            resultList.add(itemMap);
        }
        return ResultBean.newOkResult(resultList);
    }

    /**
     * 检测料盘是否绑定工单
     */
    @RequestMapping(value = "/checkLockReel",method = RequestMethod.POST)
    @ResponseBody
    public ResultBean checkLockSo(HttpServletRequest request) {
        List<Map<String, String>> bindReelInfos = new ArrayList<>();
        try {
            String paramInfo = receiveParamInfo(request,"paramInfo");
            log.info("收到检测锁定工单请求:"+paramInfo);
            if(paramInfo == null){
                return ResultBean.newErrorResult(-1,"参数为空");
            }
            List<String> reelIds = JsonUtil.toList(paramInfo, String.class);
            for (String reelId : reelIds) {
                //指定出某盘料或单独出库,如果已经绑定,不允许出,如果未绑定直接进行绑定
                StoragePos pos = storagePosDao.findByBarcode(reelId);
                if(pos != null){
                    Barcode barcode = pos.getBarcode();
                    AppendInfo appendInfo = barcode.getAppendInfo();
                    String so = appendInfo.getSo();
                    if(!Strings.isNullOrEmpty(so)){
                        String bindSlot = appendInfo.getBindSlot();
                        if(barcode.hasCutInfo()) {
                            bindSlot = "1";
                        }
                        //已经绑定过
                        Map<String,String> map = new HashMap<>();
                        map.put("reelId", reelId);
                        map.put("so", appendInfo.getSo());
                        map.put("slot", bindSlot);
                        bindReelInfos.add(map);
                    }

                }else{
                    //无库存,返回Not Found
                    Map<String,String> map = new HashMap<>();
                    map.put("reelId", reelId);
                    map.put("so", "Not Found");
                    bindReelInfos.add(map);
                }
            }
        } catch (Exception e) {
            log.error("检测料盘是否绑定工单请求处理出错", e);
            return ResultBean.newErrorResult(1001,"内部错误:" + e.getMessage());
        }
        return ResultBean.newOkResult(bindReelInfos);
    }

    /**
     * 关闭工单
     */
    @RequestMapping(value = "/closeSoSeq",method = RequestMethod.POST)
    @ResponseBody
    public ResultBean closeSoSeq(HttpServletRequest request) {
        try {
            String soseq = receiveParamInfo(request,"soseq");
            log.info("收到关闭工单请求soseq="+soseq);
            if(soseq == null){
                return ResultBean.newErrorResult(-1,"未找到soseq参数");
            }
            ResultBean resultBean = outInfoCache.closeSoSeq(soseq);
            return resultBean;
        } catch (Exception e) {
            log.error("需求单请求处理出错", e);
            return ResultBean.newErrorResult(1001,"内部错误:" + e.getMessage());
        }
    }

    /**
     * 线外发料接口
     */
    @RequestMapping(value = "/outLineSend")
    @ResponseBody
    public ResultBean outLineSend(HttpServletRequest request){
        try {
            String soseq = receiveParamInfo(request,"soseq");
            String slotserial = receiveParamInfo(request,"slotserial");
            String reelid = receiveParamInfo(request,"reelid");
            String pn = receiveParamInfo(request,"pn");
            String amount = receiveParamInfo(request,"amount");
            log.info("收到线外发料请求soseq="+soseq +" slotserial="+slotserial+" reelid="+reelid +" pn="+pn + " amount="+amount);
            if(soseq == null || slotserial == null || amount == null){
                return ResultBean.newErrorResult(-1,"参数错误:soseq,slotserial,amount为必须参数");
            }

            int outSendQty = Integer.valueOf(amount);

            OutItem cutOutItem = soseqCache.getCutOutItem(soseq, Integer.valueOf(slotserial));
            if(cutOutItem != null){
                int realBindQty = cutOutItem.getRealLockQty() + outSendQty;

                if(cutOutItem.isCutMaterial()){
                    if(DataCache.isProductionFor(DataCache.CUSTOMER.QISDA4D)){
                        //四楼线外发分盘料对已绑定的分盘料解绑,三楼不解绑
                        OutInfo cutOutInfo = soseqCache.getCutActionInfoFromCache(soseq);
                        cutOutInfo = outInfoCache.addEventItem(cutOutInfo,"线外发料,解绑站位["+slotserial+"]");
                        soseqCache.addTotalOutInfo(cutOutInfo);

                        //分盘料线外发料,全部分盘料进行解绑
                        List<StoragePos> bindPosList = storagePosDao.findBindList(soseq, Integer.valueOf(slotserial));
                        for (StoragePos storagePos : bindPosList) {
                            Barcode barcode = storagePos.getBarcode();
                            boolean hasTask = taskService.excludePosIds().contains(storagePos.getId());
                            if(hasTask){
                                log.info(barcode.getBarcode() + "["+storagePos.getPosName()+"]已有任务,不解绑");
                            }else{
                                log.info(reelid+"["+pn+"]线外发料,解除["+barcode.getBarcode()+"]的工单so=["+barcode.getAppendInfo().getSo()+"]soseq=["+barcode.getAppendInfo().getSoseq()+"]的站位["+slotserial+"]绑定");
                                storagePosDao.unbindReel(storagePos);
                            }

                        }
                        realBindQty = cutOutItem.getRealLockQty() + cutOutItem.getQty();
                    }
                }
                //更新发料数量,更新真实绑定数量
                soseqCache.addToTotalSendQty(cutOutItem,outSendQty);
                soseqCache.updateTotalRealLockQty(cutOutItem, realBindQty);
                //记录出入库日志
                saveOutLineTask(cutOutItem,reelid,pn,outSendQty);
                ResultBean resultBean = ResultBean.newOkResult("");
                return resultBean;
            }else{
                return ResultBean.newErrorResult(-1,"未找到soseq="+soseq+" slotserial="+slotserial+"的需求单");
            }

        } catch (Exception e) {
            log.error("需求单请求处理出错", e);
            return ResultBean.newErrorResult(1001,"内部错误:" + e.getMessage());
        }
    }

    /**
     * 替代料接口
     */
    @RequestMapping(value = "/replaceSlot")
    @ResponseBody
    public Object replaceSlot(HttpServletRequest request) {
        try {
            String paramInfo = receiveParamInfo(request,"paramInfo");
            log.info("收到替代料请求:"+paramInfo);
            if(paramInfo == null){
                return ResultBean.newErrorResult(-1,"参数为空");
            }

            List<RequestOutItemBean> items = JsonUtil.toList(paramInfo, RequestOutItemBean.class);

            //key为需求单号
            Map<String,OutInfo> cutOutInfoMap = new HashMap<>();
            log.info("替代料解析成功,开始处理");
            for (RequestOutItemBean itemBean : items) {
                String soseq = itemBean.getSoseq();
                int slotSeq = itemBean.getSlotlocation();
                OutInfo cutOutInfo = soseqCache.getCutActionInfoFromCache(soseq);
                if(cutOutInfo == null){
                    log.info("soseq="+soseq+"的分盘需求单不存在,不执行替代料逻辑");
                }else{
                    OutItem outItem = cutOutInfo.findOutItem(slotSeq);
                    if(outItem != null){
                        List<StoragePos> bindPosList = storagePosDao.findBindList(outItem.getSoseq(), outItem.getSlotlocation());
                        for (StoragePos storagePos : bindPosList) {
                            Barcode barcode = storagePos.getBarcode();
                            log.info("解除["+barcode.getBarcode()+"]的工单so=["+barcode.getAppendInfo().getSo()+"]soseq=["+barcode.getAppendInfo().getSoseq()+"]绑定,累计解除");
                            storagePos = storagePosDao.unbindReel(storagePos);
//                            barcode = storagePos.getBarcode();
//                            barcode = qisdaBindService.bindPutInReel(barcode);
//                            String bindSoseq = barcode.getAppendInfo().getSoseq();
//                            if(!Strings.isNullOrEmpty(bindSoseq)){
//                                log.info("料盘["+barcode.getBarcode()+"]绑定到新工单soseq="+bindSoseq);
//                                storagePos.setBarcode(barcode);
//                                storagePosDao.save(storagePos);
//                            }
                        }
                        outItem.setPn(itemBean.getPartNum());
                        outItem.setFacility(itemBean.getFacility());
                        outItem.setQty(itemBean.getQty());
                        outItem.setReelcut(itemBean.getReelcut());
                        outItem.setLockQty(-1);
                        outItem.setRealLockQty(0);
                        outItem.setFixedQty(0);
                        outItem = outItemDao.save(outItem);
                        outItem = outInfoCache.updateOutItem(outItem.getId());
                        cutOutInfo.updateItem(outItem);
                        soseqCache.addTotalOutInfo(cutOutInfo);
                        cutOutInfoMap.put(cutOutInfo.gethSerial(), cutOutInfo);
                    }
                }
            }

            for (OutInfo outInfo : cutOutInfoMap.values()) {
                log.info("工单"+outInfo.getSo()+"["+outInfo.getSoseq()+"]替代料处理完成,进行真实绑定");
                qisdaBindService.realBindOutInfo(outInfo);
            }
            return ResultBean.newOkResult("");
        } catch (Exception e) {
            log.error("替代料请求处理出错", e);
            return ResultBean.newErrorResult(1001,"内部错误:" + e.getMessage());
        }
    }

    /**
     * 更新需求单时间
     */
    @RequestMapping(value = "/updateOutInfo",method = RequestMethod.POST)
    @ResponseBody
    public Object updateOutInfo(HttpServletRequest request) {
        try {
            String paramInfo = receiveParamInfo(request,"paramInfo");
            log.info("收到需求单修改时间请求:"+paramInfo);
            if(paramInfo == null){
                return ResultBean.newErrorResult(-1,"参数为空");
            }

            List<RequestOutItemBean> items = JsonUtil.toList(paramInfo, RequestOutItemBean.class);
            Map<String,String> resultMap = new HashMap<>();
            log.info("需求单修改时间请求解析成功,开始处理");

            for (RequestOutItemBean itemBean : items) {
                OutItem outItem = new OutItem(itemBean);
                String hSerial = outItem.gethSerial();
                OutInfo outInfo = outInfoCache.getOutInfoFromCache(hSerial);
                String resultMsg = "";
                if(outInfo == null){
                    resultMsg = "需求单号不存在";
                }else{
                    boolean outInfoExecuted = outInfo.getFirstExecuteTime() > 0;
                    if(outInfoExecuted){
                        resultMsg = "需求单已执行过,不允许修改";
                    }else{
                        Date now = new Date();
                        Date oldMustDate = outInfo.getMdate();
                        Date newSuggestDate = outItem.getSdate();
                        Date newMustDate = outItem.getMdate();
//                        if(oldMustDate.before(now)){
//                            resultMsg = "需求单已到达必须时间,不允许修改";
//                        }else
                        if(newSuggestDate.before(now)){
                            resultMsg = "新的建议时间不能早于当前时间";
                        }else if(newMustDate.before(now)){
                            resultMsg = "新的必须时间不能早于当前时间";
                        }else{
                            outInfo.setMdate(outItem.getMdate());
                            outInfo.setSdate(outItem.getSdate());
                            outInfoCache.updateSMDate(outInfo);
                            resultMsg = "ok";
                        }
                    }
                }
                resultMap.put(hSerial, resultMsg);
                log.info("需求单["+hSerial+"]修改时间结果:"+resultMsg);
            }
            return ResultBean.newOkResult(resultMap);
        } catch (Exception e) {
            log.error("需求单修改时间请求处理出错", e);
            return ResultBean.newErrorResult(1001,"内部错误:" + e.getMessage());
        }
    }

    private void handleOutRequest(List<RequestOutItemBean> items){

        try {
            //key为需求单号
            Map<String, OutInfo> outInfoMap = new HashMap<>();

            log.info("开始处理需求单");
            for (RequestOutItemBean itemBean : items) {
                OutItem outItem = new OutItem(itemBean);
                String hSerial = outItem.gethSerial();
                OutInfo outInfo = outInfoMap.get(hSerial);
                if(outInfo == null){
                    outInfo = outInfoDao.findByHSerial(hSerial);
                    if(outInfo == null){
                        outInfo = new OutInfo(outItem);
                    }
                }
                String reelID = outItem.getReelID();
                if(reelID != null && !reelID.isEmpty()){
                    //指定出某盘料或单独出库,如果已经绑定,不允许出,如果未绑定直接进行绑定
                    StoragePos pos = storagePosDao.findByBarcode(reelID);
                    if(pos != null){
                        Barcode barcode = pos.getBarcode();
                        AppendInfo appendInfo = barcode.getAppendInfo();
                        int bindSlot = Integer.valueOf(appendInfo.getBindSlot());
                        if(bindSlot > 0 || barcode.hasCutInfo()){
                            //已经真实绑定过
                            log.error("料盘["+reelID+"]已经真实绑定过,不允许出库");
                        }else{
                            //未真实绑定过,可以出库,绑定
                            appendInfo.sethSerial(outItem.gethSerial());
                            appendInfo.setRefno(outItem.getRefno());
                            appendInfo.setSo("HSerial-" + outItem.gethSerial());
                            appendInfo.setSoseq("HSerial-" + outItem.gethSerial());
                            appendInfo.setSlotStr(outItem.getSlotStr());

                            appendInfo.setBindSlot("1");
                            appendInfo.setSlotIndex(1);

                            barcode.setAppendInfo(appendInfo);
                            pos.setBarcode(barcode);
                            storagePosDao.save(pos);
                            outItem.setLockQty(barcode.getAmount());
                            outItem.setRealLockQty(barcode.getAmount());
                            outItem = outItemDao.save(outItem);

                            outInfo.updateItem(outItem);
                            outInfoMap.put(hSerial, outInfo);
                        }

                    }else{
                        //未找到指定料盘
                        log.error("料盘["+reelID+"]未找到,可能已经出库,不允许出库");
                    }
                }else{
                    //不是指定料
                    if(outItem.isReelCutAction() || outItem.isFirstReelAction() || outItem.isTailAction()){
                        //判断是否有重复,如果有重复,忽略
                        OutItem oldItem = outItemDao.findItem(outItem.gethSerial(), outItem.getSlotlocation());
                        if(oldItem != null){
                            log.error("需求单["+outItem.gethSerial()+"]的站位["+outItem.getSlotlocation()+"]已存在,忽略");
                            continue;
                        }
                    }
                    outItem = outItemDao.save(outItem);
                    outInfo.updateItem(outItem);
                    outInfoMap.put(hSerial, outInfo);
                }
            }

            //分盘需求单进行预绑定
            qisdaBindService.preBindCutOutInfoList(outInfoMap.values());

            for (OutInfo outInfo : outInfoMap.values()) {

                int bindReelNum = 0;
                if(!outInfo.isPreTailAction()){
                    bindReelNum = getBindReelNum(outInfo);
                    outInfo.setTotalBindNum(bindReelNum);
                }

                log.info("创建出库需求单["+outInfo.gethSerial()+"]" + outInfo.getAction() + " 预估需求料盘数量为:" + bindReelNum);
                outInfoDao.save(outInfo);
                //新的需求单,更新缓存
                outInfoCache.addOutInfo(outInfo);
            }


        } catch (Exception e) {
            log.error("需求单处理出错", e);
        }

    }

    /**
     * 创建需求单
     */
    @RequestMapping(value = "/out",method = RequestMethod.POST)
    @ResponseBody
    public Object out(HttpServletRequest request) {
        List<String> failedReelIdList = new ArrayList<>();
        try {
            String paramInfo = receiveParamInfo(request,"paramInfo");
            log.info("收到需求单请求:"+paramInfo);
            if(paramInfo == null){
                return ResultBean.newErrorResult(-1,"参数为空");
            }

            final List<RequestOutItemBean> items = JsonUtil.toList(paramInfo, RequestOutItemBean.class);
            threadPool.execute(new Runnable() {
                @Override
                public void run() {
                    handleOutRequest(items);
                }
            });
        } catch (Exception e) {
            log.error("需求单请求处理出错", e);
            return ResultBean.newErrorResult(1001,"内部错误:" + e.getMessage());
        }
        return ResultBean.newOkResult("");
    }



    /**
     * 出库接口 (出仓完成时调用)
     * @param task 任务信息
     * @param latest 本次工单第几盘料(F 第一次,L 最后一次, M 中间)
     */
    public static void OutFinished(DataLog task, Barcode barcode, String latest){
        AppendInfo appendInfo = task.getAppendInfo();
        if(appendInfo.isFirstReelAction() || appendInfo.isTailAction()){
            log.info("工单料任务,出库时发送空的FML状态");
            latest = "";
        }

        Map<String, Object> materialInfoMap = getOutMaterialInfoMap(task, latest);
        List<Map<String, Object>> cutItems = barcode.getCutItems();
        if(cutItems != null){
            //有分盘信息,需要发送多次
            for (Map<String, Object> cutItem : cutItems) {
                Object hSerial = cutItem.get("hSerial");
                materialInfoMap.put("hSerial",hSerial);
                Object so = cutItem.get("so");
                materialInfoMap.put("so",so);
                Object qty = cutItem.get("qty");
                materialInfoMap.put("qty",qty + "");
                Object flag = cutItem.get("flag");
                materialInfoMap.put("flag", flag);//子盘或母盘(L:子盘,M:母盘,其他'')
                Object slot = cutItem.get("slot");
                materialInfoMap.put("slot", slot);

                Object slotlocation = cutItem.get("slotlocation");
                materialInfoMap.put("slotserial", slotlocation + "");

                log.info(barcode.getBarcode() + "发送分盘料信息:" + cutItem);
                QisdaApi.VMILocationOut(barcode.getBarcode(),materialInfoMap);
            }
        }else{
            QisdaApi.VMILocationOut(barcode.getBarcode(), materialInfoMap);
        }
    }


//-------------------------Private Method----------------------------------------


    /**
     * 更新需求单的绑定数量
     */
    private int getBindReelNum(OutInfo outInfo){
        List<OutItem> allItems = outInfo.getOutItems();
        if(outInfo.isUrgentAction()){
            //紧急料,每一条是一盘
            return allItems.size();
        }else if(outInfo.isReelCutAction()){
            //分盘,需求数量与分盘任务数相同
            int cutReelCount = 0;
            for (OutItem outItem : allItems) {
                if(outItem.isCutMaterial()){
                    List<StoragePos> cutPosList = storagePosDao.findCutList(outItem.getSo(), outItem.getSlotlocation(),outItem.getSoseq());
                    cutReelCount = cutReelCount + cutPosList.size();
                }
            }
            return cutReelCount;
        }else if(outInfo.isFirstReelAction()){
            //首盘
            int bindNum = 0;
            OutInfo cutOutInfo = soseqCache.getCutActionInfoFromCache(outInfo.getSoseq());
            if(cutOutInfo != null){
                for (OutItem outItem : cutOutInfo.getOutItems()) {
                    if(outItem.getRealLockQty()>0){
                        bindNum++;
                    }
                }
            }else{
                //每一条有料的是一盘
                //bindNum = allItems.size();
            }

            return bindNum;
        }else if(outInfo.isTailAction()){
            //尾料,根据绑定信息进行统计
            //绑定信息暂时放到ChartItem中,value1为需求量,value2为累计物料数量,value3为累计料盘数量
            Map<String,ChartItem> bindItemMap = new HashMap<>();
            for (OutItem outItem : allItems) {
                String slotLocationStr = outItem.getSlotlocation() + "";
                int needNum = outItem.getQty();
                ChartItem bindItem = new ChartItem();
                bindItem.setLabel(slotLocationStr);
                bindItem.setValue(needNum);
                bindItemMap.put(bindItem.getLabel(), bindItem);
            }
            List<StoragePos> bindList = storagePosDao.listSoSeqBindPos(outInfo.getSoseq());
            for (StoragePos storagePos : bindList) {
                Barcode barcode = storagePos.getBarcode();
                String slotIndex = barcode.getAppendInfo().getPreBindSlot();
                ChartItem bindItem = bindItemMap.get(slotIndex);
                if(bindItem != null){
                    if(bindItem.getValue2() < bindItem.getValue()){
                        //未满足需求
                        int amount = barcode.getAmount();
                        int bindAmount = bindItem.getValue2() + amount;
                        int reelNum = bindItem.getValue3() + 1;
                        bindItem.setValue2(bindAmount);
                        bindItem.setValue3(reelNum);
                        bindItemMap.put(bindItem.getLabel(), bindItem);
                    }
                }
            }
            int totalBindReelNum = 0;
            for (ChartItem chartItem : bindItemMap.values()) {
                totalBindReelNum = totalBindReelNum + chartItem.getValue3();
            }
            return totalBindReelNum;
        }
        return 0;
    }

    /**
     * 出仓完成时的参数
     * @param task
     * @param latest
     * @return
     */
    private static Map<String,Object> getOutMaterialInfoMap(DataLog task, String latest){
        Map<String,Object> materialInfoMap = new HashMap<String,Object>();
        AppendInfo appendInfo = task.getAppendInfo();
        materialInfoMap.put("hSerial",appendInfo.gethSerial());
        materialInfoMap.put("so",appendInfo.getSo());
        materialInfoMap.put("qty",task.getNum() + "");
        materialInfoMap.put("flag", "");//子盘或母盘(L:子盘,M:母盘,其他'')
        materialInfoMap.put("slot", appendInfo.getSlotStr());
        materialInfoMap.put("slotserial", appendInfo.getSlotIndex());

        materialInfoMap.put("action",appendInfo.getAction());
        materialInfoMap.put("partNum",task.getPartNumber());
        materialInfoMap.put("cloudLocation",task.getStorageName());//云料仓的库位
        materialInfoMap.put("vehicleID","");//料车编号
        materialInfoMap.put("vehicleLocation","");//料车架位号
        materialInfoMap.put("facility",appendInfo.getFacility());
        materialInfoMap.put("latest",latest);//本次工单第几盘料(F 第一次,L 最后一次, M 中间)
        materialInfoMap.put("reelID",task.getBarcode());
        materialInfoMap.put("location",task.getPosName());//料架库位
        String odte = DateUtil.toDateString(task.getUpdateDate(), "yyyyMMdd");
        String otme = DateUtil.toDateString(task.getUpdateDate(), "HHmmss");
        materialInfoMap.put("odte",odte);//出库日期
        materialInfoMap.put("otme",otme);//出库时间
        return materialInfoMap;
    }



    /**
     * 获取接收参数
     */
    private String receiveParamInfo(HttpServletRequest request, String paramKey){
        String paramInfo = request.getParameter(paramKey);
        if(Strings.isNullOrEmpty(paramInfo)){
            //从body里面再获取一次
            Map<String, String> bodyParamMap = getParamMapFromBody(request);
            paramInfo = bodyParamMap.get(paramKey);
        }
        return paramInfo;
    }



    private Map<String, String> getParamMapFromBody(HttpServletRequest request){
        Map<String,String> paramMap = new HashMap<>();
        try {
            String params = request.getReader().lines().collect(Collectors.joining(System.lineSeparator()));
            if(!Strings.isNullOrEmpty(params)){
                String[] paramArr = params.split("&");
                for (String paramInfo : paramArr) {
                    String[] arr = paramInfo.split("=");
                    if(arr.length == 2){
                        paramMap.put(arr[0],arr[1]);
                    }else{
                        log.error("参数错误:" + paramInfo);
                    }
                }
            }
        } catch (IOException e) {
            log.info("解析body参数出错",e);
        }
        return paramMap;
    }

    private void saveOutLineTask(OutItem outItem, String reelId, String pn, int outSendQty){
        try{
            DataLog task = new DataLog();
            task.setType(StorageConstants.OP.CHECKOUT);
            task.setStatus(StorageConstants.OP_STATUS.FINISHED.name());
            task.setSourceName("线外_"+ outItem.getSo() + "_" + outItem.getSlotlocation());

            StoragePos pos = storagePosDao.findByBarcode(reelId);
            AppendInfo appendInfo = new AppendInfo();
            if(pos != null){

                task.setCid("");
                task.setStorageId(pos.getStorageId());
                task.setStorageName("");

                task.setPosId(pos.getId());
                task.setPosName(pos.getPosName());

                Barcode barcode = pos.getBarcode();
                if(barcode != null){
                    task.setPartNumber(barcode.getPartNumber());
                    task.setBarcode(barcode.getBarcode());
                    task.setNum(barcode.getInitialAmount());
                    task.setW(barcode.getPlateSize());
                    task.setH(barcode.getHeight());

                    appendInfo = barcode.getAppendInfo();

                    log.info("线外发料["+outItem.getSoseq()+"]时,清理库位["+pos.getPosName()+"]中的库存"+barcode.getBarcode());
                    barcode.setPosName("");
                    barcodeManager.save(barcode);
                    pos.setBarcode(null);
                    pos.setUsed(false);
                    storagePosManager.save(pos);
                    dataCache.updateInventory(pos,barcode);
                }
            }else{
                task.setPartNumber(pn);
                task.setBarcode(reelId);
                task.setNum(outSendQty);
            }

            appendInfo.setSo(outItem.getSo());
            appendInfo.setSoseq(outItem.getSoseq());
            appendInfo.setRefno(outItem.getRefno());
            appendInfo.sethSerial(outItem.gethSerial());
            appendInfo.setSlotStr(outItem.getSlotStr());
            appendInfo.setSlotIndex(outItem.getSlotlocation());
            appendInfo.setAction(outItem.getAction());
            appendInfo.setOutItemId(outItem.getId());

            task.setAppendInfo(appendInfo);
            dataLogDao.save(task);
        }catch (Exception ex){
            log.info("线外发料出错",ex);
        }
    }


}