MesServiceImpl.java 64.1 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
package com.huaheng.api.mes.service;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.google.gson.JsonObject;
import com.huaheng.api.acs.domain.AgvTaskCS;
import com.huaheng.api.acs.service.AgvTaskCSService;
import com.huaheng.api.general.domain.ReceiptDomain;
import com.huaheng.api.general.domain.ShipmentDomain;
import com.huaheng.api.general.service.ReceiptApiService;
import com.huaheng.api.general.service.ShipmentApiService;
import com.huaheng.api.mes.domain.*;
import com.huaheng.api.rcs.service.RcsService;
import com.huaheng.common.constant.QuantityConstant;
import com.huaheng.common.exception.service.ServiceException;
import com.huaheng.common.support.Convert;
import com.huaheng.common.utils.StringUtils;
import com.huaheng.common.utils.Wrappers;
import com.huaheng.common.utils.http.OkHttpUtils;
import com.huaheng.common.utils.security.ShiroUtils;
import com.huaheng.framework.token.TokenService;
import com.huaheng.framework.web.controller.BaseController;
import com.huaheng.framework.web.domain.AjaxResult;
import com.huaheng.framework.web.domain.Result;
import com.huaheng.framework.web.page.TableDataInfo;
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.config.location.domain.Location;
import com.huaheng.pc.config.location.service.LocationService;
import com.huaheng.pc.config.locationType.domain.LocationType;
import com.huaheng.pc.config.locationType.service.LocationTypeService;
import com.huaheng.pc.config.material.domain.Material;
import com.huaheng.pc.config.material.service.MaterialService;
import com.huaheng.pc.config.zone.domain.Zone;
import com.huaheng.pc.config.zone.service.ZoneService;
import com.huaheng.pc.inventory.inventoryDetail.domain.InventoryDetail;
import com.huaheng.pc.inventory.inventoryDetail.service.InventoryDetailService;
import com.huaheng.pc.inventory.inventoryHeader.domain.InventoryHeader;
import com.huaheng.pc.inventory.inventoryHeader.service.InventoryHeaderService;
import com.huaheng.pc.receipt.receiptContainerDetail.domain.ReceiptContainerDetail;
import com.huaheng.pc.receipt.receiptContainerDetail.service.ReceiptContainerDetailService;
import com.huaheng.pc.receipt.receiptContainerHeader.domain.ReceiptContainerView;
import com.huaheng.pc.receipt.receiptContainerHeader.service.ReceiptContainerHeaderService;
import com.huaheng.pc.receipt.receiptDetail.domain.ReceiptDetail;
import com.huaheng.pc.receipt.receiptHeader.domain.ReceiptHeader;
import com.huaheng.pc.receipt.receiptHeader.service.ReceiptHeaderService;
import com.huaheng.pc.shipment.shipmentContainerHeader.domain.ShipmentCombinationModel;
import com.huaheng.pc.shipment.shipmentContainerHeader.domain.ShipmentContainerHeader;
import com.huaheng.pc.shipment.shipmentContainerHeader.service.ShipmentContainerHeaderService;
import com.huaheng.pc.shipment.shipmentDetail.domain.ShipmentDetail;
import com.huaheng.pc.shipment.shipmentHeader.domain.ShipmentHeader;
import com.huaheng.pc.system.dict.domain.DictData;
import com.huaheng.pc.system.dict.service.IDictDataService;
import com.huaheng.pc.system.user.domain.User;
import com.huaheng.pc.system.user.service.IUserService;
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.mapper.TaskHeaderMapper;
import com.huaheng.pc.task.taskHeader.service.ReceiptTaskService;
import com.huaheng.pc.task.taskHeader.service.TaskHeaderService;
import com.huaheng.pc.task.taskHeader.service.TransferTaskService;
import com.huaheng.pc.task.taskHeader.service.WorkTaskService;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

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

/**
 * mes接口实现层
 * @author xcq
 */
@Service
public class MesServiceImpl extends BaseController implements MesService{
    @Resource
    private TaskHeaderService taskHeaderService;
    @Resource
    private AgvTaskCSService agvTaskCSService;
    @Resource
    private AddressService addressService;
    @Resource
    private LocationTypeService locationTypeService;
    @Resource
    private LocationService locationService;

    @Override
    public AjaxResult sendTaskToAcs(TaskHeader taskHeader) {
        if (taskHeader == null){
            throw new RuntimeException("AGV任务参数不能为空!");
        }
        // 判断任务id是否为空
        if (taskHeader.getId() == null){
            throw new RuntimeException("任务ID不能为空!");
        }
        AcsTask acsTask = new AcsTask();
        acsTask.setTaskNo(taskHeader.getId().toString());
        if (taskHeader.getStatus() > QuantityConstant.AGV_TASK_STATUS_RELEASE){
            throw new RuntimeException("任务已下发!");
        }
        // 整盘出库任务和空托出库任务
        if (taskHeader.getTaskType() == QuantityConstant.TASK_TYPE_WHOLESHIPMENT
                || taskHeader.getTaskType() == QuantityConstant.TASK_TYPE_EMPTYSHIPMENT){
            // 设置起点
            acsTask.setBeginPoint(taskHeader.getFromLocation());
            // 设置终点
            acsTask.setEndPoint(taskHeader.getPickingCartPos());
        }
        // 整盘入库和空托入库任务
        if (taskHeader.getTaskType() == QuantityConstant.TASK_TYPE_WHOLERECEIPT
                || taskHeader.getTaskType() == QuantityConstant.TASK_TYPE_EMPTYRECEIPT){
            // 设置起点
            acsTask.setBeginPoint(taskHeader.getPickingCartPos());
            // 设置终点
            acsTask.setEndPoint(taskHeader.getToLocation());
        }
        // 移库
        if (taskHeader.getTaskType() == QuantityConstant.TASK_TYPE_TRANSFER){
            // 设置起点
            acsTask.setBeginPoint(taskHeader.getFromLocation());
            // 设置终点
            acsTask.setEndPoint(taskHeader.getToLocation());
        }
        // 判断起点是否为空
        if (StringUtils.isEmpty(acsTask.getEndPoint())){
            throw new RuntimeException("起点位置不能为空!");
        }
        if (StringUtils.isEmpty(acsTask.getBeginPoint())){
            throw new RuntimeException("终点位置不能为空!");
        }
        String JsonParam = JSON.toJSONString(acsTask);
        // 获取下发ACS地址
        String url = addressService.selectAddress(QuantityConstant.AGV_TASK_ASSIGN,QuantityConstant.WAREHOUSE_KS );
        String str = OkHttpUtils.bodypost(url, JsonParam, ShiroUtils.getWarehouseCode());
        if (StringUtils.isEmpty(str)){
            throw new RuntimeException("下发AGV任务失败,返回结果为空!");
        }
        AjaxResult result = JSON.parseObject(str, AjaxResult.class);
        if (result.hasErr()){
            return result;
        }
        taskHeader.setStatus(QuantityConstant.AGV_TASK_STATUS_RELEASE);
        taskHeaderService.updateById(taskHeader);
        return result;
    }

    @Override
    public AjaxResult cancelACSTaskService(Integer id) {
        TaskHeader taskHeader = taskHeaderService.getById(id);
        if (taskHeader == null){
            return AjaxResult.error("根据id查询任务表失败!");
        }
        if (QuantityConstant.AGV_TASK_STATUS_EXECUTE == taskHeader.getStatus()){
            return AjaxResult.error("AGV任务已经执行无法取消!");
        }
        AcsTask acsTask = new AcsTask();
        acsTask.setTaskNum(id);
        acsTask.setTaskNo(id.toString());
        String JsonParam = JSON.toJSONString(acsTask);
//        String url = addressService.selectAddress(QuantityConstant.AGV_TASK_CANCEL,QuantityConstant.WAREHOUSE_KS );
//        String str = OkHttpUtils.sendPost(url, JsonParam);
//        if (StringUtils.isEmpty(str)){
//            throw new RuntimeException("取消AGV任务失败,返回结果为空!");
//        }
//        AjaxResult result = JSON.parseObject(str, AjaxResult.class);
//        if (result.hasErr()){
//            return result;
//        }
        AjaxResult result = taskHeaderService.cancelTask(Convert.toIntArray(taskHeader.getId().toString()));
        return result;
    }

    @Resource
    private ReceiptHeaderService receiptHeaderService;
    @Resource
    private ReceiptApiService receiptApiService;
    @Resource
    private MesService mesService;
    @Resource
    private MaterialService materialService;
    @Resource
    private IUserService userService;

    @Override
    public AjaxResult createTaskService(MesTask mesTask) {
        if (mesTask == null){
            return AjaxResult.error("请勿提交空数据!");
        }
        // 根据区域编码查询
        LambdaQueryWrapper<LocationType> lambda = Wrappers.lambdaQuery();
        lambda.eq(LocationType::getCode, mesTask.getArea());
        lambda.last("limit 1");
        LocationType locationType = locationTypeService.getOne(lambda);
        if (locationType == null){
            return AjaxResult.error("该区域编码:"+mesTask.getArea()+"不存在");
        }
        if (ShiroUtils.getUser() == null){
            // 模拟mes登录
            userService.login(QuantityConstant.PLATFORM_MES, QuantityConstant.PLATFORM_MES_PASSWORD, QuantityConstant.WAREHOUSE_KS, false);
        }
        // 判断是开工还是完工
        if (mesTask.isType()){
            // 出库任务
            return mesService.createShipment(mesTask);
        }else {
            // 创建入库任务
            return mesService.createReceipt(mesTask);
        }
    }

    @Resource
    private ReceiptContainerHeaderService receiptContainerHeaderService;
    @Resource
    private ReceiptContainerDetailService receiptContainerDetailService;
    @Resource
    private ReceiptTaskService receiptTaskService;
    @Resource
    private ShipmentContainerHeaderService shipmentContainerHeaderService;

    @Override
    @Transactional
    public AjaxResult createReceipt(MesTask mesTask) {
        // 校验任务是否已经存在
        AjaxResult result = mesService.checkStation(mesTask.getStation(), QuantityConstant.TASK_TYPE_WHOLERECEIPT);
        if (!result.hasErr()){
            return result;
        }
        // 新增入库单之前先判断物料是否存在
        result = mesService.addMaterial(mesTask);
        if (result.hasErr()){
            return result;
        }
        Container container = null;
        // 没有单据编码和容器编码的是光腾库区
        String locationCode = null;
        if (StringUtils.isEmpty(mesTask.getOrderCode())){
            // 根据区查询可以分配的库位
            LambdaQueryWrapper<Location> query = Wrappers.lambdaQuery();
            query.eq(Location::getLocationType, mesTask.getArea())
                    .eq(Location::getContainerCode, "")
                    .eq(Location::getStatus, QuantityConstant.STATUS_LOCATION_EMPTY)
                    .last("limit 1");
            Location location = locationService.getOne(query);
            if (location == null){
                throw new RuntimeException("当前库区没有可用库位!");
            }
            locationCode = location.getCode();
            // 光腾使用虚拟托盘码
            container = containerService.getGTContainer();
        }
        // 校验机加托盘号是否正确
        if (StringUtils.isNotEmpty(mesTask.getContainerCode())){
            LambdaQueryWrapper<Container> lambdaQueryWrapper = Wrappers.lambdaQuery();
            lambdaQueryWrapper.eq(Container::getCode, mesTask.getContainerCode());
            container = containerService.getOne(lambdaQueryWrapper);
        }

        if (container == null){
            throw new RuntimeException("查询当前容器编码:"+mesTask.getContainerCode()+"不存在!");
        }
        if (QuantityConstant.STATUS_CONTAINER_LOCK.equals(container.getStatus())){
            throw new RuntimeException("当前容器已经存在任务,请勿重复下发!");
        }
        // 判断当前容器是否在库位上
        if (StringUtils.isNotEmpty(container.getLocationCode())){
            throw new RuntimeException("当前容器已经在库位上请更换托盘码!");
        }
        // 创建入库单
        ReceiptDetail receiptDetail = mesService.createReceiptDocuments(mesTask);
        // 进行入库组盘
        ReceiptContainerView receiptContainerView = new ReceiptContainerView();
        receiptContainerView.setContainerCode(container.getCode());
        receiptContainerView.setReceiptCode(receiptDetail.getReceiptCode());
        receiptContainerView.setReceiptDetailId(receiptDetail.getId());
        receiptContainerView.setLocationCode(locationCode);
        receiptContainerView.setQty(BigDecimal.valueOf(mesTask.getQty()));
        result = receiptContainerHeaderService.saveContainer(receiptContainerView);
        if (result.hasErr()){
            throw new RuntimeException(result.getMsg());
        }
        // 通过入库单详情id获取组盘详情
        LambdaQueryWrapper<ReceiptContainerDetail> queryWrapper = Wrappers.lambdaQuery();
        queryWrapper.eq(ReceiptContainerDetail::getReceiptDetailId, receiptDetail.getId());
        queryWrapper.last("limit 1");
        ReceiptContainerDetail receiptContainerDetail = receiptContainerDetailService.getOne(queryWrapper);
        if (receiptContainerDetail == null){
            throw new RuntimeException("获取入库组盘失败!");
        }
        // 创建入库任务
        List<Integer> idList = new ArrayList<>(1);
        idList.add(receiptContainerDetail.getReceiptContainerId());
        result = receiptTaskService.createReceiptTask(idList);
        if (result.hasErr()){
            throw new RuntimeException(result.getMsg());
        }
        // 获取创建的入库任务
        LambdaQueryWrapper<TaskHeader> lambdaQuery = Wrappers.lambdaQuery();
        lambdaQuery.eq(TaskHeader::getAllocationHeadId, receiptContainerDetail.getReceiptContainerId())
                .lt(TaskHeader::getStatus, QuantityConstant.TASK_STATUS_COMPLETED);
        lambdaQuery.last("limit 1");
        TaskHeader taskHeader = taskHeaderService.getOne(lambdaQuery);
        if (taskHeader == null){
            throw new RuntimeException("创建入库任务失败!");
        }
        // 将mes的任务号写入入库任务头表
        TaskHeader taskHeaderTemp = new TaskHeader();
        taskHeaderTemp.setPickingCartPos(mesTask.getStation());
        taskHeaderTemp.setId(taskHeader.getId());
        taskHeaderService.updateById(taskHeaderTemp);
        result.setData(taskHeader);
        result.setMsg("入库任务下发成功!");
        return result;
    }

    @Override
    @Transactional
    public AjaxResult createShipment(MesTask mesTask) {
        // 查询当前位置是否已经存在出库任务
        AjaxResult result = mesService.checkStation(mesTask.getStation(), QuantityConstant.TASK_TYPE_WHOLESHIPMENT);
        if (!result.hasErr()){
            return result;
        }
        LambdaQueryWrapper<Location> queryWrapper = Wrappers.lambdaQuery();
        queryWrapper.eq(Location::getLocationType, mesTask.getArea());
        List<Location> locationList = locationService.list(queryWrapper);
        if (locationList.size() == 0){
            throw new RuntimeException("该库区没有库位!");
        }
        // 根据跟踪单号查询库存
        LambdaQueryWrapper<InventoryDetail> query = Wrappers.lambdaQuery();
        query.in(InventoryDetail::getLocationCode, locationList.stream().map(Location::getCode).collect(Collectors.toList()))
                .eq(InventoryDetail::getReferCode, mesTask.getTrackingNumber())
                .last("LIMIT 1");
        InventoryDetail inventoryDetail = inventoryDetailService.getOne(query);
        if (inventoryDetail == null){
            return AjaxResult.error("当前库区没有匹配到合适出库的物料:" + mesTask.getMaterialCode());
        }
        // 创建出库单据
        ShipmentDetail shipmentDetail = mesService.createShipmentDocuments(mesTask);
        // 进行手动出库组盘
        List<ShipmentDetail> shipmentDetailList = new ArrayList<>();
        shipmentDetailList.add(shipmentDetail);
        ShipmentCombinationModel shipmentCombinationModel = new ShipmentCombinationModel();
        shipmentCombinationModel.setShipmentDetailId(shipmentDetail.getId());
        shipmentCombinationModel.setShipQty(BigDecimal.valueOf(mesTask.getQty()));
        shipmentCombinationModel.setInventoryDetailId(inventoryDetail.getId());
        ShipmentContainerHeader shipmentContainerHeader = shipmentContainerHeaderService.combination(shipmentCombinationModel);
        if (shipmentContainerHeader == null){
            throw new RuntimeException("创建出库组盘失败!");
        }
        //表头
        List<Integer> idList = Arrays.asList(Convert.toIntArray(shipmentContainerHeader.getId().toString()));
        result = shipmentContainerHeaderService.createTask(idList);
        // 查询出库任务
        LambdaQueryWrapper<TaskHeader> taskHeaderLambdaQueryWrapper = Wrappers.lambdaQuery();
        taskHeaderLambdaQueryWrapper.eq(TaskHeader::getAllocationHeadId, shipmentContainerHeader.getId());
        TaskHeader taskHeader = taskHeaderService.getOne(taskHeaderLambdaQueryWrapper);
        if (taskHeader == null){
            throw new RuntimeException("创建出库任务失败!");
        }
        TaskHeader taskHeaderTemp = new TaskHeader();
        taskHeaderTemp.setId(taskHeader.getId());
        taskHeaderTemp.setPickingCartPos(mesTask.getStation());
        // 修改任务出库口
        taskHeaderTemp.setPort(QuantityConstant.JIJIA_PORT);
        taskHeaderService.updateById(taskHeaderTemp);
        result.setData(taskHeader);
        return result;
    }

    @Override
    public AjaxResult createAgvTask(Integer type, String fromPort, String toPort, String code) {
        AgvTaskCS agvTaskCS = new AgvTaskCS();
        agvTaskCS.setTaskType(type);
        agvTaskCS.setToPort(toPort);
        agvTaskCS.setFromPort(fromPort);
        agvTaskCS.setFromUserDef1(code);
        agvTaskCS.setStatus(QuantityConstant.AGV_TASK_STATUS_ERROR);
        agvTaskCS.setZoneCode(QuantityConstant.GT_RECEIPT_TYPE);
        if (agvTaskCSService.save(agvTaskCS)){
            AjaxResult result = AjaxResult.success();
            result.setData(agvTaskCS);
            return result;
        }
        return AjaxResult.error("AGV任务创建失败!");
    }

    @Override
    public AjaxResult addMaterial(MesTask mesTask) {
        Material material = materialService.getMaterialByCode(mesTask.getMaterialCode());
        if (material == null){
            material = new Material();
            material.setCode(mesTask.getMaterialCode());
            material.setName(mesTask.getMaterialName());
            material.setSpec(mesTask.getSpec());
            material.setUnit(mesTask.getUnit());
            material.setWarehouseCode(ShiroUtils.warehouseCode);
            material.setCompanyCode(ShiroUtils.getCompanyCode());
            if (!materialService.save(material)){
                return AjaxResult.error("新增物料失败!");
            }
        }
        return AjaxResult.success();
    }

    @Resource
    private InventoryDetailService inventoryDetailService;
    @Resource
    private RcsService rcsService;
    @Resource
    private ContainerService containerService;
    @Resource
    private ShipmentApiService shipmentApiService;

    @Override
    public AjaxResult emptyContainerHandleService(MesTask mesTask) {
        if (ShiroUtils.getUser() == null){
            // 模拟mes登录
            userService.login(QuantityConstant.PLATFORM_MES, QuantityConstant.PLATFORM_MES_PASSWORD, QuantityConstant.WAREHOUSE_KS, false);
        }
        if (mesTask.isType()){
            // 空托出库任务
            return mesService.createEmptyShipmentContainer(mesTask);
        }else {
            // 空托入库任务
            return mesService.createEmptyReceiptContainer(mesTask);
        }
    }


    @Override
    public MesMaterial getMesMaterial(String code) {
        String url = addressService.selectAddress(QuantityConstant.GET_MESINFO);
        if (StringUtils.isEmpty(url)){
            throw new ServiceException("获取mes URL地址失败!");
        }
        // 获取mes物料信息
        String parameter = url + "?lotNo=" + code + "&type=" + QuantityConstant.GUANGTENG;
        String str = OkHttpUtils.bodypost(parameter, "", QuantityConstant.WAREHOUSE_KS,"MES获取物料信息");
        if (StringUtils.isEmpty(str)){
            throw new ServiceException("根据跟踪单号获取物料信息失败!");
        }
        AjaxResult ajaxResult = JSON.parseObject(str,AjaxResult.class);
        if (ajaxResult.hasErr()){
            throw new ServiceException(ajaxResult.getMsg());
        }
        parameter = (String) ajaxResult.getData();
        MesMaterial material = JSONObject.parseObject(parameter, MesMaterial.class);
        if (material == null){
            throw new ServiceException("获取MES物料信息失败!");
        }
        return material;
    }

    @Override
    public MesMaterial getMesMaterialJJ(String code) {
        String url = addressService.selectAddress(QuantityConstant.GET_MESINFO_JJ);
        if (StringUtils.isEmpty(url)){
            throw new ServiceException("获取mes URL地址失败!");
        }
        // 获取mes物料信息
        String parameter = url + "?lotNo=" + code + "&type=" + QuantityConstant.JIJIA;
        String str = OkHttpUtils.bodypost(parameter, "", QuantityConstant.WAREHOUSE_KS,"机加MES获取物料信息");
        if (StringUtils.isEmpty(str)){
            throw new ServiceException("根据跟踪单号获取物料信息失败!");
        }
        AjaxResult ajaxResult = JSON.parseObject(str,AjaxResult.class);
        if (ajaxResult.hasErr()){
            throw new ServiceException(ajaxResult.getMsg());
        }
        parameter = (String) ajaxResult.getData();
        MesMaterial material = JSONObject.parseObject(parameter, MesMaterial.class);
        if (material == null){
            throw new ServiceException("获取MES物料信息失败!");
        }
        return material;
    }

    @Override
    @Transactional
    public AjaxResult routineInitialLocationService(MesTask mesTask) {
        if (StringUtils.isEmpty(mesTask.getLocationCode())){
            return AjaxResult.error("初始货架点位不能为空!");
        }
        if (StringUtils.isEmpty(mesTask.getTrackingNumber())){
            return AjaxResult.error("跟踪单号不能为空!");
        }
        if (ShiroUtils.getUser() == null){
            // 模拟mes登录
            userService.login(QuantityConstant.PLATFORM_MES, QuantityConstant.PLATFORM_MES_PASSWORD, QuantityConstant.WAREHOUSE_KS, false);
        }
        MesMaterial material = mesService.getMesMaterial(mesTask.getTrackingNumber());
        mesTask.setMaterialCode(material.getItemCode());
        mesTask.setQty(material.getLotQty());
        mesTask.setSpec(material.getInvStd());
        mesTask.setMaterialName(material.getInvName());
        AjaxResult result = mesService.addMaterial(mesTask);
        if (result.hasErr()){
            return result;
        }
        // 获取入库库位
        Location location = locationService.getLocationByCode(mesTask.getLocationCode(), ShiroUtils.getWarehouseCode());
        if (location == null){
            return AjaxResult.error("根据初始库位编码"+mesTask.getLocationCode()+"查询入库库位失败!");
        }
        // 判断库存是否已经存在
        LambdaQueryWrapper<InventoryDetail> queryWrapper = Wrappers.lambdaQuery();
        queryWrapper.eq(InventoryDetail::getLocationCode, location.getCode())
                .eq(InventoryDetail::getReferCode, mesTask.getTrackingNumber());
        InventoryDetail inventoryDetail = inventoryDetailService.getOne(queryWrapper);
        if (inventoryDetail != null){
            return AjaxResult.success("点位上已有物料请勿重复绑定!");
        }
        // 获取可用托盘码
        Container container = containerService.getGTContainer();
        if (container == null) {
            throw new RuntimeException("查询当前容器编码:"+mesTask.getContainerCode()+"不存在!");
        }
        // 新增入库单
        ReceiptDetail receiptDetail = mesService.createReceiptDocuments(mesTask);
        result = rcsService.addInventory(receiptDetail, container.getCode(), location.getCode(), location.getZoneCode());
        if (result.hasErr()){
            return result;
        }
        Location locationTemp = new Location();
        locationTemp.setId(location.getId());
        locationTemp.setContainerCode(container.getCode());
        locationTemp.setStatus(QuantityConstant.STATUS_LOCATION_EMPTY);
        if (!locationService.updateById(locationTemp)){
            throw new RuntimeException("更新库位数据失败!");
        }
        Container containerTemp = new Container();
        containerTemp.setId(container.getId());
        containerTemp.setLocationCode(location.getCode());
        containerTemp.setStatus(QuantityConstant.STATUS_CONTAINER_SOME);
        if (!containerService.updateById(containerTemp)){
            throw new RuntimeException("更新容器状态失败!");
        }
        ReceiptHeader receiptHeaderTemp = new ReceiptHeader();
        receiptHeaderTemp.setId(receiptDetail.getReceiptId());
        receiptHeaderTemp.setReferCode(mesTask.getTrackingNumber());
        receiptHeaderTemp.setLastStatus(QuantityConstant.RECEIPT_HEADER_RETURN);
        receiptHeaderTemp.setFirstStatus(QuantityConstant.RECEIPT_HEADER_RETURN);
        if (!receiptHeaderService.updateById(receiptHeaderTemp)){
            throw new RuntimeException("更新入库单头表失败!");
        }
        return AjaxResult.success("点位初始化成功!");
    }

    @Override
    @Transactional
    public AjaxResult initialLocationService(MesTask mesTask) {
        if (StringUtils.isEmpty(mesTask.getLocationCode())){
            return AjaxResult.error("初始货架点位不能为空!");
        }
        if (StringUtils.isEmpty(mesTask.getTrackingNumber())){
            return AjaxResult.error("跟踪单号不能为空!");
        }
        if (ShiroUtils.getUser() == null){
            // 模拟mes登录
            userService.login(QuantityConstant.PLATFORM_MES, QuantityConstant.PLATFORM_MES_PASSWORD, QuantityConstant.WAREHOUSE_KS, false);
        }
        MesMaterial material = getMesMaterial(mesTask.getTrackingNumber());
        mesTask.setMaterialCode(material.getItemCode());
        mesTask.setQty(material.getLotQty());
        mesTask.setSpec(material.getInvStd());
        mesTask.setMaterialName(material.getInvName());
        // 分配毛胚区库位
        mesTask.setArea(QuantityConstant.QY001);
        mesTask.setType(false);
        // 起点为备料区库位
        mesTask.setStation(mesTask.getLocationCode());

//        // 获取入库库位
//        Location location = locationService.getLocationByCode(mesTask.getLocationCode(), ShiroUtils.getWarehouseCode());
//        if (location == null){
//            return AjaxResult.error("根据初始库位编码"+mesTask.getLocationCode()+"查询入库库位失败!");
//        }
//        // 判断库存是否已经存在
//        LambdaQueryWrapper<InventoryDetail> queryWrapper = Wrappers.lambdaQuery();
//        queryWrapper.eq(InventoryDetail::getLocationCode, location.getCode())
//                .eq(InventoryDetail::getReceiptCode, mesTask.getTrackingNumber());
//        InventoryDetail inventoryDetail = inventoryDetailService.getOne(queryWrapper);
//        if (inventoryDetail != null){
//            return AjaxResult.success("点位上已有物料请勿重复绑定!");
//        }
//        // 获取可用托盘码
//        Container container = containerService.getGTContainer();
//        if (container == null){
//            throw new RuntimeException("查询当前容器编码:"+mesTask.getContainerCode()+"不存在!");
//        }
//        // 新增入库单
//        ReceiptDetail receiptDetail = mesService.createReceiptDocuments(mesTask);
//        rcsService.addInventory(receiptDetail, container.getCode(), location.getCode(), location.getZoneCode());
//        Location locationTemp = new Location();
//        locationTemp.setId(location.getId());
//        locationTemp.setContainerCode(container.getCode());
//        locationTemp.setStatus(QuantityConstant.STATUS_LOCATION_EMPTY);
//        if (!locationService.updateById(locationTemp)){
//            throw new RuntimeException("更新库位数据失败!");
//        }
//        Container containerTemp = new Container();
//        containerTemp.setId(container.getId());
//        containerTemp.setLocationCode(location.getCode());
//        containerTemp.setStatus(QuantityConstant.STATUS_CONTAINER_SOME);
//        if (!containerService.updateById(containerTemp)){
//            throw new RuntimeException("更新容器状态失败!");
//        }
//        ReceiptHeader receiptHeaderTemp = new ReceiptHeader();
//        receiptHeaderTemp.setId(receiptDetail.getReceiptId());
//        receiptHeaderTemp.setReferCode(mesTask.getTrackingNumber());
//        receiptHeaderTemp.setLastStatus(QuantityConstant.RECEIPT_HEADER_RETURN);
//        receiptHeaderTemp.setFirstStatus(QuantityConstant.RECEIPT_HEADER_RETURN);
//        if (!receiptHeaderService.updateById(receiptHeaderTemp)){
//            throw new RuntimeException("更新入库单头表失败!");
//        }
        return        // 创建入库任务
                mesService.createReceipt(mesTask);
    }

    @Override
    public ReceiptDetail createReceiptDocuments(MesTask mesTask) {
        // 创建入库单
        ReceiptDomain receiptDomain = new ReceiptDomain();
        ReceiptHeader receiptHeader = new ReceiptHeader();
        if (QuantityConstant.ZONE_JJ_TYPE.equals(mesTask.getArea())){
            receiptHeader.setReceiptType(QuantityConstant.JJ_RECEIPT_TYPE);
        }else {
            receiptHeader.setReceiptType(QuantityConstant.GT_RECEIPT_TYPE);
        }
        receiptHeader.setWarehouseCode(ShiroUtils.getWarehouseCode());
//        receiptHeader.setCompanyCode(ShiroUtils.getCompanyCode());
        receiptHeader.setCompanyCode(QuantityConstant.KS_MES_COMPANY);
        receiptHeader.setCreatedBy(ShiroUtils.getUser().getLoginName());
        receiptHeader.setReferCode(mesTask.getTrackingNumber());
        List<ReceiptDetail> receiptDetails = new ArrayList<>();
        ReceiptDetail receiptDetail = new ReceiptDetail();
        receiptDetail.setMaterialCode(mesTask.getMaterialCode());
        receiptDetail.setMaterialName(mesTask.getMaterialName());
        receiptDetail.setMaterialSpec(mesTask.getSpec());
        receiptDetail.setMaterialUnit(mesTask.getUnit());
        receiptDetail.setQty(BigDecimal.valueOf(mesTask.getQty()));
        receiptDetail.setWarehouseCode(ShiroUtils.getWarehouseCode());
        receiptDetail.setUWarehouseCode(QuantityConstant.U_WAREHOUSE_CODE_GT);
        receiptDetail.setReferCode(mesTask.getTrackingNumber());
        receiptDetail.setInventorySts(QuantityConstant.DEFECTIVE);
        receiptDetails.add(receiptDetail);
        receiptDomain.setReceiptHeader(receiptHeader);
        receiptDomain.setReceiptDetails(receiptDetails);
        AjaxResult result = receiptApiService.receipt(receiptDomain);
        if (result.hasErr()){
            throw new RuntimeException(result.getMsg());
        }
        return receiptDetail;
    }

    @Override
    public ShipmentDetail createShipmentDocuments(MesTask mesTask) {
        // 创建出库单
        ShipmentDomain shipmentDomain = new ShipmentDomain();
        ShipmentHeader shipmentHeader = new ShipmentHeader();
        List<ShipmentDetail> shipmentDetailList = new ArrayList<>();
        if (QuantityConstant.ZONE_JJ_TYPE.equals(mesTask.getArea())){
            shipmentHeader.setShipmentType(QuantityConstant.JJ_RECEIPT_TYPE);
        }else {
            shipmentHeader.setShipmentType(QuantityConstant.GT_RECEIPT_TYPE);
        }
        shipmentHeader.setWarehouseCode(ShiroUtils.getWarehouseCode());
        shipmentHeader.setCompanyCode(ShiroUtils.getCompanyCode());
        shipmentHeader.setCompanyCode(QuantityConstant.KS_MES_COMPANY);
        shipmentHeader.setCreatedBy(ShiroUtils.getUser().getLoginName());
        // 创建出库单详情
        ShipmentDetail shipmentDetail = new ShipmentDetail();
        shipmentDetail.setMaterialCode(mesTask.getMaterialCode());
        shipmentDetail.setMaterialName(mesTask.getMaterialName());
        shipmentDetail.setMaterialSpec(mesTask.getSpec());
        shipmentDetail.setMaterialUnit(mesTask.getUnit());
        shipmentDetail.setQty(BigDecimal.valueOf(mesTask.getQty()));
        shipmentDetail.setWarehouseCode(ShiroUtils.getWarehouseCode());
        shipmentDetail.setUWarehouseCode(QuantityConstant.U_WAREHOUSE_CODE_GT);
        shipmentDetail.setCompanyCode(ShiroUtils.getCompanyCode());
        shipmentDetail.setInventorySts(QuantityConstant.GOOD);
        shipmentDetailList.add(shipmentDetail);
        shipmentDomain.setShipmentHeader(shipmentHeader);
        shipmentDomain.setShipmentDetails(shipmentDetailList);
        AjaxResult result = shipmentApiService.shipment(shipmentDomain);
        if (result.hasErr()){
            throw new RuntimeException(result.getMsg());
        }
        return shipmentDetail;
    }

    @Resource
    private TaskHeaderMapper taskHeaderMapper;

    @Override
    @Transactional
    public AjaxResult createEmptyReceiptContainer(MesTask mesTask) {
        // 判断当前位置是否有任务
        AjaxResult result = mesService.checkStation(mesTask.getStation(), QuantityConstant.TASK_TYPE_EMPTYRECEIPT);
        if (!result.hasErr()){
            return result;
        }
        Container container = null;
        String locationCode = null;
        TaskHeader task = new TaskHeader();
        task.setWarehouseCode(ShiroUtils.getWarehouseCode());
        task.setCompanyCode(ShiroUtils.getCompanyCode());
        task.setPriority(0);
        task.setTaskType(QuantityConstant.TASK_TYPE_EMPTYRECEIPT);
        task.setStatus(QuantityConstant.TASK_STATUS_BUILD);
        task.setZoneCode(mesTask.getArea());
        task.setCreated(new Date());
        task.setCreatedBy(ShiroUtils.getUserName());
        task.setPickingCartPos(mesTask.getStation());
        task.setZoneCode(QuantityConstant.GT_RECEIPT_TYPE);
        // 空托入库任务
        if (StringUtils.isEmpty(mesTask.getOrderCode())){
            LambdaQueryWrapper<LocationType> queryWrapper = Wrappers.lambdaQuery();
            queryWrapper.eq(LocationType::getZoneCode, QuantityConstant.GT_RECEIPT_TYPE);
            List<LocationType> locationTypes = locationTypeService.list(queryWrapper);
            if (locationTypes == null || locationTypes.size() == 0){
                return AjaxResult.error("获取库位类型失败!");
            }
            List<String> codes = locationTypes.stream().map(LocationType::getCode).collect(Collectors.toList());
            // 光腾车间系统直接分配库位和容器
            LambdaQueryWrapper<Location> query = Wrappers.lambdaQuery();
            query.in(Location::getLocationType, codes)
                    .eq(Location::getContainerCode, "")
                    .eq(Location::getStatus, QuantityConstant.STATUS_LOCATION_EMPTY)
                    .orderByAsc(Location::getLocationType)
                    .last("limit 1");
            Location location = locationService.getOne(query);
            if (location == null){
                throw new RuntimeException("当前库区没有可用空库位!");
            }
            // 校验起点是否为库内空托盘
            Location sourceLocationCode = locationService.getLocationByCode(mesTask.getStation());
            if (sourceLocationCode != null && StringUtils.isNotEmpty(sourceLocationCode.getContainerCode()) && QuantityConstant.STATUS_LOCATION_EMPTY.equals(sourceLocationCode.getStatus())){
                // 解绑容器
                Container sourceContainer = containerService.getContainerByCode(sourceLocationCode.getContainerCode());
                if (sourceContainer != null){
                    sourceContainer.setLocationCode(" ");
                    sourceContainer.setStatus(QuantityConstant.STATUS_LOCATION_EMPTY);
                    containerService.updateById(sourceContainer);
                }
                // 解绑源库位
                sourceLocationCode.setContainerCode(" ");
                locationService.updateById(sourceLocationCode);
                // 创建移库任务
//                return transferTaskService.createTransferTask(sourceLocationCode.getCode(), location.getCode(), ShiroUtils.getWarehouseCode());
            }
            task.setToLocation(location.getCode());
            location.setStatus(QuantityConstant.STATUS_LOCATION_LOCK);
            locationService.updateById(location);
            locationCode = location.getCode();
            container = containerService.getGTContainer();
        }
        if (container == null){
            throw new RuntimeException("该托盘码"+mesTask.getContainerCode()+"不存在!");
        }
        task.setContainerCode(container.getCode());
        if (StringUtils.isNotEmpty(container.getLocationCode())) {
            throw new RuntimeException("容器已在库位[" + container.getLocationCode() + "]上");
        }
        //判断托盘是否已经存在任务
        Integer taskCount = taskHeaderMapper.UncompleteCount(container.getCode(), ShiroUtils.getWarehouseCode());
        if (taskCount != null && taskCount.intValue() > 0) {
            throw new RuntimeException("容器已存在任务");
        }
        task.setContainerCode(container.getCode());
        container.setLocationCode(locationCode);
        if (taskHeaderService.save(task)){
            AjaxResult ajaxResult = AjaxResult.success("任务下发成功!");
            ajaxResult.setData(task);
            container.setStatus(QuantityConstant.STATUS_CONTAINER_LOCK);
            containerService.updateById(container);
            return ajaxResult;
        }
        return AjaxResult.error("任务下发失败!");
    }

    @Resource
    private WorkTaskService  workTaskService;

    @Override
    @Transactional
    public AjaxResult createEmptyShipmentContainer(MesTask mesTask) {
        AjaxResult result = mesService.checkStation(mesTask.getStation(), QuantityConstant.TASK_TYPE_EMPTYSHIPMENT);
        if (!result.hasErr()){
            return result;
        }
        // 获取光腾空托盘
        List<Location> locationList = containerService.getEmptyContainerInLocation(QuantityConstant.GT_RECEIPT_TYPE, null, null, null,ShiroUtils.getWarehouseCode());
        if (locationList == null || locationList.size() == 0){
            return AjaxResult.error("库内没有可用空托盘!");
        }
        Location location = locationList.get(0);
        // 创建空托盘出库任务
        result = workTaskService.createEmptyOut(location.getContainerCode(), location.getCode(), QuantityConstant.JIJIA_PORT);
        if (result.hasErr()){
            return result;
        }
        // 查询空托出库任务
        LambdaQueryWrapper<TaskHeader> query = Wrappers.lambdaQuery();
        query.eq(TaskHeader::getFromLocation, location.getCode())
                .eq(TaskHeader::getStatus, QuantityConstant.TASK_STATUS_BUILD)
                .eq(TaskHeader::getContainerCode, location.getContainerCode());
        TaskHeader taskHeader = taskHeaderService.getOne(query);
        if (taskHeader == null){
            throw new RuntimeException("创建空托出库任务失败!");
        }
        TaskHeader taskHeaderTemp = new TaskHeader();
        taskHeaderTemp.setId(taskHeader.getId());
        taskHeaderTemp.setPickingCartPos(mesTask.getStation());
        taskHeaderTemp.setZoneCode(QuantityConstant.GT_RECEIPT_TYPE);
        taskHeaderService.updateById(taskHeaderTemp);
        result.setData(taskHeader);
        return result;
    }

    @Override
    public AjaxResult checkStation(String station, Integer type) {
        if (StringUtils.isEmpty(station)){
            throw new RuntimeException("位置号不能为空!");
        }
        LambdaQueryWrapper<TaskHeader> taskHeaderLambdaQueryWrapper = Wrappers.lambdaQuery();
        taskHeaderLambdaQueryWrapper.eq(TaskHeader::getPickingCartPos, station)
                .eq(TaskHeader::getTaskType, type)
                .lt(TaskHeader::getStatus, QuantityConstant.TASK_STATUS_COMPLETED);
        TaskHeader taskHeader = taskHeaderService.getOne(taskHeaderLambdaQueryWrapper);
        if (taskHeader != null){
            AjaxResult result = AjaxResult.success("该点位已创建任务请勿重复创建!");
            result.setData(taskHeader);
            return result;
        }
        return AjaxResult.error("任务不存在!");
    }

    @Resource
    private InventoryHeaderService inventoryHeaderService;

    @Override
    @Transactional
    public AjaxResult untieLocationService(MesTask mesTask) {
        if (StringUtils.isEmpty(mesTask.getLocationCode())){
            return AjaxResult.error("初始货架点位不能为空!");
        }
        if(StringUtils.isEmpty(mesTask.getTrackingNumber())){
            return AjaxResult.error("跟踪单号不能为空!");
        }
        // 根据库位编码和跟踪单号查询库存详情
        LambdaQueryWrapper<InventoryDetail> query = Wrappers.lambdaQuery();
        query.eq(InventoryDetail::getLocationCode, mesTask.getLocationCode())
                .eq(InventoryDetail::getReferCode, mesTask.getTrackingNumber());
        InventoryDetail inventoryDetail = inventoryDetailService.getOne(query);
        if (inventoryDetail == null){
            return AjaxResult.error("当前点位未绑定物料,无需进行解绑!");
        }
        // 判断当前库位是否有任务
        LambdaQueryWrapper<TaskHeader> queryWrapper = Wrappers.lambdaQuery();
        queryWrapper.lt(TaskHeader::getStatus, QuantityConstant.TASK_STATUS_COMPLETED)
                .eq(TaskHeader::getContainerCode, inventoryDetail.getContainerCode())
                .eq(TaskHeader::getFromLocation, mesTask.getLocationCode());
        TaskHeader taskHeader = taskHeaderService.getOne(queryWrapper);
        if (taskHeader != null){
            return AjaxResult.error("当前料架以存在任务号:" + taskHeader.getId()+ ",无法进行解绑!");
        }
        LambdaQueryWrapper<InventoryHeader> lambdaQueryWrapper = Wrappers.lambdaQuery();
        lambdaQueryWrapper.eq(InventoryHeader::getId, inventoryDetail.getInventoryHeaderId());
        InventoryHeader inventoryHeader = inventoryHeaderService.getOne(lambdaQueryWrapper);
        if (inventoryDetail == null){
            return AjaxResult.error("查询库存详情失败!");
        }
        // 解锁容器
        LambdaQueryWrapper<Container> containerLambdaQueryWrapper = Wrappers.lambdaQuery();
        containerLambdaQueryWrapper.eq(Container::getCode, inventoryDetail.getContainerCode());
        Container container = containerService.getOne(containerLambdaQueryWrapper);
        if (container == null){
            return AjaxResult.error("根据库存查询容器数据失败,容器编码:" + inventoryDetail.getContainerCode());
        }
        Container containerTemp = new Container();
        containerTemp.setId(container.getId());
        containerTemp.setStatus(QuantityConstant.STATUS_LOCATION_EMPTY);
        containerTemp.setLocationCode("");
        containerService.updateById(containerTemp);
        // 解锁库位
        LambdaQueryWrapper<Location> locationLambdaQueryWrapper = Wrappers.lambdaQuery();
        locationLambdaQueryWrapper.eq(Location::getCode, inventoryDetail.getLocationCode());
        Location location = locationService.getOne(locationLambdaQueryWrapper);
        if (location == null){
            throw new ServiceException("根据库存查询库位数据失败,库位编码:" + inventoryDetail.getLocationCode());
        }
        Location locationTemp = new Location();
        locationTemp.setId(location.getId());
        locationTemp.setStatus(QuantityConstant.STATUS_LOCATION_EMPTY);
        locationTemp.setContainerCode("");
        locationService.updateById(locationTemp);
        inventoryDetailService.removeById(inventoryDetail.getId());
        inventoryHeaderService.removeById(inventoryHeader.getId());
        return AjaxResult.success("料架解绑成功!");
    }

    @Override
    public TableDataInfo getInventoryListService(InventoryDetailQuery query) {
        LambdaQueryWrapper<Location> queryWrapper = Wrappers.lambdaQuery();
        queryWrapper.eq(Location::getLocationType, query.getArea());
        List<Location> locationList = locationService.list(queryWrapper);
        LambdaQueryWrapper<InventoryDetail> lambdaQueryWrapper = Wrappers.lambdaQuery();
        lambdaQueryWrapper.ge(StringUtils.isNotEmpty(query.getCreatedBegin()), InventoryDetail::getCreated, query.getCreatedBegin())
                .le(StringUtils.isNotEmpty(query.getCreatedEnd()), InventoryDetail::getCreated, query.getCreatedEnd()) // 创建时间范围
                .eq(StringUtils.isNotEmpty(query.getInventoryDetail().getZoneCode()), InventoryDetail::getZoneCode, query.getInventoryDetail().getZoneCode())
                .in(locationList != null && locationList.size() > 0, InventoryDetail::getLocationCode, locationList.stream().map(Location::getCode).collect(Collectors.toList())) // 库区
                .eq(StringUtils.isNotEmpty(query.getInventoryDetail().getLocationCode()), InventoryDetail::getLocationCode, query.getInventoryDetail().getLocationCode()) // 库位
                .eq(StringUtils.isNotEmpty(query.getInventoryDetail().getContainerCode()), InventoryDetail::getContainerCode,
                        query.getInventoryDetail().getContainerCode())// 容器
                .eq(StringUtils.isNotEmpty(query.getInventoryDetail().getReferCode()), InventoryDetail::getReferCode, query.getInventoryDetail().getReferCode())
                .eq(StringUtils.isNotEmpty(query.getInventoryDetail().getMaterialCode()), InventoryDetail::getMaterialCode, query.getInventoryDetail().getMaterialCode())// 物料编码
                .like(StringUtils.isNotEmpty(query.getInventoryDetail().getMaterialName()), InventoryDetail::getMaterialName,
                        query.getInventoryDetail().getMaterialName())// 物料名称
                .like(StringUtils.isNotEmpty(query.getInventoryDetail().getMaterialSpec()), InventoryDetail::getMaterialSpec,
                        query.getInventoryDetail().getMaterialSpec())// 物料规格
                .eq(query.getInventoryDetail().getQty() != null, InventoryDetail::getQty, query.getInventoryDetail().getQty()) // 数量
                .eq(InventoryDetail::getTaskQty, BigDecimal.ZERO) // 只查询预计出库数量为0的库存
        ;
        if (StringUtils.isNotNull(query.getPageNum()) && StringUtils.isNotNull(query.getPageSize())) {
            // 分页查询
            Page<InventoryDetail> page = new Page<>(query.getPageNum(), query.getPageSize());
            IPage<InventoryDetail> iPage = inventoryDetailService.page(page, lambdaQueryWrapper);
            return getMpDataTable(iPage.getRecords(), iPage.getTotal());
        } else {
            List<InventoryDetail> list = inventoryDetailService.list(lambdaQueryWrapper);
            return getDataTable(list);
        }
    }

    @Override
    public TableDataInfo getTaskListService(TaskHeaderQuery query) {
        List<String> zoneCodes = mesService.getZoneCodes(query.getArea());
        LambdaQueryWrapper<TaskHeader> lambdaQueryWrapper = Wrappers.lambdaQuery();
        lambdaQueryWrapper.ge(StringUtils.isNotEmpty(query.getCreatedBegin()), TaskHeader::getCreated, query.getCreatedBegin())
                .le(StringUtils.isNotEmpty(query.getCreatedEnd()), TaskHeader::getCreated, query.getCreatedEnd()) // 创建时间范围
                .in((zoneCodes != null && zoneCodes.size() > 0), TaskHeader::getZoneCode, zoneCodes) // 库区
                .eq(StringUtils.isNotEmpty(query.getTaskHeader().getContainerCode()), TaskHeader::getContainerCode,
                        query.getTaskHeader().getContainerCode())// 容器
                .lt(TaskHeader::getStatus, QuantityConstant.TASK_STATUS_COMPLETED) // 只查询未完成的状态
        ;
        if (StringUtils.isNotNull(query.getPageNum()) && StringUtils.isNotNull(query.getPageSize())) {
            // 分页查询
            Page<TaskHeader> page = new Page<>(query.getPageNum(), query.getPageSize());
            IPage<TaskHeader> iPage = taskHeaderService.page(page, lambdaQueryWrapper);
            return getMpDataTable(iPage.getRecords(), iPage.getTotal());
        } else {
            List<TaskHeader> list = taskHeaderService.list(lambdaQueryWrapper);
            return getDataTable(list);
        }
    }

    @Override
    public List<String> getZoneCodes(String area) {
        List<String> zoneCodes = null;
        List<LocationType> locationTypes = null;
        LambdaQueryWrapper<LocationType> queryWrapper = Wrappers.lambdaQuery();
        if (QuantityConstant.GT_RECEIPT_TYPE.equals(area)){
            queryWrapper.like(LocationType::getCode, "QY%");
            locationTypes = locationTypeService.list(queryWrapper);
        }
        if (QuantityConstant.JJ_RECEIPT_TYPE.equals(area)){
            queryWrapper.like(LocationType::getCode, QuantityConstant.JJ_RECEIPT_TYPE);
            locationTypes = locationTypeService.list(queryWrapper);
        }
        if (locationTypes != null && locationTypes.size() > 0){
            zoneCodes = locationTypes.stream().map(LocationType::getCode).collect(Collectors.toList());
        }
        return zoneCodes;
    }

    @Override
    @Transactional
    public AjaxResult zoneSyncService(List<Zone> zones) {
        if (zones == null || zones.size() == 0){
            return AjaxResult.error("请勿提交空数据!");
        }
        LambdaQueryWrapper<LocationType> queryWrapper = Wrappers.lambdaQuery();
        queryWrapper.in(LocationType::getCode, zones.stream().map(Zone::getCode).collect(Collectors.toList()))
                .eq(LocationType::getWarehouseCode, QuantityConstant.WAREHOUSE_KS);
        List<LocationType> locationTypes = locationTypeService.list(queryWrapper);
        Map<String, LocationType> map = new HashMap<>();
        for (LocationType locationType :locationTypes){
            if (!map.containsKey(locationType.getCode())){
                map.put(locationType.getCode(), locationType);
            }
        }
        List<LocationType> insertZone = new ArrayList<>();
        List<LocationType> updateZone = new ArrayList<>();
        for (Zone zone :zones){
            if (map.containsKey(zone.getCode())){
                // 已存在代表更新
                LocationType temp = new LocationType();
                temp.setId(map.get(zone.getCode()).getId());
                temp.setName(zone.getName());
                updateZone.add(temp);
            }else {
                // 不存在代表新增
                LocationType temp = new LocationType();
                temp.setWarehouseCode(QuantityConstant.WAREHOUSE_KS);
                temp.setCreatedBy(QuantityConstant.PLATFORM_MES);
                temp.setCreated(new Date());
                temp.setCode(zone.getCode());
                temp.setName(zone.getName());
                insertZone.add(temp);
            }
        }
        if (insertZone.size() > 0){
            locationTypeService.saveBatch(insertZone);
        }
        if (updateZone.size() > 0){
            locationTypeService.updateBatchById(updateZone);
        }
        return AjaxResult.success("区域数据同步成功!");
    }

    @Override
    public AjaxResult pointToPointService(MesTask mesTask) {
        if (mesTask == null){
            return AjaxResult.error("参数不能为空!");
        }
        // 起点
        if (StringUtils.isEmpty(mesTask.getStartingPoint())){
            return AjaxResult.error("起点参数不能为空!");
        }
        if (StringUtils.isEmpty(mesTask.getEndPoint())){
            return AjaxResult.error("终点不能为空!");
        }
        AjaxResult result = mesService.checkStation(mesTask.getStartingPoint(), QuantityConstant.TASK_TYPE_OVER_STATION);
        if (!result.hasErr()){
            return result;
        }
        LambdaQueryWrapper<Container> queryWrapper = Wrappers.lambdaQuery();
        queryWrapper.eq(Container::getStatus, QuantityConstant.STATUS_LOCATION_EMPTY).eq(Container::getZoneCode, QuantityConstant.GT_RECEIPT_TYPE)
                .eq(Container::getLocationCode, "").last("LIMIT 1");
        Container container = containerService.getOne(queryWrapper);
        if (container == null){
            return AjaxResult.error("获取容器数据失败!");
        }
        container.setStatus(QuantityConstant.STATUS_LOCATION_LOCK);
        containerService.updateById(container);
        mesTask.setContainerCode(container.getCode());
        TaskHeader taskHeader = new TaskHeader();
        taskHeader.setCompanyCode(QuantityConstant.KS_MES_COMPANY);
        taskHeader.setToPort(mesTask.getEndPoint());
        taskHeader.setPort(mesTask.getStartingPoint());
        taskHeader.setContainerCode(mesTask.getContainerCode());
        taskHeader.setWarehouseCode(QuantityConstant.WAREHOUSE_KS);
        taskHeader.setTaskType(QuantityConstant.TASK_TYPE_OVER_STATION);
        taskHeader.setStatus(QuantityConstant.TASK_STATUS_BUILD);
        taskHeader.setZoneCode(QuantityConstant.ZONE_JJ_TYPE);
        taskHeader.setCreatedBy(QuantityConstant.PLATFORM_MES);
        taskHeader.setPickingCartPos(mesTask.getEndPoint());
        if (!taskHeaderService.save(taskHeader)){
            return AjaxResult.error("新增任务失败!");
        }
        result = AjaxResult.success("任务新增成功");
        result.setData(taskHeader);
        return result;
    }

    @Resource
    private TaskDetailService taskDetailService;
    @Resource
    private TransferTaskService transferTaskService;

    @Override
    public AjaxResult regionalMoveService(MesTask mesTask) {
        if (StringUtils.isEmpty(mesTask.getTrackingNumber())){
            return AjaxResult.error("跟踪单号不能为空!");
        }
        if (StringUtils.isEmpty(mesTask.getArea())){
            return AjaxResult.error("终点区域不能为空!");
        }
        // 根据跟踪单号查询库存
        LambdaQueryWrapper<InventoryDetail> queryWrapper = Wrappers.lambdaQuery();
        queryWrapper.eq(InventoryDetail::getReferCode, mesTask.getTrackingNumber())
                .last(" limit 1");
        InventoryDetail inventoryDetail = inventoryDetailService.getOne(queryWrapper);
        if (inventoryDetail == null){
            return AjaxResult.error("根据跟踪单号"+mesTask.getTrackingNumber()+"查询库存失败!");
        }
        // 查询当前位置是否已经有移库任务
        LambdaQueryWrapper<TaskDetail> query = Wrappers.lambdaQuery();
        query.eq(TaskDetail::getReferenceCode, mesTask.getTrackingNumber())
                .lt(TaskDetail::getStatus, QuantityConstant.TASK_STATUS_COMPLETED)
                .last(" limit 1");
        TaskDetail taskDetail = taskDetailService.getOne(query);
        AjaxResult result = AjaxResult.success("移库任务创建成功!");
        if (taskDetail != null){
            result.setData(taskDetail);
            return result;
        }
        // 查询终点区域空闲库位
        LambdaQueryWrapper<Location> lambdaQueryWrapper = Wrappers.lambdaQuery();
        lambdaQueryWrapper.eq(Location::getLocationType, mesTask.getArea())
                .eq(Location::getStatus, QuantityConstant.STATUS_LOCATION_EMPTY)
                .eq(Location::getContainerCode, "")
                .last(" limit 1");
        Location location = locationService.getOne(lambdaQueryWrapper);
        if (location == null){
            return AjaxResult.error("当前区域:"+mesTask.getArea()+"没有空闲库位!");
        }
        if (ShiroUtils.getUser() == null){
            // 模拟mes登录
            userService.login(QuantityConstant.PLATFORM_MES, QuantityConstant.PLATFORM_MES_PASSWORD, QuantityConstant.WAREHOUSE_KS, false);
        }
        // 创建移库任务
        return transferTaskService.createTransferTask(inventoryDetail.getLocationCode(),location.getCode(), ShiroUtils.getWarehouseCode());
    }


    @Override
    @Transactional
    public AjaxResult getMaterialByMES(MesTask mesTask) {
        if (StringUtils.isEmpty(mesTask.getTrackingNumber())) {
            return AjaxResult.error("跟踪单号不能为空!");
        }
        if (ShiroUtils.getUser() == null) {
            // 模拟mes登录
            userService.login(QuantityConstant.PLATFORM_MES, QuantityConstant.PLATFORM_MES_PASSWORD, QuantityConstant.WAREHOUSE_KS, false);
        }
        MesMaterial material = mesService.getMesMaterialJJ(mesTask.getTrackingNumber());
        mesTask.setMaterialCode(material.getItemCode());
        mesTask.setQty(material.getLotQty());
        mesTask.setSpec(material.getInvStd());
        mesTask.setMaterialName(material.getInvName());
        AjaxResult result = mesService.addMaterial(mesTask);
        if (result.hasErr()) {
            return result;
        }
        MesMaterialBack mesMaterialBack = new MesMaterialBack();
        mesMaterialBack.setMaterialSpec(mesTask.getSpec());
        mesMaterialBack.setMaterialName(mesTask.getMaterialName());
        mesMaterialBack.setMaterialCode(mesTask.getMaterialCode());
        mesMaterialBack.setQty(mesTask.getQty());
        mesMaterialBack.setReferCode(mesTask.getTrackingNumber());
        return AjaxResult.success(mesMaterialBack);
    }

    @Resource
    private IDictDataService dictDataService;

    @Override
    @Transactional
    public AjaxResult inventoryConversion(String locationCode) {
        List<DictData> dictDataList = dictDataService.selectDictDataByType(QuantityConstant.WAREHOUSE_KS,QuantityConstant.GT_AUTOMATIC_UNBINDING_AREA);
        if (dictDataList == null || dictDataList.size() == 0){
            return AjaxResult.error("获取数据字典自动解绑区域失败!");
        }
        List<String> zoneCode = dictDataList.stream().map(DictData::getDictValue).collect(Collectors.toList());
        LambdaQueryWrapper<Location> locationLambdaQueryWrapper = Wrappers.lambdaQuery();
        locationLambdaQueryWrapper.eq(Location::getCode, locationCode).in(Location::getLocationType, zoneCode);
        Location location = locationService.getOne(locationLambdaQueryWrapper);
        if (location == null){
            return AjaxResult.success("该库位编码:" + locationCode + "无需自动释放库存!");
        }
        LambdaQueryWrapper<InventoryDetail> queryWrapper = Wrappers.lambdaQuery();
        queryWrapper.eq(InventoryDetail::getZoneCode, QuantityConstant.GT_RECEIPT_TYPE).eq(InventoryDetail::getLocationCode, locationCode)
                .eq(InventoryDetail::getTaskQty, BigDecimal.ZERO);
        InventoryDetail inventoryDetail = inventoryDetailService.getOne(queryWrapper);
        if (inventoryDetail == null){
            return AjaxResult.success("该库存详情点位已经释放!");
        }
        LambdaQueryWrapper<Container> query = Wrappers.lambdaQuery();
        query.eq(Container::getCode, inventoryDetail.getContainerCode());
        Container container = containerService.getOne(query);
        if (container == null){
            return AjaxResult.error("根据库存容器编码"+inventoryDetail.getContainerCode()+"查询容器数据失败!");
        }
        InventoryHeader inventoryHeader = inventoryHeaderService.getById(inventoryDetail.getInventoryHeaderId());
        if (inventoryHeader == null){
            return AjaxResult.success("该库存头点位已经释放");
        }
        inventoryHeaderService.removeById(inventoryHeader.getId());
        inventoryDetailService.removeById(inventoryDetail.getId());
        Container temp = new Container();
        temp.setId(container.getId());
        temp.setStatus(QuantityConstant.STATUS_LOCATION_EMPTY);
        containerService.updateById(temp);
        return AjaxResult.success("库存点位信息更新完成!");
    }

    @Override
    @Transactional
    public AjaxResult updateLocationStatusService(Location location) {
        if (location == null){
            return AjaxResult.error("请勿提交空数据!");
        }
        if (StringUtils.isEmpty(location.getCode())){
            return AjaxResult.error("库位编码不能为空!");
        }
        if (location.getId() == null){
            return AjaxResult.error("库位ID不能为空!");
        }
        if (StringUtils.isEmpty(location.getStatus())){
            return AjaxResult.error("库位状态不能为空!");
        }
        LambdaQueryWrapper<InventoryDetail> queryWrapper = Wrappers.lambdaQuery();
        queryWrapper.eq(InventoryDetail::getLocationCode, location.getCode())
                .last("limit 1");
        InventoryDetail inventoryDetail = inventoryDetailService.getOne(queryWrapper);
        if (inventoryDetail != null){
            return AjaxResult.error("当前点位有库存,不允许更改点位状态,若需强制修改请先释放库存!");
        }
        Location temp = locationService.getById(location.getId());
        if (temp == null){
            return AjaxResult.error("根据ID:" + location.getId() + "查询点位信息失败!");
        }
        if (QuantityConstant.STATUS_CONTAINER_EMPTY.equals(location.getStatus())
                && StringUtils.isNotEmpty(temp.getContainerCode())){
            LambdaQueryWrapper<Container> query = Wrappers.lambdaQuery();
            query.eq(Container::getCode, temp.getContainerCode());
            Container container = containerService.getOne(query);
            if (container == null){
                return AjaxResult.error("根据容器编码:" + temp.getContainerCode() + "查询容器数据失败!");
            }
            container.setLocationCode("");
            temp.setContainerCode("");
            locationService.updateById(temp);
            containerService.updateById(container);
            return AjaxResult.success("点位信息修改成功!");
        }
        if (location.getStatus().equals(temp.getStatus())){
            return AjaxResult.success("点位信息修改成功!");
        }
        temp.setStatus(location.getStatus());
        locationService.updateById(temp);
        return AjaxResult.success("点位信息修改成功!");
    }

    @Override
    @Transactional
    public AjaxResult locationConvertService(Location location) {
        if (StringUtils.isEmpty(location.getCode())){
            return AjaxResult.error("点位编码不能为空!");
        }
        LambdaQueryWrapper<Location> queryWrapper = Wrappers.lambdaQuery();
        queryWrapper.eq(Location::getCode, location.getCode());
        Location temp = locationService.getOne(queryWrapper);
        if (temp == null){
            return AjaxResult.error("根据点位编码:" + location.getCode());
        }
        LambdaQueryWrapper<InventoryHeader> query = Wrappers.lambdaQuery();
        query.eq(InventoryHeader::getLocationCode, location.getCode());
        InventoryHeader inventoryHeader = inventoryHeaderService.getOne(query);
        if (inventoryHeader != null){
            return AjaxResult.error("当前点位绑定库存,请先释放库存在进行点位转换!");
        }
        LambdaQueryWrapper<TaskHeader> taskHeaderLambdaQueryWrapper = Wrappers.lambdaQuery();
        taskHeaderLambdaQueryWrapper.eq(TaskHeader::getToLocation, location.getCode())
                .lt(TaskHeader::getStatus, QuantityConstant.TASK_STATUS_COMPLETED);
        TaskHeader taskHeader = taskHeaderService.getOne(taskHeaderLambdaQueryWrapper);
        if (taskHeader != null){
            return AjaxResult.error("当前点位:" + location.getCode() + "存在任务,不允许进行转换!");
        }
        if (QuantityConstant.STATUS_CONTAINER_LOCK.equals(temp.getStatus())){
            return AjaxResult.error("当前点位已被占用,请先解绑在转换!");
        }
        Container container = containerService.getGTContainer();
        temp.setStatus(QuantityConstant.STATUS_LOCATION_EMPTY);
        temp.setContainerCode(container.getCode());
        container.setLocationCode(temp.getCode());
        locationService.updateById(temp);
        containerService.updateById(container);
        return AjaxResult.success("点位转换完成!");
    }


}