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

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.core.toolkit.CollectionUtils;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.huaheng.api.acs.domain.AgvTask;
import com.huaheng.api.acs.domain.StateInfoUploadModel;
import com.huaheng.api.acs.domain.ToAgvTask;
import com.huaheng.api.acs.mapper.AcsMapper;
import com.huaheng.api.mes.domain.AgvPortMES;
import com.huaheng.api.mes.service.MESHelper;
import com.huaheng.common.constant.QuantityConstant;
import com.huaheng.common.exception.service.ServiceException;
import com.huaheng.common.utils.StringUtils;
import com.huaheng.common.utils.http.HttpUtils;
import com.huaheng.common.utils.security.ShiroUtils;
import com.huaheng.framework.aspectj.lang.annotation.ApiLogger;
import com.huaheng.framework.web.domain.AjaxResult;
import com.huaheng.framework.web.domain.RetCode;
import com.huaheng.framework.web.service.ConfigService;
import com.huaheng.pc.agv.domain.*;
import com.huaheng.pc.agv.service.*;
import com.huaheng.pc.config.address.service.AddressService;
import com.huaheng.pc.config.container.domain.Container;
import com.huaheng.pc.config.container.service.ContainerService;
import com.huaheng.pc.inventory.inventoryHeader.domain.InventoryHeader;
import com.huaheng.pc.inventory.inventoryHeader.service.InventoryHeaderService;
import com.huaheng.pc.receipt.receiptContainerHeader.domain.ReceiptContainerHeader;
import com.huaheng.pc.receipt.receiptContainerHeader.service.ReceiptContainerHeaderService;
import com.huaheng.pc.receipt.receiptDetail.domain.ReceiptDetail;
import com.huaheng.pc.receipt.receiptDetail.service.ReceiptDetailService;
import com.huaheng.pc.receipt.receiptHeader.domain.ReceiptHeader;
import com.huaheng.pc.receipt.receiptHeader.service.ReceiptHeaderService;
import com.huaheng.pc.task.taskDetail.domain.TaskDetail;
import com.huaheng.pc.task.taskDetail.service.TaskDetailService;
import com.huaheng.pc.task.taskHeader.domain.TaskHeader;
import com.huaheng.pc.task.taskHeader.service.ReceiptTaskService;
import com.huaheng.pc.task.taskHeader.service.TaskHeaderService;
import org.apache.commons.beanutils.ConvertUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.transaction.interceptor.TransactionAspectSupport;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.util.*;
import java.util.stream.Collectors;

/**
 * @ClassName   AcsServiceImpl
 * @Description TODO
 * @Author      Administrator
 * @Date        2019/12/2615:38
 */
@Service
public class AcsServiceImpl extends ServiceImpl<AcsMapper, AgvTask> implements AcsService {
    /**
     * public static final int STATUS_TASK_CARRY=100; 搬运任务
     * public static final int STATUS_TASK_WALK=200; 行走任务
     * public static final int STATUS_TASK_PICKUP=300;取货任务
     * public static final int STATUS_TASK_Release=400;放货任务
     * public static final String STATUS_POSITION_EMPTY="empty";
     * public static final String STATUS_POSITION_SOME="some";
     * public static final String STATUS_POSITION_FULL="full";
     * public static final String STATUS_POSITION_LOCK="lock";
     */
    @Resource
    public AcsService acsService;

    @Resource
    private ConfigService configService;

    @Resource
    private AddressService addressService;

    @Resource
    private IAgvPortService agvPortService;

    @Resource
    private TaskHeaderService taskHeaderService;

    @Resource
    private ContainerService containerService;

    @Resource
    private InventoryHeaderService inventoryHeaderService;

    @Resource
    private IAgvInventoryService iAgvInventoryService;

    @Resource
    private IWorkStationService iWorkStationService;

    @Resource
    private IWorkStationFlowService iiWorkStationFlowService;

    @Resource
    private IAgvInventoryService agvInventoryService;

    @Resource
    private TaskDetailService taskDetailService;

    @Resource
    private ReceiptHeaderService receiptHeaderService;

    @Resource
    private ReceiptContainerHeaderService receiptContainerHeaderService;

    @Resource
    private ReceiptTaskService receiptTaskService;

    @Resource
    private ReceiptDetailService receiptDetailService;

    @Resource
    private MESHelper mesHelper;

    @Resource
    private IAgvTaskDetailService agvTaskDetailService;

    @Resource
    private IAgvTaskService agvTaskService;

    /**
     * agv 信息上传
     * @param  model
     * @return
     */
    @Override
    public AjaxResult stateInfoUpload(StateInfoUploadModel model) {
        return null;
    }

    /**
     * agv 信息回传
     * @param  agvTask
     * @return
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public AjaxResult taskConfirm(AgvTask agvTask) {
        return null;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    @ApiLogger(from = "service", apiName = "service创建agv任务")
    public AjaxResult createAGVTask(AgvTask agvTask) {
        if (StringUtils.isEmpty(agvTask.getPreTaskNo())) {
            // 校验请求参数
            checkAgvTaskPosition(agvTask);
            // 校验托盘是否存在任务及是否锁定
            checkContainerAndPositionStatus(agvTask);
            // 校验自己生成的任务中源点位的托盘和实际托盘一不一致
            checkContainerAndPositionLove(agvTask);
        }
        List<String> list = Arrays.asList("Work 679", "Work 680", "Work 681", "Work 682", "Work 1128", "Work 1127", "Work 832", "Work 833", "Work 834", "Work 835");
        if (list.contains(agvTask.getFromPort()) && agvTask.getToPort().equals("Work 842")) {
            return AjaxResult.error("不能下推");
        }
        if (agvTask.getToPort().equals("Work 831") || agvTask.getFromPort().equals("Work 830")) {
            return AjaxResult.error("不能下");
        }
        if (agvTask.getToPort().equals("Work 1209") || agvTask.getFromPort().equals("Work 1208")) {
            return AjaxResult.error("不能下");
        }
        if (agvTask.getToPort().replace(" ", "").toLowerCase().equals("work680")) {
            AjaxResult ajaxResult = checkP6001Status();
            if (ajaxResult.hasErr()) {
                return ajaxResult;
            }
        }
        agvTask.setStatus(QuantityConstant.TASK_STATUS_BUILD);
        if (StringUtils.isNotEmpty(ShiroUtils.getLoginName())) {
            agvTask.setCreatedBy(ShiroUtils.getLoginName());
        } else {
            agvTask.setCreatedBy(agvTask.getCreatedBy());
        }
        agvTask.setTaskType(QuantityConstant.STATUS_TASK_CARRY);
        agvTask.setCreatedTime(new Date());
        AgvPort fromPort = agvPortService.getAgvportByCode(agvTask.getFromPort());
        AgvPort toPort = agvPortService.getAgvportByCode(agvTask.getToPort());
        agvTask.setFromWorkStationId(String.valueOf(fromPort.getWorkStationId()));
        agvTask.setToWorkStationId(String.valueOf(toPort.getWorkStationId()));
        agvTask.setUpdated(new Date());
        if (StringUtils.isNotEmpty(ShiroUtils.getLoginName())) {
            agvTask.setUpdatedBy(ShiroUtils.getLoginName());
        } else {
            agvTask.setUpdatedBy(agvTask.getCreatedBy());
        }
        agvTask.setWarehouseCode("CS0001");
        if (acsService.save(agvTask)) {
            if (StringUtils.isEmpty(agvTask.getPreTaskNo())) {
                agvPortService.updateStatus(agvTask.getFromPort(), QuantityConstant.STATUS_POSITION_LOCK);
                AgvPort desPosition = agvPortService.getAgvportByCode(agvTask.getToPort());
                if (desPosition.getUserDef1()) {
                    agvPortService.updateStatus(agvTask.getToPort(), QuantityConstant.STATUS_POSITION_LOCK);
                }
                containerService.updateStatus(agvTask.getContainerCode(), QuantityConstant.STATUS_CONTAINER_LOCK, agvTask.getWarehouseCode());
            }
            AgvInventory agvInventory = agvInventoryService.getToByPortCode(agvTask.getToPort());
            if (agvInventory != null) {
                return AjaxResult.error("去向点位有托盘");
            }
            List<AgvInventory> invList = agvInventoryService.getListByPortCode(agvTask.getFromPort());
            List<AgvTaskDetail> detailList = new ArrayList<>();
            if (invList != null) {
                invList.forEach(it -> {
                    AgvTaskDetail detail = new AgvTaskDetail();
                    detail.setAgvTaskId(agvTask.getId());
                    detail.setMaterialCode(it.getMaterialCode());
                    detail.setMaterialName(it.getMaterialName());
                    detail.setContainerCode(it.getContainerCode());
                    detail.setBatch(it.getBatch());
                    detail.setQty(new BigDecimal(it.getQty()));
                    detailList.add(detail);
                });
                agvTaskDetailService.saveBatch(detailList);
            }
        } else {
            throw new ServiceException("AGV创建任务失败");
        }
        return AjaxResult.success("执行生成任务成功");
    }

    private AjaxResult checkP6001Status() {
        HashMap map = new HashMap();
        String url = "http://192.168.74.200:8026/api/agv_plc/rollersignalread";
        map.put("stationName", "P6001");
        map.put("signalNo", 4);
        String param = JSON.toJSONString(map);
        String result = HttpUtils.bodypost(url, param, "AGV");
        if (StringUtils.isNull(result) || StringUtils.isEmpty(result)) {
            throw new ServiceException("WCS:接口地址错误或返回为空");
        }
        JSONObject jsonObject = JSONObject.parseObject(result);
        String code = jsonObject.getString("code");
        if (code.equals("200")) {
            JSONObject data = jsonObject.getJSONObject("data");
            String flag = data.getBoolean("flag").toString();
            if (flag.equals("true")) {
                return AjaxResult.error("P6001有货,不允许放货");
            } else {
                return AjaxResult.success();
            }
        } else {
            return AjaxResult.error("P6001读取wcs异常");
        }
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public AjaxResult createAGVTask2(TaskHeader taskHeader) {
        try {
            if (taskHeader.getTaskType().equals(QuantityConstant.TASK_TYPE_WHOLESHIPMENT)) {
                AgvTask agvTask = new AgvTask();
                agvTask.setTaskType(QuantityConstant.STATUS_TASK_CARRY);
                agvTask.setContainerCode(taskHeader.getContainerCode());
                agvTask.setFromPort(taskHeader.getPort());
                agvTask.setToPort("");
                agvTask.setWarehouseCode(taskHeader.getWarehouseCode());
                agvTask.setStatus(QuantityConstant.TASK_STATUS_BUILD);
                agvTask.setCreatedBy(taskHeader.getCreatedBy());
                agvTask.setCreatedTime(new Date());
                if (save(agvTask)) {
                    agvPortService.updateStatus(agvTask.getFromPort(), QuantityConstant.STATUS_POSITION_LOCK);
                    containerService.updateStatus(agvTask.getContainerCode(), QuantityConstant.STATUS_CONTAINER_LOCK, agvTask.getWarehouseCode());
                }
            }
        } catch (Exception e) {
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
            taskHeader.setUserDef3("新增AGV任务失败了");
            taskHeaderService.updateById(taskHeader);
        }
        return null;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public AjaxResult sendTaskToAGV(Integer[] agvTaskIds) {
        AjaxResult result = null;
        boolean finished = false;
        AgvTask task = null;
        for (Integer taskId : agvTaskIds) {
            task = getById(taskId);
            if (task.getStatus() >= QuantityConstant.TASK_STATUS_RELEASE) {
                result = AjaxResult.error("任务" + taskId + "已经下发,请不要重复下发,操作中止");
                finished = true;
                break;
            }
            if (StringUtils.isEmpty(task.getToPort())) {
                result = AjaxResult.error("任务没有目标点位,不允许下发");
                finished = true;
                break;
            }
            LambdaQueryWrapper<AgvTask> agvTaskLambdaQueryWrapper = Wrappers.lambdaQuery();
            AgvPort desPosition = agvPortService.getAgvportByCode(task.getToPort());
            if (desPosition.getUserDef1() && StringUtils.isEmpty(task.getPreTaskNo())) {
                agvTaskLambdaQueryWrapper.eq(AgvTask::getToPort, task.getToPort()).eq(AgvTask::getWarehouseCode, task.getWarehouseCode())
                    .ge(AgvTask::getStatus, QuantityConstant.TASK_STATUS_RELEASE).lt(AgvTask::getStatus, QuantityConstant.TASK_STATUS_COMPLETED);
                List<AgvTask> list = list(agvTaskLambdaQueryWrapper);
                if (list != null && list.size() > 0) {
                    result = AjaxResult.error("目标点位存在任务,请更换目标点位");
                    finished = true;
                    break;
                }
            }
            // 此处判断是否需要 有尘车间和无尘车间之间进行任务中转
            AgvPort sourcePosition = agvPortService.getAgvportByCode(task.getFromPort());
            WorkStation sourceWorkStation = iWorkStationService.getById(sourcePosition.getWorkStationId());
            WorkStation desWorkStation = iWorkStationService.getById(desPosition.getWorkStationId());
            if (sourceWorkStation.getUserDef1() != null && desWorkStation.getUserDef1() != null) {
                if (!sourceWorkStation.getUserDef1().trim().equals(desWorkStation.getUserDef1().trim())) {
                    AjaxResult ajax = new AjaxResult();
                    if (sourceWorkStation.getUserDef1().trim().equals("有尘车间左") && desWorkStation.getUserDef1().trim().equals("无尘车间")) {
                        ajax = createAfterTask(sourcePosition, task, 1);
                    }
                    if (sourceWorkStation.getUserDef1().trim().equals("有尘车间右") && desWorkStation.getUserDef1().trim().equals("无尘车间")) {
                        ajax = createAfterTask(sourcePosition, task, 2);
                    }
                    if (sourceWorkStation.getUserDef1().trim().equals("无尘车间") && desWorkStation.getUserDef1().trim().equals("有尘车间左")) {
                        ajax = createAfterTask(sourcePosition, task, 3);
                    }
                    if (sourceWorkStation.getUserDef1().trim().equals("无尘车间") && desWorkStation.getUserDef1().trim().equals("有尘车间右")) {
                        ajax = createAfterTask(sourcePosition, task, 4);
                    }
                    if (ajax.hasErr()) {
                        return ajax;
                    }
                    task.setId(taskId);
                    task.setStatus(QuantityConstant.TASK_STATUS_RELEASE);
                    task.setUpdated(new Date());
                    task.setUpdatedBy(ShiroUtils.getLoginName());
                    task.setFromUserDef1(sourceWorkStation.getUserDef1());
                    task.setToUserDef1(desWorkStation.getUserDef1());
                    saveOrUpdate(task);
                    return ajax;
                }
            }
            // 给AGV传递任务
            AjaxResult ajaxResult = agvTaskAssign(task);
            if (ajaxResult != null && ajaxResult.hasErr()) {
                result = AjaxResult.error(ajaxResult.getMsg());
                finished = true;
                break;
            }
            // 修改任务头表
            task.setId(taskId);
            task.setStatus(QuantityConstant.TASK_STATUS_RELEASE);
            task.setUpdated(new Date());
            task.setUpdatedBy(ShiroUtils.getLoginName());
            saveOrUpdate(task);
        }
        if (!finished) {
            result = AjaxResult.success("执行下发任务成功", task);
        }
        return result;
    }

    private AjaxResult createAfterTask(AgvPort sourcePosition, AgvTask task, int i) {
        AjaxResult ajaxResult = new AjaxResult();
        String url = null;
        String param = null;
        if (i == 1) {
            HashMap map = new HashMap();
            url = "http://192.168.74.200:8026/api/agv_plc/carputsignalread";
            map.put("stationName", "P4001");
            map.put("signalNo", 4);
            param = JSON.toJSONString(map);
        }
        if (i == 2) {
            HashMap map = new HashMap();
            url = "http://192.168.74.200:8026/api/agv_plc/carputsignalread";
            map.put("stationName", "P4004");
            map.put("signalNo", 4);
            param = JSON.toJSONString(map);
        }
        if (i == 3) {
            HashMap map = new HashMap();
            url = "http://192.168.74.200:8026/api/agv_plc/carputsignalread";
            map.put("stationName", "P4002");
            map.put("signalNo", 4);
            param = JSON.toJSONString(map);
        }
        if (i == 4) {
            HashMap map = new HashMap();
            url = "http://192.168.74.200:8026/api/agv_plc/carputsignalread";
            map.put("stationName", "P4003");
            map.put("signalNo", 4);
            param = JSON.toJSONString(map);
        }
        String result = HttpUtils.bodypost(url, param, "AGV");
//        HashMap map = new HashMap();
//        HashMap map1 = new HashMap();
//        map.put("code","200");
//        map1.put("flag","true");
//        map.put("data",map1);
//        String result = JSON.toJSONString(map);
        if (StringUtils.isNull(result) || StringUtils.isEmpty(result)) {
            throw new ServiceException("WCS:接口地址错误或返回为空");
        }
        JSONObject jsonObject = JSONObject.parseObject(result);
        String code = jsonObject.getString("code");
        if (code.equals("200")) {
            JSONObject data = jsonObject.getJSONObject("data");
            String flag = data.getBoolean("flag").toString();
            if (flag.equals("true")) {
                AgvTask agvTask = new AgvTask();
                agvTask.setFromPort(sourcePosition.getCode());
                if (i == 1) {
                    agvTask.setToPort("Work 776");
//                    List<AgvTask> agvTasks=list(new LambdaQueryWrapper<AgvTask>().eq(AgvTask::getToPort,"Work 776").lt(AgvTask::getStatus,100));
//                    if(CollectionUtils.isNotEmpty(agvTasks)){
//                        return AjaxResult.error("接驳位P4001有任务去");
//                    }
                }
                if (i == 2) {
                    agvTask.setToPort("Work 775");
                }
                if (i == 3) {
                    agvTask.setToPort("Work 633");
//                    List<AgvTask> agvTasks=list(new LambdaQueryWrapper<AgvTask>().eq(AgvTask::getToPort,"Work 633").lt(AgvTask::getStatus,100));
//                    if(CollectionUtils.isNotEmpty(agvTasks)){
//                        return AjaxResult.error("接驳位P4002有任务去");
//                    }
                }
                if (i == 4) {
                    agvTask.setToPort("Work 630");
                }
                agvTask.setContainerCode(task.getContainerCode());
                agvTask.setWarehouseCode("CS0001");
                agvTask.setPreTaskNo(task.getId().toString());
                agvTask.setCreatedBy(task.getCreatedBy());
                ajaxResult = createAGVTask(agvTask);
                if (!ajaxResult.hasErr()) {
                    return AjaxResult.success("生成任务成功");
                }
            } else {
                if (i == 1) {
                    return AjaxResult.error("接驳位P4001不允许放货");
                }
                if (i == 2) {
                    return AjaxResult.error("接驳位P4004不允许放货");
                }
                if (i == 3) {
                    return AjaxResult.error("接驳位P4002不允许放货");
                }
                if (i == 4) {
                    return AjaxResult.error("接驳位P4003不允许放货");
                }
            }
        } else {
            return AjaxResult.error("读取wcs异常");
        }
        return AjaxResult.error("程序未执行");
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public AjaxResult agvTaskAssign(AgvTask agvTask) {
        // 1、判断agvHeader是否为空
        if (agvTask == null) {
            return AjaxResult.error("Agv任务为空");
        }
        // 2、判断必填字段是否满足
        if (agvTask.getId() == null) {
            return AjaxResult.error("Agv任务号Id为空");
        }
        if (agvTask.getTaskType() == null) {
            return AjaxResult.error("Agv任务类型为空");
        }
        String containerCode = agvTask.getContainerCode();
        if (StringUtils.isEmpty(containerCode)) {
            return AjaxResult.error("Agv任务中容器为空");
        }
        String warehouseCode = agvTask.getWarehouseCode();
        // 3、转换实体,初始化Agv任务实体
        agvTask.setTaskNo(String.valueOf(agvTask.getId()));
        ToAgvTask toAgvTask = new ToAgvTask();
        ArrayList<String> containers = new ArrayList<>();
        ArrayList<String> fromports = new ArrayList<>();
        ArrayList<String> toports = new ArrayList<>();
        containers.add(agvTask.getContainerCode());
        toAgvTask.setContainerCode(containers);
        fromports.add(agvTask.getFromPort());
        toAgvTask.setFromPort(fromports);
        toports.add(agvTask.getToPort());
        toAgvTask.setToPort(toports);
        AgvPort desPosition = agvPortService.getAgvportByCode(agvTask.getToPort());
        WorkStation workStation = iWorkStationService.getById(desPosition.getWorkStationId());
        toAgvTask.setTaskType(workStation.getTaskType());
        toAgvTask.setTaskNo(agvTask.getId().toString());
        // 4、发送数据
        return sendDataToAgv(1, warehouseCode, "1", toAgvTask);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public AjaxResult cancelAGVTask(Integer[] agvTaskIds) {
        for (int taskId : agvTaskIds) {
            AgvTask agvTask = getById(taskId);
            if (agvTask == null) {
                return AjaxResult.error("任务" + taskId + "未找到,操作中止");
            }
            if (agvTask.getStatus() > QuantityConstant.TASK_STATUS_RELEASE) {
                return AjaxResult.error("存在任务" + agvTask.getId() + "已下发或执行,操作中止");
            }
            int preTaskNo = taskId;
            LambdaQueryWrapper<AgvTask> agvLambdaQueryWrapper = Wrappers.lambdaQuery();
            agvLambdaQueryWrapper.eq(AgvTask::getPreTaskNo, preTaskNo);
            AgvTask agvTaskHeader = getOne(agvLambdaQueryWrapper);
            if (agvTaskHeader != null) {
                return AjaxResult.error("取消任务失败, 有前置任务" + agvTask.getId());
            }
            // 查出任务明细
            // 删除子任务
            // 删除主任务
            removeById(taskId);
            // 盘点取消任务,恢复明细状态为1
            int taskType = agvTask.getTaskType().intValue();
            switch (taskType) {
                case QuantityConstant.STATUS_TASK_CARRY:
                case QuantityConstant.STATUS_TASK_WALK:
                    break;
                case QuantityConstant.STATUS_TASK_PICKUP:
                case QuantityConstant.STATUS_TASK_RELEASE:
                    break;
                default:
                    break;
            }
            cancelPositionStatus(agvTask);
            cancelContainerStatus(agvTask);
        }
        return AjaxResult.success("取消任务成功!");
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public AjaxResult cancelTask(Integer id, String warehouseCode, String area) {
        // 1、判断参数是否为空
        if (id == null) {
            throw new ServiceException("任务号为空");
        }
        HashMap<String, Object> map = new HashMap();
        List<Integer> list = new ArrayList<>();
        list.add(id);
        map.put("taskNo", list);
        // 2、发送数据
        return sendDataToAgv(2, warehouseCode, area, map);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public AjaxResult updateAGVTask(String agvTaskId, Integer priority) {
        if (StringUtils.isEmpty(agvTaskId)) {
            throw new ServiceException("任务号为空");
        }
        AgvTask agvTask = getById(Integer.parseInt(agvTaskId));
        agvTask.setPriority(priority);
        agvTask.setUpdated(new Date());
        agvTask.setUpdatedBy(ShiroUtils.getLoginName());
        if (!updateById(agvTask)) {
            throw new ServiceException("更新优先级失败");
        }
        return AjaxResult.success();
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public AjaxResult updateTask(Integer id, String warehouseCode, Integer priority) {
        if (id == null) {
            throw new ServiceException("任务号为空");
        }
        AgvTask agvTask = new AgvTask();
        agvTask.setTaskNo(String.valueOf(id));
        agvTask.setPriority(priority);
        return sendDataToAgv(3, warehouseCode, "1", agvTask);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public AjaxResult notifyAGVPort(Map map) {
        AgvTask agvTask = new AgvTask();
        if (map.isEmpty()) {
            return AjaxResult.error("请求数据为空");
        }
        Object o1 = map.get("taskNo");
        Object o2 = map.get("carNo");
        Object o3 = map.get("oldPort");
        Object o4 = map.get("newPort");
        if (StringUtils.isNull(o1)) {
            return AjaxResult.error("任务号为空");
        }
        if (StringUtils.isNull(o2)) {
            return AjaxResult.error("小车编号为空");
        }
        if (StringUtils.isNull(o3)) {
            return AjaxResult.error("起点为空");
        }
        if (StringUtils.isNull(o4)) {
            return AjaxResult.error("终点为空");
        }
        Integer taskNo = Integer.valueOf(o1.toString());
        String carNo = o2.toString();
        String fromPort = o3.toString();
        String toPort = o4.toString();
        agvTask.setId(taskNo);
        agvTask.setCarNo(carNo);
        agvTask.setFromPort(fromPort);
        agvTask.setToPort(toPort);
        AjaxResult ajaxResult = checkPointPositionExist(agvTask);
        if (ajaxResult.hasErr()) {
            return ajaxResult;
        }
        if (!updateById(agvTask)) {
            throw new ServiceException("更新失败");
        } ;
        return ajaxResult;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public AjaxResult notifyAGVTask(Map map) {
        AgvTask agvTask = new AgvTask();
        if (map.isEmpty()) {
            return AjaxResult.error("请求数据为空");
        }
        Object o1 = map.get("taskNo");
        Object o2 = map.get("carNo");
        Object o3 = map.get("status");
        if (StringUtils.isNull(o1)) {
            return AjaxResult.error("任务号为空");
        }
        Integer taskNo = Integer.valueOf(o1.toString());
        List<AgvTask> list = list(new LambdaQueryWrapper<AgvTask>().eq(AgvTask::getId, taskNo));
        if (CollectionUtils.isNotEmpty(list)) {
            AgvTask agvTask1 = list.get(0);
            if (agvTask1.getStatus().equals(100)) {
                return AjaxResult.success("任务已经是完成了的");
            }
        } else {
            return AjaxResult.success("任务不存在");
        }
        if (StringUtils.isNotNull(o2)) {
            String carNo = o2.toString();
            agvTask.setCarNo(carNo);
        }
        if (StringUtils.isNull(o3)) {
            return AjaxResult.error("任务状态为空");
        }
        String status = o3.toString();
        agvTask.setId(taskNo);
        agvTaskStatusNowStart(status, agvTask);
        return AjaxResult.success();
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public AjaxResult completeTaskByWMS(String taskId) {
        AgvTask agvTask = new AgvTask();
        agvTask.setId(Integer.valueOf(taskId));
        agvTaskStatusNowStart(QuantityConstant.STATUS_TASK_FINISH, agvTask);
        return AjaxResult.success();
    }

    /**
     * 将参数传输给AGV
     * @param
     * @param  warehouseCode
     * @param  area
     * @param  object
     * @return
     */
    private AjaxResult sendDataToAgv(int i, String warehouseCode, String area, Object object) {
        String value = configService.getKey(QuantityConstant.RULE_CONNECT_AGV);
        int connectAGV = Integer.parseInt(value);
        String url = null;
        if (connectAGV == QuantityConstant.RULE_AGV_CONNECT) {
            if (i == 1) {
                url = addressService.selectAddress(QuantityConstant.ADDRESS_AGV_TASK_ASSIGN, warehouseCode, area);
            } else if (i == 2) {
                url = addressService.selectAddress(QuantityConstant.ADDRESS_AGV_TASK_CANCEL, warehouseCode, area);
            } else {
            }
            String JsonParam = JSON.toJSONString(object);
            System.out.println(JsonParam);
            // ResponseEntity<JSONObject> result = RestUtil.request_post(url, warehouseCode, JsonParam);
            String result = HttpUtils.bodypost(url, JsonParam, "CS0001");
//            if (result != null && result.getBody() != null) {
//                String code = result.getBody().getString("code");
//                String msg = result.getBody().getString("msg");
//                if (Integer.parseInt(code) != HttpConstant.OK) {
//                    return AjaxResult.error(msg);
//                }
//            } else {
//                throw new ServiceException("接口地址错误或返回为空");
//            }
//            String data = result.getBody().getString("data");
//            AjaxResult ajaxResult = JSON.parseObject(data, AjaxResult.class);
//            if(ajaxResult.getCode() != HttpConstant.OK) {
//                return AjaxResult.error(ajaxResult.getMsg());
//            }
            if (result == null) {
                throw new ServiceException("调用失败");
            } else {
                return AjaxResult.success(result);
            }
        }
        return AjaxResult.success("下发成功");
    }

    /**
     * 检查托盘和点位是否存在未完成的任务
     * @param agvTask
     */
    private void checkContainerAndPositionStatus(AgvTask agvTask) {
        TaskHeader containerLKTaskStatus = taskHeaderService.getOne(new LambdaQueryWrapper<TaskHeader>().eq(TaskHeader::getContainerCode, agvTask.getContainerCode())
            .lt(TaskHeader::getStatus, QuantityConstant.TASK_STATUS_COMPLETED));
        AgvTask containerAgvTaskStatus = getOne(new LambdaQueryWrapper<AgvTask>().eq(AgvTask::getContainerCode, agvTask.getContainerCode()).lt(AgvTask::getStatus,
            QuantityConstant.TASK_STATUS_COMPLETED));
        if (StringUtils.isNotNull(containerLKTaskStatus) || StringUtils.isNotNull(containerAgvTaskStatus)) {
            throw new ServiceException("托盘" + agvTask.getContainerCode() + "存在未完成的任务");
        }
        Container containerStatus = containerService.getContainerByCode(agvTask.getContainerCode());
        if (StringUtils.isNull(containerStatus)) {
            throw new ServiceException("托盘" + agvTask.getContainerCode() + "不存在");
        }
        if (QuantityConstant.STATUS_CONTAINER_LOCK.equals(containerStatus.getStatus())) {
            throw new ServiceException("托盘" + agvTask.getContainerCode() + "已锁定");
        }
        AgvPort pointPosition = agvPortService.getOne(new LambdaQueryWrapper<AgvPort>().eq(AgvPort::getContainerCode, agvTask.getContainerCode())
            .eq(AgvPort::getStatus, QuantityConstant.STATUS_CONTAINER_LOCK).orderByAsc(AgvPort::getType).last("limit 1"));
        if (pointPosition != null) {
            throw new ServiceException("点位" + pointPosition.getCode() + "已锁定,托盘在此位置不能生成任务");
        }
    }

    // 根据任务类型检验参数
    @SuppressWarnings({"AlibabaRemoveCommentedCode", "AlibabaCommentsMustBeJavadocFormat"})
    private void checkAgvTaskPosition(AgvTask agvTask) {
        if (StringUtils.isNull(agvTask)) {
            throw new ServiceException("任务数据为空,请重新下发");
        }
        if (StringUtils.isEmpty(agvTask.getContainerCode())) {
            throw new ServiceException("托盘为空");
        }
        AgvPort sourcePosition = agvPortService.getAgvportByCode(agvTask.getFromPort());
        AgvPort desPosition = agvPortService.getAgvportByCode(agvTask.getToPort());
        if (StringUtils.isEmpty(agvTask.getFromPort())) {
            throw new ServiceException("源点位为空");
        }
        if (StringUtils.isNull(sourcePosition)) {
            throw new ServiceException("源点位:" + sourcePosition.getName() + "未找到");
        }
//        if(sourcePosition.getStatus().equals(QuantityConstant.STATUS_POSITION_LOCK)){
//            throw new ServiceException("源点位:" + sourcePosition.getName() + "禁用");
//        }
        if (StringUtils.isEmpty(agvTask.getToPort())) {
            throw new ServiceException("目标点位为空");
        }
        if (StringUtils.isNull(desPosition)) {
            throw new ServiceException("目标点位:" + desPosition.getName() + "未找到");
        }
        if (!desPosition.getUserDef1()) {
            return;
        }
        if (desPosition.getStatus().equals(QuantityConstant.STATUS_POSITION_LOCK)) {
            throw new ServiceException("目标点位:" + desPosition.getName() + "禁用");
        }
        if (StringUtils.isNotEmpty(desPosition.getContainerCode())) {
            throw new ServiceException("目标点位:" + desPosition.getName() + "存在托盘:" + desPosition.getContainerCode());
        }
        if (QuantityConstant.STATUS_CONTAINER_FULL.equals(desPosition.getStatus())) {
            throw new ServiceException("目标点位:" + desPosition.getName() + "已满");
        }
    }

    // 更新点位状态
    @SuppressWarnings("AlibabaCommentsMustBeJavadocFormat")
    private void cancelPositionStatus(AgvTask agvTask) {
        if (agvTask.getFromPort() != null) {
            // 更新点位状态
            AgvPort agvPort = agvPortService.getAgvportByCode(agvTask.getFromPort());
            if (agvPort != null && StringUtils.isNotEmpty(agvPort.getContainerCode())) {
                agvPortService.updateStatus(agvTask.getFromPort(), QuantityConstant.STATUS_POSITION_EMPTY);
            } else {
                agvPortService.updateStatus(agvTask.getFromPort(), QuantityConstant.STATUS_POSITION_EMPTY);
            }
        }
        if (agvTask.getToPort() != null) {
            // 更新点位状态
            AgvPort agvPort = agvPortService.getAgvportByCode(agvTask.getToPort());
            if (agvPort != null && StringUtils.isNotEmpty(agvPort.getContainerCode())) {
                agvPortService.updateStatus(agvTask.getToPort(), QuantityConstant.STATUS_POSITION_EMPTY);
            } else {
                agvPortService.updateStatus(agvTask.getToPort(), QuantityConstant.STATUS_POSITION_EMPTY);
            }
        }
    }

    // 更新容器状态
    @SuppressWarnings("AlibabaCommentsMustBeJavadocFormat")
    private void cancelContainerStatus(AgvTask agvTask) {
        LambdaQueryWrapper<InventoryHeader> inventoryHeaderLambdaQueryWrapper = Wrappers.lambdaQuery();
        inventoryHeaderLambdaQueryWrapper.eq(InventoryHeader::getContainerCode, agvTask.getContainerCode());
        InventoryHeader inventoryHeader = inventoryHeaderService.getOne(inventoryHeaderLambdaQueryWrapper);
        Container container = new Container();
        container.setStatus(QuantityConstant.STATUS_CONTAINER_EMPTY);
        if (inventoryHeader != null) {
            if (QuantityConstant.STATUS_CONTAINER_SOME.equals(inventoryHeader.getContainerStatus())) {
                container.setStatus(QuantityConstant.STATUS_CONTAINER_SOME);
            }
        }
        LambdaUpdateWrapper<Container> containerUpdateWrapper = Wrappers.lambdaUpdate();
        containerUpdateWrapper.eq(Container::getCode, agvTask.getContainerCode());
        containerService.update(container, containerUpdateWrapper);
    }

    // 检查点位是否存在
    @SuppressWarnings("AlibabaCommentsMustBeJavadocFormat")
    private AjaxResult checkPointPositionExist(AgvTask agvTask) {
        AgvPort sourcePosition = agvPortService.getAgvportByCode(agvTask.getFromPort());
        AgvPort desPosition = agvPortService.getAgvportByCode(agvTask.getToPort());
        if (StringUtils.isNull(sourcePosition)) {
            return AjaxResult.error("源点位:" + sourcePosition + "未找到");
        }
        if (StringUtils.isNull(desPosition)) {
            return AjaxResult.error("目标点位:" + desPosition + "未找到");
        }
        return AjaxResult.success();
    }

    // 校验自己生成的任务中源点位的托盘和实际托盘一不一致
    @SuppressWarnings("AlibabaCommentsMustBeJavadocFormat")
    private void checkContainerAndPositionLove(AgvTask agvTask) {
        AgvPort agvPort = agvPortService.getAgvportByCode(agvTask.getFromPort());
        if (agvPort != null && StringUtils.isNotEmpty(agvPort.getContainerCode())) {
            if (!agvTask.getContainerCode().equals(agvPort.getContainerCode())) {
                throw new ServiceException("源点位上托盘数据和分配的托盘不一致,请核对");
            }
        }
    }

    // 根据agv的任务状态来判断
    private AjaxResult agvTaskStatusNowStart(String o3, AgvTask agvTask) {
        AgvTask task = getById(agvTask.getId());
        if (task == null) {
            return AjaxResult.error("任务号" + agvTask.getId() + "不存在");
        }
        if (task.getStatus().equals(QuantityConstant.TASK_STATUS_COMPLETED)) {
            return AjaxResult.error("任务" + agvTask.getId() + "已经完成");
        }
        /* if(!updateById(agvTask)){ throw new ServiceException("更新失败"); }; */
//        if(o3.equals(QuantityConstant.STATUS_TASK_WAITING)){
//             agvTask.setStatus(10);
//             updateById(agvTask);
//        }
        if (o3.equals(QuantityConstant.STATUS_TASK_AGV_START)) {
            agvTask.setStatus(15);
            updateById(agvTask);
        }
//        if(o3.equals(QuantityConstant.STATUS_TASK_DISPATCHED)){
//             agvTask.setStatus(18);
//             updateById(agvTask);
//        }
        if (o3.equals(QuantityConstant.STATUS_TASK_AGV_TASKOVER)) {
            agvTask.setStatus(20);
            agvPortService.updateStatus(task.getFromPort(), QuantityConstant.STATUS_POSITION_EMPTY);
            agvPortService.setContainerCode(task.getFromPort(), null);
            updateById(agvTask);
            AgvInventory agvInventory = new AgvInventory();
            agvInventory.setStatus("lock");
            LambdaQueryWrapper<AgvInventory> lambdaQueryWrapper = Wrappers.lambdaQuery();
            lambdaQueryWrapper.eq(AgvInventory::getContainerCode, task.getContainerCode());
            iAgvInventoryService.update(agvInventory, lambdaQueryWrapper);
            // 取走后就删除原点位上的库存
            iAgvInventoryService.removeByPortCode(task.getFromPort());
        }
        if (o3.equals(QuantityConstant.STATUS_TASK_FINISH)) {
            if (StringUtils.isNotEmpty(task.getPreTaskNo())) {
                task.setCompleteTime(new Date());
                task.setStatus(100);
                if (StringUtils.isNotEmpty(agvTask.getCarNo())) {
                    task.setCarNo(agvTask.getCarNo());
                }
                String toport = task.getToPort();
                updateById(task);
                task = getById(task.getPreTaskNo());
                if (!toport.equals(task.getToPort())) {
                    return AjaxResult.success();
                }
            }
            task.setCompleteTime(new Date());
            task.setStatus(100);
            if (StringUtils.isNotEmpty(agvTask.getCarNo())) {
                task.setCarNo(agvTask.getCarNo());
            }
            AgvPort fromPort = agvPortService.getAgvportByCode(task.getFromPort());
            WorkStation fromWorkStation = iWorkStationService.getOne(new LambdaQueryWrapper<WorkStation>().eq(WorkStation::getId, fromPort.getWorkStationId()));
            if (fromWorkStation != null && fromWorkStation.getTaskType().equals("1")) {
                agvPortService.updateStatus(task.getFromPort(), QuantityConstant.STATUS_POSITION_EMPTY);
                agvPortService.setContainerCode(task.getFromPort(), null);
            }
            updateById(task);
            // 处理一下agv_inventory
            AgvPort toPort = agvPortService.getAgvportByCode(task.getToPort());
            agvPortService.updateStatus(task.getToPort(), QuantityConstant.STATUS_POSITION_EMPTY);
            if (toPort.getUserDef1()) {
                containerService.updateLocationCodeAndStatus(task.getContainerCode(), task.getToPort(), QuantityConstant.STATUS_CONTAINER_EMPTY,
                    task.getWarehouseCode());
                agvPortService.setContainerCode(task.getToPort(), task.getContainerCode());
                transAgvInventory(task);
            } else {
                Container container = containerService.getContainerByCode(task.getContainerCode());
                containerService.updateSetLocationNullByCode(container.getCode(), QuantityConstant.STATUS_POSITION_EMPTY);
                String containerCode = task.getContainerCode();
                autoCreateReceiptTask(task);
                agvPortService.setContainerCode(task.getToPort(), null);
//                iAgvInventoryService.removeByPortCode(task.getFromPort());
            }
            cancelContainerStatus(task);
        }
        if (o3.equals(QuantityConstant.STATUS_TASK_ERROR)) {
            agvTask.setStatus(110);
            updateById(agvTask);
        }
        if (o3.equals(QuantityConstant.STATUS_TASK_WAITING_CANCEL)) {
            agvTask.setStatus(120);
            updateById(agvTask);
        }
//        if(o3.equals(QuantityConstant.STATUS_TASK_CANCEL_FINISH)){
//             agvTask.setStatus(130);
//             updateById(agvTask);
//        }
//        if(o3.equals(QuantityConstant.STATUS_TASK_WAITING_MANUALLY_FINISH)){
//             agvTask.setStatus(140);
//             updateById(agvTask);
//        }
//        if(o3.equals(QuantityConstant.STATUS_TASK_MANUALLY_FINISH)){
//            agvTask.setStatus(150);
//            agvPortService.updateStatus(task.getFromPort(),QuantityConstant.STATUS_POSITION_EMPTY);
//            agvPortService.updateStatus(task.getToPort(),QuantityConstant.STATUS_POSITION_EMPTY);
//            agvPortService.setContainerCode(task.getFromPort(),null);
//            agvPortService.setContainerCode(task.getToPort(),task.getContainerCode());
//            containerService.updateLocationCodeAndStatus(task.getContainerCode(),task.getToPort(),QuantityConstant.STATUS_CONTAINER_EMPTY,task.getWarehouseCode());
//            updateById(agvTask);
//            cancelContainerStatus(task);
//        }
        return AjaxResult.success();
    }

    private boolean transAgvInventory(AgvTask task) {
        // 删除原点位库存
//        agvInventoryService.removeByPortCode(task.getFromPort());
        // 根据任务明细建目标点位库存
        AgvPort toPort = agvPortService.getAgvportByCode(task.getToPort());
        WorkStation workStation = iWorkStationService.getOne(new LambdaQueryWrapper<WorkStation>().eq(WorkStation::getId, toPort.getWorkStationId()));
        List<AgvTaskDetail> taskDetail = agvTaskDetailService.getListByAgvTaskId(task.getId());
        List<AgvInventory> inventoryList = new ArrayList<>();
        taskDetail.forEach((it) -> {
            AgvInventory agvInventory = new AgvInventory();
            agvInventory.setWorkStationId(workStation.getId());
            agvInventory.setWorkStationCode(workStation.getCode());
            agvInventory.setAgvPortId(toPort.getId());
            agvInventory.setAgvPortCode(toPort.getCode());
            agvInventory.setMaterialCode(it.getMaterialCode());
            agvInventory.setBatch(it.getBatch());
            agvInventory.setMaterialName(it.getMaterialName());
            agvInventory.setContainerCode(task.getContainerCode());
            agvInventory.setQty(it.getQty().longValue());
            agvInventory.setStatus("empty");
            inventoryList.add(agvInventory);
        });
        agvInventoryService.saveBatch(inventoryList);
        return true;
    }

    private boolean autoCreateReceiptTask(AgvTask task) {
        if (task.getToPort().equals("Work 830") || task.getToPort().equals("Work 1208")) {
            List<AgvTaskDetail> taskDetail = agvTaskDetailService.getListByAgvTaskId(task.getId());
            if (CollectionUtils.isNotEmpty(taskDetail)) {
                ReceiptHeader receiptHeader = new ReceiptHeader();
                receiptHeader.setReceiptType("PPI");
                receiptHeader.setCompanyCode("WB");
                receiptHeaderService.saveReceiptHeader(receiptHeader);
                List<ReceiptDetail> receiptDetailList = new ArrayList<>();
                taskDetail.forEach((it) -> {
                    ReceiptDetail receiptDetail = new ReceiptDetail();
                    receiptDetail.setCompanyCode("WB");
                    receiptDetail.setInventorySts("good");
                    receiptDetail.setQcCheck("0");
                    receiptDetail.setBatch(it.getBatch());
                    receiptDetail.setReceiptCode(receiptHeader.getCode());
                    receiptDetail.setReceiptId(receiptHeader.getId());
                    receiptDetail.setMaterialCode(it.getMaterialCode());
                    receiptDetail.setTotalQty(it.getQty());
                    receiptDetailList.add(receiptDetail);
                    receiptDetailService.saveReceiptDetaial(receiptDetail);
                });
                if (CollectionUtils.isNotEmpty(receiptDetailList)) {
                    List<ReceiptContainerHeader> receiptContainerHeaders = new ArrayList<>();
                    receiptDetailList.forEach(receiptDetail -> {
                        ReceiptContainerHeader receiptContainerHeader = new ReceiptContainerHeader();
                        AjaxResult ajaxResult = receiptContainerHeaderService.saveContainer(receiptDetail.getReceiptCode(), task.getContainerCode(),
                            receiptDetail.getId(), "", receiptDetail.getTotalQty(), "");
                        receiptContainerHeaders.add((ReceiptContainerHeader)ajaxResult.getData());
                    });
                    if (CollectionUtils.isNotEmpty(receiptContainerHeaders)) {
                        List<Integer> list = new ArrayList<>();
                        for (ReceiptContainerHeader receiptContainerHeader : receiptContainerHeaders) {
                            list.add(receiptContainerHeader.getId());
                        }
                        list = list.stream().distinct().collect(Collectors.toList());
                        receiptTaskService.createReceiptTask(list);
                    }
                }
            } else {
                inventoryHeaderService.createEmptyIn(task.getContainerCode(), null);
            }
        }
        return true;
    }

    @Override
    public AjaxResult getEmptyContainer(String destinationLocation, String type) {
        if (type.trim().equals("1")) {
            AgvPort agvPort = agvPortService.getAgvportByCode(destinationLocation);
            List<WorkStationFlow> workStationFlows =
                iiWorkStationFlowService.list(new LambdaQueryWrapper<WorkStationFlow>().eq(WorkStationFlow::getWorkStationId, agvPort.getWorkStationId()));
            workStationFlows = workStationFlows.stream().filter(workStationFlow -> workStationFlow.getFlowType().trim().equals("next")).collect(Collectors.toList());
            List<Long> workStationIdRelateds =
                workStationFlows.stream().map(workStationFlow -> workStationFlow.getWorkStationIdRelated()).collect(Collectors.toList());
            for (Long workStationIdRelated : workStationIdRelateds) {
                List<AgvPort> list = agvPortService.list(new LambdaQueryWrapper<AgvPort>().eq(AgvPort::getWorkStationId, workStationIdRelated));
                list = list.stream()
                    .collect(Collectors.collectingAndThen(Collectors.toCollection(() -> new TreeSet<>(Comparator.comparing(o -> o.getName()))), ArrayList::new));
                list = list.stream().filter(agvPort1 -> StringUtils.isNotEmpty(agvPort1.getContainerCode())).collect(Collectors.toList());
                if (CollectionUtils.isNotEmpty(list)) {
                    for (AgvPort port : list) {
                        AgvTask agvTask = new AgvTask();
                        agvTask.setFromPort(port.getCode());
                        agvTask.setToPort(destinationLocation);
                        agvTask.setContainerCode(port.getContainerCode());
                        List<AgvInventory> list1 =
                            iAgvInventoryService.list(new LambdaQueryWrapper<AgvInventory>().eq(AgvInventory::getContainerCode, port.getContainerCode()));
                        if (CollectionUtils.isNotEmpty(list1)) {
                            continue;
                        }
                        try {
                            AjaxResult ajax = createAGVTask(agvTask);
                            if (ajax.getCode() == RetCode.FAIL.getValue()) {
                                continue;
                            }
                        } catch (Exception e) {
                            continue;
                        }
                        return AjaxResult.success("创建成功");
                    }
                } else {
                    return AjaxResult.error("没有空托盘可以叫");
                }
            }
        } else if (type.trim().equals("2")) {
//            AgvPort agvPort = agvPortService.getAgvportByCode(destinationLocation);
//            List<WorkStationFlow> workStationFlows = iiWorkStationFlowService.list(new LambdaQueryWrapper<WorkStationFlow>().eq(WorkStationFlow::getWorkStationId, agvPort.getWorkStationId()));
//            workStationFlows = workStationFlows.stream().filter(workStationFlow -> workStationFlow.getFlowType().trim().equals("prev")).collect(Collectors.toList());
//            List<Long> workStationIdRelateds = workStationFlows.stream().map(workStationFlow -> workStationFlow.getWorkStationIdRelated()).collect(Collectors.toList());
//            for (Long workStationIdRelated : workStationIdRelateds) {
//                List<AgvPort> list = agvPortService.list(new LambdaQueryWrapper<AgvPort>().eq(AgvPort::getWorkStationId, workStationIdRelated));
//                list = list.stream().collect(Collectors.collectingAndThen(Collectors.toCollection(() -> new TreeSet<>(Comparator.comparing(o -> o.getName()))), ArrayList::new));
//                list = list.stream().filter(agvPort1 -> StringUtils.isEmpty(agvPort1.getContainerCode())).collect(Collectors.toList());
//                if(CollectionUtils.isNotEmpty(list)){
//                    AgvTask agvTask=new AgvTask();
//                    agvTask.setFromPort(destinationLocation);
//                    agvTask.setToPort(list.get(0).getCode());
//                    agvTask.setContainerCode(agvPort.getContainerCode());
//                    createAGVTask(agvTask);
//                    return AjaxResult.success("创建成功");
//                }else {
//                    return AjaxResult.error("没有空托盘可以送");
//                }
//            }
        }
        return null;
    }

    @Override
    public void shipmentAgvPortContext(TaskHeader task) {
        String port = task.getPort();
        String work = "";
        if (port.equals("P1036")) {
            work = "Work 831";
        }
        if (port.equals("P2114")) {
            work = "Work 1209";
        }
        LambdaQueryWrapper<Container> containerLambdaQueryWrapper = Wrappers.lambdaQuery();
        containerLambdaQueryWrapper.eq(Container::getLocationCode, "Work 831").or().eq(Container::getLocationCode, "Work 1209");
        List<Container> containers = containerService.list(containerLambdaQueryWrapper);
        containers.forEach(container -> {
            if (container != null && container.getLocationCode() != null && container.getLocationCode().startsWith("Work")) {
                container.setLocationCode("");
                containerService.updateById(container);
            }
        });
        agvPortService.clearContainerCodeByCode(work);
        agvInventoryService.removeByPortCode(work);
        // 绑定托盘数据
        agvPortService.setContainerCode(work, task.getContainerCode());
        // 获取任务明细
        List<TaskDetail> taskDetails = taskDetailService.findByTaskId(task.getId());
        List<AgvInventory> agvInventories = new ArrayList<>();
        String finalWork = work;
        taskDetails.forEach(taskDetail -> {
            AgvInventory a = new AgvInventory();
            a.setAgvPortCode(finalWork);
            a.setAgvPortId(Long.valueOf("910"));
            a.setContainerCode(task.getContainerCode());
            a.setMaterialCode(taskDetail.getMaterialCode());
            a.setMaterialName(taskDetail.getMaterialName());
            a.setWorkStationCode("LK");
            a.setBatch(taskDetail.getBatch());
            a.setWorkStationId(Long.valueOf("58"));
            a.setQty(Long.valueOf(taskDetail.getQty().toString()));
            agvInventories.add(a);
        });
        agvInventoryService.addInventory(agvInventories);
    }

    @Override
    public AjaxResult emptyContainer(AgvTask agvTask) {
        agvTask.setToPort("Work 830");
        agvTask.setWarehouseCode("CS0001");
        return createAGVTask(agvTask);
    }

    @Override
    public AjaxResult<AgvTask> huichuanMesError(Integer[] toIntArray) throws Exception {
        for (Integer integer : toIntArray) {
            AgvTask agvTask = acsService.getById(integer);
            AgvPortMES agvPortMES = new AgvPortMES();
            agvPortMES.setCode(agvTask.getCode());
            agvPortMES.setStatus("error");
            String s = JSONObject.toJSONString(agvPortMES);
            mesHelper.returnMESEmptyFinsh(s);
            agvTask.setSendToMes(1);
            agvTask.setStatus(110);
            acsService.updateById(agvTask);
        }
        return AjaxResult.success("");
    }

    @Override
    @Transactional
    public AjaxResult createAGVTask2(AgvTask agvTask) {
        String preTaskNo = agvTask.getPreTaskNo();
        if (StringUtils.isEmpty(preTaskNo)) {
            return AjaxResult.error("前置任务号空!");
        }
        AgvTask preAgvTask = acsService.getById(preTaskNo);
        if (preAgvTask == null) {
            return AjaxResult.error("前置任务没有找到!");
        }
        if (preAgvTask.getStatus() == QuantityConstant.TASK_STATUS_COMPLETED) {
            return AjaxResult.error("前置任务已经完成!");
        }
        if ("第二个子任务生成".equals(preAgvTask.getRyTask())) {
            return AjaxResult.error("前置任务已经生成第二个子任务!");
        }
        if (!agvTask.getToPort().equals(preAgvTask.getToPort())) {
            return AjaxResult.error("填写的目标位置和前置任务目标位置不一致,请重新填写!");
        }
        String sonAgvTask2fromPort = agvTask.getFromPort();
        LambdaQueryWrapper<AgvTask> agvTaskLambdaQueryWrapper1 = Wrappers.lambdaQuery();
        agvTaskLambdaQueryWrapper1.eq(AgvTask::getPreTaskNo, preTaskNo);
        agvTaskLambdaQueryWrapper1.eq(AgvTask::getFromPort, preAgvTask.getFromPort());
        agvTaskLambdaQueryWrapper1.eq(AgvTask::getStatus, QuantityConstant.TASK_STATUS_COMPLETED);
        List<AgvTask> sonAgvTaskList = acsService.list(agvTaskLambdaQueryWrapper1);
        if (sonAgvTaskList.isEmpty()) {
            return AjaxResult.error("前置任务第一个子任务没有结束!");
        }
        AgvTask sonAgvTask1 = sonAgvTaskList.get(0);
        String sonAgvTask1ToPort = sonAgvTask1.getToPort();
        if ((sonAgvTask1ToPort.equals("Work 776") && !sonAgvTask2fromPort.equals("Work 632"))
            || (sonAgvTask1ToPort.equals("Work 633") && !sonAgvTask2fromPort.equals("Work 777"))
            || (sonAgvTask1ToPort.equals("Work 630") && !sonAgvTask2fromPort.equals("Work 774"))
            || (sonAgvTask1ToPort.equals("Work 775") && !sonAgvTask2fromPort.equals("Work 631"))) {
            return AjaxResult.error("填写的起始点位和前置任务的搬运路径不一致");
        }
        AgvTask agvTask2 = new AgvTask();
        agvTask2.setFromPort(agvTask.getFromPort());
        agvTask2.setToPort(preAgvTask.getToPort());
        agvTask2.setContainerCode(agvTask.getContainerCode());
        agvTask2.setWarehouseCode("CS0001");
        agvTask2.setPreTaskNo(preAgvTask.getId().toString());
        agvTask2.setCreatedBy(preAgvTask.getCreatedBy());
        acsService.createAGVTask(agvTask2);
        preAgvTask.setRyTask("第二个子任务生成");
        acsService.updateById(preAgvTask);
        createSecondTaskDetail(preAgvTask, agvTask2);
        return AjaxResult.success("成功!");
    }

    /**
     * 创建二阶段任务的明细
     * @param preTask
     * @param secondTask
     */
    private void createSecondTaskDetail(AgvTask preTask, AgvTask secondTask) {
        try {
            List<AgvTaskDetail> list = agvTaskDetailService.getListByAgvTaskId(preTask.getId());
            List<AgvTaskDetail> secondList = agvTaskDetailService.getListByAgvTaskId(secondTask.getId());
            // 先检查有没有明细,有就不再创建了
            if (secondList != null && secondList.size() > 0) {
                return;
            }
            List<AgvTaskDetail> finalSecondList = new ArrayList<>();
            list.forEach(it -> {
                AgvTaskDetail detail = new AgvTaskDetail();
                detail.setAgvTaskId(secondTask.getId());
                detail.setContainerCode(secondTask.getContainerCode());
                detail.setMaterialName(it.getMaterialName());
                detail.setMaterialCode(it.getMaterialCode());
                detail.setBatch(it.getBatch());
                detail.setQty(it.getQty());
                finalSecondList.add(detail);
            });
            agvTaskDetailService.saveBatch(finalSecondList);
        } catch (Exception e) {
            log.error("创建二阶段任务明细失败:" + e.getMessage());
        }
    }
}