ErpBackServiceImpl.java 41.4 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
package com.huaheng.api.erp.service;

import java.math.BigDecimal;
import java.util.*;
import java.util.stream.Collectors;

import javax.annotation.Resource;

import com.alibaba.fastjson.JSONObject;
import com.huaheng.api.erp.domainBack.*;
import com.huaheng.api.erp.domainBack.finishedR.ParameterFinished;
import com.huaheng.api.erp.domainBack.inventoryScrapC.ParameterInventoryScrap;
import com.huaheng.api.erp.domainBack.issuanceC.ParameterIssuance;
import com.huaheng.api.erp.domainBack.miscellaneousR.ParameterMiscellaneous;
import com.huaheng.api.erp.domainBack.noticeWmsC.ParameterNotice;
import com.huaheng.api.erp.domainBack.purchaseWmsR.ParameterPurchase;
import com.huaheng.api.erp.domainBack.saleR.Parameter;
import com.huaheng.api.erp.domainBack.scrapC.ParameterScrap;
import com.huaheng.api.erp.domainBack.shipmentWmsC.ParameterShipmentWms;
import com.huaheng.api.erp.domainBack.transferD.ParameterTransfer;
import com.huaheng.api.erp.domainBack.warehouseC.ParameterWarehouse;
import com.huaheng.common.utils.DateUtils;
import com.huaheng.common.utils.StringUtils;
import com.huaheng.common.utils.Wrappers;
import com.huaheng.framework.web.domain.ResultErpBack;
import com.huaheng.pc.config.address.domain.Address;
import com.huaheng.pc.srm.domain.SrmDetail;
import com.huaheng.pc.srm.domain.SrmHeader;
import com.huaheng.pc.system.user.domain.User;
import com.huaheng.pc.task.taskDetail.domain.TaskDetail;
import com.huaheng.pc.task.taskDetail.service.TaskDetailService;
import com.huaheng.pc.task.taskHeader.domain.TaskHeader;
import com.huaheng.pc.task.taskHeader.service.CallBack;
import com.huaheng.pc.task.taskHeader.service.TaskHeaderService;
import org.springframework.beans.BeanUtils;
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.huaheng.api.erp.domain.*;
import com.huaheng.common.constant.QuantityConstant;
import com.huaheng.common.exception.service.ServiceException;
import com.huaheng.common.utils.http.OkHttpUtils;
import com.huaheng.common.utils.security.ShiroUtils;
import com.huaheng.framework.web.domain.AjaxResult;
import com.huaheng.framework.web.domain.ResultErp;
import com.huaheng.pc.config.address.service.AddressService;
import com.huaheng.pc.config.company.domain.Company;
import com.huaheng.pc.config.company.service.CompanyService;
import com.huaheng.pc.config.customer.domain.Customer;
import com.huaheng.pc.config.customer.service.CustomerServiceImpl;
import com.huaheng.pc.config.material.domain.Material;
import com.huaheng.pc.config.material.service.MaterialService;
import com.huaheng.pc.config.supplier.domain.Supplier;
import com.huaheng.pc.config.supplier.service.SupplierService;
import com.huaheng.pc.config.warehouse.service.WarehouseService;
import com.huaheng.pc.inventory.inventoryDetail.domain.InventoryDetail;
import com.huaheng.pc.inventory.inventoryDetail.service.InventoryDetailService;
import com.huaheng.pc.receipt.receiptDetail.domain.ReceiptDetail;
import com.huaheng.pc.receipt.receiptDetail.service.ReceiptDetailService;
import com.huaheng.pc.receipt.receiptHeader.domain.ReceiptHeader;
import com.huaheng.pc.receipt.receiptHeader.service.ReceiptHeaderService;
import com.huaheng.pc.receipt.receiptHeaderHistory.service.ReceiptHeaderHistoryService;
import com.huaheng.pc.shipment.shipmentDetail.domain.ShipmentDetail;
import com.huaheng.pc.shipment.shipmentDetail.service.ShipmentDetailService;
import com.huaheng.pc.shipment.shipmentHeader.domain.ShipmentHeader;
import com.huaheng.pc.shipment.shipmentHeader.service.ShipmentHeaderService;
import com.huaheng.pc.system.user.service.IUserService;

/**
 * @author 游杰
 */
@Service
public class ErpBackServiceImpl implements IErpBackService {

    @Resource
    private IErpBackTypeService erpBackTypeService;
    @Resource
    private ReceiptHeaderService receiptHeaderService;
    @Resource
    private ShipmentHeaderService shipmentHeaderService;
    @Resource
    private ShipmentDetailService shipmentDetailService;
    @Resource
    private ReceiptDetailService receiptDetailService;

    @Resource
    private TaskHeaderService taskHeaderService;
    @Resource
    private TaskDetailService taskDetailService;
    @Resource
    private AddressService addressService;
    @Resource
    private ErpBackUpdateStatusServiceImpl erpBackUpdateStatusService;
    @Resource
    private CompanyService companyService;
    @Resource
    private IUserService userService;


    /**
     * 任务回传:
     * 单据回传:
     * 销退单(入)、超领单(出)、退料单(入)、完工入库单(入)、杂收单(入)、
     * 下阶料报废(出)、调拨单(出入)、杂发单(出)、库存报废(出)、仓退单(出)、成套发料(出)、
     * isAuto  true 自动回传,false 手动回传
     * @param taskHeader
     * @return
     */
    public AjaxResult setErpBackData(TaskHeader taskHeader,Boolean isAuto){
            TaskHeader task = taskHeaderService.getById(taskHeader.getId());
            if(task==null){
//                throw new ServiceException("任务信息为空");
                return AjaxResult.error("任务信息为空");
            }
            switch (task.getTaskType()){
                case QuantityConstant.TASK_TYPE_WHOLERECEIPT:
                case QuantityConstant.TASK_TYPE_SUPPLEMENTRECEIPT:

                    break;
                case QuantityConstant.TASK_TYPE_WHOLESHIPMENT:
                case QuantityConstant.TASK_TYPE_SORTINGSHIPMENT:
                    break;
                default:
                    TaskHeader taskHeader1=new TaskHeader();
                    taskHeader1.setId(task.getId());
                    taskHeader1.setBackInfo("无需回传");
                    taskHeader1.setIsReturn(2);
                    taskHeaderService.updateById(taskHeader1);
                    return AjaxResult.success("无需回传");
            }
            List<TaskDetail> taskDetails = taskDetailService.findByTaskId(task.getId());
            if(taskDetails==null || taskDetails.size()==0){
                throw new ServiceException("找不到任务id为:"+task.getId()+"的任务,没有任务明细");
            }

            Address address=addressService.selectAddressByParam("ERP",task.getWarehouseCode());

            List<String> billCodes = taskDetails.stream().map(TaskDetail::getBillCode).collect(Collectors.toList());
            List<BackTaskStatus> backTaskStatusList=null;
            switch(task.getInternalTaskType()){
                case 100:
                    backTaskStatusList=createReceiptBack(task,billCodes,address.getUrl(),address.getUserDef2());
                    break;
                case 200:
                    backTaskStatusList=createShipmentBack(task,billCodes,address.getUrl(),address.getUserDef2(),isAuto);
                    break;
                default:
                    break;
            }
            //修改入库单、出库单状态,任务头状态
            AjaxResult ajaxResult=erpBackUpdateStatusService.backTaskUpdateStatus(task,backTaskStatusList);
            return ajaxResult;

//        return AjaxResult.success("回传成功");
    }

    /**
     * 整单回传
     * 销退单(入)、调拨单(出入)、退料单(入)、完工入库单(入)、杂收单(入)、多角采购(入)
     * 整单回传的单据:查询该入库单详情是否都已完成,都完成则回传,否则不回传
     * @param task
     * @param billCodes
     * @param url
     * @return
     */
    //根据任务详情的入库单号,查找单据类型,回传到erp
    @Transactional(rollbackFor = Exception.class)
    public List<BackTaskStatus> createReceiptBack( TaskHeader task,List<String> billCodes,String url,String datakeyEntId){
        LambdaQueryWrapper<ReceiptHeader> queryWrapper = Wrappers.lambdaQuery();
        queryWrapper.in(ReceiptHeader::getCode,billCodes)
                .eq(ReceiptHeader::getWarehouseCode,task.getWarehouseCode());
        //获取任务中的入库单
        List<ReceiptHeader> list = receiptHeaderService.list(queryWrapper);
        //Integer 3无需回传,2回传成功,1回传失败
        List<BackTaskStatus> backTaskStatusList=new ArrayList<>();
        for (ReceiptHeader receiptHeader : list) {
            Company company=companyService.getCompanyByCode(receiptHeader.getCompanyCode(),receiptHeader.getWarehouseCode());
            //获取未回传任务集
            List<TaskDetail> unBackTask = getUnBackTask(receiptHeader.getCode(),receiptHeader.getWarehouseCode(),task.getId());
//            List<TaskDetail> unBackTaskReturn =unBackTask;
            if(unBackTask.size()==0){
                BackTaskStatus backTaskStatus=new BackTaskStatus();
                backTaskStatus.setBillCode(receiptHeader.getCode());
                backTaskStatus.setBillId(receiptHeader.getId());
                backTaskStatus.setStatus(QuantityConstant.ISRETURN_SUCC);
                backTaskStatus.setMsg("过账成功");
                backTaskStatus.setIsSuccess(true);
                backTaskStatusList.add(backTaskStatus);
                if(StringUtils.isNotEmpty(receiptHeader.getBackMsg())){
                    receiptHeader.setBackMsg(receiptHeader.getBackMsg());
                }else{
                    receiptHeader.setBackMsg("过账成功");
                }
                receiptHeaderService.updateById(receiptHeader);
                continue;
            }
            if(StringUtils.isEmpty(receiptHeader.getReferCode())){
                BackTaskStatus backTaskStatus=new BackTaskStatus();
                backTaskStatus.setBillCode(receiptHeader.getCode());
                backTaskStatus.setBillId(receiptHeader.getId());
                backTaskStatus.setStatus(QuantityConstant.NOT_RETURN);
                backTaskStatus.setMsg("无需回传");
                backTaskStatus.setIsSuccess(true);
                backTaskStatusList.add(backTaskStatus);
                receiptHeader.setBackMsg("无需回传");
                receiptHeaderService.updateById(receiptHeader);
                continue;
            }
            if(taskAllComplete(receiptHeader.getCode(),receiptHeader.getWarehouseCode(),task.getId())){
                //同一个单据该任务还有未完成的
                continue;
            }
            Set<Integer> uniqueTaskIds =new LinkedHashSet<>();
            switch (receiptHeader.getReceiptType()){
                case QuantityConstant.SALES_R:
                case QuantityConstant.TRANSFER_R:
                case QuantityConstant.RETURN_R:
                case QuantityConstant.FINISHED_R:
                case QuantityConstant.MISCELLANEOUS_R:
//                case QuantityConstant.WAREHOUSE_R:
                case QuantityConstant.PUR_R:
                    if(receiptAllComplete(receiptHeader.getId(),receiptHeader.getWarehouseCode())){
                        //同一个单据该任务还有未完成的
                        continue;
                    }
                    //先查taskdetail表还有该单据未完成任务的,再查下该单据完成任务没回传的
                    List<TaskDetail> unCompaleteTask1 = getUnBackTaskBill(receiptHeader.getCode(),receiptHeader.getWarehouseCode());
                    if(unCompaleteTask1.size()>0){
                        continue;
                    }
                    //获取未回传任务集
                    unBackTask = getUnBackTask(receiptHeader.getCode(),receiptHeader.getWarehouseCode(),null);
                    if(unBackTask.size()==0){
                        continue;
                    }
                    //将t100相同序号的汇总,整单回传的写到整单里面
//                    unBackTaskReturn=erpBackTypeService.allReceiptTask(receiptHeader,unBackTask);
                    uniqueTaskIds = unBackTask.stream()
                            .map(TaskDetail::getTaskId)
                            .collect(Collectors.toSet());

                    break;
                default:
                    break;
            }
            AjaxResult ajaxResult=getBackDataReceipt(receiptHeader,unBackTask,datakeyEntId);
//            AjaxResult ajaxResult=getBackDataReceipt(receiptHeader,unBackTaskReturn,datakeyEntId);
            if(ajaxResult.hasErr()){
                BackTaskStatus backTaskStatus=new BackTaskStatus();
                backTaskStatus.setBillCode(receiptHeader.getCode());
                backTaskStatus.setBillId(receiptHeader.getId());
                backTaskStatus.setStatus(QuantityConstant.NOT_RETURN);
                backTaskStatus.setMsg("无需回传");
                backTaskStatus.setIsSuccess(true);
                backTaskStatusList.add(backTaskStatus);
                continue;
            }
            //给erp回传数据
            AjaxResult ajaxResult1=sendDataToERP(ajaxResult,url,task.getWarehouseCode(),datakeyEntId,company.getErpCompany());
//            AjaxResult ajaxResult1=AjaxResult.success("过账成功");
            if(!ajaxResult1.hasErr()){
                List<TaskDetail> unBackTaskUpdate=new ArrayList<>();
                for (TaskDetail taskDetail : unBackTask) {
                    TaskDetail taskDetail1=new TaskDetail();
                    taskDetail1.setId(taskDetail.getId());
                    taskDetail1.setBack(1);
                    unBackTaskUpdate.add(taskDetail1);
                }
                taskDetailService.updateBatchById(unBackTaskUpdate);
                //更改入库单明细表回传数
                BackTaskStatus backTaskStatus=new BackTaskStatus();
                backTaskStatus.setBillCode(receiptHeader.getCode());
                backTaskStatus.setBillId(receiptHeader.getId());
                backTaskStatus.setStatus(QuantityConstant.ISRETURN_SUCC);
                backTaskStatus.setTaskIds(uniqueTaskIds);
                backTaskStatus.setMsg(ajaxResult1.getMsg());
                backTaskStatus.setIsSuccess(true);
                backTaskStatusList.add(backTaskStatus);
            }
            if(ajaxResult1.hasErr()){
//                receiptHeader.setBackMsg(receiptHeader.getBackMsg()+",失败");
//                receiptHeaderService.updateById(receiptHeader);
                BackTaskStatus backTaskStatus=new BackTaskStatus();
                backTaskStatus.setBillCode(receiptHeader.getCode());
                backTaskStatus.setBillId(receiptHeader.getId());
                backTaskStatus.setStatus(QuantityConstant.ISRETURN_FAIL);
                backTaskStatus.setIsSuccess(false);
                backTaskStatus.setMsg(ajaxResult1.getMsg());
                backTaskStatusList.add(backTaskStatus);
            }
        }
        return backTaskStatusList;
    }

    /**
     * 整单回传:
     * 下阶料报废(出)、杂发单(出)、库存报废(出)、仓退单(出)、成套发料(出)、超领单(出)、
     *  * 整单回传的单据:查询该出库单详情是否都已完成,都完成则回传,否则不回传
     * @param task
     * @param billCodes
     * @param url
     * @return
     */
    //根据任务详情的出库单号,查找单据类型,回传到erp
    @Transactional(rollbackFor = Exception.class)
    public List<BackTaskStatus> createShipmentBack( TaskHeader task,List<String> billCodes,String url,String datakeyEntId,Boolean isAuto){
        LambdaQueryWrapper<ShipmentHeader> queryWrapper = Wrappers.lambdaQuery();
        queryWrapper.in(ShipmentHeader::getCode,billCodes)
                .eq(ShipmentHeader::getWarehouseCode,task.getWarehouseCode());
        //获取任务中的出库单
        List<ShipmentHeader> list = shipmentHeaderService.list(queryWrapper);
        //Integer 3无需回传,2回传成功,1回传失败
        List<BackTaskStatus> backTaskStatusList=new ArrayList<>();
        for (ShipmentHeader shipmentHeader : list) {
            Company company=companyService.getCompanyByCode(shipmentHeader.getCompanyCode(),shipmentHeader.getWarehouseCode());
            if(StringUtils.isEmpty(shipmentHeader.getReferCode())||shipmentHeader.getShipmentType().equals(QuantityConstant.TRANSFER_C)){
                shipmentHeader.setBackMsg("无需回传");
                shipmentHeaderService.updateById(shipmentHeader);
                BackTaskStatus backTaskStatus=new BackTaskStatus();
                backTaskStatus.setBillCode(shipmentHeader.getCode());
                backTaskStatus.setBillId(shipmentHeader.getId());
                backTaskStatus.setStatus(QuantityConstant.NOT_RETURN);
                backTaskStatus.setMsg("无需回传");
                backTaskStatus.setIsSuccess(true);
                backTaskStatusList.add(backTaskStatus);
                continue;
            }
            if(taskAllComplete(shipmentHeader.getCode(),shipmentHeader.getWarehouseCode(),task.getId())){
                //同一个单据该任务还有未完成的
                continue;
            }
            //获取未回传任务集
            List<TaskDetail> unBackTask = getUnBackTask(shipmentHeader.getCode(),shipmentHeader.getWarehouseCode(),task.getId());
//            List<TaskDetail> unBackTaskReturn=unBackTask;
            if(unBackTask.size()==0){
                BackTaskStatus backTaskStatus=new BackTaskStatus();
                backTaskStatus.setBillCode(shipmentHeader.getCode());
                backTaskStatus.setBillId(shipmentHeader.getId());
                backTaskStatus.setStatus(QuantityConstant.ISRETURN_SUCC);
                backTaskStatus.setMsg("过账成功");
                backTaskStatus.setIsSuccess(true);
                backTaskStatusList.add(backTaskStatus);
                if(StringUtils.isNotEmpty(shipmentHeader.getBackMsg())){
                    shipmentHeader.setBackMsg(shipmentHeader.getBackMsg());
                }else{
                    shipmentHeader.setBackMsg("过账成功");
                }
//                shipmentHeader.setBackMsg(shipmentHeader.getBackMsg()+",过账成功");
                shipmentHeaderService.updateById(shipmentHeader);
                continue;
            }
            Set<Integer> uniqueTaskIds =new LinkedHashSet<>();
            switch (shipmentHeader.getShipmentType()){
                case QuantityConstant.SCRAP_C:
                case QuantityConstant.MISCELLANEOUS_C:
                case QuantityConstant.INVENTORYSCRAP_C:
                case QuantityConstant.WAREHOUSE_C:
                case QuantityConstant.ISSUANCE_C:
                case QuantityConstant.OVER_C:
                    if(shipmentAllComplete(shipmentHeader.getId(),shipmentHeader.getWarehouseCode())){
                        //同一个单据该任务还有未完成的
                        continue;
                    }
                    //先查taskdetail表还有该单据未完成任务的,再查下该单据完成任务没回传的
                    List<TaskDetail> unCompaleteTask = getUnBackTaskBill(shipmentHeader.getCode(),shipmentHeader.getWarehouseCode());
                    if(unCompaleteTask.size()>0){
                        continue;
                    }
                    //获取未回传任务集
                    unBackTask = getUnBackTask(shipmentHeader.getCode(),shipmentHeader.getWarehouseCode(),null);
                    if(unBackTask.size()==0){
                        continue;
                    }
//                    unBackTaskReturn=erpBackTypeService.allShipmentTask(shipmentHeader,unBackTask);
                    uniqueTaskIds = unBackTask.stream()
                            .map(TaskDetail::getTaskId)
                            .collect(Collectors.toSet());
                    break;
                case QuantityConstant.NOTICE_C:
                    List<TaskDetail> taskDetails=getUnCompaleteTask(shipmentHeader.getCode(),shipmentHeader.getWarehouseCode(),null);
                    if(taskDetails.size()>0){
                        continue;
                    }
                    //先查taskdetail表还有该单据未完成任务的,再查下该单据完成任务没回传的
                    List<TaskDetail> unCompaleteTask1 = getUnBackTaskBill(shipmentHeader.getCode(),shipmentHeader.getWarehouseCode());
                    if(unCompaleteTask1.size()>0){
                        continue;
                    }
                    //获取未回传任务集
                    unBackTask = getUnBackTask(shipmentHeader.getCode(),shipmentHeader.getWarehouseCode(),null);
                    if(unBackTask.size()==0){
                        continue;
                    }
//                  出通单判断该单据里面是否sn号,有sn号则手动回传
                    Boolean isHaveSn=erpBackUpdateStatusService.shipmentHaveSn(unBackTask);
                    if(isHaveSn&&isAuto){
                        //含有sn则回传状态未4,
                        BackTaskStatus backTaskStatus=new BackTaskStatus();
                        backTaskStatus.setBillCode(shipmentHeader.getCode());
                        backTaskStatus.setBillId(shipmentHeader.getId());
                        backTaskStatus.setStatus(QuantityConstant.SN_RETURN);
                        backTaskStatus.setMsg("手动回传");
                        backTaskStatus.setIsSuccess(true);
                        backTaskStatusList.add(backTaskStatus);
                        continue;
                    }
//                    unBackTaskReturn=unBackTask;
                    uniqueTaskIds = unBackTask.stream()
                            .map(TaskDetail::getTaskId)
                            .collect(Collectors.toSet());
                    break;
                default:
                    break;
            }
            AjaxResult ajaxResult=getBackDataShipment(shipmentHeader,unBackTask,datakeyEntId);
//            AjaxResult ajaxResult=getBackDataShipment(shipmentHeader,unBackTaskReturn,datakeyEntId);
            if(ajaxResult.hasErr()){
                BackTaskStatus backTaskStatus=new BackTaskStatus();
                backTaskStatus.setBillCode(shipmentHeader.getCode());
                backTaskStatus.setBillId(shipmentHeader.getId());
                backTaskStatus.setStatus(QuantityConstant.NOT_RETURN);
                backTaskStatus.setMsg("无需回传");
                backTaskStatus.setIsSuccess(true);
                backTaskStatusList.add(backTaskStatus);
                continue;
            }
            AjaxResult ajaxResult1=sendDataToERP(ajaxResult,url,task.getWarehouseCode(),datakeyEntId,company.getErpCompany());
//            AjaxResult ajaxResult1=AjaxResult.success("过账成功");
            if(!ajaxResult1.hasErr()){
                List<TaskDetail> unBackTaskUpdate=new ArrayList<>();
                for (TaskDetail taskDetail : unBackTask) {
                    TaskDetail taskDetail1=new TaskDetail();
                    taskDetail1.setId(taskDetail.getId());
                    taskDetail1.setBack(1);
                    unBackTaskUpdate.add(taskDetail1);
                }
                taskDetailService.updateBatchById(unBackTaskUpdate);
                BackTaskStatus backTaskStatus=new BackTaskStatus();
                backTaskStatus.setBillCode(shipmentHeader.getCode());
                backTaskStatus.setBillId(shipmentHeader.getId());
                backTaskStatus.setStatus(QuantityConstant.ISRETURN_SUCC);
                backTaskStatus.setMsg(ajaxResult1.getMsg());
                backTaskStatus.setTaskIds(uniqueTaskIds);
                backTaskStatus.setIsSuccess(true);
                backTaskStatusList.add(backTaskStatus);
            }
            if(ajaxResult1.hasErr()){
//                shipmentHeader.setBackMsg(shipmentHeader.getBackMsg()+",失败");
//                shipmentHeaderService.updateById(shipmentHeader);
                BackTaskStatus backTaskStatus=new BackTaskStatus();
                backTaskStatus.setBillCode(shipmentHeader.getCode());
                backTaskStatus.setBillId(shipmentHeader.getId());
                backTaskStatus.setStatus(QuantityConstant.ISRETURN_FAIL);
                backTaskStatus.setMsg(ajaxResult1.getMsg());
                backTaskStatus.setIsSuccess(false);
                backTaskStatusList.add(backTaskStatus);
            }
        }
        return backTaskStatusList;
    }

    /**
     * 返回true则是还有未完成的,false则是空的
     * @param billCode
     * @param warehouseCode
     * @param taskid
     * @return
     */
    public boolean taskAllComplete(String billCode,String warehouseCode,Integer taskid){
        LambdaQueryWrapper<TaskDetail> queryWrapper = Wrappers.lambdaQuery();
        queryWrapper.eq(TaskDetail::getBillCode,billCode)
                .eq(TaskDetail::getWarehouseCode,warehouseCode)
                .eq(TaskDetail::getTaskId,taskid)
                .lt(TaskDetail::getStatus,QuantityConstant.TASK_STATUS_COMPLETED);
        List<TaskDetail> taskDetails = taskDetailService.list(queryWrapper);
        return !taskDetails.isEmpty();
    }
    /**
     * 检查该入库单是否有未完成的任务
     * @param receiptId
     * @param warehouseCode
     * @return
     */
    public boolean receiptAllComplete(Integer receiptId,String warehouseCode){
        LambdaQueryWrapper<ReceiptDetail> queryWrapper = Wrappers.lambdaQuery();
        queryWrapper.eq(ReceiptDetail::getReceiptId,receiptId)
                .eq(ReceiptDetail::getWarehouseCode,warehouseCode)
                .lt(ReceiptDetail::getProcessStamp,QuantityConstant.RECEIPT_HEADER_POSTING);
        List<ReceiptDetail> receiptDetailList = receiptDetailService.list(queryWrapper);
        return !receiptDetailList.isEmpty();
    }
    /**
     * 检查该出库单是否有未完成的任务
     * @param shipmentId
     * @param warehouseCode
     * @return
     */
    public boolean shipmentAllComplete(Integer shipmentId,String warehouseCode){
        LambdaQueryWrapper<ShipmentDetail> queryWrapper = Wrappers.lambdaQuery();
        queryWrapper.eq(ShipmentDetail::getShipmentId,shipmentId)
                .eq(ShipmentDetail::getWarehouseCode,warehouseCode)
                .lt(ShipmentDetail::getStatus,QuantityConstant.SHIPMENT_HEADER_COMPLETED);
        List<ShipmentDetail> shipmentDetailList = shipmentDetailService.list(queryWrapper);
        return !shipmentDetailList.isEmpty();
    }
    public List<TaskDetail> getUnBackTask(String billCode,String warehouseCode,Integer taskid){
        LambdaQueryWrapper<TaskDetail> queryWrapper = Wrappers.lambdaQuery();
        queryWrapper.eq(TaskDetail::getBillCode,billCode)
                .eq(TaskDetail::getWarehouseCode,warehouseCode)
                .eq(StringUtils.isNotNull(taskid),TaskDetail::getTaskId,taskid)
                .eq(TaskDetail::getStatus,QuantityConstant.TASK_STATUS_COMPLETED)
                .eq(TaskDetail::getBack,0);
        List<TaskDetail> taskDetails = taskDetailService.list(queryWrapper);
        return taskDetails;
    }

    public List<TaskDetail> getUnBackTaskBill(String billCode,String warehouseCode){
        LambdaQueryWrapper<TaskDetail> queryWrapper = Wrappers.lambdaQuery();
        queryWrapper.eq(TaskDetail::getBillCode,billCode)
                .eq(TaskDetail::getWarehouseCode,warehouseCode)
                .lt(TaskDetail::getStatus,QuantityConstant.TASK_STATUS_COMPLETED);
        List<TaskDetail> taskDetails = taskDetailService.list(queryWrapper);
        return taskDetails;
    }

    public List<TaskDetail> getUnCompaleteTask(String billCode,String warehouseCode,Integer taskid){
        LambdaQueryWrapper<TaskDetail> queryWrapper = Wrappers.lambdaQuery();
        queryWrapper.eq(TaskDetail::getBillCode,billCode)
                .eq(TaskDetail::getWarehouseCode,warehouseCode)
                .eq(StringUtils.isNotNull(taskid),TaskDetail::getTaskId,taskid)
                .lt(TaskDetail::getStatus,QuantityConstant.TASK_STATUS_COMPLETED);
        List<TaskDetail> taskDetails = taskDetailService.list(queryWrapper);
        return taskDetails;
    }


    public Map<Integer, TaskDetail> combineTaskDetailByBill(List<TaskDetail> unBackTask){
        Map<Integer, TaskDetail> detailsQtyMap =new HashMap<>();
        for (TaskDetail taskDetail : unBackTask) {
            TaskDetail taskDetail1=detailsQtyMap.get(taskDetail.getBillDetailId());
            if(taskDetail1!=null){
                BigDecimal bigDecimal =taskDetail1.getQty().add(taskDetail.getQty());
                taskDetail1.setQty(bigDecimal);
                detailsQtyMap.put(taskDetail.getBillDetailId(),taskDetail1);
            }else{
                detailsQtyMap.put(taskDetail.getBillDetailId(),taskDetail1);
            }
        }
        return detailsQtyMap;
    }

    @Transactional(rollbackFor = Exception.class)
    public AjaxResult getBackDataReceipt(ReceiptHeader receiptHeader,List<TaskDetail> unBackTask,String datakeyEntId){
        //将相同入库详情id,BillDetailId的任务详情整合到一起;
//        Map<Integer, TaskDetail> detailMap=combineTaskDetailByBill(unBackTask);
        String receipttype=receiptHeader.getReceiptType();
        ParameterApi parameterApi=new ParameterApi();
        String username=unBackTask.get(0).getCreatedBy();
        if(StringUtils.isNotEmpty(username)){
            User user=userService.selectLoginname(username);
            if(user!=null){
                parameterApi.setAcct(user.getLoginName());
            }
        }
        switch (receipttype){
            case QuantityConstant.SALES_R:
                Parameter parameter=erpBackTypeService.backSalesR(receiptHeader,unBackTask);
                parameterApi.setApiName("ERP销退入库单回传");
                parameterApi.setParameter(parameter);
                parameterApi.setApiNameEn("SalesPost");
                return AjaxResult.success().setData(parameterApi);
            case QuantityConstant.MES_RECEIPT_TYPE_SI:
                ParameterFinished parameterFinishedSI=erpBackTypeService.backFinishedR(receiptHeader,unBackTask,receipttype,datakeyEntId);
                parameterApi.setApiName("ERP产成品入库单回传");
                parameterApi.setParameter(parameterFinishedSI);
                parameterApi.setApiNameEn("WorkOrderFinishCreate");
                return AjaxResult.success().setData(parameterApi);
            case QuantityConstant.PURCHASER_R:
                ParameterPurchase parameterPurchaser=erpBackTypeService.backPurchaseR(receiptHeader,null,unBackTask,receipttype,datakeyEntId);
                parameterApi.setApiName("ERP采购收货入库单回传");
                parameterApi.setParameter(parameterPurchaser);
                parameterApi.setApiNameEn("PurchaseDeliveryCreate");
                return AjaxResult.success().setData(parameterApi);
            case QuantityConstant.PURCHASE_R:
                ParameterPurchase parameterPurchase=erpBackTypeService.backPurchaseWmsR(receiptHeader,unBackTask,receipttype,datakeyEntId);
                parameterApi.setApiName("ERP采购收货单入库单回传");
                parameterApi.setParameter(parameterPurchase);
                parameterApi.setApiNameEn("PurchaseDeliveryCreate");
                return AjaxResult.success().setData(parameterApi);
            case QuantityConstant.OUTSOURCED_R:
                ParameterPurchase parameterPurchased=erpBackTypeService.backPurchaseR(receiptHeader,null,unBackTask,receipttype,datakeyEntId);
                parameterApi.setApiName("ERP委外收货单入库单回传");
                parameterApi.setParameter(parameterPurchased);
                parameterApi.setApiNameEn("PurchaseDeliveryCreate");
                return AjaxResult.success().setData(parameterApi);
            case QuantityConstant.FINISHED_R:
                ParameterFinished parameterFinished=erpBackTypeService.backFinishedR(receiptHeader,unBackTask,receipttype,datakeyEntId);
                parameterApi.setApiName("ERP完工入库单回传");
                parameterApi.setParameter(parameterFinished);
                parameterApi.setApiNameEn("WorkOrderFinishPost");
                return AjaxResult.success().setData(parameterApi);
            case QuantityConstant.MISCELLANEOUS_R:
                ParameterMiscellaneous parameterMiscellaneous=erpBackTypeService.backMisceLLaneousC(receiptHeader,null,unBackTask);
                parameterApi.setApiName("ERP杂收入库单回传");
                parameterApi.setParameter(parameterMiscellaneous);
                parameterApi.setApiNameEn("ReceiveDispatchPostS");
                return AjaxResult.success().setData(parameterApi);
            case QuantityConstant.RETURN_R:
                ParameterIssuance parameterIssuance=erpBackTypeService.backIssuanceC(receiptHeader,null,unBackTask);
                parameterApi.setApiName("ERP退料入库单回传");
                parameterApi.setParameter(parameterIssuance);
                parameterApi.setApiNameEn("WorkOrderIssuePost");
                return AjaxResult.success().setData(parameterApi);
            case QuantityConstant.OVER_R:
                ParameterIssuance parameterIssuance1=erpBackTypeService.backIssuanceC(receiptHeader,null,unBackTask);
                parameterApi.setApiName("ERP超领退料单回传");
                parameterApi.setParameter(parameterIssuance1);
                parameterApi.setApiNameEn("WorkOrderIssuePost");
                return AjaxResult.success().setData(parameterApi);
//            case QuantityConstant.WAREHOUSE_R:
//                ParameterPurchase parameterPurchase1=erpBackTypeService.backPurchaseR(receiptHeader,null,unBackTask,receipttype,datakeyEntId);
//                parameterApi.setApiName("ERP仓退入库回传");
//                parameterApi.setParameter(parameterPurchase1);
//                parameterApi.setApiNameEn("PurchaseDeliveryPost");
//                return AjaxResult.success().setData(parameterApi);
            case QuantityConstant.TRANSFER_R:
                ParameterTransfer parameterTransfer=erpBackTypeService.backTransferC(receiptHeader,unBackTask);
                parameterApi.setApiName("ERP调拨单回传");
                parameterApi.setParameter(parameterTransfer);
                parameterApi.setApiNameEn("RequisitionNotePost");
                return AjaxResult.success().setData(parameterApi);
            case QuantityConstant.PUR_R:
                ParameterPurchase parameterPurchase2=erpBackTypeService.backPurR(receiptHeader,unBackTask);
                parameterApi.setApiName("ERP多角采购回传");
                parameterApi.setParameter(parameterPurchase2);
                parameterApi.setApiNameEn("PurchaseReceiptPost");
                return AjaxResult.success().setData(parameterApi);
            case QuantityConstant.RETURNF_R:
//                Parameter parameter1=erpBackTypeService.returnFR(receiptHeader,unBackTask);
//                parameterApi.setApiName("ERP签退单回传");
//                parameterApi.setParameter(parameter1);
//                parameterApi.setApiNameEn("PurchaseReceiptPost");
//                return AjaxResult.success().setData(parameterApi);
                return AjaxResult.error("单据类型不用回传");
            default:
                return AjaxResult.error("单据类型不用回传");

        }
    }

    @Transactional(rollbackFor = Exception.class)
    public AjaxResult getBackDataShipment(ShipmentHeader shipmentHeader,List<TaskDetail> unBackTask,String datakeyEntId){
        String shipmenttype=shipmentHeader.getShipmentType();
        ParameterApi parameterApi=new ParameterApi();
        String username=unBackTask.get(0).getCreatedBy();
        if(StringUtils.isNotEmpty(username)){
            User user=userService.selectLoginname(username);
            if(user!=null){
                parameterApi.setAcct(user.getLoginName());
            }
        }
        switch (shipmenttype){
            case QuantityConstant.NOTICE_C:
                ParameterShipmentWms parameter=erpBackTypeService.backShipmentWmsC(null,shipmentHeader,unBackTask,datakeyEntId);
                parameterApi.setApiName("ERP出货通知单回传");
                parameterApi.setParameter(parameter);
                parameterApi.setApiNameEn("DeliveryOrderCreate");
//                parameterApi.setAcct(parameter.getMaster().get(0).getXmdkcnfid());
                return AjaxResult.success().setData(parameterApi);
            case QuantityConstant.MISCELLANEOUS_C:
                ParameterMiscellaneous parameterMiscellaneous=erpBackTypeService.backMisceLLaneousC(null,shipmentHeader,unBackTask);
                parameterApi.setApiName("ERP杂发出库回传");
                parameterApi.setParameter(parameterMiscellaneous);
                parameterApi.setApiNameEn("ReceiveDispatchPostF");
                return AjaxResult.success().setData(parameterApi);
            case QuantityConstant.ISSUANCE_C:
                ParameterIssuance parameterIssuance=erpBackTypeService.backIssuanceC(null,shipmentHeader,unBackTask);
                parameterApi.setApiName("ERP成套发料出库回传");
                parameterApi.setParameter(parameterIssuance);
                parameterApi.setApiNameEn("WorkOrderIssuePost");
                return AjaxResult.success().setData(parameterApi);
            case QuantityConstant.OVER_C:
                ParameterIssuance parameterIssuance1=erpBackTypeService.backIssuanceC(null,shipmentHeader,unBackTask);
                parameterApi.setApiName("ERP超领出库回传");
                parameterApi.setParameter(parameterIssuance1);
                parameterApi.setApiNameEn("WorkOrderOverPost");
                return AjaxResult.success().setData(parameterApi);
            case QuantityConstant.SCRAP_C:
                ParameterScrap parameterScrap=erpBackTypeService.backScrapC(shipmentHeader,unBackTask);
                parameterApi.setApiName("ERP下阶料报废出库回传");
                parameterApi.setParameter(parameterScrap);
                parameterApi.setApiNameEn("NextLevelMaterialPost");
                return AjaxResult.success().setData(parameterApi);
            case QuantityConstant.INVENTORYSCRAP_C:
                ParameterInventoryScrap parameterInventoryScrap=erpBackTypeService.backInventoryScrapC(shipmentHeader,unBackTask);
                parameterApi.setApiName("ERP库存报废出库回传");
                parameterApi.setParameter(parameterInventoryScrap);
                parameterApi.setApiNameEn("InventoryScrapFormPost");
                return AjaxResult.success().setData(parameterApi);
            case QuantityConstant.WAREHOUSE_C:
                ParameterWarehouse parameterPurchase1=erpBackTypeService.warehouseC(shipmentHeader,unBackTask);
                parameterApi.setApiName("ERP仓退出库回传");
                parameterApi.setParameter(parameterPurchase1);
                parameterApi.setApiNameEn("PurchaseDeliveryPost");
                return AjaxResult.success().setData(parameterApi);

            case QuantityConstant.TRANSFER_C:
                return AjaxResult.error("单据类型不用回传");
            default:
                return AjaxResult.error("单据类型不用回传");
        }
    }
    public SendOut createSendOut( Payload payload,String api,String datakeyEntId,String datakeyCompanyId){
        SendOut sendOut=new SendOut();
        Host host=new Host();
        ErpService service=new ErpService();
        service.setName(api);
        Datakey datakey=new Datakey();
        datakey.setEntId(datakeyEntId);
        datakey.setCompanyId(datakeyCompanyId);

        host.setTimestamp(DateUtils.getNowTime());

        sendOut.setHost(host);
        sendOut.setService(service);
        sendOut.setDatakey(datakey);
        sendOut.setPayload(payload);
        return sendOut;
    }

    public AjaxResult sendDataToERP(AjaxResult ajaxResult,String url,String warehouseCode,String datakeyEntId,String datakeyCompanyId){
        Payload payload=new Payload();
        StdData stdData=new StdData();
        ParameterApi parameterApi=(ParameterApi)ajaxResult.getData();
        stdData.setParameter(parameterApi.getParameter());
        payload.setStd_data(stdData);
        //构建回传体
        SendOut sendOut=createSendOut(payload,parameterApi.getApiNameEn(),datakeyEntId,datakeyCompanyId);


        if(StringUtils.isNotEmpty(parameterApi.getAcct())){
            sendOut.getHost().setAcct(parameterApi.getAcct().toLowerCase());
        }

        String jsonString = JSONObject.toJSONString(sendOut);
        String result=OkHttpUtils.bodypost(url,jsonString,warehouseCode,parameterApi.getApiName());
        if (StringUtils.isEmpty(result)) {
            return AjaxResult.error("ERP接口地址错误或服务器连接不到或返回为空");
        }
        ResultErpBack ajaxResult1 = JSON.parseObject(result, ResultErpBack.class);
        return ajaxResult1.responseAnalyz();
//        if(ajaxResult1.responseAnalyz().hasErr()){
//            return AjaxResult.error(ajaxResult1.responseAnalyz().getMsg());
//        }
//        return AjaxResult.success(ajaxResult1.responseAnalyz().getMsg());
    }


    public AjaxResult createErpYanTui(List<SrmDetail> details, SrmHeader srmHeader){
        Address address=addressService.selectAddressByParam("ERP",srmHeader.getWarehouseCode());
        ParameterPurchase parameterPurchase=erpBackTypeService.backYanTuiR(srmHeader,details,address.getUserDef2());
        ParameterApi parameterApi=new ParameterApi();
        parameterApi.setApiName("ERP验退单回传");
        parameterApi.setParameter(parameterPurchase);
        parameterApi.setApiNameEn("PurchaseDeliveryCreate");
        AjaxResult ajaxResult=AjaxResult.success().setData(parameterApi);


        String companyCode=details.get(0).getCompanyCode();
        Company company=companyService.getCompanyByU8Code(companyCode);
        AjaxResult ajaxResult1=sendDataToERP(ajaxResult,address.getUrl(),srmHeader.getWarehouseCode(),address.getUserDef2(),company.getErpCompany());
        return ajaxResult1;

    }

}