QisdaApiController.java 66.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 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 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 1198 1199 1200 1201 1202 1203 1204 1205 1206 1207 1208 1209 1210 1211 1212 1213 1214 1215 1216 1217 1218 1219 1220 1221 1222 1223 1224 1225 1226 1227 1228 1229 1230 1231 1232 1233 1234 1235 1236 1237 1238 1239 1240 1241 1242 1243 1244 1245 1246 1247 1248 1249 1250 1251 1252 1253 1254 1255 1256 1257 1258 1259 1260 1261 1262 1263 1264 1265 1266 1267 1268 1269 1270 1271 1272 1273 1274 1275 1276 1277 1278 1279 1280 1281 1282 1283 1284 1285 1286 1287 1288 1289 1290 1291 1292 1293 1294 1295 1296 1297 1298 1299 1300 1301 1302 1303 1304 1305 1306 1307 1308 1309 1310 1311 1312 1313 1314 1315 1316 1317 1318 1319 1320 1321 1322 1323 1324 1325 1326 1327 1328 1329 1330 1331 1332 1333 1334 1335 1336 1337 1338 1339 1340 1341 1342 1343 1344 1345 1346 1347 1348 1349 1350 1351 1352 1353 1354 1355 1356 1357 1358 1359 1360 1361 1362 1363 1364 1365 1366 1367 1368 1369 1370 1371 1372 1373 1374 1375 1376 1377 1378 1379 1380 1381 1382 1383 1384 1385 1386 1387 1388 1389 1390 1391 1392 1393 1394 1395 1396 1397 1398 1399 1400 1401 1402 1403 1404 1405 1406 1407 1408 1409 1410 1411 1412 1413 1414 1415 1416 1417 1418 1419 1420 1421 1422 1423 1424 1425 1426 1427 1428 1429 1430 1431 1432 1433 1434 1435 1436 1437 1438 1439 1440 1441 1442 1443 1444 1445 1446 1447 1448 1449 1450 1451 1452 1453 1454 1455 1456 1457 1458 1459 1460 1461 1462 1463 1464 1465 1466 1467
package com.myproject.webapp.controller.webService;

import com.google.common.base.Strings;
import com.google.common.collect.Lists;
import com.myproject.bean.qisda.*;
import com.myproject.bean.update.*;
import com.myproject.bean.update.qisda.DNInfo;
import com.myproject.bean.update.qisda.DNItem;
import com.myproject.bean.update.qisda.OutInfo;
import com.myproject.bean.update.qisda.OutItem;
import com.myproject.dao.mongo.IBarcodeDao;
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.ApiException;
import com.myproject.exception.ValidateException;
import com.myproject.manager.IComponentManager;
import com.myproject.util.*;
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.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.stream.Collectors;


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

    @Autowired
    protected ITaskService taskService;

    @Autowired
    protected IComponentManager componentManager;

    @Autowired
    private IStoragePosDao storagePosDao;

    @Autowired
    private IOutItemDao outItemDao;

    @Autowired
    private IOutInfoDao outInfoDao;

    @Autowired
    private IBarcodeDao barcodeDao;

    @Autowired
    private DataCache dataCache;

    @Autowired
    private IDataLogDao dataLogDao;

    @Autowired
    private OutInfoCache outInfoCache;

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

    private static String USER_NAME = "SMD-BOX";

    /**
     * 基础数据同步
     */
    @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");
        String maxReelStr = request.getParameter("max");
        int maxReelNum = -1;
        if(maxReelStr != null){
            maxReelNum = Integer.valueOf(maxReelStr);
        }
        return checkOutOutItems(hSerial,maxReelNum);
    }

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

    /**
     * 入库完成通知
     * @param barcode
     * @param task
     */
    public static void PutInFinished(Barcode barcode, DataLog task){
        //纯入库
        if(barcode.getAppendInfo().isCISIn()){
            VMILocationIn(barcode.getBarcode(),task.getPosName());
        }else{
            //DN单收料或Facility收料
            VMIMateriaReceive(barcode, task);
        }
    }

    /**
     * 出库
     */
    @RequestMapping(value = "/out",method = RequestMethod.POST)
    @ResponseBody
    public Object out(HttpServletRequest request) {
        List<String> failedReelIdList = new ArrayList<>();
        try {
            String paramInfo = request.getParameter("paramInfo");
            if(Strings.isNullOrEmpty(paramInfo)){
                //从body里面再获取一次
                Map<String, String> bodyParamMap = getParamMapFromBody(request);
                paramInfo = bodyParamMap.get("paramInfo");
            }
            log.info("收到需求单请求:"+paramInfo);
            if(paramInfo == null){
                return ResultBean.newErrorResult(-1,"参数为空");
            }

            List<RequestOutItemBean> items = JsonUtil.toList(paramInfo, RequestOutItemBean.class);
            //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){
                        log.info("创建出库需求单["+hSerial+"]");
                        outInfo = new OutInfo(outItem);
                        outInfo = outInfoDao.save(outInfo);
                    }
                }

                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+"]已经真实绑定过,不允许出库");
                            failedReelIdList.add(reelID);
                        }else{
                            //未真实绑定过,可以出库,绑定
                            appendInfo.sethSerial(outItem.gethSerial());
                            appendInfo.setRefno(outItem.getRefno());
                            appendInfo.setSo("HSerial:" + outItem.gethSerial());
                            appendInfo.setSoseq("HSerial:" + outItem.getSoseq());
                            appendInfo.setSlotStr(outItem.getSlotStr());

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

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

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

                    }else{
                        //未找到指定料盘
                        log.error("料盘["+reelID+"]未找到,可能已经出库,不允许出库");
                        failedReelIdList.add(reelID);
                    }
                }else{
                    //不是指定料
                    outItem = outItemDao.save(outItem);
                    outInfo.updateItem(outItem);
                    outInfoMap.put(hSerial, outInfo);
                }
            }

            bindOutInfoList(outInfoMap.values());

            log.info("需求单请求处理完成");
        } catch (Exception e) {
            log.error("需求单请求处理出错", e);
            return ResultBean.newErrorResult(1001,"内部错误:" + e.getMessage());
        }
        if(!failedReelIdList.isEmpty()){
            String data = String.join(";",failedReelIdList);
            return ResultBean.newOkResult(data);
        }
        return ResultBean.newOkResult("");
    }

    private void bindOutInfoList(Collection<OutInfo> outInfoList){

        for (OutInfo outInfo : outInfoList) {
            if(outInfo.isReelCutAction() || outInfo.isFirstReelAction()){
                //首盘和分盘进行缺料反馈
                log.info("需求单["+outInfo+"]开始进行绑定");
                for (OutItem outItem : outInfo.getOutItems()) {
                    if(outItem.isReelCutAction()){//分盘
                        firstBindCutReel(outItem);
                        preBindReel(outItem);
                    }else if(outItem.isFirstReelAction()){//首盘
                        firstBindCutReel(outItem);
                        secondBindCutReel(outItem);
                        realBindReel(outItem);
                        bindSamePnFromOtherSlotForFirstAction(outItem,new ArrayList<String>());

                    }else{//补料盘,急料,指定料,单独出库

                    }
                }
            }else{
                log.info("需求单["+outInfo+"]不需要进行绑定");
            }
        }

        for (OutInfo outInfo : outInfoList) {
            if(outInfo.isReelCutAction()){
                //首盘和分盘进行缺料反馈
                log.info("分盘需求单["+outInfo+"]开始进行二次分盘绑定");
                for (OutItem outItem : outInfo.getOutItems()) {
                    if(outItem.isReelCutAction()){//分盘
                        secondBindCutReel(outItem);
                    }
                }
            }
        }

        for (OutInfo outInfo : outInfoList) {
            //新的需求单,更新缓存
            outInfoCache.addOutInfo(outInfo);

            if(outInfo.isReelCutAction() || outInfo.isFirstReelAction()){
                //首盘和分盘进行缺料反馈
                List<OutItem> outItemList = outItemDao.findByHSerial(outInfo.gethSerial());
                boolean lessBind = true;
                VMILocationOutFeedback(outItemList, lessBind);
            }else{
                log.info("需求单["+outInfo+"]不需要进行缺料反馈");
            }
        }

    }

    /**
     * 检查首盘料中不同Slot上相同的PN, 如果缺料,出首盘时要保证每一个Slot上都有料
     */
    private void bindSamePnFromOtherSlotForFirstAction(OutItem outItem, Collection<String> excludeBarcodeList){
        if(outItem.getRealLockQty() == 0){
            //绑定数量为0,说明缺料,查找是否有绑定的本工单的其他Slot相同PN的料
            List<StoragePos> posList = storagePosDao.findBindByPn(outItem.getSoseq(), outItem.getPn());
            if(posList != null && !posList.isEmpty()){
                //站位的绑定的料盘数量,大于2盘才可以抢
                Map<String,Integer> slotReelCountMap = new HashMap<>();
                for (StoragePos storagePos : posList) {
                    //其他工位绑定至少两盘才可以抢
                    Barcode barcode = storagePos.getBarcode();
                    String bindSlot = barcode.getAppendInfo().getBindSlot();
                    if(bindSlot != null){
                        Integer reelCount = slotReelCountMap.get(bindSlot);
                        if(reelCount == null){
                            reelCount = 0;
                        }
                        reelCount = reelCount + 1;
                        slotReelCountMap.put(bindSlot, reelCount);
                    }
                }
                List<String> canRobSlotList = new ArrayList<>();
                for (StoragePos storagePos : posList) {
                    //其他工位绑定至少两盘才可以抢
                    Barcode barcode = storagePos.getBarcode();
                    String bindSlot = barcode.getAppendInfo().getBindSlot();
                    if(bindSlot != null){
                        Integer reelCount = slotReelCountMap.get(bindSlot);
                        if(reelCount >= 2){
                            canRobSlotList.add(bindSlot);
                        }
                    }
                }

                //抢最大的一盘
                StoragePos robPos = null;
                for (StoragePos storagePos : posList) {
                    //其他工位绑定至少两盘才可以抢
                    Barcode barcode = storagePos.getBarcode();
                    String bindSlot = barcode.getAppendInfo().getBindSlot();
                    if(bindSlot != null && canRobSlotList.contains(bindSlot)){
                        if(!excludeBarcodeList.contains(barcode.getBarcode())){
                            //这盘料可以抢
                            if(robPos == null || robPos.getBarcode().getAmount() < barcode.getAmount()){
                                robPos = storagePos;
                            }
                        }
                    }
                }

                if(robPos != null){
                    Barcode barcode = robPos.getBarcode();
                    AppendInfo appendInfo = barcode.getAppendInfo();
                    String hSerial = outItem.gethSerial();
                    int reelQty = barcode.getAmount();
                    String oldSlot = appendInfo.getBindSlot();
                    log.info("首盘需求单["+hSerial+"]站位["+outItem.getSlotlocation()+"]缺料,从站位["+oldSlot+"]绑定料盘中抢夺料盘"+barcode.getBarcode()+"["+reelQty+"]进行绑定");
                    OutItem oldItem = outItemDao.findItem(hSerial,Integer.valueOf(oldSlot));
                    oldItem.setRealLockQty(oldItem.getRealLockQty() - reelQty);
                    outItemDao.save(oldItem);

                    appendInfo.setBindSlot(outItem.getSlotlocation() + "");
                    barcode.setAppendInfo(appendInfo);
                    barcodeDao.save(barcode);
                    robPos.setBarcode(barcode);
                    storagePosDao.save(robPos);
                    outItem.setRealLockQty(outItem.getRealLockQty() + reelQty);
                    outItemDao.save(outItem);
                    outInfoCache.updateOutItem(oldItem.getId());
                    outInfoCache.updateOutItem(outItem.getId());
                }

            }


        }
    }

    /**
     * 移远料号转换
     */
    public static String PartNoMapping(String vdPartNum) throws ApiException{
        String url = "http://10.85.17.233/ESMTCommonInterface/CommonService.asmx/PartNoMapping";
        Map<String,Object> paramMap = new HashMap<String,Object>();
        paramMap.put("vdPartNum",vdPartNum);
        log.info("从Qisda获取料号转换:vdPartNum=" + vdPartNum);

        String result = HttpHelper.postParam(url,paramMap);
        log.info("从Qisda获取料号转换:(PartNoMapping)返回:" + result);
        Map<String, Object> resultMap = JsonUtil.toMap(result);
        String msg = resultMap.get("msg").toString();
        if(msg.startsWith("0")){
            String errorMsg = "从Qisda获取料号["+vdPartNum+"]转换出错:" + msg;
            log.info(errorMsg);
            throw new ApiException(errorMsg);
        }
        return msg;
    }


    /**
     *
     * 缺料反馈接口 (出完工单时调用),绑定首盘不管是否缺料都调用,其他类型的只在所有出库完成时调用一次
     *
     * 只有首盘会反馈多次缺料信息,若首盘反馈第一次缺料后,料自动匹配齐了,第二次反馈时料号传N/A
     *
     * @param outItemList
     * @param lessBind 是否是绑定缺料反馈
     */
    public static void VMILocationOutFeedback(List<OutItem> outItemList, boolean lessBind){
        String url = "http://10.85.17.233/ESMTCommonInterface/CommonService.asmx/VMILocationOutFeedback";
        List<Map<String,Object>> materialInfoList = new ArrayList<>();
        for (OutItem outItem : outItemList) {
            Map<String,Object> materialInfoMap = new HashMap<String,Object>();
            materialInfoMap.put("so",outItem.getSo());//DN单号或者是厂别
            materialInfoMap.put("partNum",outItem.getPn());//料号
            int lossqty = outItem.outLessQty();
            if(lessBind){
                //绑定缺料反馈
                lossqty = outItem.preBindLessQty();
            }

            materialInfoMap.put("lossqty",lossqty + "");//缺料数量
            materialInfoMap.put("slot",outItem.getSlotStr());//料站
            materialInfoMap.put("serial",outItem.gethSerial());//需求单号

            materialInfoList.add(materialInfoMap);
        }

        if(materialInfoList.isEmpty()){
            log.info("需求单不缺料,不进行缺料反馈");
        }else{
            String lackOfMaterial = JsonUtil.toJsonStr(materialInfoList);
            Map<String,Object> paramMap = new HashMap<String,Object>();
            paramMap.put("lackOfMaterial",lackOfMaterial);
            log.info("缺料反馈接口(VMILocationOutFeedback)参数lackOfMaterial="+lackOfMaterial);
            try {
                String result = HttpHelper.postParam(url,paramMap);
                log.info("收到缺料反馈接口(VMILocationOutFeedback)返回:" + result);
            } catch (ApiException e) {
                log.error("缺料反馈接口(VMILocationOutFeedback)接口出错",e);
            }
        }
    }

    /**
     * 获取DN单详情
     * @param dnNo
     * @param isCheck
     * @return
     * @throws ApiException
     */
    public static List<DNItem> GetDNDetails(String dnNo, boolean isCheck) throws ApiException {

        String url = "http://10.85.17.43:8080/WMSWeb.asmx/GetDNDetailsJson";
        Map<String,Object> paramMap = new HashMap<String,Object>();
        //paramMap.put("DHNO","DNMISW1911197845");
        paramMap.put("DHNO",dnNo);
        String isCheckStr = "N";
        if(isCheck){
            isCheckStr = "Y";
        }
        paramMap.put("ISCheck",isCheckStr);
        paramMap.put("isBack","Y");
        String errorMsg = "";
        Map<String,DNItem> itemMap = new HashMap<>();
        try {
            String returnResult = HttpHelper.postParam(url,paramMap);
            log.info("获取DN单详情结果:" + returnResult);
            String resultStr = XmlUtil.getNodeBody("string", returnResult);
            if(resultStr.startsWith("[")){
                List<Map<String,Object>> items = JsonUtil.toObj(resultStr, List.class);
                for (Map<String,Object> map : items) {
                    DNItem item = new DNItem();
                    String no = map.get("DLNO").toString();
                    item.setDnNo(no);

                    String dnDateStr = map.get("DLCRDTE").toString()+ " " + map.get("DLCRTIME").toString();
                    item.setDnDateStr(dnDateStr);

                    int dnQty = Float.valueOf(map.get("WACTQTY").toString()).intValue();
                    item.setDnQty(dnQty);

                    String facility = map.get("WPORD").toString();
                    item.setFacility(facility);

                    String company = map.get("DSN").toString();
                    item.setCompany(company);

                    String pn = map.get("WPROD").toString();
                    item.setPn(pn);

                    DNItem dnItem = itemMap.get(pn);
                    if(dnItem != null){
                        int totalDNQty = dnItem.getDnQty() + item.getDnQty();
                        log.info("PN["+pn+"]有重复,合并数量[" + dnItem.getDnQty() +" + " + item.getDnQty() + " = " + totalDNQty);
                        dnItem.setDnQty(totalDNQty);
                    }else{
                        dnItem = item;
                    }
                    itemMap.put(pn, dnItem);
                }
            }else{
                //返回错训误了
                errorMsg = resultStr;
            }
        } catch (Exception e) {
            errorMsg = e.getMessage();
            log.error("获取DN单详情接口出错",e);
        }

        if(!Strings.isNullOrEmpty(errorMsg)){
            throw new ApiException(errorMsg);
        }
        List<DNItem> dnItems = Lists.newArrayList();
        if(!itemMap.isEmpty()){
            dnItems.addAll(itemMap.values());
        }
        return dnItems;
    }

//-------------------------Private Method----------------------------------------
    /**
     * 尝试真实绑定
     * @param pos 包含料盘的库位
     * @param outItem 出库需求项
     * @return 如果库位为null,返回null;否则返回更新后的出库需求项
     */
    private OutItem tryRealBind(StoragePos pos, OutItem outItem){
        if(pos == null){
            log.info("\t真实绑定"+outItem.getSlotlocation() + "的pn=["+outItem.getPn()+"]facility = "+outItem.getFacility()+"时无库存,跳出绑定");
            return null;
        }else{
            Barcode barcode = pos.getBarcode();
            int dbQty = barcode.getAmount();
            int realLockQty = outItem.getRealLockQty();
            int newRealLockQty = realLockQty + dbQty;

            log.info("\t真实绑定["+pos.getBarcode().getBarcode()+"]到So=["+outItem.getSo()+"]hSerial=["+outItem.gethSerial()+"]refno=["+outItem.getRefno()+"]的["+outItem.getSlotlocation()+"] 绑定数量:" + outItem.getRealLockQty() +"/" + outItem.getQty());
            AppendInfo appendInfo = barcode.getAppendInfo();
            appendInfo.sethSerial(outItem.gethSerial());
            appendInfo.setRefno(outItem.getRefno());
            appendInfo.setSo(outItem.getSo());
            appendInfo.setSoseq(outItem.getSoseq());
            appendInfo.setSlotStr(outItem.getSlotStr());
            appendInfo.setBindSlot(outItem.getSlotlocation()+"");
            appendInfo.setSlotIndex(outItem.getSlotlocation());
            barcode.setAppendInfo(appendInfo);
            pos.setBarcode(barcode);
            storagePosDao.save(pos);
            outItem.setRealLockQty(newRealLockQty);
            outItem = outItemDao.save(outItem);

            return outItem;
        }
    }

    private OutItem updateRealLockQty(OutItem outItem){
        //查找真实绑定
        List<StoragePos> bindPosList = storagePosDao.findBindList(outItem.getSo(), outItem.getSlotlocation());
        int realBindQty = 0;
        for (StoragePos bindPos : bindPosList) {
            realBindQty = realBindQty + bindPos.getBarcode().getAmount();
        }
        outItem.setRealLockQty(realBindQty);
        int lockQty = outItem.getLockQty();
        if(lockQty < realBindQty){
            lockQty = realBindQty;
            outItem.setLockQty(lockQty);
        }
        outItem = outItemDao.save(outItem);
        log.info("更新["+outItem.getSlotlocation()+"]"+outItem.getPn()+"真实绑定数量为["+realBindQty+"/"+outItem.getQty()+"]");
        return outItem;
    }

    /**
     * 真实绑定非分盘料
     */
    private void realBindReel(OutItem outItem){
        if(!outItem.isCutMaterial()){
            //先从预绑定料盘中进行绑定,如果还有缺料的,从未使用的物料中查找,如果还缺料,从预绑定的物料中查找
            updateRealLockQty(outItem);
            log.info("绑定非分盘料:So=["+outItem.getSo()+"]hSerial=["+outItem.gethSerial()+"]+refno=["+outItem.getRefno()+"]的slotLoction"+outItem.getSlotlocation()+"]pn=["+outItem.getPn()+"]当前绑定数量["+outItem.getRealLockQty()+"/"+outItem.getQty()+"]当前出库/发料数量["+outItem.getOutQty()+"/"+outItem.getSendQty()+"]");

            List<StoragePos> preBindPosList = storagePosDao.findPreBindList(outItem.getSo(), outItem.getSlotlocation());
            for (StoragePos pos : preBindPosList) {
                outItem = tryRealBind(pos, outItem);
            }
            //所需数量=需求单数量-已发料数量-真实绑定数量
            int needNum = outItem.getQty() - outItem.getSendQty() - outItem.getRealLockQty();
            log.info("将预绑定转为真实绑定结束,所需数量("+needNum+")=需求单数量("+outItem.getQty()+")-已发料数量("+ outItem.getSendQty()+")-真实绑定数量"+ outItem.getRealLockQty() +")");
            if(needNum >= 0){
                log.info("预绑定数量不足,查找未绑定料盘进行真实绑定结束,当前数量:"+outItem.getSendQty()+"+"+ outItem.getRealLockQty() +"/" + outItem.getQty());
                while(needNum >= 0){
                    StoragePos pos = storagePosDao.findNoBindMinQty(outItem.getPn(), outItem.getFacility());
                    OutItem resultOutItem = tryRealBind(pos, outItem);
                    if(resultOutItem == null){
                        break;
                    }
                    outItem = resultOutItem;
                    if(outItem.getRealLockQty() > outItem.getQty()){
                        //已经满足需求了,直接跳出
                        break;
                    }
                }
            }


            needNum = outItem.getQty() - outItem.getSendQty() - outItem.getRealLockQty();
            if(needNum >= 0 ){
                log.info("未绑定料盘数量不足,开始抢其他工单的预绑定物料进行真实绑定,当前数量:"+outItem.getSendQty()+"+"+ outItem.getRealLockQty() +"/" + outItem.getQty());
                //抢其他工单的预绑定
                while(needNum >= 0){
                    StoragePos pos = storagePosDao.findOtherPreBindMinQty(outItem.getPn(), outItem.getFacility());
                    OutItem resultOutItem = tryRealBind(pos, outItem);
                    if(resultOutItem == null){
                        break;
                    }
                    outItem = resultOutItem;
                    if(outItem.getRealLockQty() + outItem.getSendQty() > outItem.getQty()){
                        //已经满足需求了,直接跳出
                        break;
                    }
                }
            }

            //首盘,如果此站位一盘也没有,查找是否有同工单不同站位的PN,如果有,抢一盘过来
            log.info("So=["+outItem.getSo()+"]hSerial=["+outItem.gethSerial()+"]+refno=["+outItem.getRefno()+"]的slot"+outItem.getSlotlocation()+"]pn=["+outItem.getPn()+"]真实绑定结束,当前数量:"+outItem.getSendQty()+"+"+ outItem.getRealLockQty() +"/" + outItem.getQty());
        }
    }

    /**
     * 预绑定非分盘料
     */
    private void preBindReel(OutItem outItem){
        if(!outItem.isCutMaterial()){
            log.info("预绑定非分盘料:So=["+outItem.getSo()+"]hSerial=["+outItem.gethSerial()+"]+refno=["+outItem.getRefno()+"]的slot"+outItem.getSlotlocation()+"]pn=["+outItem.getPn()+"]当前预绑定数量["+outItem.getLockQty()+"/"+outItem.getQty()+"]");
            while (true){
                StoragePos pos = storagePosDao.findNoBindMinQty(outItem.getPn(), outItem.getFacility());
                if(pos == null){
                    log.info("\t预绑定"+outItem.getSlotlocation() + "的pn=["+outItem.getPn()+"]facility = "+outItem.getFacility()+"时无库存,跳出预绑定");
                    break;
                }else{
                    int dbQty = pos.getBarcode().getAmount();
                    int lockQty = outItem.getLockQty();
                    int newLockQty = lockQty + dbQty;
                    log.info("\t预绑定["+pos.getBarcode().getBarcode()+"]到So=["+outItem.getSo()+"]hSerial=["+outItem.gethSerial()+"]refno=["+outItem.getRefno()+"]的["+outItem.getSlotlocation()+"] 数量:" + newLockQty +"/" + outItem.getQty());
                    Barcode barcode = pos.getBarcode();
                    AppendInfo appendInfo = barcode.getAppendInfo();
                    appendInfo.sethSerial(outItem.gethSerial());
                    appendInfo.setRefno(outItem.getRefno());
                    appendInfo.setSo(outItem.getSo());
                    appendInfo.setSoseq(outItem.getSoseq());
                    appendInfo.setPreBindSlot(outItem.getSlotlocation()+"");
                    barcode.setAppendInfo(appendInfo);
                    pos.setBarcode(barcode);
                    storagePosDao.save(pos);
                    outItem.setLockQty(newLockQty);
                    outItem = outItemDao.save(outItem);
                    if(newLockQty > outItem.getQty()){
                        //已经满足需求了,直接跳出
                        break;
                    }
                }
            }
        }
    }

    /**
     * 分盘需求第一次绑定: 第一轮挑料:
     1.料卷数量等于需求
     2.料卷数量,从小到大去挑选,加总数量小于等于需求
     */
    private void firstBindCutReel(OutItem outItem){
        if(outItem.isCutMaterial()){
            updateRealLockQty(outItem);
            log.info("第一轮绑定分盘料:So=["+outItem.getSo()+"]hSerial=["+outItem.gethSerial()+"]的slot"+outItem.getSlotlocation()+"]pn=["+outItem.getPn()+"]当前绑定数量["+outItem.getLockQty()+"/"+outItem.getQty()+"]");

            //剩余需求数量
            int needNum = outItem.getQty() - outItem.getLockQty();
            while(needNum > 0){
                //分盘料
                StoragePos pos = storagePosDao.findNoBindNoCutMinQty(outItem.getPn(), outItem.getFacility());
                if(pos == null){
                    log.info("\t第一轮绑定分盘料"+outItem.getSlotlocation() + "的pn=["+outItem.getPn()+"]facility = "+outItem.getFacility()+"时无库存,跳出绑定");
                    break;
                }else{
                    Barcode barcode = pos.getBarcode();
                    int totalLockQty = outItem.getLockQty() + barcode.getAmount();
                    if(totalLockQty > outItem.getQty()){

                        log.info("加总数量["+totalLockQty+"]大于需求数量["+outItem.getQty()+"]跳出第一轮绑定");
                        break;
                    }

                    if(!barcode.hasCutInfo()){
                        log.info("\t第一轮绑定分盘料["+barcode.getBarcode()+"]绑定到So=["+outItem.getSo()+"]hSerial=["+outItem.gethSerial()+"]refno=["+outItem.getRefno()+"]的["+outItem.getSlotlocation()+"] 数量:" + totalLockQty +"/" + outItem.getQty());
                        //没有分盘信息,可以直接绑定
                        AppendInfo appendInfo = barcode.getAppendInfo();
                        appendInfo.sethSerial(outItem.gethSerial());
                        appendInfo.setRefno(outItem.getRefno());
                        appendInfo.setSo(outItem.getSo());
                        appendInfo.setSoseq(outItem.getSoseq());
                        appendInfo.setSlotStr(outItem.getSlotStr());
                        appendInfo.setBindSlot(outItem.getSlotlocation() + "");
                        appendInfo.setSlotIndex(outItem.getSlotlocation());
                        barcode.setAppendInfo(appendInfo);
                        int realLockQty = outItem.getRealLockQty() + barcode.getAmount();
                        outItem.setRealLockQty(realLockQty);

                        barcode = barcodeDao.save(barcode);
                        pos.setBarcode(barcode);
                        storagePosDao.save(pos);
                        outItem.setLockQty(totalLockQty);
                        outItemDao.save(outItem);
                        needNum = outItem.getQty() - totalLockQty;
                    }else{
                        log.error("这句不应该出现,第一轮绑定分盘料时查到分盘信息的物料,分盘料["+barcode.getBarcode()+"]分盘信息:" + barcode.getAppendInfo().getCutMap());
                        break;
                    }
                }
            }
        }
    }

    /**
     * 1.料卷数量等于余量(需分盘的数量)的总数量
     2.By SO逐一挑选,料卷数量,从小到大去挑选
     * @param outItem
     */
    private void secondBindCutReel(OutItem outItem){
        if(outItem.isCutMaterial()){
            log.info("第二轮绑定分盘料:So=["+outItem.getSo()+"]hSerial=["+outItem.gethSerial()+"]+refno=["+outItem.getRefno()+"]的slot"+outItem.getSlotlocation()+"]pn=["+outItem.getPn()+"]当前预绑定数量["+outItem.getLockQty()+"/"+outItem.getQty()+"]");
            //剩余需求数量
            int needNum = outItem.getQty() - outItem.getLockQty();
            while(needNum > 0){
                //分盘料
                StoragePos pos = storagePosDao.findNoBindMinQty(outItem.getPn(), outItem.getFacility());
                if(pos == null){
                    log.info("\t第二轮分盘料绑定"+outItem.getSlotlocation() + "的pn=["+outItem.getPn()+"]facility = "+outItem.getFacility()+"时无库存,跳出绑定");
                    break;
                }else{
                    Barcode barcode = pos.getBarcode();
                    int lockQty = outItem.getLockQty();
                    int remainQty = outItem.getQty() - lockQty;
                    //还有未绑定的需求
                    int reelRemainNum = barcode.cutCount(outItem.getSoseq(), outItem.getSo(), outItem.getSlotlocation(), outItem.getSlotStr(), outItem.gethSerial(), remainQty);
                    if(reelRemainNum > 0){
                        //母盘还有剩余,说明该需求slot已经满足
                        lockQty = outItem.getQty();
                    }else {
                        //母盘正好用完或全部用完也达不到需求量,此母盘绑定slot后,继续寻找其他盘进行绑定
                        lockQty = lockQty + barcode.getAmount();
                    }
                    log.info("\t分盘料["+barcode.getBarcode()+"]绑定到Soseq=["+outItem.getSoseq()+"]So=["+outItem.getSo()+"]hSerial=["+outItem.gethSerial()+"]refno=["+outItem.getRefno()+"]的["+outItem.getSlotlocation()+"] 数量:" + lockQty +"/" + outItem.getQty());
                    if(!barcode.hasCutInfo()){
                        //没有分盘信息,可以直接绑定
                        AppendInfo appendInfo = barcode.getAppendInfo();
                        appendInfo.sethSerial(outItem.gethSerial());
                        appendInfo.setRefno(outItem.getRefno());
                        appendInfo.setSo(outItem.getSo());
                        appendInfo.setSoseq(outItem.getSoseq());
                        appendInfo.setSlotStr(outItem.getSlotStr());
                        appendInfo.setBindSlot(outItem.getSlotlocation() + "");
                        appendInfo.setSlotIndex(outItem.getSlotlocation());
                        barcode.setAppendInfo(appendInfo);
                        int realLockQty = outItem.getRealLockQty() + barcode.getAmount();
                        outItem.setRealLockQty(realLockQty);
                    }else{
                        AppendInfo appendInfo = barcode.getAppendInfo();
                        appendInfo.setSo(outItem.getSo());
                        appendInfo.setSoseq(outItem.getSoseq());
                        barcode.setAppendInfo(appendInfo);
                        log.info("分盘料["+barcode.getBarcode()+"]分盘信息:" + barcode.getAppendInfo().getCutMap());
                    }
                    barcode = barcodeDao.save(barcode);
                    pos.setBarcode(barcode);
                    storagePosDao.save(pos);
                    outItem.setLockQty(lockQty);
                    outItemDao.save(outItem);
                    needNum = outItem.getQty() - lockQty;
                }
            }
        }
    }


    /**
     * 6.	 CIS收料判定接口(绑过料串的条码扫码入库时判断)
     */
    private static void VMIMateriaReceiveJudge(DNInfo dnInfo,Barcode barcode) throws ValidateException{

        String url = "http://10.85.17.233/ESMTCommonInterface/CommonService.asmx/VMIMateriaReceiveJudge";

        Map<String,Object> materialInfoMap = new HashMap<String,Object>();
        String dnOrFacility = dnInfo.getDnNo();
        if(dnInfo.isFacilityIn()){
            dnOrFacility = dnInfo.getFacility();
        }
        materialInfoMap.put("dnOrFacility",dnOrFacility);//DN单号或者是厂别
        materialInfoMap.put("reelID",barcode.getBarcode());//料卷ID
        materialInfoMap.put("partNum",barcode.getPartNumber());//料号
        materialInfoMap.put("qty",barcode.getAmount());//数量
        materialInfoMap.put("lifeCycle",barcode.getLifeCycle());//生命周期
        String productCode = DateUtil.toDateString(barcode.getProduceDate(),"yyyyMMdd");
        materialInfoMap.put("productCode",productCode);//生产日期
        materialInfoMap.put("lot", barcode.getBatch());//生产批次(批次号)
        materialInfoMap.put("vendor",barcode.getProvider());//供应商
        materialInfoMap.put("location","");//location
        materialInfoMap.put("qrCodeInfo",barcode.getFullCodeStr());//完整的二维码信息
        String materialInfo = JsonUtil.toJsonStr(materialInfoMap);

        Map<String,Object> paramMap = new HashMap<String,Object>();
        paramMap.put("materialInfo",materialInfo);
        log.info("DN单Facility收料判断参数:materialInfo=" + materialInfo);

        try {
            String result = HttpHelper.postParam(url,paramMap);
            log.info("DN单Facility收料判定接口返回:" + result);
            String resultStr = XmlUtil.getNodeBody("string", result);
            //0+提示信息/1/-1 0为NG,1为OK,-1为系统内部异常
            if(resultStr.startsWith("1")){
                log.info(barcode.getBarcode() + " ["+dnOrFacility+"]收料判定: OK");
            }else{
                log.info(barcode.getBarcode() + " ["+dnOrFacility+"]收料判定: NG" + resultStr);
                if(resultStr.startsWith("0")){
                    throw new ValidateException(" ["+dnOrFacility+"]收料判定NG:" + resultStr);
                }else{
                    throw new ValidateException(" ["+dnOrFacility+"]收料判定NG:" + resultStr);
                }
            }


        } catch (ApiException e) {
            log.error(" ["+dnOrFacility+"]收料判定接口",e);
            throw new ValidateException(" ["+dnOrFacility+"]收料接口处理异常:" + e.getMessage());
        }
    }



    /**
     * 3. CIS入库判定接口 (没绑过料串的条码调用此接口)
     */
    public static Barcode VMILocationInCheck(Barcode barcode) throws ValidateException{
        String url = "http://10.85.17.233/ESMTCommonInterface/CommonService.asmx/VMILocationInCheck";
        String reelid = barcode.getBarcode();
        Map<String,Object> paramMap = new HashMap<String,Object>();
        paramMap.put("reelid",reelid);

        log.info("纯入库判断参数:reelid=" + reelid);
        try {
            //0+提示信息/1+工单 0:为NG ;1:为OK 工单号码则表示该料卷被绑定在此工单上;-1为内部异常
            String result = HttpHelper.postParam(url,paramMap);
            //String result = "<?xml version=\"1.0\" encoding=\"utf-8\"?><string xmlns=\"http://tempuri.org/\">{\"state\":\"1\",\"msg\":\"入库判定OK\",\"info\":{\"so\":\"2388518\",\"facility\":\"ST\",\"company\":\"BACHS\",\"qty\":\"1\",\"soseq\":\"2092475\",\"slot\":\"5-4\"}}</string>";
            log.info("收到纯入库判定接口返回:" + result);

            String resultStr = XmlUtil.getNodeBody("string", result);
            //0+提示信息/1/-1 0为NG,1为OK,-1为系统内部异常

            Map<String, Object> resultMap = JsonUtil.toMap(resultStr);
            String state = resultMap.get("state").toString();
            if(state.equals("1")){
                log.info(reelid + " CIS入库判定: OK");
                AppendInfo appendInfo = barcode.getAppendInfo();
                Object infoObj = resultMap.get("info");
                if(infoObj != null){
                    log.info("写入条码工单数量信息,并清空分盘数据");
                    Map infoMap = (Map)infoObj;
                    String so = infoMap.get("so").toString();
                    //有工单信息,需要绑定工单
                    String soseq = infoMap.get("soseq").toString();
                    String facility = infoMap.get("facility").toString();
                    String company = infoMap.get("company").toString();
                    String qty = infoMap.get("qty").toString();
                    String slot = infoMap.get("slot").toString();
                    Object slotlocation = infoMap.get("slotserial");

                    if(so.equals("0")){
                        so = null;
                        slot = null;
                    }

                    appendInfo.setCutMap(null);
                    appendInfo.setSo(so);
                    appendInfo.setSoseq(soseq);
                    appendInfo.setSlotStr(slot);
                    if(slotlocation == null || slotlocation.equals("0")){
                        appendInfo.setBindSlot(null);
                        appendInfo.setPreBindSlot(null);
                        appendInfo.setSlotIndex(-1);
                    }else{
                        String location = slotlocation.toString();
                        log.info(reelid + "数量:"+ qty + "绑定工单"+ so + "["+location+"]");
                        appendInfo.setBindSlot(location);
                        appendInfo.setPreBindSlot(location);
                        try{
                            int slotIndex = Integer.valueOf(location);
                            appendInfo.setSlotIndex(slotIndex);
                            //TODO:需要重新绑定

                        }catch (Exception e){

                        }
                    }


                    appendInfo.setFacility(facility);
                    appendInfo.setCompany(company);
                    int amount = Integer.valueOf(qty);
                    barcode.setAmount(amount);
                    barcode.setInitialAmount(amount);

                    //绑定工单
//                        appendInfo.sethSerial(outItem.gethSerial());
//                        appendInfo.setRefno(outItem.getRefno());
//                        appendInfo.setSlotIndex(outItem.getSlotlocation());
//                        barcode.setAppendInfo(appendInfo);
//                        int realLockQty = outItem.getRealLockQty() + barcode.getAmount();
//                        outItem.setRealLockQty(realLockQty);

                    barcode.setAppendInfo(appendInfo);
                }
            }else{
                log.info(reelid + " 纯入库判定: NG" + resultStr);
                String ngMsg = resultMap.get("msg").toString();
                throw new ValidateException("纯入库判定NG:["+state+"]" + ngMsg);
            }
        } catch (Exception e) {
            log.error("纯入库判定接口出错"+e.getMessage());
            throw new ValidateException("纯入库判定接口处理异常:" + e.getMessage());
        }
        return barcode;
    }

    /**
     * 纯入库操作完成时通知Qisda
     */
    private static void VMILocationIn(String reelID, String location){
        String url = "http://10.85.17.233/ESMTCommonInterface/CommonService.asmx/VMILocationIn";
        Map<String,Object> paramMap = new HashMap<String,Object>();
        paramMap.put("reelID",reelID);
        paramMap.put("location",location);
        paramMap.put("userName",USER_NAME);
        log.info("纯入库操作完成时通知Qisda接口(VMILocationIn):reelID=" + reelID + "&location="+location);
        try {
            String result = HttpHelper.postParam(url,paramMap);
            log.info("纯入库操作完成时通知Qisda接口(VMILocationIn)返回:" + result);
        } catch (ApiException e) {
            log.error("纯入库操作完成时通知Qisda接口(VMILocationIn)出错",e);
        }
    }

    /**
     * CIS收料入库接口
     */
    private static void VMIMateriaReceive(Barcode barcode,DataLog task){
        String url = "http://10.85.17.233/ESMTCommonInterface/CommonService.asmx/VMIMateriaReceive";

        Map<String,Object> materialInfoMap = new HashMap<String,Object>();
        materialInfoMap.put("dnOrFacility",barcode.getAppendInfo().getDnOrFacility());//DN单号或者是厂别
        materialInfoMap.put("reelID",barcode.getBarcode());//料卷ID
        materialInfoMap.put("partNum",barcode.getPartNumber());//料号
        materialInfoMap.put("qty",barcode.getAmount() + "");//数量
        materialInfoMap.put("lifeCycle",barcode.getLifeCycle());//生命周期
        String productCode = DateUtil.toDateString(barcode.getProduceDate(),"yyyyMMdd");
        materialInfoMap.put("productCode",productCode);//生产日期
        materialInfoMap.put("lot", barcode.getBatch());//生产批次(批次号)
        materialInfoMap.put("vendor",barcode.getProvider());//供应商
        materialInfoMap.put("location",task.getPosName());//location
        materialInfoMap.put("qrCodeInfo",barcode.getFullCodeStr());//完整的二维码信息
        materialInfoMap.put("reelType","0");//料卷类型
        String materialInfo = JsonUtil.toJsonStr(materialInfoMap);

        //materialInfo = "{\"dnOrFacility\":\"DNMIST1901002587\",\"reelID\":\"R000002014042300013\",\"reelType\":\"0\",\"partNum\":\"6H.15010.204\",\"qty\":\"3\",\"lifeCycle\":\"240\",\"productCode\":\"20191102\",\"lot\":\"L00000000IA9617JL1D81\",\"vendor\":\"82012\",\"location\":\"1-1\",\"qrCodeInfo\":\"L00000000IA9617JL1D81;E20190101 0730;B8C.00501.010503562019010103000;R000002014042300013\"}";

        Map<String,Object> paramMap = new HashMap<String,Object>();
        paramMap.put("materialInfo",materialInfo);
        paramMap.put("userName",USER_NAME);
        log.info("DN单收料或Facility收料通知Qisda接口(VMIMateriaReceive)返回:" + materialInfo);
        try {
            String result = HttpHelper.postParam(url,paramMap);
            log.info("DN单收料或Facility收料接口返回:" + result);
        } catch (ApiException e) {
            log.error("DN单收料或Facility收料接口出错",e);
        }
    }


    /**
     * 出库接口 (出仓完成时调用)
     * @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("发送分盘料信息:" + cutItem);
                VMILocationOut(materialInfoMap);
            }
        }else{
            VMILocationOut(materialInfoMap);
        }
    }

    /**
     * 出仓完成时的参数
     * @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 static void VMILocationOut(Map<String, Object> materialInfoMap){
        String url = "http://10.85.17.233/ESMTCommonInterface/CommonService.asmx/VMILocationOut";
        String materialInfo = JsonUtil.toJsonStr(materialInfoMap);

        Map<String,Object> paramMap = new HashMap<String,Object>();
        paramMap.put("materialInfo",materialInfo);
        paramMap.put("userName",USER_NAME);
        log.info("出仓完成时通知Qisda:materialInfo=" + materialInfo);

        try {
            String result = HttpHelper.postParam(url,paramMap);
            log.info("出仓完成时通知Qisda(VMILocationOut)返回:" + result);
        } catch (ApiException e) {
            log.error("出仓完成时通知Qisda(VMILocationOut)接口出错",e);
        }
    }



    /**
     * 物料放上小车时调用
     * @param task 任务信息
     * @param barcode 条码信息
     * @param latest 本次工单第几盘料(F 第一次,L 最后一次, M 中间)
     */
    public static void VMIMateriaRecAss(DataLog task, Barcode barcode, String latest){
        String url = "http://10.85.17.233/ESMTCommonInterface/CommonService.asmx/VMIMateriaRecAss";
        Map<String,Object> materialInfoMap = new HashMap<String,Object>();
        AppendInfo appendInfo = task.getAppendInfo();
        materialInfoMap.put("action",appendInfo.getAction());
        materialInfoMap.put("facility",appendInfo.getFacility());
        materialInfoMap.put("so",appendInfo.getSo());
        materialInfoMap.put("partNum",task.getPartNumber());
        materialInfoMap.put("reelID",task.getBarcode());
        materialInfoMap.put("slot", appendInfo.getSlotStr());
        materialInfoMap.put("slotserial", appendInfo.getSlotIndex());
        materialInfoMap.put("qty",task.getNum() +"");
        materialInfoMap.put("latest",latest);//本次工单第几盘料(F 第一次,L 最后一次, M 中间, E是错误)
        materialInfoMap.put("cloudLocation",task.getPosName());//云料仓的库位
        materialInfoMap.put("location","");//料架库位
        materialInfoMap.put("vehicleID",appendInfo.getRfid());//料车编号
        if(latest.equals("E")){
            //错误状态不发料车编号
            materialInfoMap.put("vehicleID","");//料车编号
        }
        materialInfoMap.put("vehicleLocation",appendInfo.getRfidLoc());//料车架位号
        materialInfoMap.put("lot", barcode.getBatch());//生产批次(批次号)
        String productCode = DateUtil.toDateString(barcode.getProduceDate(),"yyyyMMdd");
        materialInfoMap.put("productCode",productCode);//生产日期
        materialInfoMap.put("vendorCode",barcode.getProvider());//供应商
        materialInfoMap.put("hSerial",appendInfo.gethSerial());
        materialInfoMap.put("flag", "");//子盘或母盘(L:子盘,M:母盘,其他'')
        String idte = DateUtil.toDateString(task.getUpdateDate(), "yyyyMMdd");
        String idme = DateUtil.toDateString(task.getUpdateDate(), "HHmmss");
        materialInfoMap.put("idte",idte);//发料日期
        materialInfoMap.put("itme",idme);//发料时间
        materialInfoMap.put("soseq",appendInfo.getSoseq());//工单序号
        String materialInfo = JsonUtil.toJsonStr(materialInfoMap);


        Map<String,Object> paramMap = new HashMap<String,Object>();
        paramMap.put("materialInfo",materialInfo);
        paramMap.put("userName",USER_NAME);
        log.info("物料放上小车时通知Qisda:materialInfo=" + materialInfo);

        try {
            String result = HttpHelper.postParam(url,paramMap);
            log.info("物料放上小车时通知Qisda(VMIMateriaRecAss)返回:" + result);
        } catch (ApiException e) {
            log.error("物料放上小车时通知Qisda(VMIMateriaRecAss)接口出错",e);
        }
    }


    private List<DataLog> checkOutUrgent(OutItem outItem){
        List<DataLog> tasks = new ArrayList<>();
        //紧急料,直接出库
        String reelID = outItem.getReelID();
        if(reelID != null){
            //指定出某盘料或单独出库
            StoragePos pos = storagePosDao.findByBarcode(reelID);
            if(pos != null){
                DataLog task = newTask(outItem, pos);
                task = InquiryShelfBean.addUnlimitLoc(task, outItem);
                task = dataLogDao.save(task);
                tasks.add(task);
            }
        }else{
            //紧急料,未绑定数量=需求单数量-已出库数量-已绑数量
            int needNum = outItem.getQty() - outItem.getOutQty() - outItem.getRealLockQty();
            if(needNum >= 0){
                log.info("紧急料,查找未绑定料盘进行出库,未绑数量为"+needNum+"=(需求单"+  outItem.getQty() + ") - (已出" + outItem.getOutQty() + ")-已绑(" + outItem.getRealLockQty()+")");
                while(needNum >= 0){
                    StoragePos pos = storagePosDao.findNoBindMinQty(outItem.getPn(), outItem.getFacility());
                    if(pos != null){
                        //找到了,进行出库
                        DataLog task = newTask(outItem, pos);
                        task = InquiryShelfBean.addUnlimitLoc(task, outItem);
                        task = dataLogDao.save(task);
                        tasks.add(task);
                        outItem.setRealLockQty(outItem.getRealLockQty() + task.getNum());
                        needNum = outItem.getQty() - outItem.getRealLockQty();
                    }else{
                        //未找到未绑定的物料了
                        break;
                    }
                }
            }
        }
        return tasks;
    }

    private List<DataLog> checkOutCut(OutItem outItem){
        List<DataLog> tasks = new ArrayList<>();
        if(outItem.isCutMaterial()){
            //分盘料
            secondBindCutReel(outItem);
            //出分盘料
            List<StoragePos> cutPosList = storagePosDao.findCutList(outItem.getSo(), outItem.getSlotlocation(),outItem.getSoseq());
            for (StoragePos pos : cutPosList) {
                DataLog task = newTask(outItem, pos);
                task = InquiryShelfBean.addUnlimitLoc(task, outItem);
                task = dataLogDao.save(task);
                tasks.add(task);
            }
        }
        return tasks;
    }

    private List<DataLog> checkOutTail(OutItem outItem){
        List<DataLog> tasks = new ArrayList<>();
        if(outItem.getSendQty() > outItem.getQty()){
            //出经发完料
            return tasks;
        }
        //再绑定一遍
        firstBindCutReel(outItem);
        secondBindCutReel(outItem);
        realBindReel(outItem);
        List<StoragePos> bindPosList = storagePosDao.findBindList(outItem.getSo(), outItem.getSlotlocation());
        //没有顺序
        int sendQty = outItem.getSendQty();
        for (StoragePos pos : bindPosList) {
            Barcode posBarcode = pos.getBarcode();
            DataLog task = newTask(outItem, pos);
            task = InquiryShelfBean.addUnlimitLoc(task, outItem);
            task = dataLogDao.save(task);
            tasks.add(task);
            sendQty = sendQty + posBarcode.getAmount();
            if(sendQty > outItem.getQty()){
                break;
            }
        }
        return tasks;
    }

    private List<DataLog> checkOutFirst(OutItem outItem,List<String> outReelIdList){
        List<DataLog> tasks = new ArrayList<>();
        //再绑定一遍
        firstBindCutReel(outItem);
        secondBindCutReel(outItem);
        realBindReel(outItem);

        if(outItem.getSendQty() > 0){
            //出经发完料
            return tasks;
        }
        bindSamePnFromOtherSlotForFirstAction(outItem,outReelIdList);

        //taskService

        List<StoragePos> bindPosList = storagePosDao.findBindList(outItem.getSo(), outItem.getSlotlocation());
        //首盘料,出到双层线上,按站位顺序,只出最大的一盘
        StoragePos maxQtyPos = null;
        for (StoragePos pos : bindPosList) {
            //不是需要分盘但未分盘的料
            Barcode posBarcode = pos.getBarcode();
            if(!posBarcode.hasCutInfo()){
                if(maxQtyPos == null){
                    maxQtyPos = pos;
                }
                if(posBarcode.getAmount() > maxQtyPos.getBarcode().getAmount()){
                    maxQtyPos = pos;
                }
            }
        }
        if(maxQtyPos != null){
            //加入料架
            log.info(outItem.toString() + "找到最大数量料盘["+maxQtyPos.getBarcode().getBarcode()+"],准备出库");
            DataLog task = newTask(outItem, maxQtyPos);
            task = InquiryShelfBean.addLimitLoc(task, outItem);
            task = dataLogDao.save(task);
            tasks.add(task);
        }else{

            //缺料,查看是否有本工单,同PN的,如果有抢一个过来

            //缺料,料架留空
            Component c = componentManager.findByPartNumber(outItem.getPn());
            if(c != null){
                String shelfType = StorageConstants.SHEFL_TYPE.D;
                if(c.getPlateSize() > 7 || c.getHeight() > 12){
                    shelfType = StorageConstants.SHEFL_TYPE.C;
                }
                log.info(outItem.getSlotlocation() + "["+outItem.getPn()+"]缺料,保留"+shelfType+"类型架位");
                InquiryShelfBean.addEmptyLoc(outItem, shelfType);
            }else{
                log.error("未找到物料["+outItem.getPn()+"]的尺寸信息,保留C类型架位");
                InquiryShelfBean.addEmptyLoc(outItem, StorageConstants.SHEFL_TYPE.C);
            }
        }
        return tasks;
    }

    private String checkOutOutItems(String hSerial, int maxReelNum){
        log.info("执行需求单["+hSerial+"]出库");
        OutInfo outInfo = outInfoDao.findByHSerial(hSerial);
        if(outInfo == null){
            return "未找到需求单["+hSerial+"]";
        }
        //如果有其他任务在执行,不允许出库
        Collection<DataLog> queueTasks = taskService.getQueueTasks();
        List<DataLog> allTasks = taskService.getFinishedTasks();
        if(!queueTasks.isEmpty()){
            allTasks.addAll(queueTasks);
        }

        for (DataLog dataLog : allTasks) {
            if(dataLog.isCheckOutTask()){
                //首盘和补料
                if(!outInfo.isReelCutAction() && !outInfo.isUrgentAction()){
                    //InquiryShelfBean.hSerialShelfMap.clear();
                    return "全部任务完成后才可执行";
                }else{
                    //分盘和紧急料
                    String taskHSerial = dataLog.getAppendInfo().gethSerial();
                    if(taskHSerial.equals(hSerial)){
                        return "当前需求单还有未完成的任务";
                    }
                }
            }
        }



        //如果是工单需求单,设置当前正在执行的工单需求单
        if(outInfo.isFirstReelAction() || outInfo.isTailAction()){
            String oldHSerial = outInfoCache.getCurrentOrderHSerial();
            log.info("设置当前正在执行的工单料需求为:" + outInfo.gethSerial()+"清理之前["+oldHSerial+"]出库使用的料架");
            InquiryShelfBean.clearShelf(oldHSerial);
            outInfoCache.setCurrentOrderHSerial(outInfo.gethSerial());
        }

        List<DataLog> tasks = new ArrayList<>();
        List<String> outReelIdList = new ArrayList<>();

        List<OutItem> itemList = outItemDao.findByHSerial(hSerial);


        for (OutItem outItem : itemList) {
            outItem = updateRealLockQty(outItem);
            List<DataLog> itemTasks = null;
            if(outItem.isUrgentAction()){
                itemTasks  = checkOutUrgent(outItem);
            }else if(outItem.isReelCutAction()){
                //分盘需求单
                itemTasks = checkOutCut(outItem);
            }else if(outItem.isFirstReelAction()){
                //首盘料需求单
                itemTasks = checkOutFirst(outItem,outReelIdList);
            }else{
                //尾料需求单
                itemTasks = checkOutTail(outItem);
            }
            if(itemTasks != null && !itemTasks.isEmpty()){
                for (DataLog itemTask : itemTasks) {
                    tasks.add(itemTask);
                    outReelIdList.add(itemTask.getBarcode());
                }
            }
            outInfoCache.updateOutItem(outItem.getId());
            if(maxReelNum != -1){
                if(tasks.size() >= maxReelNum){
                    log.info("限制料盘数为:"+maxReelNum);
                    break;
                }
            }
        }


        int outReelNum = tasks.size();
        if(outReelNum > 0){
            log.info("需求单"+outInfo.gethSerial()+"已出("+outInfo.getOutReelNum()+")/已发("+outInfo.getTaskFinishNum()+") 本次出库料盘数量:" + outReelNum);
            outInfo.setOutReelNum(0);
            outInfo.setTaskFinishNum(0);
            outInfo.setTaskNum(outReelNum);
            outInfo = outInfoDao.save(outInfo);

            //先出小料盘,再出大料盘
            for (DataLog task : tasks) {
                if(task.isSmallReel()){
                    taskService.addTaskToExecute(task);
                }
            }
            for (DataLog task : tasks) {
                if(!task.isSmallReel()){
                    taskService.addTaskToExecute(task);
                }
            }

        }

        if(outInfo.isReelCutAction() || outInfo.isFirstReelAction()){
            if(outReelNum == 0){
                List<OutItem> outItemList = outItemDao.findByHSerial(outInfo.gethSerial());
                boolean lessBind = false;
                VMILocationOutFeedback(outItemList, lessBind);
            }
        }

        return "需求单任务分配完成,共["+outReelNum+"]盘任务";
    }

    private DataLog newTask(OutItem outItem, StoragePos pos){
        DataLog task = new DataLog();
        task.setType(StorageConstants.OP.CHECKOUT);
        task.setStatus(StorageConstants.OP_STATUS.WAIT.name());

        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());
            task.setSourceName(outItem.getSourceName());

            AppendInfo appendInfo = barcode.getAppendInfo();
            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);
            if(barcode.hasCutInfo()){
                task.setCutReel(true);
            }
        }

        if(outItem.isUrgentAction()){
            task.setUrgentReel(true);
        }

        Storage storage = dataCache.getStorageById(pos.getStorageId());
        if(storage.isPackage()){
            //包装料仓
            task.setPackageReel(true);
        }
        task.setCid(storage.getCid());
        task.setStorageId(storage.getId());
        task.setStorageName(storage.getName());

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

        return task;
    }

    private Map<String, String> getParamMapFromBody(HttpServletRequest request){
        Map<String,String> paramMap = new HashMap<>();
        try {
            String params = request.getReader().lines().collect(Collectors.joining(System.lineSeparator()));
            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;
    }



}