TaskService.java 87.7 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 1468 1469 1470 1471 1472 1473 1474 1475 1476 1477 1478 1479 1480 1481 1482 1483 1484 1485 1486 1487 1488 1489 1490 1491 1492 1493 1494 1495 1496 1497 1498 1499 1500 1501 1502 1503 1504 1505 1506 1507 1508 1509 1510 1511 1512 1513 1514 1515 1516 1517 1518 1519 1520 1521 1522 1523 1524 1525 1526 1527 1528 1529 1530 1531 1532 1533 1534 1535 1536 1537 1538 1539 1540 1541 1542 1543 1544 1545 1546 1547 1548 1549 1550 1551 1552 1553 1554 1555 1556 1557 1558 1559 1560 1561 1562 1563 1564 1565 1566 1567 1568 1569 1570 1571 1572 1573 1574 1575 1576 1577 1578 1579 1580 1581 1582 1583 1584 1585 1586 1587 1588 1589 1590 1591 1592 1593 1594 1595 1596 1597 1598 1599 1600 1601 1602 1603 1604 1605 1606 1607 1608 1609 1610 1611 1612 1613 1614 1615 1616 1617 1618 1619 1620 1621 1622 1623 1624 1625 1626 1627 1628 1629 1630 1631 1632 1633 1634 1635 1636 1637 1638 1639 1640 1641 1642 1643 1644 1645 1646 1647 1648 1649 1650 1651 1652 1653 1654 1655 1656 1657 1658 1659 1660 1661 1662 1663 1664 1665 1666 1667 1668 1669 1670 1671 1672 1673 1674 1675 1676 1677 1678 1679 1680 1681 1682 1683 1684 1685 1686 1687 1688 1689 1690 1691 1692 1693 1694 1695 1696 1697 1698 1699 1700 1701 1702 1703 1704 1705 1706 1707 1708 1709 1710 1711 1712 1713 1714 1715 1716 1717 1718 1719 1720 1721 1722 1723 1724 1725 1726 1727 1728 1729 1730 1731 1732 1733 1734 1735 1736 1737 1738 1739 1740 1741 1742 1743 1744 1745 1746 1747 1748 1749 1750 1751 1752 1753 1754 1755 1756 1757 1758 1759 1760 1761 1762 1763 1764 1765 1766 1767 1768 1769 1770 1771 1772 1773 1774 1775 1776 1777 1778 1779 1780 1781 1782 1783 1784 1785 1786 1787 1788 1789 1790 1791 1792 1793 1794 1795 1796 1797 1798 1799 1800 1801 1802 1803 1804 1805 1806 1807 1808 1809 1810 1811 1812 1813 1814 1815 1816 1817 1818 1819 1820 1821 1822 1823 1824 1825 1826 1827 1828 1829 1830 1831 1832 1833 1834 1835 1836 1837 1838 1839 1840 1841 1842 1843 1844 1845 1846 1847 1848 1849 1850 1851 1852 1853 1854 1855 1856 1857 1858 1859 1860 1861 1862 1863 1864 1865 1866 1867 1868 1869 1870 1871 1872 1873 1874 1875 1876 1877 1878 1879 1880 1881 1882 1883 1884 1885 1886 1887 1888 1889 1890 1891 1892 1893 1894 1895 1896 1897 1898 1899 1900 1901 1902 1903 1904 1905 1906 1907 1908 1909 1910 1911 1912 1913 1914 1915 1916 1917 1918 1919 1920 1921 1922 1923 1924 1925 1926 1927 1928 1929 1930 1931 1932 1933 1934 1935 1936 1937 1938 1939 1940 1941 1942 1943 1944 1945 1946 1947 1948 1949 1950 1951 1952 1953 1954 1955 1956 1957 1958 1959 1960 1961 1962 1963 1964 1965 1966 1967 1968 1969 1970 1971 1972 1973 1974 1975 1976 1977 1978 1979 1980 1981 1982 1983 1984 1985 1986 1987 1988 1989 1990 1991 1992 1993 1994 1995 1996 1997 1998 1999 2000 2001 2002 2003 2004 2005 2006 2007 2008 2009 2010 2011 2012 2013 2014 2015 2016 2017 2018 2019 2020 2021 2022 2023 2024 2025 2026 2027 2028 2029 2030 2031 2032 2033 2034 2035 2036 2037 2038 2039 2040 2041 2042 2043 2044 2045
package com.myproject.webapp.controller.webService;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.google.common.base.Strings;
import com.google.common.collect.*;
import com.myproject.bean.CodeBean;
import com.myproject.bean.json.LiteOrder;
import com.myproject.bean.json.LiteOrderItem;
import com.myproject.bean.update.*;
import com.myproject.bean.utils.BoxStatusBean;
import com.myproject.bean.utils.StatusBean;
import com.myproject.dao.mongo.*;
import com.myproject.exception.ValidateException;
import com.myproject.manager.IBarcodeManager;
import com.myproject.manager.IComponentManager;
import com.myproject.manager.IHumitureManager;
import com.myproject.manager.IStoragePosManager;
import com.myproject.model.User;
import com.myproject.service.UserManager;
import com.myproject.webapp.controller.webService.boxHandler.SmdXlBoxHandler;
import com.myproject.webapp.controller.webService.boxHandler.VerticalBoxHandler;
import com.myproject.util.HttpHelper;
import com.myproject.util.StorageConstants;
import org.apache.commons.lang.StringUtils;
import org.apache.commons.lang.math.RandomUtils;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

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

/**
 * 出入库操作队列缓存等
 */
@Service
public class TaskService implements ITaskService {

    private ObjectMapper mapper = new ObjectMapper();

    @Autowired
    private IStoragePosManager storagePosManager;

    @Autowired
    private IHumitureManager humitureManager;

    @Autowired
    private IBarcodeManager barcodeManager;

    @Autowired
    private IComponentManager componentManager;

    @Autowired
    private IDataLogDao dataLogDao;

    @Autowired
    private ILiteOrderDao liteOrderDao;

    @Autowired
    private ILiteOrderItemDao liteOrderItemDao;

    @Autowired
    private DataCache dataCache;


    @Autowired
    private IAlarmInfoDao alarmInfoDao;

    @Autowired
    private UserManager userManager;

    /**
     * 任务队列,Key 为dataLog的ID,value 为本区域待执行的任务
     */
    private static Map<String, DataLog> taskMap = Maps.newConcurrentMap();

    /**
     * 正在执行的任务列表rowKey 为 cid, columnKey 为 ReelId 即 barcode, Value为 DataLog
     */
    //private static Map<String, DataLog> executingTaskMap = Maps.newConcurrentMap();

    /**
     * 完成的任务列表Key 为dataLog的ID, Value 为 Datalog
    */
    private static Map<String,DataLog> theFinishedTaskMap = Maps.newConcurrentMap();

    /**
     * 状态 map,key为 cid value 为状态 Bean
     */
    protected static Map<String, StatusBean> statusMap = Maps.newConcurrentMap();

    protected final transient Logger log = LogManager.getLogger(getClass());
    /**
     * CID的设备故障消息(key 为 cid)
     */
    private static Map<String, StatusBean> clientMsgs = new ConcurrentHashMap<>();

    /**
     * CID的服务器消息(key 为 cid)
     */
    private static Map<String, Exception> serverExceptions = new ConcurrentHashMap<>();


    /**
     * 正在执行的liteOrderMap, key 为orderNo,value 为order
     */
    public static Map<String, LiteOrder>  liteOrderMap = new ConcurrentHashMap<>();

    @Autowired
    private VerticalBoxHandler verticalBoxHandler;

    @Autowired
    private SmdXlBoxHandler smdXlBoxHandler;

    /**
     * 更新客户端发上来的消息(设备故障等消息)
     */
    public static void updateClientMsg(String cid, String clientMsg, String clientMsgEn){
        if(clientMsg == null){
            clientMsg = "";
            clientMsgEn = "";
        }
        StatusBean statusBean = new StatusBean();
        statusBean.setMsg(clientMsg);
        statusBean.setMsgEn(clientMsgEn);
        clientMsgs.put(cid,statusBean);
    }

    /**
     * 获取某区域正在执行的任务
     */
    @Override
    public Collection<DataLog> getQueueTasks(){
        return taskMap.values();
    }

    @Override
    public Collection<DataLog> getQueueTasks(String cid) {
        List<DataLog> tasks = new ArrayList<>();
        for (DataLog dataLog : taskMap.values()) {
            if(dataLog.getCid().equals(cid)){
                tasks.add(dataLog);
            }
        }
        return tasks;
    }

    @Override
    public void updateQueueTask(DataLog task){
        taskMap.put(task.getId(), task);
    }

    /**
     * 将任务从执行队列中移动到完成队列中
     * @param task
     */
    @Override
    public void moveTaskToFinished(DataLog task){
        taskMap.remove(task.getId());
        theFinishedTaskMap.put(task.getId(),task);
    }

    /**
     * 获取某区域已完成的任务
     */
    @Override
    public List<DataLog> getFinishedTasks(){
        List<DataLog> areaFinishedTasks = Lists.newArrayList(theFinishedTaskMap.values());
        List<DataLog> resultTasks = Lists.newArrayList();
        for(DataLog task : areaFinishedTasks){
            if(task.needRemoveFromCache()){
                theFinishedTaskMap.remove(task.getId());
            }else{
                resultTasks.add(task);
            }
        }
        return resultTasks;
    }

    /**
     * 更新条码为锡膏条码
     * @param barcode
     * @return
     */
    private Barcode updateToSolderBarcode(Barcode barcode, int weight) throws ValidateException {
        Component component = componentManager.findOneByPN(barcode.getPartNumber());
        if(!component.isSolder()){
            component.setType(StorageConstants.COMPONENT_TYPE.SOLDERPASTE);
            //搅拌时间默认为3分钟即180秒
            component.setMixTime(0);
            //回温时间默认为8小时
            component.setWarmTime(8);
            component.setAmount(1);
            component = componentManager.save(component);
        }
        barcode.setAmount(weight);
        barcode.setType(component.getType());
        barcode.setWarmTime(component.getWarmTime());
        barcode.setMixTime(component.getMixTime());
        barcode = barcodeManager.save(barcode);
        return barcode;
    }

    /**
     * 流水线入库:优先查找空闲BOX中同尺寸的,如果找不到,再查找可入库 BOX(可用且不是出库状态) 同尺寸或比盘尺寸大的仓位
     */
    public StatusBean putInLine(Storage storage, StatusBean statusBean){
        try {
            String barcode = statusBean.getCode();
            Barcode barcodeSave = resolveBarcode(barcode);

            if(storage.isSolderPaste()){
                int weight = statusBean.getWeight();
                //锡膏料仓,修改类型
                barcodeSave = updateToSolderBarcode(barcodeSave,weight);
            }

            verifyBarcodePutIn(Lists.<Storage>newArrayList(storage),barcodeSave);

            int w = barcodeSave.getPlateSize();
            int h = barcodeSave.getHeight();
            if(!storage.canPutIn(w, h)){
                //throw new ValidateException("尺寸["+w+"x"+h+"]不符");
                throw new ValidateException("error.barcode.wrongSize",new String[]{w+"x"+h});
            }

            StoragePos storagePos;
            DataLog executingTask = null;
            //如果有正在执行的任务,把库位发过去
            for (DataLog task : taskMap.values()) {
                if(task.getBarcode().equals(barcodeSave.getBarcode())){
                    //同条码,且同料仓的入库任务
                    if(task.isPutInTask() && task.getStorageId().equals(storage.getId())){
                        executingTask = task;
                    }else{
                        //同条码,但不是同料仓
                        log.error("条码["+barcodeSave.getBarcode()+"]任务正在执行,但任务料仓为:" + task.getStorageId() + " 请求料仓为:" + task.getStorageId());
                        //throw new ValidateException("条码["+barcodeSave.getBarcode()+"]任务正在执行");
                        throw new ValidateException("error.barcode.executing",new String[]{barcodeSave.getBarcode()});
                    }

                }
            }

            if(executingTask != null){
                String posId = executingTask.getPosId();
                log.info(barcodeSave.getBarcode() + " 已有任务,返回任务中的库位:" + executingTask.getPosName());
                storagePos = storagePosManager.get(posId);
            }else{
                String posName = statusBean.getFromData("inPos");
                if(!Strings.isNullOrEmpty(posName)){
                    log.info("指定入库到" + posName);

                    storagePos = storagePosManager.getByPosName(posName);
                    if(storagePos == null){
                        throw new ValidateException("error.pos.notExist",new String[]{posName}, "库位【"+posName+"】不存在,无法入库");
                    }
                    if(!storage.getId().equals(storagePos.getStorageId())){
                        throw new ValidateException("error.pos.wrong",new String[]{posName,storage.getCid()}, "库位【"+posName+"】与料仓["+storage.getCid()+"]不匹配,无法入库");
                    };
                    if(storagePos.getBarcode() != null){
                        throw new ValidateException("error.pos.hasReel",new String[]{posName}, "库位【"+posName+"】中已有物料,无法入库");
                    }

                    if(!storage.canPutInPos(barcodeSave.getPlateSize(),barcodeSave.getHeight(), storagePos.getW(), storagePos.getH())){
                        String reelSize = barcodeSave.getPlateSize() + "x" + barcodeSave.getHeight();
                        String posSize = storagePos.getW() + "x" + storagePos.getH();
                        throw new ValidateException("error.pos.sizeNotMatch",new String[]{}, "料盘尺寸["+reelSize+"]与库位"+posName+"尺寸["+posSize+"]不符,无法入库");
                    }

                }else{
                    String codeBoxId = statusBean.getCodeBoxId();
                    storagePos = findLineEmptyPosForPutIn(storage, barcodeSave, codeBoxId);
                }


                String singleIn = statusBean.getFromData("singleIn");
                if(!Strings.isNullOrEmpty(singleIn)){
                    //批量料仓单盘入库的只能单盘出,不可批量
                    if(singleIn.equalsIgnoreCase("true")){
                        log.info(barcodeSave.getBarcode() + "单盘入库,出库时此条码只可单盘出库");
                        barcodeSave.setOnlySingleOut(true);
                        barcodeManager.save(barcodeSave);
                    }
                }

                addPutInTaskToExecute(storage, barcodeSave, storagePos);
            }


            String posId = storagePos.getPosName();
            int plateW = barcodeSave.getPlateSize();
            int plateH = barcodeSave.getHeight();
            statusBean.addPosInfo(barcode, posId,plateW,plateH,false);

            log.info(barcode+"["+plateW+"x"+plateH + "]开始入库到"+storage.getCid()+"["+posId+"]");
            //清空展示的消息

            serverExceptions.remove(storage.getCid());

        } catch (ValidateException e) {
            log.warn(statusBean.getCode() + "入库到"+storage.getCid() + "失败:"+e.getMessage());
            statusBean.setMsg(e.getMessage());
            serverExceptions.put(storage.getCid(),e);
        } catch (Exception e) {
            log.error(statusBean.getCode() + "入库到"+storage.getCid() + "失败", e);
            statusBean.setMsg(e.getMessage());
            serverExceptions.put(storage.getCid(),e);
        }
        return statusBean;
    }

    private Barcode resolveBarcode(String barcodeStr)throws ValidateException {
        Collection<CodeBean> codeBeans = dataCache.resolveCodeStr(barcodeStr);

        if(codeBeans.isEmpty()){
            log.info("未扫描到条码");
            throw new ValidateException("error.barcode.empty","未扫描到条码");
        }

        List<Barcode> allBarcode = Lists.newArrayList();
        for (CodeBean codeBean : codeBeans) {
            if(codeBean.getError() == null){
                Barcode barcode = codeBean.getBarcode();
                if(barcode != null){
                    allBarcode.add(barcode);
                }
            }else{
                //throw new ValidateException(codeBean.getError());
            }

        }

        int codeSize = allBarcode.size();
        if(codeSize == 0){
            throw new ValidateException("error.barcode.noValidCode",new String[]{codeBeans.size()+"",barcodeStr},barcodeStr + "不是有效的条码");
        }else if(codeSize > 1){
            throw new ValidateException("error.barcode.many","找到多个有效条码,无法入库");
        }
        return allBarcode.get(0);
    }

    /**
     * 检查二维码是否合法并且可以入库,没问题的话存入到数据库
     */

    @Override
    public Barcode verifyBarcodePutIn(List<Storage> storageList, Barcode barcodeSave) throws ValidateException {

        if(barcodeSave == null){
            throw new ValidateException("error.barcode.invalid",new String[]{""},"条码无效");
        }

        Date expireDate = barcodeSave.getExpireDate();
        if(expireDate != null){
            if(System.currentTimeMillis() > expireDate.getTime()){
                throw new ValidateException("error.barcode.expired","物料已过期,无法入库.");
            }
        }

        if(dataCache.isProductionFor(DataCache.CUSTOMER.PANACIM)){
            //松下PanaCIM需要进行验证
            boolean checkResult = PanaApiController.requestReel(barcodeSave.getBarcode());
            if(!checkResult){
                throw new ValidateException("PanaCIM验证条码["+barcodeSave.getBarcode()+"]失败","PanaCIM验证失败");
            }
        }

//        if(barcodeSave.getPlateSize() <=0 || barcodeSave.getHeight() <= 0){
//            throw new ValidateException("无法入库,请先设置料盘尺寸");
//        }

        StoragePos pos;

        //夹具,查询 relationCode
        if(StorageConstants.COMPONENT_TYPE.FIXTURE == barcodeSave.getType()){
            pos = storagePosManager.getByFixtureCode(barcodeSave.getBarcode());
        }else {
            pos = storagePosManager.getByBarcodeId(barcodeSave.getId());

            if (barcodeSave.getAmount() <= 0) {
                throw new ValidateException("error.barcode.wrongQty",new String[]{barcodeSave.getBarcode(),barcodeSave.getAmount()+""},"条码[" + barcodeSave.getBarcode() + "]对应的数量<=0为: " + barcodeSave.getAmount());
            }
        }

        if (pos != null) {
            Storage storage = dataCache.getStorageById(pos.getStorageId());
            throw new ValidateException("error.barcode.inStorage",new String[]{barcodeSave.getBarcode(), storage.getName(),pos.getPosName()},"[ " + barcodeSave.getBarcode() + "]已在"+storage.getName()+"["+pos.getPosName()+"]中");
        }

        for (DataLog task : taskMap.values()) {
            if(task.isPutInTask()){
                if(task.getBarcode().equals(barcodeSave.getBarcode())){
                    //同一个条码的入库任务
                    for (Storage storage : storageList) {
                        if(task.getStorageId().equals(storage.getId())){
                            return barcodeSave;
                        }
                    }
                    throw new ValidateException("error.barcode.taskNotEnd",new String[]{barcodeSave.getBarcode()},"料盘[ " + barcodeSave.getBarcode() + "]的操作未完成,无法执行入库操作");
                }
            }
        }
        return barcodeSave;
    }



    /**
     * 查找可以入库的空位
     * @param storageList
     * @param barcode
     * @return
     */
    @Override
    public StoragePos findEmptyPosForPutIn(List<Storage> storageList, Barcode barcode) throws ValidateException{
        verifyBarcodePutIn(storageList ,barcode);

        //如果有正在执行的任务,把库位发过去
        Collection<DataLog> allTasks = taskMap.values();
        for (DataLog task : allTasks) {
            if(barcode.getBarcode().equals(task.getBarcode())){
                String posId = task.getPosId();
                log.info(barcode.getBarcode() + " 已有任务,返回任务中的库位:" + task.getPosName());
                return storagePosManager.get(posId);
            }
        }


        //查找任务数最少的料仓
        Map<String,Integer> countMap = new HashMap<>();
        for (Storage storage : storageList) {
            countMap.put(storage.getId(), 0);
        }

        for (DataLog task : allTasks) {
            String storageId = task.getStorageId();
            if(!Strings.isNullOrEmpty(storageId)){
                Integer taskCount = countMap.get(storageId);
                if(taskCount != null){
                    taskCount = taskCount + 1;
                    countMap.put(storageId, taskCount);
                }
            }
        }

        //按任务数量从小到大排序
        List<Map.Entry<String, Integer>> list = new ArrayList<>(countMap.entrySet());
        Collections.sort(list, new Comparator<Map.Entry<String, Integer>>()
        {
            @Override
            public int compare(Map.Entry<String, Integer> o1, Map.Entry<String, Integer> o2)
            {
                //按照value值,用compareTo()方法默认是从小到大排序
                return o1.getValue().compareTo(o2.getValue());
            }
        });


        for (Map.Entry<String, Integer> entry : list) {
            String storageId = entry.getKey();
            Storage theStorage = dataCache.getStorageById(storageId);
            try{
                log.info("尝试从"+theStorage.getName()+"["+theStorage.getCid()+"]查找空位,当前料仓任务数:" + entry.getValue());
                return findLineEmptyPosForPutIn(theStorage,barcode,"");
            }catch(Exception e){
                log.info("从"+theStorage.getName()+"["+theStorage.getCid()+"]查找空位失败:" + e.getMessage());
            }
        }

        return null;

    }
    /**
     * 为 barcode 查找流水线料仓中空闲的仓位
     */
    private StoragePos findLineEmptyPosForPutIn(Storage storage, Barcode barcode, String codeBoxId) throws ValidateException {

        String storageCid = storage.getCid();
        //先查找空闲 BOX同尺寸的,如果找不到,再查找可入库 BOX 同尺寸或比盘尺寸大的仓位
        StatusBean statusBean = statusMap.get(storageCid);
        if (statusBean == null) {//当前料仓不可用
            throw new ValidateException("error.storage.unavailable",new String[]{storageCid},"料仓[ " + storageCid + "]不可用");
        }
        //还需要排除掉正在队列里的仓位
        StoragePos storagePos = null;

        Collection<String> operatingPosIds = excludePosIds();

        //客户端扫码时指定了 boxId
        if(!Strings.isNullOrEmpty(codeBoxId)){
            log.info("客户端扫码时指定入库到 Box["+codeBoxId+"]");
            int inBoxId = Integer.valueOf(codeBoxId);
            if(statusBean.isBoxCanPutIn(inBoxId)){
                ArrayList<Integer> boxIds = Lists.newArrayList();
                boxIds.add(inBoxId);
                storagePos = storagePosManager.getEmptyPosByStorage(storage, barcode , operatingPosIds);
            }else{
                //throw new ValidateException(storage.getName() + "的 BOX-"+codeBoxId+" 不可用");

                String statusStr = "";
                for (BoxStatusBean boxStatusBean : statusBean.getBoxStatus().values()) {
                    //可正常使用,且未在出库执行中
                    int bid = boxStatusBean.getBoxId();
                    statusStr = statusStr +  bid + "=" + boxStatusBean.getStatus();
                }
                log.info(barcode.getBarcode() + "入库失败,料仓不可用,当前状态:" + statusStr);
                throw new ValidateException("error.storage.unavailable",new String[]{storageCid+"-"+codeBoxId},storage.getName() + "的 BOX-"+codeBoxId+" 不可用");
            }
        }else{
            Set<Integer> checkOutBoxIds = getExcutingBoxIds(storageCid,StorageConstants.OP.CHECKOUT);

            List<Integer> idleBoxIds = new ArrayList<>();
            for (Integer idleBoxId : statusBean.allIdleBoxIds()){
                if(!checkOutBoxIds.contains(idleBoxId) && storage.isBoxEnable(idleBoxId)){//正在出库的 BOX 是不能分配入库的(被限制的 box 也不可分配入库)
                    idleBoxIds.add(idleBoxId);
                }
            }

            if (!idleBoxIds.isEmpty()) {
                log.info("从"+storage.getName()+" 中为"+barcode.getBarcode()+"寻找空的仓位");
                storagePos = storagePosManager.getEmptyPosByStorage(storage, barcode, operatingPosIds);
            }

            //没有空闲的 BOX或者查找到的仓位与料盘的尺寸不是最匹配的,查找所有可以入库的 BOX,
            if (storagePos == null || storagePos.getW() != barcode.getPlateSize() || storagePos.getH() != barcode.getHeight()) {
                List<Integer> canPutInBoxIds = new ArrayList<>();
                for (Integer canPutInBoxId : statusBean.allCanPutInBoxIds()){
                    if(!checkOutBoxIds.contains(canPutInBoxId) && storage.isBoxEnable(canPutInBoxId)){//正在出库的 BOX 是不能分配入库的(被限制的 box 也不可分配入库)
                        canPutInBoxIds.add(canPutInBoxId);
                    }
                }
                if (canPutInBoxIds.isEmpty()) {
                    //无可用Box
                    //throw new ValidateException(storage.getName() + "无可用的 BOX");
                    throw new ValidateException("error.storage.unavailable",new String[]{storageCid});
                }
                int availbleBoxCount = canPutInBoxIds.size();
                if(availbleBoxCount > 1){//多于一个随机才有意义
                    //先再随机一次,如果找不到合适的就使用所有可以入库的 BOX
                    int randomIndex = RandomUtils.nextInt(availbleBoxCount);
                    Integer boxId = canPutInBoxIds.get(randomIndex);
                    log.info("从"+storage.getName()+"随机到BOX["+boxId+"]为"+barcode.getBarcode()+"寻找空的仓位");
                    storagePos = storagePosManager.getEmptyPosByStorage(storage, barcode, operatingPosIds);
                }

                if(storagePos == null){
                    log.info("从"+storage.getName()+"中为"+barcode.getBarcode()+"寻找空的仓位");
                    storagePos = storagePosManager.getEmptyPosByStorage(storage, barcode, operatingPosIds);
                }

            }
        }


        if (storagePos == null) {
            String boxIdStr = "";
            if(Strings.isNullOrEmpty(codeBoxId)){
                boxIdStr = "BOX-"+codeBoxId;
            }
            throw new ValidateException("error.storage.noPos",new String[]{barcode.getPlateSize() +"x" + barcode.getHeight()},storage.getName() + boxIdStr + "的料格["+barcode.getPlateSize() +"x" + barcode.getHeight() +"]已满,无法继续放入");
        }
        log.info("["+ barcode.getBarcode() + "]寻找到"+storage.getName()+"的空仓位["+storagePos.getPosName()+"]");
        return storagePos;
    }

    /**
     * 出库处理
     */
    public StatusBean checkOut(Storage storage, StatusBean statusBean){
        try{
            List<Integer> canCheckoutBoxIds = statusBean.allCanCheckoutBoxIds();//可接受出库任务的 BOX
            String cid = storage.getCid();
            Set<Integer> putInBoxIds = getExcutingBoxIds(cid, StorageConstants.OP.PUT_IN);

            if(!putInBoxIds.isEmpty()){
                log.debug(storage.getName() + "所有可出库的 BOX["+StringUtils.join(canCheckoutBoxIds, ",")+"]正在入库的 BOX "+ StringUtils.join(putInBoxIds,","));
            }

            for (Integer idleBoxId : canCheckoutBoxIds) {
                if(!putInBoxIds.contains(idleBoxId)){//正在入库的料仓不可以分配出库任务
                    DataLog task = findCheckoutBoxTask(cid, idleBoxId);
                    if (task != null) {

                        statusBean.setOp(StorageConstants.OP.CHECKOUT);
                        String posName = task.getPosName();
                        //taskService.updateBoxStatus(statusBean.getCid(),posName, StorageConstants.OP.CHECKOUT);

                        Barcode codeObj = barcodeManager.findByBarcode(task.getBarcode());
                        int plateW = 0;
                        int plateH = 0;
                        //是否是单盘出库,批量上下料使用
                        boolean isSingleOut = task.isSingleOut();
                        if(codeObj != null){
                            plateW = codeObj.getPlateSize();
                            plateH = codeObj.getHeight();
                            if(codeObj.isOnlySingleOut()){
                                log.info(codeObj.getBarcode() + " 只能单盘出库");
                                isSingleOut = true;
                            }
                        }else{
                            log.warn("出库无料仓位"+storage.getName()+"["+posName+"]");
                        }
                        statusBean.addPosInfo(task.getBarcode(), posName,plateW,plateH, isSingleOut);
                        log.info("出库"+storage.getName()+"["+posName+"]物料["+task.getBarcode()+"]"+isSingleOut+"发送到客户端" + cid);
                    }
                }
            }
            String posId = statusBean.getData().get("posId");
            if(!Strings.isNullOrEmpty(posId)){
                log.info("SEQ:" + statusBean.getSeq() + "出库库位信息:["+posId+"]发送到客户端");
            }
        }catch (Exception e){
            log.error("出库出错",e);
        }

        return statusBean;
    }

//    /**
//     * 从库位中查找20条呆滞料,并生成任务保存到数据库中,返回生成的任务数
//     */
//    private List<DataLog> saveInactionTasks(InactionTaskSet inactionTaskSet){
//        int day = inactionTaskSet.getDay();
//        List<String> storageIds = dataCache.needClearInactionStorageIds();
//        //每个料仓找5个
//        int count = 3;
//        List<StoragePos> list = Lists.newArrayList();
//        for(String storageId : storageIds){
//            List<StoragePos> storageList = storagePosManager.findInaction(Lists.<String>newArrayList(storageId), day, excludePosIds(), count);
//            list.addAll(storageList);
//        }
//        List<DataLog> tasks = Lists.newArrayList();
//        for (StoragePos pos : list){
//            DataLog task = newTask(pos);
//            task.setType(StorageConstants.OP.CHECKOUT);
//            task.setStatus(StorageConstants.OP_STATUS.WAIT.name());
//            //来源
//            task.setSourceType(StorageConstants.TASK_SOURCE.INACTION.name());
//            task.setSourceId(inactionTaskSet.getId());
//            task.setSourceName(inactionTaskSet.getName());
//            //将天数放在 subSourceId 中
//            task.setSubSourceId(day+"");
//            task.setSubSourceInfo("");
//            tasks.add(task);
//        }
//        if(!tasks.isEmpty()){
//            dataLogDao.insertAll(tasks);
//        }
//        return tasks;
//
//    }

    public DataLog newTask(StoragePos pos){

        DataLog task = new DataLog();

        Barcode barcode = pos.getBarcode();
        if(barcode != null){
            task.setPartNumber(barcode.getPartNumber());
            task.setBarcode(barcode.getBarcode());
            task.setNum(barcode.getAmount());
            task.setMemo(barcode.getMemo());
        }

        Storage storage = dataCache.getStorageById(pos.getStorageId());
        task.setCid(storage.getCid());
        task.setStorageId(storage.getId());
        task.setStorageName(storage.getName());

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

        return task;
    }

    private boolean cancelTask(DataLog task){
        if(task != null){
            //从正在执行和等待列表中移除
            taskMap.remove(task.getId());

            theFinishedTaskMap.put(task.getId(), task);

            task.setStatus(StorageConstants.OP_STATUS.CANCEL.name());
            dataLogDao.save(task);
            log.info("任务["+task.getId() + "] posName["+task.getPosName()+"] Reel Id["+task.getBarcode()+"]取消成功");

            //如果是料架,需要灭灯
            StorageDataController.appendOp(task.getCid(),"close", task.getPosName());

            finishedOrderTask(task);
            return true;
        }
        return false;
    }

    @Override
    public boolean cancelTask(String taskId) {
        DataLog task = dataLogDao.findOneById(taskId);
        return cancelTask(task);
    }

    /**
     * 获取正在执行出库(或入库)的 boxID,用作出入库时分配仓位,防止卡死的问题
     */
    private Set<Integer> getExcutingBoxIds(String cid, int type){
        Set<Integer> excuteBoxIds = Sets.newHashSet();
        for (DataLog task : taskMap.values()){
            if(type == task.getType()){
                String posName = task.getPosName();
                int index = posName.indexOf("#");
                if(index>0){
                    //String boxId = posName.substring(0,index);
                    String boxId = "1";
                    excuteBoxIds.add(Integer.valueOf(boxId));
                }
            }
        }
        return excuteBoxIds;
    }


    /**
     * 防止仓位任务重复,需要排除掉已经分配掉的仓位
     */
    @Override
    public Collection<String> excludePosIds(){
        //排除掉正在执行的仓位
        Collection<DataLog> allTasks = taskMap.values();
        Collection<String> operatingPosIds = new HashSet<>();
        for(DataLog task : allTasks){
            String posId = task.getPosId();
            if(!Strings.isNullOrEmpty(posId)){
                operatingPosIds.add(task.getPosId());
            }
        }
        return operatingPosIds;
    }


    /**
     * 为 box 分配出库任务
     */
    private DataLog findCheckoutBoxTask(String cid, Integer boxId) {
        Storage storage = dataCache.getStorage(cid);
        if(storage == null || !storage.isBoxEnable(boxId)){//该 Box 已经被限制出入库
            log.info("BOX"+boxId+"已被禁止出入库");
           return null;
        }
        int checkoutSize = 0;
        for(DataLog task : taskMap.values()){
            if(!task.isCheckOutTask()){
                continue;
            }
            //如果该BOX在已执行任务中已经有入库任务,不再分配直接返回
            if(cid.equals(task.getCid()) && task.isExecuting()){
                if(task.isPutInTask()){
                    log.error("cid["+cid + "]box["+boxId+"]已有入库任务,不可再分配出库任务");
                    return null;
                }else if(task.needReSendToClient() && task.isCheckOutTask()){//超过30秒仍未完成的出库再次发送到客户端
                    log.error("cid["+cid + "]的出库任务["+ task.getPosName()+"]超过60秒仍未完成,重新发送到客户端!");
                    task.setUpdateDate(new Date());
                    return task;
                }
                //某个 Box 只能同时有两个正在执行的出库任务,如果超过两个不再分配了

                if(task.isCheckOutTask()){
                    checkoutSize ++;
                    if(checkoutSize >=2){
                        //log.error("cid["+cid + "]的BOX["+ boxId+"]的出库任务已经超过2个,不再分配!");
                        return null;
                    }
                }
            }
        }


        Collection<DataLog> allTasks = taskMap.values();

        //指定紧急单盘出库的优先出库,否则按批量出库处理
        for (DataLog task : allTasks) {//优先分配单盘任务和没有工单的任务
            if(cid.equals(task.getCid()) && task.isCheckOutTask()){
                if(task.isSingleOut()){
                    //只有等待或执行中的任务
                    if(task.isWait()) {
                        String posName = task.getPosName();
                        if(!Strings.isNullOrEmpty(posName)){
                            //从等待列表中删除,加入到执行列表中
                            log.info("分配优先(单盘或无工单)出库任务"+task.getBarcode()+"["+posName+"]到 BOX"+boxId);
                            task.setStatus(StorageConstants.OP_STATUS.EXECUTING.name());
                            taskMap.put(task.getId(), task);
                            dataLogDao.save(task);
                            return task;
                        }
                    }
                }

            }
        }

        //优先查找有库位信息的
        Map<String,DataLog> partNumberTaskMap = new HashMap<>();
        for (DataLog task : allTasks) {//分配任务
            //只有等待或执行中的出库任务
            if(task.isCheckOutTask()){
                if(task.isWait() || task.isExecuting()){
                    String posName = task.getPosName();
                    if(!Strings.isNullOrEmpty(posName)){//已经有位置信息的,分配到执行列表
                        if (cid.equals(task.getCid())) {//是同一个仓库
                            //从等待列表中删除,加入到执行列表中
                            log.info("分配任务"+task.getBarcode()+"["+posName+"]到 BOX"+boxId);
                            task.setStatus(StorageConstants.OP_STATUS.EXECUTING.name());
                            taskMap.put(task.getId(), task);
                            dataLogDao.save(task);
                            return task;
                        }
                    } else { //无位置信息的根据 partNumber 进行分配
                        String partNumber = task.getPartNumber();
                        partNumberTaskMap.put(partNumber,task);
                    }
                }else{
                    //取消或超时或已完成的任务加入到完成列表中
                    //log.warn("将取消或已完成的任务["+task.getId()+"]barcode:"+task.getBarcode()+" PartNumber: "+task.getPartNumber()+"加入到完成列表中,并从等待列表中删除");
                    //waitingTasks.remove(areaId, task);
                    //finishedTasks.put(areaId,task.getBarcode(), task);
                }
            }

        }


        if(!partNumberTaskMap.isEmpty()){
            //排除掉正在执行的仓位
            Collection<String> excludePosIds = excludePosIds();

            StorageConstants.CHECKOUT_TYPE checkOutType = dataCache.getCheckOutType();
            StoragePos pos = storagePosManager.findComponent(storage.getId(), boxId.toString(), partNumberTaskMap.keySet(),excludePosIds,checkOutType);

            if (pos != null) {//找到了,出库
                Barcode barcode = pos.getBarcode();
                if (barcode != null) {
                    DataLog task = partNumberTaskMap.get(barcode.getPartNumber());

                    String partNumber = barcode.getPartNumber();
                    String reelId = barcode.getBarcode();
                    task.setBarcode(reelId);
                    task.setMemo(barcode.getMemo());
                    task.setNum(barcode.getAmount());

                    task.setCid(cid);
                    task.setStorageId(storage.getId());
                    task.setStorageName(storage.getName());

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

                    task.setStatus(StorageConstants.OP_STATUS.EXECUTING.name());
                    //从等待列表中删除,加入到执行列表中
                    taskMap.put(task.getId(), task);
                    dataLogDao.save(task);

                    log.info("查找到物料" + partNumber + "[" + reelId + "]分配任务" + task.getBarcode() + "[" + pos.getPosName() + "]到" + cid);
                    return task;
                }else{
                    log.error("查找BOX["+boxId+"]出库找到库位"+storage.getName()+"["+pos.getPosName()+"],但里面没有 barcode,忽略");
                }
            }else{
                //这个 box 没找到
                //log.info("从 BOX["+boxId+"] 中未找到查找物料"+StringUtils.join(taskPartNumbers,","));
            }
        }
        return null;
    }

    @Override
    public synchronized String checkOutLiteOrder(String orderNo, boolean outBom){
        LiteOrder cacheOrder = liteOrderMap.get(orderNo);
        if(cacheOrder != null && !cacheOrder.isTaskFinished() && !cacheOrder.isNew()){
            log.info("工单["+orderNo+"]正在执行");
            return "order.out.executing";
        }
        if(cacheOrder == null){
            cacheOrder = liteOrderDao.findWithItemsByOrderNo(orderNo);
        }

        if(cacheOrder == null){
            return "order.out.notFound";
        }


        //设置颜色
        Set<String> currentColors = new HashSet<>();
        for (DataLog dataLog : getQueueTasks()) {
            currentColors.add(dataLog.getLightColor());
        }

        StorageConstants.ORDER_COLOR nextColor = StorageConstants.ORDER_COLOR.nextColor(currentColors);
        if(nextColor == null){
            log.info("执行工单["+orderNo+"] outBom="+outBom+"时,已达最大可执行工单数");
            return "order.out.maxOrder";
        }

        log.info("开始执行工单["+orderNo+"] outBom="+outBom);
        cacheOrder.setTaskReelCount(0);
        cacheOrder.setTaskFinishedTime(-1);
        cacheOrder.setFinishedReelCount(0);
        if(outBom){
            cacheOrder.setStatus(StorageConstants.LITEORDER_STATUS.BOM);
        }else{
            cacheOrder.setStatus(StorageConstants.LITEORDER_STATUS.TAILS);
        }
        //liteOrderMap.put(cacheOrder.getOrderNo(), cacheOrder);
        int taskReelCount = 0;
        StorageConstants.CHECKOUT_TYPE checkoutType = dataCache.getCheckOutType();
        List<String> availableStorageIds = new ArrayList<>();
        for (Storage storage : dataCache.getAllStorage().values()) {
            StatusBean statusBean = getStatus(storage.getCid());
            if(statusBean.isAvailable()){
                availableStorageIds.add(storage.getId());
            }
        }


        //其他出库模式一次性全部生成任务
        for (LiteOrderItem orderItem : cacheOrder.getOrderItems()) {
            //剩余未出数量
            int remainNum = orderItem.getNeedNum() - orderItem.getOutNum();
            //此PN未完成
            if(remainNum > 0 ){
                if(outBom){
                    //套料出库,设置剩余数量为1,这样就只会出一盘
                    remainNum = 1;
                }
                int assignNum = 0;
                while (assignNum < remainNum){
                    Collection<String> excludePosIds = excludePosIds();
                    String partNumber = orderItem.getPn();
                    StoragePos pos = storagePosManager.findPartNumberInStorages(availableStorageIds, partNumber, excludePosIds, checkoutType);
                    if(pos == null){
                        log.error("未找到可以出库的物料["+partNumber+"]");
                        break;
                    }else{
                        assignNum = assignNum + pos.getBarcode().getAmount();
                        taskReelCount = taskReelCount + 1;
                        log.info("工单["+orderNo+"],任务数["+taskReelCount+"]出库位置仓位【"+pos.getPosName()+"】RI=["+pos.getBarcode().getBarcode()+"] PN=[" + partNumber + "] num:" + pos.getBarcode().getAmount());
                        DataLog task = newTask(pos);
                        task.setSourceId(cacheOrder.getId());
                        task.setSourceName(cacheOrder.getOrderNo());
                        task.setSubSourceId(orderItem.getId());
                        task.setSubSourceInfo(orderItem.getFeederInfo());
                        task.setType(StorageConstants.OP.CHECKOUT);
                        task.setLightColor(nextColor.getRgb());
                        task.setStatus(StorageConstants.OP_STATUS.WAIT.name());
                        task = dataLogDao.save(task);
                        addTaskToExecute(task);
                    }
                }
            }
        }

        cacheOrder.setTaskReelCount(taskReelCount);
        log.info("工单["+orderNo+"]任务分配结束,任务数["+taskReelCount+"]");
        //有需要出库的
        if(taskReelCount <= 0){
            cacheOrder.finishedTasks();
        }

        liteOrderDao.save(cacheOrder);
        liteOrderMap.put(cacheOrder.getOrderNo(), cacheOrder);
        if(taskReelCount <= 0){
            return "工单无可执行的任务";
        }
        return "";
    }


    /**
     * 根据回温取料任务查找回温放料任务
     * @param rewarmTakingTask
     * @return
     */
    private DataLog findRewarmPuttingTask(DataLog rewarmTakingTask){
        for (DataLog dataLog : taskMap.values()) {
            if(dataLog.isRewarmPuttingTask()){
                if(dataLog.getBarcode().equals(rewarmTakingTask.getBarcode())){
                    return dataLog;
                }
            }
        }
        return null;
    }

    /**
     * 处理客户端发送上来的请求
     */
    @Override
    public StatusBean handleClientRequest(StatusBean statusBean,HttpServletRequest request) {
        try {
            String cid = statusBean.getCid();
            Storage storage = dataCache.getStorage(cid);
            if(storage == null){
                log.error("料仓cid: [" + cid + "]不存在");
                return null;
            }
            //处理客户端发上来的消息
            handleMsg(statusBean);

            synchronized (storage){
                //log.info("reqseq:"+statusBean.getSeq());
                statusBean = saveStatus(statusBean);

                if(storage.isVerticalBox()){
                    //垂直货柜
                    return verticalBoxHandler.handleClientStatusBean(statusBean);
                }

                if(storage.isSmdXl()){
                    statusBean = smdXlBoxHandler.handleClientStatusBean(statusBean);
                }

                statusBean = handleClientStatusBean(statusBean);

                if(statusBean.getOp() == StorageConstants.OP.ALARM_DATA){
                    log.info("获取温湿度报警值");
                    statusBean.setTemperature(dataCache.getSettings().getMaxTemperature());
                    statusBean.setHumidity(dataCache.getSettings().getMaxHumidity());
                    //resultStatus = statusBean;
                    return statusBean;
                }else if(dataCache.needUpdateHumidiy(cid)){
                    log.info("发送温湿度报警值");
                    statusBean.setTemperature(dataCache.getSettings().getMaxTemperature());
                    statusBean.setHumidity(dataCache.getSettings().getMaxHumidity());
                    //resultStatus = statusBean;
                    return statusBean;
                }

                if(storage.isCabinet() || storage.isShelf() || storage.isAccShelf() || storage.isCodeShelf()){
                    //料柜和料架
                    return handleShelfAndCabinet(storage, statusBean);
                }

                if(storage.isSolderPaste()){
                    StatusBean result = handleSolderPaste(cid, statusBean);
                    if(result != null){
                        return result;
                    }
                }

                if(!storage.isSmdXl()){
                    if(statusBean.getOp() == StorageConstants.OP.PUT_IN){
                        log.debug("入库:"+mapper.writeValueAsString(statusBean));
                        statusBean = putInLine(storage, statusBean);
                    }else {
                        //查看是否有要出库的操作
                        statusBean = checkOut(storage, statusBean);
                    }
                }

                //log.info(mapper.writeValueAsString(resultStatus));
                return statusBean;
            }
        } catch (Exception e) {
            log.error("", e);
        }
        return null;
    }

    private StatusBean handleShelfAndCabinet(Storage storage, StatusBean statusBean){
        String cardResult = statusBean.getFromData("cardResult");
        if(!Strings.isNullOrEmpty(cardResult)){
            //写入卡片完成,后续再加密解密,暂就先使用用户名=授权码
            try{
                log.info("收到卡片写入结果【"+cardResult+"】");
                String[] cardInfo = cardResult.split("=");
                User user = userManager.getUser(cardInfo[0]);
                if(user != null && Strings.isNullOrEmpty(user.getAuthCode())){
                    user.setAuthCode(cardInfo[1]);
                    userManager.save(user);
                    log.info("卡片信息【"+cardResult+"】写入成功");
                }
            }catch (Exception e){
                log.error("卡片写入结果出错");
            }
        }
        //出库任务开灯或者开门
        Collection<DataLog> areaWaitTasks = taskMap.values();
        for (DataLog task : areaWaitTasks) {
            if(storage.getCid().equals(task.getCid()) && task.isCheckOutTask()){

                String lightColor = task.getLightColor();
                String opValue = task.getPosName();
                if(!Strings.isNullOrEmpty(lightColor)){
                    StorageConstants.ORDER_COLOR orderColor = StorageConstants.ORDER_COLOR.fromRgb(lightColor);
                    if(orderColor != null){
                        opValue = opValue + "=" + orderColor.name().toLowerCase();
                    }
                }

                if(task.isWait()){
                    //加入到正在执行的列表中
                    log.info("执行开灯:"+opValue);
                    statusBean.addData("open", opValue);
                    //从等待列表中删除,加入到执行列表中
                    task.setStatus(StorageConstants.OP_STATUS.EXECUTING.name());
                    taskMap.put(task.getId(), task);
                    dataLogDao.save(task);
                }else if(task.isExecuting() && task.needReSendToClient()){
//                    log.error("cid["+storage.getCid() + "]的出库任务["+ task.getPosName()+"]超过60秒仍未完成,重新发送到客户端!");
//                    task.setUpdateDate(new Date());
//                    statusBean.addData("open", opValue);
//                    taskMap.put(task.getId(), task);
                }
            }
        }
        return statusBean;
    }

    /**
     * 处理锡膏料仓相关信息
     */
    private StatusBean handleSolderPaste(String cid, StatusBean statusBean){
        if(statusBean.getStatus() == StorageConstants.STATUS.READY){
            //锡膏料仓空闲
            Collection<DataLog> areaWaitTasks = taskMap.values();
            for (DataLog task : areaWaitTasks) {
                if(cid.equals(task.getCid()) && task.isWait()){
                    if(task.isRewarmTakingTask()){
                        //回温取料任务
                        statusBean.setOp(StorageConstants.OP.REWARM_TAKING);
                        statusBean.addData("posId",task.getPosName());

                        DataLog rewarmPuttingTask = findRewarmPuttingTask(task);
                        statusBean.addData("secondPosId",rewarmPuttingTask.getPosName());

                        log.info(task.getBarcode() + "回温移库信息发送到客户端["+task.getPosName()+"]=>" + rewarmPuttingTask.getPosName());

                        rewarmPuttingTask.setStatus(StorageConstants.OP_STATUS.EXECUTING.name());
                        taskMap.put(rewarmPuttingTask.getId(), rewarmPuttingTask);
                        dataLogDao.save(rewarmPuttingTask);

                        task.setStatus(StorageConstants.OP_STATUS.EXECUTING.name());
                        taskMap.put(task.getId(), task);
                        dataLogDao.save(task);

                        return statusBean;
                    }else if(task.isMixTask()){
                        //搅拌任务
                        statusBean.setOp(StorageConstants.OP.MIX);
                        statusBean.addData("posId",task.getPosName());
                        statusBean.addData("barcode",task.getBarcode());
                        statusBean.addData("weight", task.getNum()+"");
                        statusBean.addData("mixTime", task.getMixTime() + "");

                        task.setStatus(StorageConstants.OP_STATUS.EXECUTING.name());
                        dataLogDao.save(task);
                        taskMap.put(task.getId(), task);
                        return statusBean;
                    }
                }
            }
        }
        return null;
    }

    /**
     * 处理客户端发送上来的消息(保存故障信息,并显示界面)
     * @param statusBean
     */
    private void handleMsg(StatusBean statusBean){
        try{
            //展示到界面
            String msg = statusBean.getMsg();
            String msgEn = statusBean.getMsgEn();
            updateClientMsg(statusBean.getCid(),msg,msgEn);
        }catch (Exception e){
            log.error("客户端故障消息处理出错",e);
        }
    }

    private StatusBean handleClientStatusBean(StatusBean statusBean){
        Map<Integer, BoxStatusBean> statusOfBoxes = statusBean.getBoxStatus();
        if (statusOfBoxes != null) {
            for (BoxStatusBean boxStatus : statusOfBoxes.values()) {
                try {
                    //出库入库完成处理
                    int status = boxStatus.getStatus();
                    String posName = boxStatus.getPosId();
                    if(!Strings.isNullOrEmpty(posName)){//客户端发一次完成之后,会发空的 posName,不需要处理
                        if (StorageConstants.BOX_STATUS.IN_FINISHED == status) {//入仓完成
                            DataLog task = findExecutingTask(statusBean.getCid(), boxStatus.getPosId());
                            if (task != null && task.isPutInTask()) {
                                log.info(task.getBarcode() + "入仓位[" + task.getPosName() + "]完成");
                                DataLog cancelTask = findFinishedTask(statusBean.getCid(), boxStatus.getPosId());
                                if(cancelTask != null && cancelTask.isCancel()){
                                    //将相同库位已经取消的任务从完成队列里删除
                                    theFinishedTaskMap.remove(cancelTask.getId());
                                    log.info("从已完成的任务列表中删除之前取消的任务:"+cancelTask.getPosName() + " ReelId:" + cancelTask.getBarcode());
                                }
                                putInFinished(task);
                            } else {
                                //从已完成列表中找,如果还找不到就忽略
                                task = findFinishedTask(statusBean.getCid(), boxStatus.getPosId());
                                if (task != null && task.isPutInTask()) {
                                    if(task.isCancel()){//被取消的任务,客户端发完成信号过来,修改取消状态为已完成
                                        log.info(task.getBarcode() + "入仓位[" + task.getPosName() + "]完成,但任务已被取消,修改为完成");
                                        putInFinished(task);
                                    }
                                }else {
                                    log.error(statusBean.getCid() + "入仓位[" + boxStatus.getPosId() + "]完成时任务不存在");
                                }
                            }
                        } else if (StorageConstants.BOX_STATUS.IN_FAILED == status) {//入库失败

                            //暂不处理
                        } else if (StorageConstants.BOX_STATUS.OUT_FINISHED == status) {//出仓完成
                            DataLog task = findExecutingTask(statusBean.getCid(), boxStatus.getPosId());
                            if (task != null && task.isCheckOutTask()) {
                                log.info(task.getBarcode() + "出仓位[" + task.getPosName() + "]完成");
                                DataLog cancelTask = findFinishedTask(statusBean.getCid(), boxStatus.getPosId());
                                if(cancelTask != null && cancelTask.isCancel()){
                                    //将相同库位已经取消的任务从完成队列里删除
                                    theFinishedTaskMap.remove(cancelTask.getId());
                                    log.info("从已完成的任务列表中删除之前取消的任务:"+cancelTask.getPosName() + " ReelId:" + cancelTask.getBarcode());
                                }
                                //dataCache.unLockOneReel(task.getCid(),task.getPartNumber());
                                checkoutFinished(task);
                            }else{
                                //log.error(operationKey + "触发仓位完成时,操作队列中不存在");
                                //从已完成列表中找,如果还找不到就忽略
                                task = findFinishedTask(statusBean.getCid(), boxStatus.getPosId());
                                if (task != null && task.isCheckOutTask()) {
                                    if(task.isCancel()){//被取消的任务,客户端发完成信号过来,修改取消状态为已完成
                                        log.info(task.getBarcode() + "出仓位[" + task.getPosName() + "]完成,但任务已被取消,修改为完成");
                                        checkoutFinished(task);
                                    }
                                }else {
                                    log.warn(statusBean.getCid() + "出仓位[" + boxStatus.getPosId() + "]完成时任务不存在");
                                }
                            }
                        } else if (StorageConstants.BOX_STATUS.OUT_END == status) {//出库完成(放到仓门口
                            //暂不处理
                        }else if(StorageConstants.BOX_STATUS.REWARM_TAKING_END == status){
                            //回温取料完成, 将库位清空
                            DataLog takingTask = findExecutingTask(statusBean.getCid(), boxStatus.getPosId());
                            if(takingTask == null){
                                //从已完成列表中找,如果还找不到就忽略
                                takingTask = findFinishedTask(statusBean.getCid(), boxStatus.getPosId());
                            }
                            if(takingTask != null){
                                if(takingTask.isCancel()){//被取消的任务,客户端发完成信号过来,修改取消状态为已完成
                                    log.warn(statusBean.getCid() + "回温取料[" + boxStatus.getPosId() + "]完成时任务不存在");
                                }
                                DataLog puttingTask = null;
                                for (DataLog dataLog : taskMap.values()) {
                                    if (dataLog.getCid().equals(statusBean.getCid())) {
                                        if(dataLog.getBarcode().equals(takingTask.getBarcode())){
                                            if(dataLog.isRewarmPuttingTask()){
                                                puttingTask = dataLog;
                                            }
                                        }
                                    }
                                }
                                rewarmTakingEnd(takingTask);
                                if(puttingTask != null){
                                    puttingTask.setStatus(StorageConstants.OP_STATUS.EXECUTING.name());
                                    //dataLog.setSourceType();

                                    dataLogDao.save(puttingTask);
                                    taskMap.put(puttingTask.getId(), puttingTask);
                                    statusBean.addData("secondPosId",puttingTask.getPosName());
                                }
                            }else{
                                log.warn(statusBean.getCid() + "出仓位[" + boxStatus.getPosId() + "]完成时任务不存在");
                            }
                        }else if(StorageConstants.BOX_STATUS.REWARM_PUTTING_END == status){
                            //回温放料结束
                            DataLog puttingTask = findExecutingTask(statusBean.getCid(), boxStatus.getPosId());
                            if(puttingTask == null){
                                //从已完成列表中找,如果还找不到就忽略
                                puttingTask = findFinishedTask(statusBean.getCid(), boxStatus.getPosId());
                            }
                            if(puttingTask != null) {
                                if (puttingTask.isCancel()) {//被取消的任务,客户端发完成信号过来,修改取消状态为已完成
                                    log.warn(statusBean.getCid() + "回温取料[" + boxStatus.getPosId() + "]完成时任务不存在");
                                }
                            }
                            rewarmPuttingEnd(puttingTask);

                        }else if(StorageConstants.BOX_STATUS.MIX_TAKING == status){
                            //搅拌取料

                        }else if(StorageConstants.BOX_STATUS.WAIT_MIX == status){
                            //搅拌取料结束,等待搅拌

                        }else if(StorageConstants.BOX_STATUS.MIXING == status){
                            //搅拌中
                            changeSolderStatus(boxStatus.getPosId(),StorageConstants.SOLDER_STATUS.MIXING);
                        }else if(StorageConstants.BOX_STATUS.MIX_PUTTING == status){
                            //搅拌完成

                        }else if(StorageConstants.BOX_STATUS.MIX_END == status){
                            //搅拌放回原位完成
                            DataLog mixTask = findExecutingTask(statusBean.getCid(), boxStatus.getPosId());
                            mixEnd(mixTask);
                        }
                    }
                } catch (ValidateException e) {
                    log.error("更新状态时出错" + e.getMessage());
                }
            }
        }
        return statusBean;
    }


    /**
     * 出库完成 status为 OUT_FINISHED = 10 出仓位完成,设置posId
     * @param statusBeanToSave
     * @return
     */
    public StatusBean saveStatus(StatusBean statusBeanToSave) {
        String cid = statusBeanToSave.getCid();
        StatusBean statusBean = statusMap.get(cid);
        boolean needSaveToMongo = false;
        if (statusBean == null) {
            statusBean = statusBeanToSave;
            needSaveToMongo = true;
        } else {
            needSaveToMongo = statusBean.needSaveToMongo();
        }
        statusBean.setTime(System.currentTimeMillis());
        Map<Integer, BoxStatusBean> statusOfBoxes = statusBeanToSave.getBoxStatus();

        statusBean.setBoxStatus(statusOfBoxes);
        statusBean.setData(statusBeanToSave.getData());
        statusBean.setMsg(statusBeanToSave.getMsg());
        statusBean.setStatus(statusBeanToSave.getStatus());
        statusBean.setOp(statusBeanToSave.getOp());
        statusBean.setSeq(statusBeanToSave.getSeq());

        /**
         * 已解除的报警信息存到数据库中
         */
        Storage storage = dataCache.getStorage(cid);
        if(storage != null){
            List<AlarmInfo> endAlarmList = statusBean.getEndAlarmList(storage.getName(), statusBeanToSave.getAlarmList());
            alarmInfoDao.insertAll(endAlarmList);
        }

        if(statusOfBoxes != null){
            for (BoxStatusBean boxStatus : statusOfBoxes.values()) {
                int boxId = boxStatus.getBoxId();
                //判断设备状态是否需要保存到数据库中
                dataCache.updateDeviceStatus(cid, boxId, boxStatus.getData());

                if (needSaveToMongo) {
                    //保存温湿度到数据库
                    Humiture humiture = new Humiture();
                    humiture.setCid(cid);
                    humiture.setBoxId(boxId);
                    String humidity = boxStatus.getHumidity();
                    String temperature = boxStatus.getTemperature();
                    if (!Strings.isNullOrEmpty(humidity) && !Strings.isNullOrEmpty(temperature)) {
                        humiture.setHumidity(humidity);
                        humiture.setTemperature(temperature);
                        try {
                            humitureManager.save(humiture);
                            statusBean.setLastSaveTime(System.currentTimeMillis());
                        } catch (ValidateException e) {
                        }
                    }
                }
            }
        }

        statusMap.put(cid, statusBean);

        //清空 msg 的内容,因为客户端会据此决定命令是否执行
        statusBean.setMsg("");
        statusBean.setMsgEn("");

        return statusBean;
    }

    private void changeSolderStatus(String posId, int solderStatus) throws ValidateException {
        StoragePos storagePos = storagePosManager.get(posId);
        if(storagePos == null){
            log.error("更改状态为["+solderStatus+"]时,未找到库位["+posId+"]");
            return;
        }
        Barcode barcode = storagePos.getBarcode();
        if(barcode != null && barcode.getSolderStatus() != solderStatus){
            barcode.setSolderStatus(solderStatus);
            barcode = barcodeManager.save(barcode);

            storagePos.setBarcode(barcode);
            storagePosManager.save(storagePos);
        }

    }

    private void mixEnd(DataLog mixTask) throws ValidateException {
        if(mixTask != null){
            log.info(mixTask.getBarcode() + "搅拌完成,送回原库位,更改状态为待出库");
            taskMap.remove(mixTask.getId());
            mixTask.setStatus(StorageConstants.OP_STATUS.FINISHED.name());
            dataLogDao.save(mixTask);
            theFinishedTaskMap.put(mixTask.getId(),mixTask);

            changeSolderStatus(mixTask.getPosId(),StorageConstants.SOLDER_STATUS.TO_BE_OUT);
        }else{
            log.error("搅拌完成时,未找到任务");
        }
    }

    private void rewarmPuttingEnd(DataLog puttingTask) throws ValidateException {
        //从队列里面移除操作
        taskMap.remove(puttingTask.getId());

        StoragePos storagePos = storagePosManager.get(puttingTask.getPosId());

        if(storagePos.getBarcode() != null){
            log.warn("任务:"+puttingTask.getId() +" 仓位:"+puttingTask.getPosId()+" 已有物料["+storagePos.getBarcode().getBarcode()+"], 之前可能处理过直接返回");
            return;
        }
        //二维码状态
        Barcode barcode = barcodeManager.findByBarcode(puttingTask.getBarcode());
        barcode.setPosName(puttingTask.getPosName());
        barcode.setStartWarmTime(System.currentTimeMillis());
        barcode.setSolderStatus(StorageConstants.SOLDER_STATUS.REWARMING);
        barcodeManager.save(barcode);
        /**
         * 仓位状态
         */
        storagePos.setBarcode(barcode);
        storagePos.setUsed(true);
        storagePosManager.save(storagePos);

        //更新缓存中的库存信息
        dataCache.updateInventory(storagePos,barcode);

        //记录日志,完成 task
        puttingTask.setStatus(StorageConstants.OP_STATUS.FINISHED.name());
        dataLogDao.save(puttingTask);
        theFinishedTaskMap.put(puttingTask.getId(),puttingTask);
    }

    /**
     * 锡膏回温完成处理
     */
    private void rewarmTakingEnd(DataLog task)  throws ValidateException{
        //从队列里面移除操作
        taskMap.remove(task.getId());
        StoragePos storagePos = storagePosManager.get(task.getPosId());

        Barcode barcode = storagePos.getBarcode();
        if(barcode == null){
            log.warn("任务:"+task.getId() +" 仓位:"+task.getPosId()+" 的 Barcode 为null, 之前可能处理过直接返回");
            return;
        }
        storagePos.setBarcode(null);
        storagePos.setUsed(false);
        storagePosManager.save(storagePos);

        log.info("回温取料完成,清空仓位: " + storagePos.getId() + "[" + storagePos.getPosName() + "]");

        //更新缓存中的库存信息
        dataCache.updateInventory(storagePos,barcode);

        //记录日志
        task.setStatus(StorageConstants.OP_STATUS.FINISHED.name());
        dataLogDao.save(task);
        theFinishedTaskMap.put(task.getId(),task);
    }

    private DataLog findFinishedTask(String cid, String posName){
        Collection<DataLog> areaFinishedTasks = getFinishedTasks();
        for (DataLog task : areaFinishedTasks) {
            if (task.getPosName().equals(posName) && task.getCid().equals(cid)) {
                return task;
            }
        }
        return null;
    }

    /**
     * 根据cid 和 posName 查找正在执行的任务,不存在时返回 null
     */
    private DataLog findExecutingTask(String cid, String posName) {
        for (DataLog task : taskMap.values()) {
            if (task.getCid().equals(cid) && task.getPosName().equals(posName)) {
                return task;
            }
        }
        return null;
    }

    @Override
    public Exception getServerException(String cid){
        return serverExceptions.get(cid);
    }

    @Override
    public StatusBean getStatus(String cid) {
        StatusBean statusBean = statusMap.get(cid);
        if (statusBean == null || statusBean.timeOut()) {
            statusBean = new StatusBean();
            statusBean.setCid(cid);
            statusBean.setStatus(StorageConstants.STATUS.OFFLINE);
        }

        Storage storage = dataCache.getStorage(cid);
        if(storage != null && storage.isVirtual()){
            statusBean.setStatus(StorageConstants.STATUS.READY);
            statusBean.setTime(System.currentTimeMillis());
            BoxStatusBean boxStatusBean = new BoxStatusBean();
            boxStatusBean.setBoxId(1);
            boxStatusBean.setStatus(StorageConstants.STATUS.READY);
            Map<Integer,BoxStatusBean> boxMap = new HashMap<>();
            boxMap.put(1,boxStatusBean);
            statusBean.setBoxStatus(boxMap);
        }
        return statusBean;
    }

    @Override
    public Collection<StatusBean> allStatus(){
        return statusMap.values();
    }

    @Override
    public synchronized String checkout(StoragePos pos, boolean forceOut, String subSourceId, boolean isSingleOut){

        Barcode barcode = pos.getBarcode();
        if(barcode != null){
            if(barcode.isSolder()){
                //锡膏出库
                log.info("设置库位["+pos.getPosName()+"]中的锡膏["+barcode.getBarcode()+"]的出库时间为立即出库");
                try {
                    barcode.setNeedOutDate(new Date());
                    barcode = barcodeManager.save(barcode);
                    pos.setBarcode(barcode);
                    storagePosManager.save(pos);
                    return "";
                } catch (ValidateException e) {
                    e.printStackTrace();
                }
            }
        }else{
            if(!forceOut){
                String msg = "库位["+pos.getPosName()+"]中已无物料,忽略";
                log.info(msg);
                //return msg;
                return "allBoxView.noReel";
            }
        }

        Collection<DataLog> allTasks = taskMap.values();
        for(DataLog taskInList : allTasks){
            if(taskInList.getPosId() == null) continue;
            if(taskInList.getPosId().equals(pos.getId())){
                String msg = "库位【"+pos.getPosName()+"已在任务列表中,忽略】";
                log.info(msg);
                //return msg;
                return "order.error.executing";
            }
        }

        DataLog task = newTask(pos);
        task.setType(StorageConstants.OP.CHECKOUT);
        task.setStatus(StorageConstants.OP_STATUS.WAIT.name());
        task.setSingleOut(isSingleOut);
        //工单出库任务
        if(!Strings.isNullOrEmpty(subSourceId)){
            LiteOrderItem liteOrderItem = liteOrderItemDao.findOneById(subSourceId);
            if(liteOrderItem != null){
                String orderNo = liteOrderItem.getOrderNo();
                LiteOrder cacheOrder = liteOrderMap.get(orderNo);
                if(cacheOrder == null || cacheOrder.isOutOne() || cacheOrder.isTaskFinished() || cacheOrder.isNew()){
                    if(cacheOrder == null){
                        //缓存中没有,加入到缓存中
                        cacheOrder = liteOrderDao.findWithItemsByOrderNo(orderNo);
                        cacheOrder.setTaskReelCount(1);
                        cacheOrder.setFinishedReelCount(0);
                    }else if(cacheOrder.isOutOne() || cacheOrder.isOutOneFinished()){
                        //数量+上去
                        cacheOrder.setTaskReelCount(cacheOrder.getTaskReelCount() + 1);
                    }else{
                        cacheOrder.setTaskReelCount(1);
                        cacheOrder.setFinishedReelCount(0);
                    }

                    cacheOrder.setTaskFinishedTime(-1);
                    log.info("订单["+orderNo+"]补料任务" + task.getBarcode() + " 任务数:" +cacheOrder.getFinishedReelCount() + "/"+ cacheOrder.getTaskReelCount());
                    task.setSourceId(cacheOrder.getId());
                    task.setSourceName(orderNo);
                    task.setSubSourceId(liteOrderItem.getId());
                    task.setSubSourceInfo(liteOrderItem.getFeederInfo());
                    cacheOrder.setStatus(StorageConstants.LITEORDER_STATUS.ONE);
                    liteOrderDao.save(cacheOrder);
                    liteOrderMap.put(orderNo,cacheOrder);

                }else{
                    //return "无法执行工单补料任务";
                    return "order.out.failed";
                }
            }else{
                //return "未找到工单信息";
                return "order.out.notFound";
            }
        }
        task = dataLogDao.save(task);
        addTaskToExecute(task);
        return "";
    }


    @Override
    public void addTaskToFinished(StoragePos pos, Barcode barcode, String opUser){
        try{
            //当前库位或barcode有正在执行的任务,完成掉
            if(Strings.isNullOrEmpty(opUser)){
                opUser = StorageDataController.getLoginUsername();
            }
            Collection<DataLog> allTasks = taskMap.values();
            if(pos.getBarcode() != null){
                barcode = pos.getBarcode();
                for(DataLog task : allTasks){
                    if(task.isCheckOutTask()){
                        String executeBarcode = task.getBarcode();
                        String executePosId = task.getPosId();
                        boolean isSameTask = false;
                        if(executeBarcode != null && barcode.getBarcode().equals(executeBarcode)){
                            isSameTask = true;
                        }

                        if(executePosId != null && pos.getId().equals(executePosId)){
                            isSameTask = true;
                        }
                        if(isSameTask){
                            log.info(executeBarcode + "找到正在执行的出库任务["+pos.getPosName()+"],直接完成");
                            if(task.isWait()){
                                taskMap.put(task.getId(),task);
                            }
                            task.setOperator(opUser);
                            checkoutFinished(task);
                            return;
                        }
                    }
                }
            }


            //没有正在执行的任务,直接添加一条已完成的任务
            DataLog task = newTask(pos);
            if(pos.getBarcode() == null){
                log.info(opUser + "入库【"+barcode.getBarcode()+"】到【"+pos.getPosName()+"】");
                task.setType(StorageConstants.OP.PUT_IN);
                barcode.setUsedCount(barcode.getUsedCount() + 1);
                barcode.setUsedDate(new Date());
                barcode.setPutInTime(System.currentTimeMillis());
                barcode.setInOpor(opUser);
                barcode.setCheckOutDate(null,"");
                barcode.setPosName(task.getPosName());

                barcodeManager.save(barcode);

                pos.setBarcode(barcode);
                pos.setUsed(true);
                pos.setCanCheckOutTime(System.currentTimeMillis());
                storagePosManager.save(pos);


                task.setPartNumber(barcode.getPartNumber());
                task.setBarcode(barcode.getBarcode());
                task.setNum(barcode.getAmount());
                task.setMemo(barcode.getMemo());

                dataCache.updateInventory(pos,barcode);

                Storage storage = dataCache.getStorage(task.getCid());
                if(storage != null){
                    if(dataCache.isProductionFor(DataCache.CUSTOMER.PANACIM)){
                        PanaApiController.checkInNotification(barcode);
                    }else{
                        postInNotification(dataCache.getSettings().getInNotifyApi(), task.getBarcode(), task.getStorageId());
                    }
                }
                //dataCache.updateStorage(task.getCid());

            }else{
                barcode = pos.getBarcode();
                log.info(opUser + "将【"+barcode.getBarcode()+"】从【"+pos.getPosName()+"】出库");
                task.setType(StorageConstants.OP.CHECKOUT);
                barcode.setUsed(true);
                barcode.setUsedDate(new Date());
                //仓位状态
                barcode.setCheckOutDate(new Date(),task.getOperator());
                barcode.setPosName("");
                barcodeManager.save(barcode);

                pos.setBarcode(null);
                pos.setUsed(false);
                storagePosManager.save(pos);

                dataCache.updateInventory(pos, barcode);
                //dataCache.updateStorage(task.getCid());

            }

            task.setOperator(opUser);

            task.setBatchInfo(barcode.getBatch());

            task.setStatus(StorageConstants.OP_STATUS.FINISHED.name());
            task = dataLogDao.save(task);

            theFinishedTaskMap.put(task.getId(),task);
        }catch (Exception e){

        }
    }

    @Override
    public void addTaskToExecute(DataLog task) {
        String loginUser = StorageDataController.getLoginUsername();
        task.setOperator(loginUser);
        task = dataLogDao.save(task);
        taskMap.put(task.getId(),task);
    }

    /**
     * 加入要执行的任务
     */
    protected synchronized DataLog addPutInTaskToExecute(Storage storage, Barcode barcode, StoragePos storagePos) throws ValidateException {

        Collection<DataLog> tasks = taskMap.values();
        for (DataLog task : tasks) {
            //检查 barcode
            if (task.getBarcode().equals(barcode.getBarcode())) {
                log.info("二维码:[" + barcode.getBarcode() + "]已在操作队列中,操作失败");
                throw new ValidateException("error.barcode.inQueue",new String[]{storagePos.getPosName()});
            } else if (task.getPosId().equals(storagePos.getId())) {
                log.info("位置:[" + storagePos.getPosName() + "]已在操作队列中,操作失败");
                throw new ValidateException("error.pos.inQueue",new String[]{storagePos.getPosName()});
            }
        }

        DataLog dataLog = new DataLog();
        dataLog.setStorageId(storage.getId());
        dataLog.setStorageName(storage.getName());
        dataLog.setBarcode(barcode.getBarcode());
        dataLog.setMemo(barcode.getMemo());
        dataLog.setType(StorageConstants.OP.PUT_IN);
        dataLog.setNum(barcode.getAmount());

        dataLog.setCid(storage.getCid());
        //dataLog.setComponentName(barcode.getComponentName());
        //TODO:上次出库时间
        //dataLog.setLastOperateDate();
        //操作人

        String loginUser = StorageDataController.getLoginUsername();
        dataLog.setOperator(loginUser);
        dataLog.setPartNumber(barcode.getPartNumber());
        dataLog.setPosId(storagePos.getId());
        dataLog.setPosName(storagePos.getPosName());
        dataLog.setStatus(StorageConstants.OP_STATUS.EXECUTING.name());
        //dataLog.setSourceType();

        dataLogDao.save(dataLog);
        taskMap.put(dataLog.getId(), dataLog);
        log.info("cid:[" + storage.getCid() + "] barcode:[" + barcode.getBarcode() + "] partNumber:[" + dataLog.getPartNumber() + "]位置[" + storagePos.getPosName() + "]的入库操作成功加入队列");
        return dataLog;
    }


    //入仓位完成
    public void putInFinished(DataLog task) throws ValidateException {

        //从队列里面移除操作
        taskMap.remove(task.getId());

        StoragePos storagePos = storagePosManager.get(task.getPosId());
        //二维码状态
        Barcode barcode = barcodeManager.findByBarcode(task.getBarcode());
        if(barcode != null){
            barcode.setUsedCount(barcode.getUsedCount() + 1);
            //barcode.setUsedDate(new Date());
            barcode.setPutInTime(System.currentTimeMillis());
            barcode.setInOpor(task.getOperator());
            barcode.setCheckOutDate(null,"");
            barcode.setPosName(task.getPosName());
            if(barcode.isSolder()){
                if(storagePos.isWarmPos()){
                    //回温仓位
                    barcode.setSolderStatus(StorageConstants.SOLDER_STATUS.RETREAT_STORAGE);
                }else{
                    barcode.setSolderStatus(StorageConstants.SOLDER_STATUS.UNDER_REFRIGERATION);
                }
                barcode.setNeedOutDate(null);
            }
//        if(Strings.isNullOrEmpty(barcode.getProviderNumber())){//补上供应商编号
//            Component component = componentManager.findByPartNumber(barcode.getPartNumber());
//            if(component != null){
//                barcode.setProviderNumber(component.getProviderNumber());
//            }
//        }
            barcodeManager.save(barcode);
        }



        /**
         * 仓位状态
         */
        storagePos.setBarcode(barcode);
        storagePos.setUsed(true);
        storagePos.setCanCheckOutTime(System.currentTimeMillis());
        storagePosManager.save(storagePos);

        if(barcode != null){
            dataCache.updateInventory(storagePos,barcode);

            //dataCache.updateStorage(task.getCid());

            Storage storage = dataCache.getStorage(task.getCid());
            if(storage != null){
                if(dataCache.isProductionFor(DataCache.CUSTOMER.PANACIM)){
                    PanaApiController.checkInNotification(barcode);
                }else{
                    postInNotification(dataCache.getSettings().getInNotifyApi(), task.getBarcode(), task.getStorageId());
                }
            }


            //记录日志,完成 task
            task.setBatchInfo(barcode.getBatch());
            task.setNum(barcode.getAmount());
        }
        //更新缓存中的库存信息

        task.setStatus(StorageConstants.OP_STATUS.FINISHED.name());
        dataLogDao.save(task);

        theFinishedTaskMap.put(task.getId(),task);
    }

    private boolean postInNotification(String url, String reelBarcode, String storageId){
        try {

            if(Strings.isNullOrEmpty(url)){
                return false;
            }
            log.info("向 MES("+url+") 通知【"+reelBarcode+"】的入库信息");
            Barcode barcode = barcodeManager.findByBarcode(reelBarcode);
            Map<String, Object> params = new HashMap<String, Object>();
            params.put("RI",reelBarcode);
            params.put("LOC",storageId);
            if(barcode != null){
                params.put("PN",barcode.getPartNumber());
                params.put("QTY",barcode.getAmount());
                params.put("PRODATE",barcode.getProduceDate());
                params.put("EXPDATE",barcode.getExpireDate());
                params.put("SP",barcode.getProvider());
                params.put("BATCH",barcode.getAmount());
            }
            String result = HttpHelper.postParam(url,params);
            log.info("收到MES ["+ url+"]的关于["+reelBarcode+"]入库通知的反馈信息:"+result);
            return true;
        }catch (Exception e){
            log.error("向  MES ["+url+"]入库通知【"+reelBarcode+"】的信息出错",e);
        }
        return false;
    }

    private boolean postOutNotification(String url, String reelBarcode, String cid){
        try {
            //log.info("出库完成,通知 Agv 小车开始取料");
           // AgvUtil.ArmGet();
            if(Strings.isNullOrEmpty(url)){
                return false;
            }
            log.info("向 MES 通知【"+reelBarcode+"】的出库信息");
            Map<String, Object> params = new HashMap<String, Object>();
            params.put("ReelID",reelBarcode);
            String result = HttpHelper.postParam(url,params);
            log.info("收到MES ["+ url+"]的关于["+reelBarcode+"]出库通知的反馈信息:"+result);
            return true;
        }catch (Exception e){
            log.error("向  MES ["+url+"]出库通知【"+reelBarcode+"】的信息出错",e);
        }
        return false;
    }


    /**
     * 出库完成
     */
    public void checkoutFinished(DataLog task) throws ValidateException {

        //从队列里面移除操作
        taskMap.remove(task.getId());

        StoragePos storagePos = storagePosManager.get(task.getPosId());

        Barcode barcode = storagePos.getBarcode();
        if(barcode == null){
            log.warn("任务:"+task.getId() +" 仓位:"+task.getPosId()+" 的 Barcode 为null, 之前可能处理过直接返回");
            return;
        }

        barcode = barcodeManager.get(barcode.getId());
        if(barcode != null){
            //二维码状态
            barcode.setUsed(true);

            barcode.setUsedDate(new Date());
            //仓位状态
            barcode.setCheckOutDate(new Date(),task.getOperator());
            barcode.setPosName("");
            barcodeManager.save(barcode);

//            String specifiedBatchId = barcode.getLockId();
//            if(!Strings.isNullOrEmpty(specifiedBatchId)){
//                task.setBatchId(specifiedBatchId);
//                task.setBatchInfo(barcode.getLockName());
//            }
            task.setBatchInfo(barcode.getBatch());
        }

        storagePos.setBarcode(null);
        storagePos.setUsed(false);
        storagePosManager.save(storagePos);

        log.info("出库完成,清空仓位: " + storagePos.getId() + "[" + storagePos.getPosName() + "]");

        //更新缓存中的库存信息
        dataCache.updateInventory(storagePos,barcode);


        //通知消息
        Storage storage = dataCache.getStorage(task.getCid());
        if(storage != null){
            if(dataCache.isProductionFor(DataCache.CUSTOMER.PANACIM)){
                PanaApiController.deliverNotification(barcode);
            }else{
                postOutNotification(dataCache.getSettings().getOutNotifyApi(), task.getBarcode(), task.getCid());
            }

        }


        //记录日志
        task.setStatus(StorageConstants.OP_STATUS.FINISHED.name());
        dataLogDao.save(task);

        theFinishedTaskMap.put(task.getId(),task);
        //notifyTask(task);

        //dataCache.updateStorage(task.getCid());

        finishedOrderTask(task);
        //checkTaskSetFinished(task);
    }

    /**
     * 更新工单状态信息
     */
    private synchronized void finishedOrderTask(DataLog task){
        if(StorageConstants.OP.CHECKOUT == task.getType()){
            //更新工单状态
            String orderNo = task.getSourceName();
            if(!Strings.isNullOrEmpty(orderNo)){
                LiteOrder order = liteOrderMap.get(orderNo);
                if(order == null){
                    log.info("缓存中未找到["+orderNo+"],从数据库中重新加载");
                    order = liteOrderDao.findWithItemsByOrderNo(orderNo);
                }
                if(order != null){
                    //任务是取消的,需要将总待出库数量-1
                    if(task.isCancel()){
                        order.setTaskReelCount(order.getTaskReelCount() -1);
                        log.info("工单["+orderNo+"]的任务"+task.getPartNumber()+"["+task.getBarcode()+"]已取消,任务数-1="+order.getFinishedReelCount() + "/" + order.getTaskReelCount());
                    }else if(task.isFinished()){
                        order.setFinishedReelCount(order.getFinishedReelCount() + 1);
                        String orderItemId = task.getSubSourceId();
                        List<LiteOrderItem> items = new ArrayList<>();
                        for (LiteOrderItem liteOrderItem : order.getOrderItems()) {
                            if(liteOrderItem.getId().equals(orderItemId)){
                                log.info("工单["+orderNo+"]的任务"+task.getPartNumber()+"["+task.getBarcode()+"]出库完成,已完成数量+1="+order.getFinishedReelCount()+"/" + order.getTaskReelCount());
                                //更新对应条目的已出库数量和出库盘数
                                liteOrderItem.setOutNum(liteOrderItem.getOutNum() + task.getNum());
                                liteOrderItem.setOutReelCount(liteOrderItem.getOutReelCount() + 1);
                                liteOrderItem = liteOrderItemDao.save(liteOrderItem);
                                Barcode barcode = barcodeManager.findByBarcode(task.getBarcode());
                                if(barcode != null){
                                    int barcodeRemainNum = liteOrderItem.getOutNum() - liteOrderItem.getNeedNum();
                                    if(barcodeRemainNum < 0){
                                        barcodeRemainNum = 0;
                                    }
                                    barcode.setAmount(barcodeRemainNum);
                                    log.info("条码["+task.getBarcode()+"]从工单出库,更改数量为:" + barcodeRemainNum);
                                    try {
                                        barcodeManager.save(barcode);
                                    } catch (ValidateException e) {
                                        e.printStackTrace();
                                    }
                                }
                            }
                            items.add(liteOrderItem);
                        }
                        order.setOrderItems(items);
                        if(!order.isClosed()){
                            //工单未关闭的话,检查状态,全部都出完进行关闭
                            boolean closed = true;
                            for (LiteOrderItem liteOrderItem : order.getOrderItems()) {
                                if(!liteOrderItem.isOutFinished()){
                                    closed = false;
                                    break;
                                }
                            }
                            order.setClosed(closed);
                        }
                    }else{
                        log.error("工单["+orderNo+"]的任务["+task.getBarcode()+"]完成时,状态为:"+ task.getStatus());
                    }

                    if(order.getFinishedReelCount() >= order.getTaskReelCount()){
                        log.info("工单["+orderNo+"]的出库任务已完成,共出库:"+ order.getFinishedReelCount() +" 盘");
                        order.finishedTasks();
                    }
                    liteOrderDao.save(order);
                    liteOrderMap.put(orderNo, order);
                } else{
                    log.error("完成任务时,未找到工单["+orderNo+"]信息");
                }
            }
        }
    }

}