AcsServiceImpl.java 37.2 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
package com.huaheng.api.acs.service;

import java.math.BigDecimal;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

import javax.annotation.Resource;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.huaheng.api.acs.domain.AcsStatus;
import com.huaheng.api.acs.domain.AgvDomain;
import com.huaheng.api.acs.domain.StateInfoUploadModel;
import com.huaheng.api.utils.SAPUtils;
import com.huaheng.api.wcs.service.warecellAllocation.WarecellAllocationService;
import com.huaheng.common.constant.QuantityConstant;
import com.huaheng.common.exception.service.ServiceException;
import com.huaheng.common.utils.DateUtils;
import com.huaheng.common.utils.StringUtils;
import com.huaheng.common.utils.bean.BeanUtils;
import com.huaheng.common.utils.http.HttpUtils;
import com.huaheng.common.utils.http.OkHttpUtils;
import com.huaheng.framework.aspectj.lang.annotation.ByPassOperator;
import com.huaheng.framework.web.domain.AjaxResult;
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.material.domain.Material;
import com.huaheng.pc.config.material.domain.MaterialDiameter;
import com.huaheng.pc.config.material.service.MaterialDiameterService;
import com.huaheng.pc.config.material.service.MaterialService;
import com.huaheng.pc.config.station.domain.Station;
import com.huaheng.pc.config.station.service.StationService;
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.inventory.inventoryTransaction.domain.InventoryTransaction;
import com.huaheng.pc.inventory.inventoryTransaction.service.InventoryTransactionService;
import com.huaheng.pc.receipt.receiptDetail.domain.ReceiptDetail;
import com.huaheng.pc.receipt.receiptDetail.service.ReceiptDetailService;
import com.huaheng.pc.sap.domain.Zarsh;
import com.huaheng.pc.sap.domain.Zarsi;
import com.huaheng.pc.sap.service.BackSapStatusService;
import com.huaheng.pc.sap.service.ZarshService;
import com.huaheng.pc.sap.service.ZarsiService;
import com.huaheng.pc.task.agvTask.domain.AgvTask;
import com.huaheng.pc.task.agvTask.service.AgvTaskService;
import com.huaheng.pc.task.taskHeader.domain.TaskHeader;
import com.huaheng.pc.task.taskHeader.service.TaskHeaderService;
import com.huaheng.pc.task.taskHeader.service.WorkTaskService;

/**
 * @ClassName   AcsServiceImpl
 * @Description TODO
 * @Author      Administrator
 * @Date        2019/12/2615:38
 */
@Service
public class AcsServiceImpl implements AcsService {

    private static final Logger logger = LoggerFactory.getLogger(AcsServiceImpl.class);

    @Resource
    private LocationService locationService;
    @Resource
    private ContainerService containerService;
    @Resource
    private AddressService addressService;
    @Resource
    private AgvTaskService agvTaskService;
    @Resource
    private TaskHeaderService taskHeaderService;
    @Resource
    private MaterialDiameterService materialDiameterService;
    @Resource
    private ZarshService zarshService;
    @Resource
    private ZarsiService zarsiService;
    @Resource
    private AcsService acsService;
    @Resource
    private InventoryHeaderService inventoryHeaderService;
    @Resource
    private InventoryDetailService inventoryDetailService;
    @Resource
    private InventoryTransactionService inventoryTransactionService;
    @Resource
    private MaterialService materialService;
    @Resource
    private StationService stationService;
    @Resource
    private WorkTaskService workTaskService;
    @Resource
    private ZoneService zoneService;
    @Resource
    private WarecellAllocationService warecellAllocationService;
    @Resource
    private BackSapStatusService backSapStatusService;
    @Resource
    private AcsByCSWXFService acsByCSWXFService;
    @Resource
    private ReceiptDetailService receiptDetailService;

    @Override
    public AjaxResult StateInfoUpload(StateInfoUploadModel model) {
        return null;
    }

    private String getUrl(String zoneCode) {
        String area = zoneService.getZoneAreaByCode(zoneCode);
        if (StringUtils.isEmpty(area)) {
            throw new ServiceException("未找到库区" + zoneCode);
        }
        String url = addressService.selectAddress("AGV", QuantityConstant.WAREHOUSECODE, area);
        return url;
    }

    /**
     * 下发任务
     * wms-acs
     * @param  model
     * @return
     */
    @Override
    public AjaxResult TaskAssign(AgvTask model) {
        String PalletNo = model.getPalletNo();
        switch (model.getToPoint()) {
            case "P4102":
                model.setToPoint("P4101");
                break;
            case "P4202":
                model.setToPoint("P4201");
                break;
            default:
        }
        switch (model.getFromPoint()) {
            case "P4102":
                model.setFromPoint("P4101");
                break;
            case "P4202":
                model.setFromPoint("P4201");
                break;
            default:
        }

        AgvDomain domain = new AgvDomain();
        BeanUtils.copyBeanProp(domain, model);

        String url = null;
        String area = zoneService.getZoneAreaByCode(model.getZoneCode());
        if (StringUtils.isEmpty(area)) {
            throw new ServiceException("未找到库区" + model.getZoneCode());
        }
        if (area.equals("20")) {
            // 长沙agv任务
            return acsByCSWXFService.createAGVTask(model, area);
        }

        url = addressService.selectAddress("AGV", QuantityConstant.WAREHOUSECODE, area, model.getLayer()) + "TaskAssign";
        String JsonParam = JSON.toJSONString(domain);
        logger.info("任务下发:{}", JsonParam);
        String result = OkHttpUtils.bodypost(url, JsonParam, "", "AGV下发任务");
        if (StringUtils.isEmpty(result)) {
            throw new ServiceException("ACS接口地址错误或服务器连接不到或返回为空");
        }
        AjaxResult ajaxResultACS = JSON.parseObject(result, AjaxResult.class);
        if (!ajaxResultACS.state) {
            model.setRemark(ajaxResultACS.getMessage());
            agvTaskService.updateById(model);
            if ("重入".equals(ajaxResultACS.getMessage())) {
                String doubleIn = model.getLocationCode();
                warecellAllocationService.agvWarecellAllocation(model);
                AgvTask agvTask = agvTaskService.getAgvTaskByTaskNo(model.getTaskNo());
                agvTask.setDoubleIn(doubleIn);
                agvTaskService.updateById(agvTask);
            }
            if ("空出".equals(ajaxResultACS.getMessage())) {
                String uniqueId = model.getUniqueId();
                Zarsh zarsh = zarshService.getZarshByUnique(uniqueId);
                if (StringUtils.isNotNull(zarsh)) {
                    backSapStatusService.addBackSapStatus(model.getUniqueId(), SAPUtils.getZoneCode(zarsh), null, zarsh.getMFlag(), "C", null, "物料空出");
                    model.setEmptyOut(model.getLocationCode());
                    agvTaskService.updateById(model);
                } else {
                    model.setEmptyOut(model.getLocationCode());
                    agvTaskService.updateById(model);
                }
            }
            return AjaxResult.error(ajaxResultACS.getMessage());
        } else {
            model.setSendDate(DateUtils.getNowDate());
            model.setRemark(ajaxResultACS.getMessage());
            agvTaskService.updateById(model);
        }
        // 下发成功
        model.setState(10);
        agvTaskService.updateById(model);
        return AjaxResult.success(ajaxResultACS.getMessage()).setData(ajaxResultACS.getData());
    }

    /**
     * 回传任务
     * acs-wms
     * @param  model
     * @return
     */
    @Override
    public AjaxResult TaskConfirm(AgvTask model) {
        Integer taskNo = model.getTaskNo();
        if (StringUtils.isNull(taskNo)) {
            return AjaxResult.error("没有填写任务托盘号");
        }
        if (StringUtils.isEmpty(model.getAgvNo())) {
            return AjaxResult.error("没有填写小车号");
        }
        if (StringUtils.isNull(model.getState())) {
            return AjaxResult.error("没有填写任务状态");
        }
        AgvTask agvTask = agvTaskService.getAgvTaskByTaskNo(taskNo);
        if (agvTask == null) {
            return AjaxResult.error("找不到该任务" + taskNo);
        }
        agvTask.setState(model.getState());
        agvTask.setLastUpdatedBy("acs");
        agvTaskService.updateById(agvTask);

        return AjaxResult.success(agvTask);
    }

    /**
     * 取消任务
     * wms-acs
     * @param  model
     * @return
     */
    @Override
    public AjaxResult TaskCancel(AgvTask model) {
        Integer taskNo = model.getTaskNo();
        if (StringUtils.isNull(taskNo)) {
            return AjaxResult.error("没有填写任务号");
        }
        Map<String, Object> map = new HashMap<>();
        map.put("TaskNo", taskNo);
        map.put("Reason", model.getRemark());
        String JsonParam = JSON.toJSONString(map);
        String zoneCode = model.getZoneCode();
        if (StringUtils.isEmpty(model.getZoneCode())) {
            zoneCode = "C";
        }
        AgvTask agvTask = agvTaskService.getById(taskNo);
        if (agvTask == null) {
            return AjaxResult.error("任务不存在");
        }
        if (agvTask.getState() >= 90) {
            return AjaxResult.success("任务已完成,不能取消");
        }
        if (agvTask.getState() >= 10) {
            String area = zoneService.getZoneAreaByCode(model.getZoneCode());
            if (StringUtils.isEmpty(area)) {
                throw new ServiceException("未找到库区" + model.getZoneCode());
            }
            String url = addressService.selectAddress("AGV", QuantityConstant.WAREHOUSECODE, area, model.getLayer()) + "TaskCancel";
            String result = HttpUtils.bodypost(url, JsonParam, QuantityConstant.WAREHOUSECODE, "AGV任务取消");
            AjaxResult ajaxResultACS = JSON.parseObject(result, AjaxResult.class);
            if (ajaxResultACS == null || !ajaxResultACS.state) {
                return AjaxResult.error("ACS报错:" + ajaxResultACS.getMessage());
            }
        }
        try {
            if (StringUtils.isNotEmpty(agvTask.getUniqueId())) {
                TaskHeader taskHeader = taskHeaderService.getOne(new LambdaQueryWrapper<TaskHeader>().eq(TaskHeader::getUniqueIds, agvTask.getUniqueId()));
                if (taskHeader == null) {
                    // 当玻璃布回库时删除入库单据
                    if ((agvTask.getToPoint().equals("P1039") || agvTask.getToPoint().equals("P1040")) && StringUtils.isNotEmpty(agvTask.getLot())) {
                        ReceiptDetail receiptDetail = receiptDetailService.getReceiptDetailByRollNumber(agvTask.getLot(), "A");
                        if (receiptDetail != null) {
                            receiptDetailService.removeById(receiptDetail.getId());
                        }
                    }
//                    zarshService.removeByZarshId(agvTask.getUniqueId(), null);
                }
            }
        } catch (Exception e) {

        }
        String locationCode = "";
        if (StringUtils.isNotEmpty(agvTask.getTaskTypes())) {
            switch (agvTask.getTaskTypes()) {
                case "pick":
                    locationCode = agvTask.getToPoint();
                    break;
                case "putway":
                    locationCode = agvTask.getFromPoint();
                    break;
                default:

            }
        }
        if (StringUtils.isNotEmpty(agvTask.getPalletNo())) {
            if (agvTask.getIsEmpty() == 1) {
                containerService.updateStatus(agvTask.getPalletNo(), QuantityConstant.STATUS_CONTAINER_SOME, QuantityConstant.WAREHOUSECODE);
            } else {
                containerService.updateStatus(agvTask.getPalletNo(), QuantityConstant.STATUS_CONTAINER_EMPTY, QuantityConstant.WAREHOUSECODE);
            }
        }
        locationService.updateStatus(locationCode, QuantityConstant.STATUS_CONTAINER_EMPTY, QuantityConstant.WAREHOUSECODE);

        agvTaskService.removeById(agvTask.getTaskNo());

        return AjaxResult.success("取消成功");
    }

    /**
     * 人工完成接口
     * wms-acs
     * @param  model
     * @return
     */
    @Override
    public AjaxResult TaskFinish(AgvTask model) {
        if (StringUtils.isEmpty(model.getPalletNo())) {
            return AjaxResult.error("没有填写任务托盘号");
        }
        Map<String, Object> map = new HashMap<>();
        // 站台
        map.put("StName", model.getToPoint());
        map.put("PalletNo", model.getPalletNo());
        map.put("StState", 99);
        String JsonParam = JSON.toJSONString(map);
        String url = this.getUrl(model.getZoneCode()) + "TaskFinish";
        String result = HttpUtils.bodypost(url, JsonParam, QuantityConstant.WAREHOUSECODE, "AGV任务完成");
        AjaxResult ajaxResultACS = JSON.parseObject(result, AjaxResult.class);
        if (!ajaxResultACS.state) {
            return AjaxResult.error(ajaxResultACS.getMessage());
        }
        return AjaxResult.success(ajaxResultACS.getMessage()).setData(ajaxResultACS.getData());
    }

    /**
     * AGV 的状态信息
     * wms-acs
     * @param  model
     * @return
     */
    @Override
    public AjaxResult AgvInfo(AgvTask model) {
        if (StringUtils.isEmpty(model.getAgvNo())) {
            return AjaxResult.error("没有填写小车号");
        }
        Map<String, Object> map = new HashMap<>();
        // 站台
        map.put("AgvNos", model.getAgvNo());
        String JsonParam = JSON.toJSONString(map);
        String url = this.getUrl(model.getZoneCode()) + "AgvInfo";
        String result = HttpUtils.bodypost(url, JsonParam, QuantityConstant.WAREHOUSECODE, "获取AGV信息");
        AjaxResult ajaxResultACS = JSON.parseObject(result, AjaxResult.class);
        if (!ajaxResultACS.state) {
            return AjaxResult.error(ajaxResultACS.getMessage());
        }
        return AjaxResult.success(ajaxResultACS.getMessage()).setData(ajaxResultACS.getData());
    }

    /**
     * 继续任务
     * wms-acs
     * @param  model
     * @return
     */
    @Override
    public AjaxResult ContinueTask(AgvTask model) {
        if (StringUtils.isNull(model.getTaskNo())) {
            return AjaxResult.error("没有填写任务号");
        }
        Map<String, Object> map = new HashMap<>();
        // 站台
        map.put("TaskNo", model.getTaskNo());
        map.put("TaskStatus", model.getState());
        String JsonParam = JSON.toJSONString(map);
        String url = this.getUrl(model.getZoneCode()) + "ContinueTask";
        String result = HttpUtils.bodypost(url, JsonParam, QuantityConstant.WAREHOUSECODE, "AGV任务继续");
        AjaxResult ajaxResultACS = JSON.parseObject(result, AjaxResult.class);
        if (!ajaxResultACS.state) {
            return AjaxResult.error(ajaxResultACS.getMessage());
        }
        return AjaxResult.success(ajaxResultACS.getMessage()).setData(ajaxResultACS.getData());
    }

    @Override
    @Transactional
    public AjaxResult notifyAGVTask(AcsStatus acsStatus) {
        if (acsStatus == null) {
            return AjaxResult.error("更新AGV状态信息为空");
        }
        String taskNo = acsStatus.getTaskNo();
        String carNo = acsStatus.getAgvNo();
        int status = acsStatus.getState();
        if (StringUtils.isNull(acsStatus.getTaskNo())) {
            return AjaxResult.error("更新AGV状态,任务号为空");
        }
        if (status == 0) {
            return AjaxResult.error("更新AGV状态,状态信息为空");
        }
        String updateBy = "acs";
        AgvTask agvTask = agvTaskService.getById(taskNo);
        if (agvTask == null) {
            return AjaxResult.error("没有找到对应AGV任务,任务号为" + taskNo);
        }
        if (agvTask.getState() < QuantityConstant.AGV_TASK_STATUS_RELEASE) {
            return AjaxResult.success("该任务状态还未下发,任务号为" + taskNo);
        }
        if (status == 90) {
            // 任务完成
            agvTask.setFinishDate(DateUtils.getNowDate());
            acsService.busTaskFinish(agvTask);
        }
        String executeDate = acsStatus.getExecuteDate();
        if (StringUtils.isNotEmpty(executeDate)) {
            Date date = new Date(executeDate);
            agvTask.setExecuteDate(date);
        }
        agvTask.setState(status);
        agvTask.setAgvNo(carNo);
        agvTask.setLastUpdatedBy(updateBy);
        boolean result = agvTaskService.updateById(agvTask);

        if (!result) {
            return AjaxResult.error("更新AGV任务状态信息失败 ");
        }
        return AjaxResult.success("更新任务信息成功");
    }

    @Override
    @Transactional
    public AjaxResult acsCancelAGVTask(AcsStatus acsStatus) {
        if (StringUtils.isEmpty(acsStatus.getTaskNo())) {
            return AjaxResult.error("请填写任务号");
        }
        AgvTask agvTask = agvTaskService.getById(acsStatus.getTaskNo());
        if (agvTask == null) {
            return AjaxResult.error("任务不存在");
        }
        agvTaskService.removeById(agvTask.getTaskNo());
        return AjaxResult.success();
    }

    @ByPassOperator
    @Override
    public AjaxResult busTaskFinish(AgvTask agvTask) {
        Integer taskNo = agvTask.getTaskNo();
        AgvTask agvTask1 = agvTaskService.getAgvTaskByTaskNo(taskNo);
        if (agvTask1 == null) {
            return AjaxResult.error("任务号" + taskNo + "未找到任务");
        }
        if (agvTask1.getState() == 90) {
            return AjaxResult.success("任务已经完成").setData(agvTask1);
        }
        if (StringUtils.isNotNull(agvTask.getMaterialDiameter()) && agvTask.getMaterialDiameter() != 0) {
            MaterialDiameter materialDiameter = new MaterialDiameter();
            materialDiameter.setLot(agvTask1.getLot());
            materialDiameter.setDiameter(agvTask.getMaterialDiameter());
            materialDiameterService.saveMaterialDiameter(materialDiameter);
            // 保存到任务表中
            agvTask1.setMaterialDiameter(agvTask.getMaterialDiameter());
        }

        if (!"P31151".equals(agvTask.getToPoint())) {
            agvTask1.setState(90);
            agvTask1.setAgvNo(agvTask.getAgvNo());
            agvTaskService.updateById(agvTask1);
            completeAGVTask(agvTask1);
        } else {
            if (agvTask1.getState() == 60) {
                agvTask1.setState(90);
                agvTask1.setAgvNo(agvTask.getAgvNo());
                agvTaskService.updateById(agvTask1);
                completeAGVTask(agvTask1);
            } else if (agvTask1.getState() < 60) {
                agvTask1.setState(60);
                agvTask1.setAgvNo(agvTask.getAgvNo());
                agvTaskService.updateById(agvTask1);
            }

        }
        return AjaxResult.success(agvTask1);
    }

    @Override
    public AjaxResult agvCallEmptyOut(int area, String port, String warehouseCode, int containerType) {
        Station station = stationService.getStaionByCode(port);

        if (station == null) {
            return AjaxResult.error("站台不存在 " + port);
        }
        String unActivePort;
        Integer outSlicePalletArea = station.getOutSlicePalletArea();
        Integer outRollPalletArea = station.getOutRollPalletArea();
        if (station.getDefineProperty() == 1) {
            switch (containerType) {
                case 1:
                    if (outSlicePalletArea > 0) {
                        area = outSlicePalletArea;
                    }
                    break;
                case 0:
                    if (outSlicePalletArea > 0) {
                        area = outSlicePalletArea;
                    }
                    break;
                default:
            }
        }
        Zone zone = zoneService.getZoneByArea(String.valueOf(area));

        TaskHeader taskHeader = taskHeaderService.getOne(new LambdaQueryWrapper<TaskHeader>().eq(TaskHeader::getZoneCode, zone.getCode())
            .eq(TaskHeader::getWarehouseCode, warehouseCode).eq(TaskHeader::getToPort, port).lt(TaskHeader::getStatus, QuantityConstant.TASK_STATUS_COMPLETED));
        if (taskHeader != null) {
            return AjaxResult.success("任务已创建!");
        }

        if (taskHeader == null) {
            AgvTask agv = agvTaskService.getOne(new LambdaQueryWrapper<AgvTask>().eq(AgvTask::getPlatform, "AGV").eq(AgvTask::getToPoint, port)
                .eq(AgvTask::getIsEmpty, 0).eq(AgvTask::getLayer, station.getLayer()).eq(AgvTask::getZoneCode, station.getZoneCode()).lt(AgvTask::getState, 90));
            if (agv != null) {
                return AjaxResult.success("任务创建成功!");
            }
        }

        /**
         * 优先AGV边线库出库
         */
        if (station.getAssist() == 2 && containerType == 0 && station.getLayer() == 2) {
            // 通过XBK获取空托盘
            String emptyContainerCode = containerService.getEmptyContainerList(station.getZoneCode(), station.getRoadways(), null, containerType);
            if (!StringUtils.isEmpty(emptyContainerCode)) {

                Container container = containerService.getContainerByCode(emptyContainerCode, QuantityConstant.WAREHOUSECODE);
                String locationCode = container.getLocationCode();
                int pointType = -1;
                if (StringUtils.isNotNull(container.getPlType())) {
                    if (container.getPlType() == 0) {
                        pointType = 3;
                    }
                    if (container.getPlType() == 1) {
                        pointType = 0;
                    }
                }

                AgvTask agvTask = new AgvTask();
                agvTask.setLayer(station.getLayer());
                agvTask.setIsEmpty(0);
                agvTask.setFromPoint(locationCode);
                agvTask.setToPoint(station.getCode());
                agvTask.setZoneCode(station.getZoneCode());
                // AGV任务类型都为配送
                agvTask.setTaskType(QuantityConstant.PEISONG_AGV);
                agvTask.setTaskTypes(QuantityConstant.SHIPMENT_AGV);
                agvTask.setPalletNo(emptyContainerCode);
                agvTask.setCreatedBy(QuantityConstant.PLATFORM_SAP);
                agvTask.setCreated(DateUtils.getNowDate());
                agvTask.setPointType(pointType);
                agvTask.setPlatform("AGV");
                agvTask.setTaskLevel(station.getPriority());
                agvTaskService.save(agvTask);
                containerService.updateStatus(container.getCode(), QuantityConstant.STATUS_CONTAINER_LOCK, QuantityConstant.WAREHOUSECODE);
                locationService.updateStatus(locationCode, QuantityConstant.STATUS_CONTAINER_LOCK, QuantityConstant.WAREHOUSECODE);
                return AjaxResult.success(agvTask);
            }
        }

        if (station.getDefineProperty() == 1) {
            unActivePort = zarshService.getLKAGVPort(zone.getCode(), station.getLayer(), null, QuantityConstant.SHIPMENT_STATION_TYPE, outSlicePalletArea,
                outRollPalletArea, station.getRangeStation());
        } else {
            unActivePort = station.getCode();
        }
        Station unActiveStation = stationService.getStaionByCode(unActivePort);

        String emptyContainer = containerService.getEmptyContainerList(zone.getCode(), unActiveStation.getRoadways(), station.getAreaByWcs(), containerType);
        if (StringUtils.isEmpty(emptyContainer)) {
            return AjaxResult.error("没有空托盘可出库");
        }
        Container container = containerService.getContainerByCode(emptyContainer, QuantityConstant.WAREHOUSECODE);
        if (container == null) {
            return AjaxResult.error("容器号" + emptyContainer + "不在系统中");
        }
        AjaxResult ajaxResult = workTaskService.createEmptyOut(emptyContainer, container.getLocationCode(), unActivePort, warehouseCode, null, port);
        return ajaxResult;
    }

    @Override
    public AjaxResult bindContainer(AcsStatus acsStatus) {
        String taskNo = acsStatus.getTaskNo();
        if (StringUtils.isEmpty(taskNo)) {
            return AjaxResult.error("agv任务绑定托盘:未找到任务号");
        }
        if (StringUtils.isEmpty(acsStatus.getContainerCode())) {
            return AjaxResult.error("agv任务绑定托盘:未找到任务号");
        }
        AgvTask agvTask = agvTaskService.getAgvTaskByTaskNo(Integer.parseInt(taskNo));
        if (agvTask == null) {
            return AjaxResult.error("agv任务绑定托盘:agv任务号" + taskNo + "未找到任务");
        }
        TaskHeader task = findTaskByAgvNo(Integer.parseInt(taskNo));
        if (task == null) {
            return AjaxResult.error("agv任务绑定托盘:agv任务号" + taskNo + "未找到立库任务");
        }
        if (task.getStatus().intValue() == QuantityConstant.TASK_STATUS_COMPLETED) {
            return AjaxResult.error("agv任务绑定托盘:agv任务号" + taskNo + "立库任务已完成");
        }
        task.setContainerCode(acsStatus.getContainerCode());
        taskHeaderService.updateById(task);
        return AjaxResult.success();
    }

    @Override
    public AjaxResult addMaterialDiameter(AgvTask agvTask) {
        Integer taskNo = agvTask.getTaskNo();
        AgvTask task = agvTaskService.getAgvTaskByTaskNo(taskNo);
        if (task != null) {
            if (StringUtils.isNotNull(agvTask.getMaterialDiameter()) && agvTask.getMaterialDiameter() != 0) {
                MaterialDiameter materialDiameter = new MaterialDiameter();
                materialDiameter.setLot(task.getLot());
                materialDiameter.setDiameter(agvTask.getMaterialDiameter());
                materialDiameterService.saveMaterialDiameter(materialDiameter);
                // 保存到任务表中
                task.setMaterialDiameter(agvTask.getMaterialDiameter());
                agvTaskService.updateById(task);
            }
        }
        return AjaxResult.success();
    }

    public TaskHeader findTaskByAgvNo(Integer agvNo) {
        LambdaQueryWrapper<TaskHeader> lambdaQuery = Wrappers.lambdaQuery();
        lambdaQuery.eq(TaskHeader::getAgvNo, agvNo);
        lambdaQuery.last("limit 1");
        TaskHeader task = taskHeaderService.getOne(lambdaQuery);
        return task;
    }

    @Transactional(rollbackFor = Exception.class)
    public void completeAGVTask(AgvTask agvTask) {
        String fromPoint = agvTask.getFromPoint();
        Location location1 = locationService.getLocationByCode(fromPoint, QuantityConstant.WAREHOUSECODE);
        String toPoint = agvTask.getToPoint();
        Location location2 = locationService.getLocationByCode(toPoint, QuantityConstant.WAREHOUSECODE);
        int agvTaskType = 0;
        if (location1 != null) {
            agvTaskType = 1;
        }
        if (location2 != null) {
            agvTaskType += 2;
        }
        switch (agvTaskType) {
            // 站台到站台
            case 0:
                completeStationToStation(agvTask);
                break;
            // 库位到站台
            case 1:
                completeLocationToStation(agvTask);
                break;
            // 站台到库位
            case 2:
                completeStationToLocation(agvTask);
                break;
            default:
        }
    }

    // 站台到库位
    public void completeStationToLocation(AgvTask agvTask) {
        String warehouseCode = QuantityConstant.WAREHOUSECODE;
        String companycode = QuantityConstant.COMPANYCODE;
        Zarsh zarsh = zarshService.getZarshByUnique(agvTask.getUniqueId());
        if (zarsh == null) {
            return;
        }
        if (zarsh.getInKind() == 1) {
            List<Zarsi> zarsis = zarsiService.getListByUniq(zarsh.getUniqueId());
            InventoryHeader inventoryHeader = new InventoryHeader();
            inventoryHeader.setWarehouseCode(warehouseCode);
            inventoryHeader.setLocationCode(agvTask.getToPoint());
            inventoryHeader.setZoneCode(agvTask.getZoneCode());
            inventoryHeader.setContainerCode(agvTask.getPalletNo());

            inventoryHeader.setContainerStatus(QuantityConstant.STATUS_CONTAINER_SOME);
            inventoryHeader.setTotalQty(new BigDecimal(0));
            inventoryHeader.setTotalLines(0);
            inventoryHeader.setLocking(1);
            inventoryHeader.setEnable(1);
            inventoryHeader.setCompanyCode(companycode);
            inventoryHeader.setCreated(new Date());
            inventoryHeader.setCreatedBy("");
            inventoryHeader.setLastUpdated(new Date());
            inventoryHeader.setLastUpdatedBy("");
            if (!inventoryHeaderService.save(inventoryHeader)) {
                throw new ServiceException("添加库存单失败");
            }
            for (Zarsi zarsi : zarsis) {
                addSuppleInventoryDetail(zarsi, agvTask, inventoryHeader);
            }
        }
        String containerStatus = QuantityConstant.STATUS_CONTAINER_EMPTY;
        if (zarsh.getInKind() == 1) {
            containerStatus = QuantityConstant.STATUS_CONTAINER_SOME;
        }
        String locationCode = agvTask.getToPoint();
        containerService.updateLocationCodeAndStatus(agvTask.getPalletNo(), locationCode, containerStatus, warehouseCode);
        locationService.updateContainerCodeAndStatus(locationCode, agvTask.getPalletNo(), QuantityConstant.STATUS_LOCATION_EMPTY, warehouseCode);

    }

    // 库位到站台
    public void completeLocationToStation(AgvTask agvTask) {
        String warehouseCode = QuantityConstant.WAREHOUSECODE;
        InventoryHeader inventoryHeader =
            inventoryHeaderService.getOne(new LambdaQueryWrapper<InventoryHeader>().eq(InventoryHeader::getLocationCode, agvTask.getFromPoint())
                .eq(InventoryHeader::getWarehouseCode, QuantityConstant.WAREHOUSECODE).eq(InventoryHeader::getZoneCode, agvTask.getZoneCode()));
        if (inventoryHeader != null) {
            List<InventoryDetail> details = inventoryDetailService.getByHeaderId(inventoryHeader.getId().toString());
            for (InventoryDetail detail : details) {
                // 记录库存交易记录
                InventoryTransaction inventoryTransaction = new InventoryTransaction();
                inventoryTransaction.setWarehouseCode(warehouseCode);
                inventoryTransaction.setCompanyCode(detail.getCompanyCode());
                inventoryTransaction.setLocationCode(detail.getLocationCode());
                inventoryTransaction.setContainerCode(detail.getContainerCode());
                inventoryTransaction.setTransactionType(QuantityConstant.INVENTORY_TRANSACTION_SHIPMENT);
                inventoryTransaction.setMaterialCode(detail.getMaterialCode());
                inventoryTransaction.setMaterialName(detail.getMaterialName());
                inventoryTransaction.setMaterialSpec(detail.getMaterialSpec());
                inventoryTransaction.setMaterialUnit(detail.getMaterialUnit());
                inventoryTransaction.setLevel(detail.getLevel());
                inventoryTransaction.setBillCode("");
                inventoryTransaction.setZoneCode(inventoryHeader.getZoneCode());
                inventoryTransaction.setBatch(detail.getBatch());
                inventoryTransaction.setLot(detail.getLot());
                inventoryTransaction.setProjectNo(detail.getProjectNo());
                inventoryTransaction.setQcCheck(detail.getQcCheck());
                inventoryTransaction.setSupplierCode(detail.getSupplierCode());
                inventoryTransaction.setManufactureDate(detail.getManufactureDate());
                inventoryTransaction.setExpirationDate(detail.getExpirationDate());
                inventoryTransaction.setInventorySts(detail.getInventorySts());
                // 这里取反,更符合出库的语义,同时方便对记录进行统计
                inventoryTransaction.setTaskQty(detail.getQty());
                inventoryTransactionService.save(inventoryTransaction);
            }
            List<Integer> ids = details.stream().map(InventoryDetail::getId).collect(Collectors.toList());
            inventoryDetailService.removeByIds(ids);
            inventoryHeaderService.removeById(inventoryHeader.getId());
        }
        containerService.updateLocationCodeAndStatus(agvTask.getPalletNo(), "", QuantityConstant.STATUS_LOCATION_EMPTY, warehouseCode);
        locationService.updateContainerCodeAndStatus(agvTask.getFromPoint(), "", QuantityConstant.STATUS_LOCATION_EMPTY, warehouseCode);
        Container container = containerService.getContainerByCode(agvTask.getPalletNo(), QuantityConstant.WAREHOUSECODE);
        if (StringUtils.isNull(container.getPlType())) {
//            containerService.removeById(container.getId());
        }
    }

    // 站台到站台
    public void completeStationToStation(AgvTask agvTask) {
        containerService.updateLocationCodeAndStatus(agvTask.getPalletNo(), "", QuantityConstant.STATUS_LOCATION_EMPTY, QuantityConstant.WAREHOUSECODE);
    }

    private BigDecimal addSuppleInventoryDetail(Zarsi zarsi, AgvTask agvTask, InventoryHeader inventoryHeader) {
        String warehouseCode = inventoryHeader.getWarehouseCode();
        /* 该入库明细是否已存在库存明细记录,已存在更新数量、不存在新增记录 */
        /* 单位换算 */
        BigDecimal receiptQty = zarsi.getVerme();
        if (StringUtils.isNull(receiptQty)) {
            receiptQty = BigDecimal.ONE;
        }
        InventoryDetail inventoryDetail = new InventoryDetail();
        inventoryDetail.setInventoryHeaderId(inventoryHeader.getId());
        inventoryDetail.setWarehouseCode(warehouseCode);
        inventoryDetail.setZoneCode(inventoryHeader.getZoneCode());
        inventoryDetail.setCompanyCode(QuantityConstant.COMPANYCODE);
        inventoryDetail.setLocationCode(agvTask.getToPoint());
        inventoryDetail.setContainerCode(agvTask.getPalletNo());
        Material material = materialService.getMaterialByCode(zarsi.getMatnr(), QuantityConstant.WAREHOUSECODE);
        inventoryDetail.setContainerDetailNumber(zarsi.getPosnr());
        inventoryDetail.setMaterialCode(zarsi.getMatnr());
        inventoryDetail.setMaterialName(material.getName());
        inventoryDetail.setMaterialSpec(material.getSpec());
        inventoryDetail.setRollNumber(zarsi.getCharg());
        inventoryDetail.setQty(receiptQty);
        inventoryDetail.setTaskQty(new BigDecimal(0));
        inventoryDetail.setInventorySts("good");
        inventoryDetail.setReceiptDetailId(0);
        inventoryHeader.setTotalLines(inventoryHeader.getTotalLines() + 1);
        if (!inventoryDetailService.saveOrUpdate(inventoryDetail)) {
            throw new ServiceException("保存库存明细失败");
        }
        inventoryHeader.setTotalQty(inventoryHeader.getTotalQty().add(inventoryDetail.getQty()));
        inventoryHeaderService.updateById(inventoryHeader);
        // 记录库存交易记录
        InventoryTransaction inventoryTransaction = new InventoryTransaction();
        inventoryTransaction.setTransactionType(QuantityConstant.INVENTORY_TRANSACTION_RECEIPT);
        inventoryTransaction.setWarehouseCode(warehouseCode);
        inventoryTransaction.setCompanyCode(QuantityConstant.COMPANYCODE);
        inventoryTransaction.setLocationCode(inventoryHeader.getLocationCode());
        inventoryTransaction.setContainerCode(inventoryHeader.getContainerCode());
        inventoryTransaction.setMaterialCode(material.getCode());
        inventoryTransaction.setMaterialName(material.getName());
        inventoryTransaction.setMaterialSpec(material.getSpec());
        inventoryTransaction.setBillCode(QuantityConstant.EMPTY_STRING);
        inventoryTransaction.setBillDetailId(0);
        inventoryTransaction.setInventorySts(QuantityConstant.GOOD);
        inventoryTransaction.setTaskQty(receiptQty);
        inventoryTransaction.setRollNumber(zarsi.getCharg());
        inventoryTransaction.setZoneCode(inventoryHeader.getZoneCode());
        if (!inventoryTransactionService.save(inventoryTransaction)) {
            throw new ServiceException("新增库存记录失败");
        }
        return receiptQty;
    }

    /**
     * 创建商片桁架抓取任务
     */
    public void createPickContainerTask(AgvTask agvTask) {
        if (agvTask == null) {
            return;
        }
        if (StringUtils.isEmpty(agvTask.getUniqueId())) {
            return;
        }

        LambdaQueryWrapper<Zarsh> queryWrapper = Wrappers.lambdaQuery();
        queryWrapper.eq(Zarsh::getUniqueId, agvTask);
    }
}