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

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.huaheng.api.srm.domain.ICSRuternASN;
import com.huaheng.common.utils.DateUtils;
import com.huaheng.common.utils.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
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.http.HttpUtils;
import com.huaheng.common.utils.security.ShiroUtils;
import com.huaheng.framework.aspectj.ApiLogAspect;
import com.huaheng.framework.web.domain.AjaxResult;
import com.huaheng.pc.check.checkDetail.domain.CheckDetail;
import com.huaheng.pc.check.checkDetail.service.CheckDetailService;
import com.huaheng.pc.check.checkHeader.domain.CheckHeader;
import com.huaheng.pc.check.checkHeader.service.CheckHeaderService;
import com.huaheng.pc.config.address.service.AddressService;
import com.huaheng.pc.config.company.domain.Company;
import com.huaheng.pc.config.company.domain.CompanyU8;
import com.huaheng.pc.config.company.service.CompanyService;
import com.huaheng.pc.config.company.service.CompanyU8Service;
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.receiptType.domain.ReceiptType;
import com.huaheng.pc.config.receiptType.service.ReceiptTypeService;
import com.huaheng.pc.config.statusFlow.domain.StatusFlowDetail;
import com.huaheng.pc.config.warehouse.service.WarehouseU8Service;
import com.huaheng.pc.inventory.inventoryDetail.service.InventoryDetailService;
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.monitor.apilog.domain.ApiLog;
import com.huaheng.pc.receipt.receiptContainerHeader.domain.ReceiptContainerHeader;
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.receiptDetail.service.ReceiptDetailService;
import com.huaheng.pc.receipt.receiptDetailHistory.domain.ReceiptDetailHistory;
import com.huaheng.pc.receipt.receiptDetailHistory.service.ReceiptDetailHistoryService;
import com.huaheng.pc.receipt.receiptHeader.domain.ReceiptHeader;
import com.huaheng.pc.receipt.receiptHeader.mapper.ReceiptHeaderMapper;
import com.huaheng.pc.receipt.receiptHeader.mapper.ReceiptHeaderhistoryMapper;
import com.huaheng.pc.receipt.receiptHeaderHistory.domain.ReceiptHeaderHistory;
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.srm.domain.MesPostBack;
import com.huaheng.pc.srm.service.ICSASNService;
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.service.ReceiptTaskService;
import com.huaheng.pc.task.taskHeader.service.TaskHeaderService;
import com.huaheng.pc.u8.domain.*;
import com.huaheng.pc.u8.service.ICSReceiptDetailService;
import com.huaheng.pc.u8.service.ICSReceiptHeaderService;
import org.apache.commons.collections.CollectionUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.http.HttpHeaders;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

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

@Service
public class ReceiptHeaderService extends ServiceImpl<ReceiptHeaderMapper, ReceiptHeader> {
    @Resource
    private ReceiptHeaderService receiptHeaderService;
    @Resource
    private ReceiptTypeService receiptTypeService;
    @Resource
    private ReceiptDetailService receiptDetailService;
    @Resource
    private CheckHeaderService checkHeaderService;
    @Resource
    private CheckDetailService checkDetailService;
    @Resource
    private ShipmentHeaderService shipmentHeaderService;
    @Resource
    private ReceiptHeaderMapper receiptHeaderMapper;
    @Resource
    private ReceiptHeaderhistoryMapper receiptheaderhistoryMapper;
    @Resource
    private WarehouseU8Service warehouseU8Service;
    @Resource
    private InventoryDetailService inventoryDetailService;
    @Resource
    private ShipmentDetailService shipmentDetailService;
    @Resource
    private InventoryTransactionService inventoryTransactionService;
    @Resource
    private AddressService addressService;
    @Resource
    private CompanyU8Service companyWuService;
    @Resource
    private ICSReceiptHeaderService icsReceiptHeaderService;
    @Resource
    private ICSReceiptDetailService icsReceiptDetailService;
    @Resource
    private ContainerService containerService;
    @Resource
    private ReceiptContainerHeaderService receiptContainerHeaderService;
    @Resource
    private TaskHeaderService taskHeaderService;
    @Resource
    private TaskDetailService taskDetailService;
    @Resource
    private ReceiptTaskService receiptTaskService;
    @Resource
    private ReceiptDetailHistoryService receiptDetailHistoryService;
    @Resource
    private ReceiptHeaderHistoryService receiptheaderhistoryService;
    @Resource
    private LocationService locationService;
    @Resource
    private ICSASNService icsasnService;
    @Resource
    private IUserService userService;
    @Resource
    private CompanyService companyService;
    /**
     * 保存入库单
     *
     * @param receiptHeader
     * @return
     */
    public AjaxResult saveReceiptHeader(ReceiptHeader receiptHeader) {
        //根据仓库和货主以及传入单据类型编码判断单据类型是否存在
        LambdaQueryWrapper<ReceiptType> lambdaQueryWrapper = Wrappers.lambdaQuery();
        lambdaQueryWrapper.eq(ReceiptType::getCode, receiptHeader.getReceiptType())
                .eq(ReceiptType::getWarehouseCode, ShiroUtils.getWarehouseCode());
//                .eq(ReceiptType::getCompanyCode, receiptHeader.getCompanyCode());
        ReceiptType receiptType = receiptTypeService.getOne(lambdaQueryWrapper);
        if (receiptType == null) {
            throw new ServiceException(ShiroUtils.getWarehouseCode(), receiptHeader.getCompanyCode(), "没有对应的入库单类型");
        }
        receiptHeader.setWarehouseCode(ShiroUtils.getWarehouseCode());
        //根据单据类型生成单号
        String code = createCode(receiptHeader.getReceiptType(),receiptHeader.getWarehouseCode());
        if (StringUtils.isEmpty(code)) {
            throw new ServiceException("根据单据类型" + receiptHeader.getReceiptType() + "生成单号失败");
        }
        Company company=companyService.getCompanyByCode(receiptHeader.getCompanyCode(),receiptHeader.getWarehouseCode());
        if(company!=null){
            receiptHeader.setErpCompanyCode(company.getErpCompany());
        }
        //根据货主、u8仓库找到对应erp仓库code
        String erpCode=warehouseU8Service.getWarehouseErpCode(receiptHeader.getWarehouseCode(),receiptHeader.getCompanyCode(),receiptHeader.getUWarehouseCode());
        receiptHeader.setErpWarehouseCode(erpCode);
        receiptHeader.setCode(code);
        receiptHeader.setDeleted(false);
        receiptHeader.setFirstStatus(QuantityConstant.RECEIPT_HEADER_BUILD);
        receiptHeader.setLastStatus(QuantityConstant.RECEIPT_HEADER_BUILD);

        return AjaxResult.toAjax(this.save(receiptHeader));
    }

    /**
     * 保存入库单
     *
     * @param receiptHeader
     * @return
     */
    public AjaxResult saveReceiptHeaderErp(ReceiptHeader receiptHeader) {
        //根据仓库和货主以及传入单据类型编码判断单据类型是否存在
        LambdaQueryWrapper<ReceiptType> lambdaQueryWrapper = new LambdaQueryWrapper<>();
        lambdaQueryWrapper.eq(ReceiptType::getCode, receiptHeader.getReceiptType());
        lambdaQueryWrapper.eq(ReceiptType::getWarehouseCode, receiptHeader.getWarehouseCode());
//                .eq(ReceiptType::getCompanyCode, receiptHeader.getCompanyCode());
        lambdaQueryWrapper.last("limit 1");
        ReceiptType receiptType = receiptTypeService.getOne(lambdaQueryWrapper);
        if (receiptType == null) {
            throw new ServiceException(receiptHeader.getWarehouseCode(), receiptHeader.getReceiptType(), "没有对应的入库单类型");
        }
        //根据单据类型生成单号
        String code = createCode(receiptHeader.getReceiptType(),receiptHeader.getWarehouseCode());
        if (StringUtils.isEmpty(code)) {
            throw new ServiceException("根据单据类型" + receiptHeader.getReceiptType() + "生成单号失败");
        }
        //根据货主、u8仓库找到对应erp仓库code
        String erpCode=warehouseU8Service.getWarehouseErpCode(receiptHeader.getWarehouseCode(),receiptHeader.getCompanyCode(),receiptHeader.getUWarehouseCode());
        receiptHeader.setErpWarehouseCode(erpCode);
        receiptHeader.setCode(code);
        receiptHeader.setDeleted(false);
        receiptHeader.setFirstStatus(QuantityConstant.RECEIPT_HEADER_BUILD);
        receiptHeader.setLastStatus(QuantityConstant.RECEIPT_HEADER_BUILD);

        return AjaxResult.toAjax(this.save(receiptHeader));
    }

    /**
     * 根据单据类型生成单号  规则:入库单类型 + 年月日 + 5位(排序号 + 1)
     *
     * @param receiptType
     * @return
     */
    //todo:huhai 单据生成规则,后续版本计划追加一个序列号生成规则表:统一设定前缀,填充位,流水码等
    public String createCode(String receiptType,String warehouseCode) {
        String code = null;
        int i = 1;
        Date now = new Date();
        SimpleDateFormat df = new SimpleDateFormat("yyyyMMdd");
        LambdaQueryWrapper<ReceiptHeader> lambda = Wrappers.lambdaQuery();
        lambda.select(ReceiptHeader::getCode).eq(ReceiptHeader::getReceiptType, receiptType);
        lambda.eq(StringUtils.isNotEmpty(warehouseCode),ReceiptHeader::getWarehouseCode,warehouseCode)
                .orderByDesc(ReceiptHeader::getId).last("Limit 1");
        //如果指定类型的最后的code存在,并且日期一致。那么 code = 入库单类型 + 年月日 + (排序号 + 1)
        String maxCode = null;
        ReceiptHeader receiptHeader = this.getOne(lambda);
        if (receiptHeader != null) {
            maxCode = this.getOne(lambda).getCode();
        }

        //todo:隐藏了BUG,请修正。 修改好  去掉todo

        while (i != 0) {
            LambdaQueryWrapper<ReceiptHeaderHistory> aa = Wrappers.lambdaQuery();
            if (maxCode != null && maxCode.substring(maxCode.length() - 13, maxCode.length() - 5).equals(df.format(now))) {
                Integer Count = Integer.valueOf(maxCode.substring(maxCode.length() - 5, maxCode.length()));
                code = receiptType + df.format(now) + String.format("%05d", Count + i++);
            } else {
                code = receiptType + df.format(now) + String.format("%05d", 0000+i++);
            }
            aa.select(ReceiptHeaderHistory::getCode).eq(ReceiptHeaderHistory::getCode, code);
            List<ReceiptHeaderHistory> list = receiptheaderhistoryMapper.selectList(aa);
            if (list.size() <= 0) {
                i=0;
            }
        }
        return code;
    }

    /**
     * 入库预约
     *
     * @param receiptHeader
     * @return
     */
    public AjaxResult reservation(ReceiptHeader receiptHeader) {
        LambdaQueryWrapper<ReceiptDetail> receiptDetailLambda = Wrappers.lambdaQuery();
        receiptDetailLambda.eq(ReceiptDetail::getReceiptId, receiptHeader.getId());
        List<ReceiptDetail> receiptDetails = receiptDetailService.list(receiptDetailLambda);
        //更新入库明细流程
        for (ReceiptDetail receiptDetail : receiptDetails) {
            receiptDetail.setProcessStamp(QuantityConstant.RECEIPT_HEADER_RESERVATION.toString());
            if (!receiptDetailService.updateById(receiptDetail)) {
                throw new ServiceException("更新入库明细处理标记失败");
            }
            receiptDetail = receiptDetailService.queryflow(receiptDetail);
            if (!receiptDetailService.updateById(receiptDetail)) {
                throw new ServiceException("更新入库明细流程失败");
            }
        }
        receiptHeader.setLastUpdatedBy(ShiroUtils.getLoginName());
        //更新入库单预约时间
        if (!this.updateById(receiptHeader)) {
            throw new ServiceException("更新入库单预约时间失败");
        }
        receiptDetailService.updateReceiptHeaderLastStatus(receiptHeader.getId());
        return AjaxResult.success("预约成功");
    }

    /**
     * 入库到货
     *
     * @param id
     * @return
     */
    public AjaxResult arrival(Integer id) {
        LambdaQueryWrapper<ReceiptDetail> receiptDetailLambda = Wrappers.lambdaQuery();
        receiptDetailLambda.eq(ReceiptDetail::getReceiptId, id)
                .eq(ReceiptDetail::getProcessStamp, QuantityConstant.RECEIPT_HEADER_ARRIVAL.toString());
        List<ReceiptDetail> receiptDetails = receiptDetailService.list(receiptDetailLambda);
        //更新入库明细流程
        for (ReceiptDetail receiptDetail : receiptDetails) {
            receiptDetailService.queryflow(receiptDetail);
        }
        //更新入库单头表
        receiptDetailService.updateReceiptHeaderLastStatus(id);
        return AjaxResult.success("已通知到货");
    }

    /**
     * 入库质检
     */
    public AjaxResult check(Integer id) {

        ReceiptHeader receiptHeader = this.getById(id);
        LambdaQueryWrapper<ReceiptDetail> receiptDetailLambda = Wrappers.lambdaQuery();
        receiptDetailLambda.eq(ReceiptDetail::getReceiptId, id);
        List<ReceiptDetail> receiptDetails = receiptDetailService.list(receiptDetailLambda);

        //判断是否已经生成了质检单
        LambdaQueryWrapper<CheckHeader> checkHeaderLambdaQueryWrapper = Wrappers.lambdaQuery();
        checkHeaderLambdaQueryWrapper.eq(CheckHeader::getCode, receiptHeader.getCode());
        CheckHeader checkHeaderQuery = checkHeaderService.getOne(checkHeaderLambdaQueryWrapper);
        if (checkHeaderQuery != null) {
            throw new ServiceException("质检单已生成");
        }
        //创建质检头表
        CheckHeader checkHeader = new CheckHeader();
        checkHeader.setCode(receiptHeader.getCode());
        checkHeader.setType(QuantityConstant.CHECK_TYPE_RECEIPT.toString());
        checkHeader.setWarehouseCode(ShiroUtils.getWarehouseCode());
        checkHeader.setReferCode(receiptHeader.getReferCode());
        checkHeader.setEnable(1);
        checkHeader.setStatus(QuantityConstant.CHECK_STATUS_BUILD.toString());
        checkHeader.setCreatedBy(ShiroUtils.getLoginName());
        checkHeader.setLastUpdatedBy(ShiroUtils.getLoginName());

        if (!checkHeaderService.save(checkHeader)) {
            throw new ServiceException("添加质检头表错误");
        }

        //查询保存后的质检头表
        LambdaQueryWrapper<CheckHeader> checkHeaderLambda = Wrappers.lambdaQuery(checkHeader);
        checkHeader = checkHeaderService.getOne(checkHeaderLambda);

        for (ReceiptDetail receiptDetail : receiptDetails) {
            CheckDetail checkDetail = new CheckDetail();
            checkDetail.setCheckHeaderId(checkHeader.getId());
            checkDetail.setWarehouseCode(ShiroUtils.getWarehouseCode());
            checkDetail.setCheckCode(checkHeader.getCode());
            checkDetail.setReceiptDetailId(receiptDetail.getId());
            checkDetail.setReceiptCode(receiptDetail.getReceiptCode());
            checkDetail.setReferCode(checkHeader.getReferCode());
            checkDetail.setMaterialCode(receiptDetail.getMaterialCode());
            checkDetail.setMaterialName(receiptDetail.getMaterialName());
            checkDetail.setMaterialSpec(receiptDetail.getMaterialSpec());
            checkDetail.setMaterialUnit(receiptDetail.getMaterialUnit());
            checkDetail.setCompanyCode(receiptDetail.getCompanyCode());
            checkDetail.setInventorySts(receiptDetail.getInventorySts());
            checkDetail.setStatus(QuantityConstant.CHECK_STATUS_BUILD.toString());
            checkDetail.setQty(receiptDetail.getQty());
            checkDetail.setCheckBy(ShiroUtils.getLoginName());
            checkDetail.setCreatedBy(ShiroUtils.getLoginName());
            checkDetail.setLastUpdatedBy(ShiroUtils.getLoginName());
            if (!checkDetailService.save(checkDetail)) {
                throw new ServiceException("保存质检明细失败");
            }
        }
        return AjaxResult.success("创建质检单成功");
    }

    /**
     * 提交审核入库单
     */
    @Transactional
    public AjaxResult submitReview(String ids) {
        String warehouseCode = ShiroUtils.getWarehouseCode();
        if (StringUtils.isEmpty(ids)) {
            return AjaxResult.error("仓库:" + warehouseCode + ",提交入库单审核,id不能为空");
        }
        Integer[] idArray = Convert.toIntArray(ids);
        for (int i = 0; i < idArray.length; i++) {
            ReceiptHeader receiptHeader = this.getById(idArray[i]);
            if (receiptHeader.getFirstStatus() > QuantityConstant.RECEIPT_HEADER_VERIFYING
                    || receiptHeader.getLastStatus() > QuantityConstant.RECEIPT_HEADER_VERIFYING) {
                return AjaxResult.error("仓库:" + warehouseCode + ",单据号:" + receiptHeader.getCode() + "入库单不需要审核");
            }
            LambdaQueryWrapper<ReceiptDetail> lambdaQueryWrapper = Wrappers.lambdaQuery();
            lambdaQueryWrapper.eq(ReceiptDetail::getReceiptId, idArray[i]);
            List<ReceiptDetail> receiptDetailList = receiptDetailService.list(lambdaQueryWrapper);
            if (receiptDetailList.isEmpty()) {
                return AjaxResult.error("仓库:" + warehouseCode + ",单据号:" + receiptHeader.getCode() + "入库单没有明细");
            }
            receiptHeader.setFirstStatus(QuantityConstant.RECEIPT_HEADER_VERIFYING);
            receiptHeader.setLastStatus(QuantityConstant.RECEIPT_HEADER_VERIFYING);
            if (!this.updateById(receiptHeader)) {
                throw new ServiceException("仓库:" + warehouseCode + ",单据号:" + receiptHeader.getCode() + " 失败");
            }
        }
        return AjaxResult.success("仓库:" + warehouseCode + ",提交审核成功");
    }

    /**
     * 到货通知
     *
     * @param id
     * @return
     */
    public AjaxResult arrivalNotice(String id) {
        LambdaQueryWrapper<ReceiptDetail> lambda = Wrappers.lambdaQuery();
        lambda.eq(ReceiptDetail::getReceiptId, id);
        List<ReceiptDetail> receiptDetails = receiptDetailService.list(lambda);
        for (ReceiptDetail receiptDetail : receiptDetails) {
            receiptDetail.setProcessStamp(QuantityConstant.RECEIPT_HEADER_ARRIVAL.toString());
            receiptDetailService.updateById(receiptDetail);
            if (!receiptDetailService.updateById(receiptDetailService.queryflow(receiptDetail))) {
                throw new ServiceException("更新入库明细处理标记出错");
            }
            receiptDetailService.updateReceiptHeaderLastStatus(receiptDetail.getReceiptId());
        }
        return AjaxResult.success("已通知到货");
    }

    /**
     * 加入订单池
     *
     * @param ids 头表id字符串
     * @return
     */
    @Transactional
    public AjaxResult addPool(String ids) {
        List<Integer> idList = Arrays.asList(Convert.toIntArray(ids));
        List<StatusFlowDetail> statusFlowDetailList = receiptDetailService.queryflow();
        List<StatusFlowDetail> verifyList = statusFlowDetailList.stream().filter(item -> {
            return "审核".equals(item.getRecordType());
        }).collect(Collectors.toList());
        Integer nessaryFlag = 0;
        for (Integer id : idList) {
            LambdaQueryWrapper<ReceiptDetail> lambdaQueryWrapper = Wrappers.lambdaQuery();
            lambdaQueryWrapper.eq(ReceiptDetail::getReceiptId, id);
            List<ReceiptDetail> list = receiptDetailService.list(lambdaQueryWrapper);
            if (list.size() != 0) {
                if (nessaryFlag.equals(verifyList.get(0).getNessary())) {
                    for (ReceiptDetail receiptDetail : list) {
                        if (Integer.parseInt(receiptDetail.getProcessStamp()) < QuantityConstant.RECEIPT_HEADER_POOL) {
                            //加入订单池
                            receiptDetail.setProcessStamp(QuantityConstant.RECEIPT_HEADER_POOL.toString());
                            ReceiptDetail receiptDetail1 = receiptDetailService.queryflow(receiptDetail);
                            if (!receiptDetailService.updateById(receiptDetail1)) {
                                throw new ServiceException("更新入库明细状态失败");
                            }
                        } else {
                            throw new ServiceException("已有入库明细进入订单池");
                        }
                    }
                } else {
                    for (ReceiptDetail receiptDetail : list) {
                        if (Integer.parseInt(receiptDetail.getProcessStamp()) < QuantityConstant.RECEIPT_HEADER_POOL) {
                            //判断入库明细是否需要审核
                            ReceiptDetail beforeReceiptDetail = receiptDetailService.queryflow(receiptDetail);
                            if (Integer.parseInt(beforeReceiptDetail.getProcessStamp()) == QuantityConstant.RECEIPT_HEADER_VERIFYING
//                                    || Integer.parseInt(beforeReceiptDetail.getProcessStamp()) == QuantityConstant.RECEIPT_HEADER_APPROVE
                            ) {
                                throw new ServiceException("请先通过审核");
                            }
                            //加入订单池
                            receiptDetail.setProcessStamp(QuantityConstant.RECEIPT_HEADER_POOL.toString());
                            ReceiptDetail receiptDetail1 = receiptDetailService.queryflow(receiptDetail);
                            if (!receiptDetailService.updateById(receiptDetail1)) {
                                throw new ServiceException("更新入库明细状态失败");
                            }
                        } else {
                            throw new ServiceException("已有入库明细进入订单池");
                        }
                    }
                }

            }
            //更新头表状态
            receiptDetailService.updateReceiptHeaderLastStatus(id);
        }
        return AjaxResult.success("加入成功");
    }


    public List<ReceiptHeader> selectListByCreated() {
        return receiptHeaderMapper.selectListByCreated();
    }


    @Transactional(rollbackFor = Exception.class)
    public Integer createTodayHeader(String companyCode) {
        String receiptType = QuantityConstant.RECEIPT_TYPE_PPI;
        String code = null;
        Date now = new Date();
        SimpleDateFormat df = new SimpleDateFormat("yyyyMMdd");
//        String maxCode = receiptHeaderMapper.createCode(receiptType);

        LambdaQueryWrapper<ReceiptHeader> lambdaQueryWrapper = Wrappers.lambdaQuery();
        lambdaQueryWrapper.eq(ReceiptHeader::getReceiptType, receiptType);
        lambdaQueryWrapper.eq(ReceiptHeader::getWarehouseCode,ShiroUtils.getWarehouseCode());
        lambdaQueryWrapper.orderByDesc(ReceiptHeader::getId);
        lambdaQueryWrapper.last("limit 1");
        ReceiptHeader receiptHeader1=this.getOne(lambdaQueryWrapper);
        String maxCode =null;
        if(receiptHeader1!=null){
            maxCode=receiptHeader1.getCode();
        }
        //如果指定类型的最后的code存在,并且日期一致。那么 code = 入库单类型 + 年月日 + (排序号 + 1)
        if (maxCode != null && maxCode.substring(maxCode.length() - 13, maxCode.length() - 5).equals(df.format(now))) {
            Integer Count = Integer.valueOf(maxCode.substring(maxCode.length() - 5, maxCode.length()));
            code = receiptType + df.format(now) + String.format("%05d", Count + 1);
        } else {
            code = receiptType + df.format(now) + "00001";
        }
        ReceiptHeader receiptHeader = new ReceiptHeader();
        receiptHeader.setId(null);
        receiptHeader.setCode(code);
        receiptHeader.setReceiptType(receiptType);
        receiptHeader.setWarehouseCode(ShiroUtils.getWarehouseCode());
        receiptHeader.setCreated(null);
        receiptHeader.setCreatedBy(ShiroUtils.getLoginName());
        receiptHeader.setLastUpdated(null);
        receiptHeader.setLastUpdatedBy(ShiroUtils.getLoginName());
        receiptHeader.setFirstStatus(200);
        receiptHeader.setLastStatus(200);
        receiptHeader.setCompanyCode(companyCode);
        this.save(receiptHeader);
        return receiptHeader.getId();
    }

    @Transactional(rollbackFor = Exception.class)
    public Integer createTodayHeader(String companyCode,String uWarehouseCode) {
        String receiptType = QuantityConstant.RECEIPT_TYPE_PPI;
        String code = null;
        Date now = new Date();
        SimpleDateFormat df = new SimpleDateFormat("yyyyMMdd");
//        String maxCode = receiptHeaderMapper.createCode(receiptType);

        LambdaQueryWrapper<ReceiptHeader> lambdaQueryWrapper = Wrappers.lambdaQuery();
        lambdaQueryWrapper.eq(ReceiptHeader::getReceiptType, receiptType);
        lambdaQueryWrapper.eq(ReceiptHeader::getWarehouseCode,ShiroUtils.getWarehouseCode());
        lambdaQueryWrapper.orderByDesc(ReceiptHeader::getId);
        lambdaQueryWrapper.last("limit 1");
        ReceiptHeader receiptHeader1=this.getOne(lambdaQueryWrapper);
        String maxCode =null;
        if(receiptHeader1!=null){
            maxCode=receiptHeader1.getCode();
        }
        //如果指定类型的最后的code存在,并且日期一致。那么 code = 入库单类型 + 年月日 + (排序号 + 1)
        if (maxCode != null && maxCode.substring(maxCode.length() - 13, maxCode.length() - 5).equals(df.format(now))) {
            Integer Count = Integer.valueOf(maxCode.substring(maxCode.length() - 5, maxCode.length()));
            code = receiptType + df.format(now) + String.format("%05d", Count + 1);
        } else {
            code = receiptType + df.format(now) + "00001";
        }
        ReceiptHeader receiptHeader = new ReceiptHeader();
        receiptHeader.setId(null);
        receiptHeader.setCode(code);
        receiptHeader.setReceiptType(receiptType);
        receiptHeader.setWarehouseCode(ShiroUtils.getWarehouseCode());
        receiptHeader.setCreated(null);
        receiptHeader.setCreatedBy(ShiroUtils.getLoginName());
        receiptHeader.setLastUpdated(null);
        receiptHeader.setLastUpdatedBy(ShiroUtils.getLoginName());
        receiptHeader.setFirstStatus(200);
        receiptHeader.setLastStatus(200);
        receiptHeader.setCompanyCode(companyCode);
        receiptHeader.setUWarehouseCode(uWarehouseCode);
        this.save(receiptHeader);
        return receiptHeader.getId();
    }
    @Transactional(rollbackFor = Exception.class)
    public Integer createTodayHeaderJJ(String companyCode,String uWarehouseCode) {
        String receiptType = QuantityConstant.RECEIPT_TYPE_JJP;
        String code = null;
        Date now = new Date();
        SimpleDateFormat df = new SimpleDateFormat("yyyyMMdd");
//        String maxCode = receiptHeaderMapper.createCode(receiptType);

        LambdaQueryWrapper<ReceiptHeader> lambdaQueryWrapper = Wrappers.lambdaQuery();
        lambdaQueryWrapper.eq(ReceiptHeader::getReceiptType, receiptType);
        lambdaQueryWrapper.eq(ReceiptHeader::getWarehouseCode,ShiroUtils.getWarehouseCode());
        lambdaQueryWrapper.orderByDesc(ReceiptHeader::getId);
        lambdaQueryWrapper.last("limit 1");
        ReceiptHeader receiptHeader1=this.getOne(lambdaQueryWrapper);
        String maxCode =null;
        if(receiptHeader1!=null){
            maxCode=receiptHeader1.getCode();
        }
        //如果指定类型的最后的code存在,并且日期一致。那么 code = 入库单类型 + 年月日 + (排序号 + 1)
        if (maxCode != null && maxCode.substring(maxCode.length() - 13, maxCode.length() - 5).equals(df.format(now))) {
            Integer Count = Integer.valueOf(maxCode.substring(maxCode.length() - 5, maxCode.length()));
            code = receiptType + df.format(now) + String.format("%05d", Count + 1);
        } else {
            code = receiptType + df.format(now) + "00001";
        }
        ReceiptHeader receiptHeader = new ReceiptHeader();
        receiptHeader.setId(null);
        receiptHeader.setCode(code);
        receiptHeader.setReceiptType(receiptType);
        receiptHeader.setWarehouseCode(ShiroUtils.getWarehouseCode());
        receiptHeader.setCreated(null);
        receiptHeader.setCreatedBy(ShiroUtils.getLoginName());
        receiptHeader.setLastUpdated(null);
        receiptHeader.setLastUpdatedBy(ShiroUtils.getLoginName());
        receiptHeader.setFirstStatus(200);
        receiptHeader.setLastStatus(200);
        receiptHeader.setCompanyCode(companyCode);
        receiptHeader.setUWarehouseCode(uWarehouseCode);
        this.save(receiptHeader);
        return receiptHeader.getId();
    }

    @Transactional(rollbackFor = Exception.class)
    public List<ReceiptHeader> getLatestReceipt(String warehouseCode, String companyCode) {
        return receiptHeaderMapper.getLatestReceipt(warehouseCode, companyCode);
    }

    /**
     * 修改回传后状态
     *
     * @param id
     * @return
     */
    private AjaxResult editReceiveStatus(Integer id) {
        ReceiptHeader receiptHeader = new ReceiptHeader();
        receiptHeader.setId(id);
        receiptHeader.setFirstStatus(900);
        receiptHeader.setLastStatus(900);
        if (!updateById(receiptHeader)) {
            throw new ServiceException("更新头表状态失败");
        } else {
            LambdaQueryWrapper<ReceiptDetail> lambdaQueryWrapper = Wrappers.lambdaQuery();
            lambdaQueryWrapper.eq(ReceiptDetail::getReceiptId, id);
            List<ReceiptDetail> receiptDetails = receiptDetailService.list(lambdaQueryWrapper);
            for (ReceiptDetail receiptDetail : receiptDetails) {
                receiptDetail.setProcessStamp("900");
            }
            if (!receiptDetailService.updateBatchById(receiptDetails)) {
                throw new ServiceException("更新明细失败");
            }
        }
        return AjaxResult.success("");
    }

    public AjaxResult crossLocation(String ids) {
        String containerCode = "YKR01";
        String locationCode = "YRL01";
        for (Integer id : Convert.toIntArray(ids)) {
            ReceiptHeader receiptHeader = this.getById(id);
            /* 创建出库单*/
            ShipmentHeader shipmentHeader = new ShipmentHeader();
            shipmentHeader.setWarehouseCode(receiptHeader.getWarehouseCode());
            shipmentHeader.setCompanyCode(receiptHeader.getCompanyCode());
            shipmentHeader.setCode(receiptHeader.getCode());
            shipmentHeader.setFirstStatus(QuantityConstant.SHIPMENT_CONTAINER_BUILD);
            shipmentHeader.setLastStatus(QuantityConstant.SHIPMENT_CONTAINER_BUILD);
            shipmentHeader.setShipmentType("YK");
            shipmentHeader.setTotalQty(receiptHeader.getTotalQty());
            shipmentHeader.setTotalLines(receiptHeader.getTotalLines());
            try{
                shipmentHeaderService.save(shipmentHeader);
            }catch (Exception e){
                throw new ServiceException("创建出库单失败或已越库");
            }

            List<ReceiptDetail> receiptDetailList = receiptDetailService.findByReceiptId(id);
            /* 遍历入库单明细生成出库单与库存交易记录*/
            for (ReceiptDetail receiptDetail : receiptDetailList) {

                /* 创建出库明细*/
                ShipmentDetail shipmentDetail = new ShipmentDetail();
                shipmentDetail.setShipmentId(shipmentHeader.getId());
                shipmentDetail.setWarehouseCode(shipmentHeader.getWarehouseCode());
                shipmentDetail.setCompanyCode(shipmentHeader.getCompanyCode());
                shipmentDetail.setShipmentCode(shipmentHeader.getCode());
                shipmentDetail.setMaterialCode(receiptDetail.getMaterialCode());
                shipmentDetail.setMaterialName(receiptDetail.getMaterialName());
                shipmentDetail.setMaterialSpec(receiptDetail.getMaterialSpec());
                shipmentDetail.setMaterialUnit(receiptDetail.getMaterialUnit());
                shipmentDetail.setQty(receiptDetail.getQty());
                shipmentDetail.setTaskQty(BigDecimal.ZERO);
                shipmentDetail.setBatch(receiptDetail.getBatch());
                shipmentDetail.setLot(receiptDetail.getLot());
                shipmentDetail.setProjectNo(receiptDetail.getProjectNo());
                shipmentDetail.setManufactureDate(receiptDetail.getManufactureDate());
                shipmentDetail.setExpirationDate(receiptDetail.getExpirationDate());
                shipmentDetail.setAgingDate(receiptDetail.getAgingDate());
                shipmentDetail.setInventorySts(receiptDetail.getInventorySts());
                shipmentDetail.setStatus(QuantityConstant.TASK_STATUS_BUILD);
                if (!shipmentDetailService.save(shipmentDetail)) {
                    throw new ServiceException("创建出库单明细失败");
                }

                InventoryTransaction inventoryTransaction = new InventoryTransaction();
                inventoryTransaction.setWarehouseCode(receiptHeader.getWarehouseCode());
                inventoryTransaction.setCompanyCode(receiptHeader.getCompanyCode());
                inventoryTransaction.setLocationCode(locationCode);
                inventoryTransaction.setContainerCode(containerCode);
                inventoryTransaction.setTransactionType(QuantityConstant.INVENTORY_TRANSACTION_RECEIPT);
                inventoryTransaction.setMaterialCode(receiptDetail.getMaterialCode());
                inventoryTransaction.setMaterialName(receiptDetail.getMaterialName());
                inventoryTransaction.setMaterialSpec(receiptDetail.getMaterialSpec());
                inventoryTransaction.setMaterialUnit(receiptDetail.getMaterialUnit());
                inventoryTransaction.setTaskQty(receiptDetail.getQty());
                inventoryTransaction.setInventorySts(receiptDetail.getInventorySts());
                inventoryTransaction.setReferCode(receiptHeader.getReferCode());
                inventoryTransaction.setReferDetailId(receiptDetail.getReferLineNum());
                inventoryTransaction.setBatch(receiptDetail.getBatch());
                inventoryTransaction.setLot(receiptDetail.getLot());
                inventoryTransaction.setProjectNo(receiptDetail.getProjectNo());
                inventoryTransaction.setQcCheck(receiptDetail.getQcCheck());
                inventoryTransaction.setManufactureDate(receiptDetail.getManufactureDate());
                inventoryTransaction.setExpirationDate(receiptDetail.getExpirationDate());
                inventoryTransaction.setAgingDate(receiptDetail.getAgingDate());
                inventoryTransaction.setAttribute1(receiptDetail.getAttribute1());
                inventoryTransaction.setAttribute2(receiptDetail.getAttribute2());
                inventoryTransaction.setAttribute3(receiptDetail.getAttribute3());
                inventoryTransaction.setBillCode(receiptHeader.getCode());
                inventoryTransaction.setBillDetailId(receiptDetail.getId());
                inventoryTransaction.setSupplierCode(receiptDetail.getSupplierCode());
                /*if (!inventoryTransactionService.save(inventoryTransaction)) {
                    throw new ServiceException("保存库存交易记录失败");
                }*/
                inventoryTransaction.setTransactionType(QuantityConstant.INVENTORY_TRANSACTION_SHIPMENT);
                inventoryTransaction.setBillCode(shipmentHeader.getCode());
                inventoryTransaction.setBillDetailId(shipmentDetail.getId());
                if (!inventoryTransactionService.save(inventoryTransaction)) {
                    throw new ServiceException("保存库存交易记录失败");
                }
            }

            receiptHeader.setFirstStatus(QuantityConstant.RECEIPT_HEADER_POSTING);
            receiptHeader.setLastStatus(QuantityConstant.RECEIPT_HEADER_POSTING);
            if (!this.updateById(receiptHeader)) {
                throw new ServiceException("更新入库单状态失败");
            }
            shipmentHeader.setFirstStatus(QuantityConstant.SHIPMENT_HEADER_COMPLETED);
            shipmentHeader.setLastStatus(QuantityConstant.SHIPMENT_HEADER_COMPLETED);
            if (!shipmentHeaderService.updateById(shipmentHeader)) {
                throw new ServiceException("更新入库单状态失败");
            }

        }

        return AjaxResult.success();
    }

    public List<ReceiptHeader> getByDomain(ReceiptHeader receiptHeader){
        LambdaQueryWrapper<ReceiptHeader> lambdaQueryWrapper = Wrappers.lambdaQuery();
        lambdaQueryWrapper.eq(StringUtils.isNotEmpty(receiptHeader.getUserDef3()),ReceiptHeader::getUserDef3, receiptHeader.getUserDef3());
        lambdaQueryWrapper.eq(StringUtils.isNotEmpty(receiptHeader.getReferCode()),ReceiptHeader::getReferCode, receiptHeader.getReferCode());
        lambdaQueryWrapper.eq(StringUtils.isNotEmpty(receiptHeader.getCompanyCode()),ReceiptHeader::getCompanyCode, receiptHeader.getCompanyCode());
        lambdaQueryWrapper.ne(ReceiptHeader::getReceiptType,QuantityConstant.GT_RECEIPT_TYPE);
        lambdaQueryWrapper.ne(ReceiptHeader::getReceiptType,"JJP");
        return this.list(lambdaQueryWrapper);
    }

    /**
     * 回传U8
     * 单据类型 :PCI CI SRI SI
     * @param taskHeader
     * @param id
     * @param detailsQtyMap 单个任务中 每个单据明细的明细数量总和 出入单明细id -> 任务出入明细数量总和
     * @return
     */
    public AjaxResult postBack(TaskHeader taskHeader,String id, Map<Integer,BigDecimal> detailsQtyMap){
        AjaxResult ajaxResult = AjaxResult.error();
        ReceiptHeader receiptHeader = this.getById(id);
        String warehouseCode = receiptHeader.getWarehouseCode();
        if(receiptHeader==null){
            return AjaxResult.error("回传:入库单"+id+" 不存在。");
        }
        String type = receiptHeader.getReceiptType();
        ICSReceiptModel model = new ICSReceiptModel();
        String JsonParam = null;
        String url = null;
        CompanyU8 companyU8 = companyWuService.getCompanyU8ByCode(taskHeader.getCompanyCode(), taskHeader.getWarehouseCode());
        switch (type){
            case "PCI" :
                model = postBackByPCI(receiptHeader,type,detailsQtyMap);
                break;
            case "CI" :
                model = postBackByCI(receiptHeader,type,detailsQtyMap);
                break;
            case "SRI" :
                model = postBackBySRI(receiptHeader,type,detailsQtyMap);
                break;
            case "PI" :
            case "PII" :
                model = postBackByPI(receiptHeader,type,detailsQtyMap);
                break;
            case "SI" :
                model = postBackBySI(receiptHeader,type,taskHeader,detailsQtyMap);
                break;
            case "TI":
                ICSReceiptHeader icsReceiptHeaderTI = createICSReceiptHeader(receiptHeader,companyU8);
                ShipmentHeader shipmentHeader = shipmentHeaderService.getOne(new LambdaQueryWrapper<ShipmentHeader>()
                        .eq(ShipmentHeader::getReferCode, receiptHeader.getReferCode())
                        .eq(ShipmentHeader::getWarehouseCode, receiptHeader.getWarehouseCode()));
                if(StringUtils.isNotNull(shipmentHeader)){
                    if(shipmentHeader.getLastStatus().intValue() < 500){
                        return AjaxResult.error("对应调拨出库单未完成。出库单号"+receiptHeader.getReferCode());
                    }
                    //出库仓库
                    icsReceiptHeaderTI.setCWHCode(shipmentHeader.getUWarehouseCode());
                    //入库仓库
                    icsReceiptHeaderTI.setIWHCode(receiptHeader.getUWarehouseCode());
                }else{
                    return AjaxResult.error("未找到对应的调拨出库单。出库单号"+receiptHeader.getReferCode());
                }
                // 根据需求设置不同字段的值
                icsReceiptHeaderTI.setVoucherType("CreateICSRdRecord_0809");
                List<ICSReceiptDetail> icsReceiptDetailsTI = createICSReceiptDetails(receiptHeader,detailsQtyMap, companyU8,type);
                model.setIcsReceiptHeader(icsReceiptHeaderTI);
                model.setIcsReceiptDetails(icsReceiptDetailsTI);
                break;
            case "QI":
//            case "JJP":
                ICSReceiptHeader icsReceiptHeaderQI = createICSReceiptHeader(receiptHeader,companyU8);
                // 根据需求设置不同字段的值
                icsReceiptHeaderQI.setVoucherType("UpdateICSRdRecord_08_Confirm");
                List<ICSReceiptDetail> icsReceiptDetailsQI = createICSReceiptDetails(receiptHeader,detailsQtyMap, companyU8,type);
                model.setIcsReceiptHeader(icsReceiptHeaderQI);
                model.setIcsReceiptDetails(icsReceiptDetailsQI);
                break;
            default:
                return AjaxResult.error("该类型无需回传");
        }
        switch (type){
            case "PCI" :
            case "CI" :
            case "SRI" :
            case "PI" :
            case "PII" :
            case "SI" :
            case "TI" :
            case "QI" :
//            case "JJP" :
                url = addressService.selectAddress(QuantityConstant.U8_RECEIPT_BACK, warehouseCode);
                JsonParam = JSON.toJSONString(model);
                break;
            default:
        }

        String result = HttpUtils.bodypost(url, JsonParam,warehouseCode);
        ajaxResult = JSON.parseObject(result, AjaxResult.class);
        return ajaxResult;
    }

    // 创建 ICSReceiptHeader 对象并设置基本属性
    private ICSReceiptHeader createICSReceiptHeader(ReceiptHeader receiptHeader, CompanyU8 companyU8) {
        ICSReceiptHeader icsReceiptHeader = new ICSReceiptHeader();
        icsReceiptHeader.setID(receiptHeader.getReferId());
        icsReceiptHeader.setCCode(receiptHeader.getReferCode());
        icsReceiptHeader.setDDate(DateUtils.getTime());
        icsReceiptHeader.setCWHCode(receiptHeader.getUWarehouseCode());
        icsReceiptHeader.setCMaker(receiptHeader.getCreatedBy());
        icsReceiptHeader.setCVerifier(receiptHeader.getLastUpdatedBy());
        icsReceiptHeader.setCompanyCode(companyU8.getUCompanyCode());
        return icsReceiptHeader;
    }

    // 创建 ICSReceiptDetail 列表并设置属性
    private List<ICSReceiptDetail> createICSReceiptDetails(ReceiptHeader receiptHeader,Map<Integer, BigDecimal> detailsQtyMap, CompanyU8 companyU8, String type) {
        List<ICSReceiptDetail> icsReceiptDetails = new ArrayList<>();

        for (Integer receiptDetailId : detailsQtyMap.keySet()) {
            ReceiptDetail receiptDetail = receiptDetailService.getById(receiptDetailId);
            ICSReceiptDetail icsReceiptDetail = new ICSReceiptDetail();
            icsReceiptDetail.setID(receiptHeader.getReferId());
            icsReceiptDetail.setAutoID(receiptDetail.getAutoId());
            icsReceiptDetail.setCItemName(receiptDetail.getProjectNo());
            icsReceiptDetail.setCInvCode(receiptDetail.getMaterialCode());
            icsReceiptDetail.setIQuantity(detailsQtyMap.get(receiptDetailId));
            icsReceiptDetail.setCompanyCode(companyU8.getUCompanyCode());

            // 根据类型设置不同字段的值
            switch (type) {
                case "TI":
                    // 根据需求设置不同字段的值
                    icsReceiptDetail.setITrIds(receiptDetail.getAutoId());
                    break;
                case "QI":
                    // 根据需求设置不同字段的值
                    icsReceiptDetail.setIQuantity(receiptDetail.getQty());
                    icsReceiptDetail.setCQuantity(detailsQtyMap.get(receiptDetailId));
                    break;
                default:
                    // 处理其他类型的情况
                    break;
            }

            icsReceiptDetails.add(icsReceiptDetail);
        }

        return icsReceiptDetails;
    }

    /**
     * 回传MES
     * 单据类型 : SI
     * @param taskHeader
     * @param id
     * @param detailsQtyMap
     * @return
     */
    public AjaxResult postBack2Mes(TaskHeader taskHeader,String id, Map<Integer,BigDecimal> detailsQtyMap){
        AjaxResult ajaxResult = AjaxResult.error();
        ReceiptHeader receiptHeader = this.getById(id);
        String warehouseCode = receiptHeader.getWarehouseCode();
        if(receiptHeader==null){
            return AjaxResult.error("回传:入库单"+id+" 不存在。");
        }
        String type = receiptHeader.getReceiptType();
        ICSReceiptModel model = null;
        String JsonParam = null;
        String url = null;
        switch (type){
            case "SI" :
                model = postBackBySI2Mes(receiptHeader,type,taskHeader);
                break;
        }
        switch (type){
            case "PCI" :
            case "CI" :
            case "SRI" :
            case "PI" :
            case "SI" :
                url = addressService.selectAddress(QuantityConstant.MES_RECEIPT_BACK, warehouseCode);
                JsonParam = JSON.toJSONString(model);
                break;
        }
        String msg = "接口地址错误或服务器连接不到或返回为空";
        ApiLog log = null;
        HttpHeaders headers = new HttpHeaders();
        try {
            log = ApiLogAspect.initApiLog("post", url,
                    JsonParam, headers, warehouseCode);
            String result = HttpUtils.bodypost(url, JsonParam,warehouseCode);
            if(StringUtils.isEmpty(result)){
                return AjaxResult.error("接口地址错误或服务器连接不到或返回为空");
            }
            ajaxResult = JSON.parseObject(result, AjaxResult.class);
            msg = JSON.toJSONString(ajaxResult);
        }catch (Exception e) {
            e.printStackTrace();
            ApiLogAspect.setApiLogException(log, e);
        } finally {
            ApiLogAspect.finishApiLog(log, headers, msg);
        }
        return ajaxResult;
    }

    public AjaxResult postBack2SRM(ReceiptHeader receiptHeader,List<Map> list,Map<Integer,BigDecimal> detailsQtyMap){
        String warehouseCode = receiptHeader.getWarehouseCode();
        if(QuantityConstant.PLATFORM_SRM.equals(receiptHeader.getSourcePlatform())){
            List<ICSRuternASN> icsRuternASNs = new ArrayList<>();
            for (Map map : list) {
                String returnCode=map.get("Code").toString();
                String irowno=map.get("irowno").toString();
                String autoId=map.get("AutoID").toString();

                ReceiptDetail receiptDetail = receiptDetailService.getOne(new LambdaQueryWrapper<ReceiptDetail>()
                        .eq(ReceiptDetail::getAutoId, autoId)
                        .eq(ReceiptDetail::getWarehouseCode,warehouseCode));
                if(receiptDetail !=null){
                    receiptDetail.setReferLineNum(irowno);
                    receiptDetailService.updateById(receiptDetail);
                }
                TaskDetail taskDetail = taskDetailService.getOne(new LambdaQueryWrapper<TaskDetail>()
                        .eq(TaskDetail::getBillDetailId, receiptDetail.getId())
                        .eq(TaskDetail::getWarehouseCode,warehouseCode)
                        .last("LIMIT 1"));
                ICSRuternASN icsRuternASN = new ICSRuternASN();
                String toLocation = taskDetail.getToLocation();
                Location location = locationService.getLocationByCode(toLocation, warehouseCode);
                if(location!=null) {
                    icsRuternASN.setSerial(location.getId().toString());
                }
                icsRuternASN.setReturnDoc(returnCode);
                icsRuternASN.setReturnDocLine(Integer.valueOf(irowno));
                icsRuternASN.setLotNo(receiptDetail.getUserDef2());
                icsRuternASN.setBinCode(toLocation);
                icsRuternASN.setLotQty(taskDetail.getQty().doubleValue());
                icsRuternASN.setUser(taskDetail.getLastUpdatedBy());
                icsRuternASN.setMUSERName(taskDetail.getCreatedBy());
                icsRuternASN.setMTime(DateUtils.parseDateToStr(DateUtils.YYYY_MM_DD_HH_MM_SS,DateUtils.getNowDate()));
                icsRuternASNs.add(icsRuternASN);
            }
            if(!icsRuternASNs.isEmpty()){
                AjaxResult ajaxResult = icsasnService.returnICSRuternASN(icsRuternASNs, warehouseCode);
                return ajaxResult;
            }
        }
        return AjaxResult.success();
    }

    private ICSReceiptModel postBackBySI2Mes(ReceiptHeader receiptHeader,String type,TaskHeader taskHeader){
        ICSReceiptModel model = new ICSReceiptModel();
        if(!type.equals(QuantityConstant.U8_RECEIPT_TYPE_CI)){
            return model;
        }
        MesPostBack mesPostBack = new MesPostBack();
        mesPostBack.setLotno(receiptHeader.getReferCode());
        User user=new User();
        user.setUserName(taskHeader.getCreatedBy());
        List<User> users = userService.selectUserList(user);
        if(CollectionUtils.isNotEmpty(users)){
            mesPostBack.setMuser(users.get(0).getLoginName());
        }else {
            mesPostBack.setMuser(taskHeader.getCreatedBy());
        }
        String warehouseCode = taskHeader.getWarehouseCode();
        String companyCode = taskHeader.getCompanyCode();
        CompanyU8 companyU8 = companyWuService.getCompanyU8ByCode(companyCode, warehouseCode);
        mesPostBack.setType(companyU8.getUCompanyCode().substring(7,10));

        return model;
    }
    private ICSReceiptModel postBackBySI(ReceiptHeader receiptHeader,String type,TaskHeader taskHeader,Map<Integer,BigDecimal> detailsQtyMap){
        ICSReceiptModel model = new ICSReceiptModel();
        if(!type.equals(QuantityConstant.MES_RECEIPT_TYPE_SI)){
            return model;
        }
        List<ReceiptDetail> details = receiptDetailService.findByReceiptId(receiptHeader.getId());
        ICSReceiptHeader headerByCI = icsReceiptHeaderService.getHeaderBySI(receiptHeader,taskHeader);
        List<ICSReceiptDetail> detailsByCI = icsReceiptDetailService.getDetailsBySI(details,headerByCI,detailsQtyMap);
        model.setIcsReceiptHeader(headerByCI);
        model.setIcsReceiptDetails(detailsByCI);
        return model;
    }
    private ICSReceiptModel postBackByPCI(ReceiptHeader receiptHeader,String type,Map<Integer,BigDecimal> detailsQtyMap){
        ICSReceiptModel model = new ICSReceiptModel();
        if(!type.equals(QuantityConstant.U8_RECEIPT_TYPE_PCI)){
            return model;
        }
        ICSReceiptHeader icsReceiptHeader = new ICSReceiptHeader();
        return model;
    }
    private ICSReceiptModel postBackByCI(ReceiptHeader receiptHeader,String type,Map<Integer,BigDecimal> detailsQtyMap){
        ICSReceiptModel model = new ICSReceiptModel();
        if(!type.equals(QuantityConstant.U8_RECEIPT_TYPE_CI)){
            return model;
        }
        List<ReceiptDetail> details = receiptDetailService.findByReceiptId(receiptHeader.getId());
        ICSReceiptHeader headerByCI = icsReceiptHeaderService.getHeaderByCI(receiptHeader);
        List<ICSReceiptDetail> detailsByCI = icsReceiptDetailService.getDetailsByCI(details,headerByCI,detailsQtyMap);
        model.setIcsReceiptHeader(headerByCI);
        model.setIcsReceiptDetails(detailsByCI);
        return model;
    }
    private ICSReceiptModel postBackByPI(ReceiptHeader receiptHeader,String type,Map<Integer,BigDecimal> detailsQtyMap){
        ICSReceiptModel model = new ICSReceiptModel();
        if(!type.equals(QuantityConstant.U8_RECEIPT_TYPE_PI)&&!type.equals(QuantityConstant.U8_RECEIPT_TYPE_PII)){
            return model;
        }
        List<ReceiptDetail> details = receiptDetailService.findByReceiptId(receiptHeader.getId());
        ICSReceiptHeader headerByPI = icsReceiptHeaderService.getHeaderByPI(receiptHeader);
        List<ICSReceiptDetail> detailsByPI = icsReceiptDetailService.getDetailsByPI(details,headerByPI,detailsQtyMap);
        model.setIcsReceiptHeader(headerByPI);
        model.setIcsReceiptDetails(detailsByPI);
        return model;
    }
    private ICSReceiptModel postBackBySRI(ReceiptHeader receiptHeader,String type,Map<Integer,BigDecimal> detailsQtyMap){
        ICSReceiptModel model = new ICSReceiptModel();
        if(!type.equals(QuantityConstant.U8_RECEIPT_TYPE_SRI)){
            return model;
        }
        List<ReceiptDetail> details = receiptDetailService.findByReceiptId(receiptHeader.getId());
        ICSReceiptHeader headerBySRI = icsReceiptHeaderService.getHeaderBySRI(receiptHeader);
        List<ICSReceiptDetail> detailsBySRI = icsReceiptDetailService.getDetailsBySRI(details,headerBySRI,detailsQtyMap);
        model.setIcsReceiptHeader(headerBySRI);
        model.setIcsReceiptDetails(detailsBySRI);
        return model;
    }

    public List<ReceiptHeader> selectListhuichuanLimit100(ReceiptHeader receiptHeader){
        LambdaQueryWrapper<ReceiptHeader> lambdaQueryWrapper = Wrappers.lambdaQuery();
        lambdaQueryWrapper.eq(StringUtils.isNull(receiptHeader.getFirstStatus()),ReceiptHeader::getFirstStatus, receiptHeader.getFirstStatus());
        lambdaQueryWrapper.eq(StringUtils.isNull(receiptHeader.getLastStatus()),ReceiptHeader::getLastStatus, receiptHeader.getLastStatus());
        lambdaQueryWrapper.eq(ReceiptHeader::getDeleted, 0);
        lambdaQueryWrapper.lt(ReceiptHeader::getCreated, DateUtils.getNowPreDay(DateUtils.YYYY_MM_DD_HH_MM_SS));
        lambdaQueryWrapper.last("limit 7");
        return this.list(lambdaQueryWrapper);
    }

    public List<ReceiptHeader> getHistoryReceiptHeader(String num){
        LambdaQueryWrapper<ReceiptHeader> lambdaQueryWrapper = Wrappers.lambdaQuery();
        lambdaQueryWrapper.eq(ReceiptHeader::getFirstStatus,num);
        lambdaQueryWrapper.eq(ReceiptHeader::getDeleted, 0);
        lambdaQueryWrapper.lt(ReceiptHeader::getCreated, DateUtils.getNowPreWeek(DateUtils.YYYY_MM_DD_HH_MM_SS));
        lambdaQueryWrapper.last("limit 1");
        return this.list(lambdaQueryWrapper);
    }

    public ReceiptHeader selectFirstEntity( ReceiptHeader receiptHeader){
        LambdaQueryWrapper<ReceiptHeader> lambdaQueryWrapper = new LambdaQueryWrapper<>();
        lambdaQueryWrapper.eq(StringUtils.isNotEmpty(receiptHeader.getCode()),ReceiptHeader::getCode, receiptHeader.getCode());
        lambdaQueryWrapper.eq(StringUtils.isNotEmpty(receiptHeader.getCompanyCode()),ReceiptHeader::getCompanyCode, receiptHeader.getCompanyCode());
        lambdaQueryWrapper.eq(StringUtils.isNotEmpty(receiptHeader.getWarehouseCode()),ReceiptHeader::getWarehouseCode, receiptHeader.getWarehouseCode());
        lambdaQueryWrapper.eq(StringUtils.isNotEmpty(receiptHeader.getReferCode()),ReceiptHeader::getReferCode, receiptHeader.getReferCode());
        lambdaQueryWrapper.last("limit 1");
        return this.getOne(lambdaQueryWrapper);
    }

    public List<ReceiptHeader> listByCodes(Collection<String> codes,String warehouseCode){
        if(codes == null || codes.isEmpty()){
            return Collections.emptyList();
        }
        List<ReceiptHeader> receiptHeaders = this.list(new LambdaQueryWrapper<ReceiptHeader>()
                .in(ReceiptHeader::getCode, codes)
                .eq(ReceiptHeader::getWarehouseCode, warehouseCode));

        return receiptHeaders;
    }

    public AjaxResult yueku(String ids) {
        Integer[] idArray = Convert.toIntArray(ids);
        for (Integer id : idArray) {
            ReceiptHeader receiptHeader=this.getById(id);
            if(receiptHeader==null){
                return AjaxResult.error("找不到主单据");
            }
            List<ReceiptDetail> receiptDetails=receiptDetailService.getByHeaderCode(receiptHeader.getCode());
            if(receiptDetails==null && receiptDetails.size()<1){
                return AjaxResult.error("找不到子单据");
            }
            for(ReceiptDetail item :receiptDetails){
                ReceiptContainerView record=new ReceiptContainerView();
                record.setReceiptCode(receiptHeader.getCode());
                record.setReceiptDetailId(item.getId());
                record.setQty(item.getQty().subtract(item.getTaskQty()));

                //根据单据货主和仓库找到虚拟容器和库位
                Container container=containerService.getOne(new LambdaQueryWrapper<Container>()
                        .eq(Container::getWarehouseCode,ShiroUtils.getWarehouseCode())
                        .eq(Container::getContainerType,"X")
                        .orderByAsc(Container::getCode)
                        .last("limit 1"));
                if(container == null){
                    return AjaxResult.error("系统没有此货主的虚拟容器");
                }
                record.setContainerCode(container.getCode());
                record.setLocationCode(container.getLocationCode());
                //入库组盘并生成任务
                receiptContainerHeaderService.saveContainer(record);

                LambdaQueryWrapper<ReceiptContainerHeader> lambdaQueryWrapper= Wrappers.lambdaQuery();
                lambdaQueryWrapper.eq(ReceiptContainerHeader::getContainerCode,record.getContainerCode());
                lambdaQueryWrapper.le(ReceiptContainerHeader::getStatus,10);
                List<ReceiptContainerHeader> receiptContainerHeaders=receiptContainerHeaderService.list(lambdaQueryWrapper);
                for(ReceiptContainerHeader receiptContainerHeader:receiptContainerHeaders) {
                    String i = receiptContainerHeader.getId().toString();
                    Integer[] idArrays = Convert.toIntArray(i);
                    List<Integer> islist= Arrays.asList(idArrays);
                    try {
                        AjaxResult ajaxResult1=receiptTaskService.createReceiptTask(islist);
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                }
            }
            //完成任务
            List<TaskHeader> tasks=taskHeaderService.list(new LambdaQueryWrapper<TaskHeader>().likeRight(TaskHeader::getContainerCode,"X")
                    .eq(TaskHeader::getStatus,QuantityConstant.TASK_STATUS_BUILD)
                    .eq(TaskHeader::getWarehouseCode,ShiroUtils.getWarehouseCode()));
            if(tasks!=null && tasks.size()>0) {
                for (TaskHeader tas:tasks) {
                    taskHeaderService.completeTask(tas);
                }
            }
        }
        return AjaxResult.success("越库成功");
    }

    public List<ReceiptHeader> getExpiredBill() {
        List<ReceiptHeader> receiptHeaderList = receiptHeaderMapper.getExpiredBill();
        return receiptHeaderList;
    }
    //清理入库单
    @Transactional(rollbackFor = Exception.class)
    public int cleanDocuments() {
        //查找过期的入库单据
        String expireTime=DateUtils.getNowPreDays("yyyy-MM-dd 00:00:00", 150);
        LambdaQueryWrapper<ReceiptHeader>  receWrapper=new LambdaQueryWrapper<>();
        receWrapper.lt(ReceiptHeader::getCreated,expireTime);
//        receWrapper.ge(ReceiptHeader::getLastStatus,800);
        receWrapper.last("limit 20");
        List<ReceiptHeader> receiptHeaderList= this.list(receWrapper);
//        List<ReceiptHeader> receiptHeaderList = this.getExpiredBill();
        if (receiptHeaderList.isEmpty()) {
            return 1;
        }
        for (ReceiptHeader receiptHeader : receiptHeaderList) {
            this.deleteHeaderHistory(receiptHeader.getId());
        }
        return 1;
    }
    public AjaxResult deleteHeaderHistory(Integer id){
        ReceiptHeader receiptHeader = this.getById(id);
        if (receiptHeader == null) {
            return AjaxResult.error("没有找到单据" + String.valueOf(id));
        }
        LambdaQueryWrapper<ReceiptDetail> lambdaQueryWrapper = Wrappers.lambdaQuery();
        lambdaQueryWrapper.eq(ReceiptDetail::getReceiptId, id);
        List<ReceiptDetail> list = receiptDetailService.list(lambdaQueryWrapper);

        List<ReceiptDetailHistory> receiptDetailHistoryList = new ArrayList<>();
        if (!this.removeById(receiptHeader)) {
            throw new ServiceException("删除头表失败");
        }
        List<Integer> receiptDetailIds = new ArrayList<>();
        ReceiptHeaderHistory receiptHeaderHistory = new ReceiptHeaderHistory();
        BeanUtils.copyProperties(receiptHeader, receiptHeaderHistory);
        receiptHeaderHistory.setLastUpdated(new Date());
        if (!receiptheaderhistoryService.save(receiptHeaderHistory)) {
            throw new ServiceException("新增历史头表失败");
        }
        for (ReceiptDetail receiptDetail: list) {
            receiptDetailIds.add(receiptDetail.getId());
            ReceiptDetailHistory receiptDetailHistory = new ReceiptDetailHistory();
            BeanUtils.copyProperties(receiptDetail, receiptDetailHistory);
            receiptDetailHistory.setReceiptId(receiptHeaderHistory.getId());
            receiptDetailHistoryList.add(receiptDetailHistory);
        }
        if(receiptDetailIds.size() > 0) {
            if (!receiptDetailService.removeByIds(receiptDetailIds)) {
                throw new ServiceException("删除明细表失败");
            }
        }
        if(receiptDetailHistoryList.size() > 0) {
            if (!receiptDetailHistoryService.saveBatch(receiptDetailHistoryList)) {
                throw new ServiceException("新增历史入库明细失败");
            }
        }
        return AjaxResult.success("删除成功");
    }
    public AjaxResult deleteHeaderAndDetail(String ids,boolean isErp){
        List<Integer> idList = Arrays.asList(Convert.toIntArray(ids));
        for (Integer id : idList) {
            ReceiptHeader receiptHeader = this.getById(id);
            if (receiptHeader == null) {
                return AjaxResult.error("没有找到单据" + String.valueOf(id));
            }
            if(!isErp){
                if(StringUtils.isNotEmpty(receiptHeader.getReferCode())){
                    return AjaxResult.error("上游下发的单子只能从上游取消:" + receiptHeader.getReferCode());
                }
            }
            if(receiptHeader.getFirstStatus() >= QuantityConstant.RECEIPT_HEADER_POSTING) {
                return AjaxResult.error("订单状态大于800收货不能删除");
            }
            LambdaQueryWrapper<ReceiptDetail> lambdaQueryWrapper = new LambdaQueryWrapper<>();
            lambdaQueryWrapper.eq(ReceiptDetail::getReceiptId, id);
            List<ReceiptDetail> list = receiptDetailService.list(lambdaQueryWrapper);
            for(ReceiptDetail receiptDetail:list){
                if(Integer.parseInt(receiptDetail.getProcessStamp())> QuantityConstant.RECEIPT_HEADER_WAIT){
                    throw new ServiceException("入库明细物料:"+receiptDetail.getMaterialName()+"已收货,不能删除");
                }
            }
            List<ReceiptDetailHistory> receiptDetailHistoryList = new ArrayList<>();
            if (!this.removeById(receiptHeader)) {
                throw new ServiceException("删除头表失败");
            }
            List<Integer> receiptDetailIds = new ArrayList<>();
            ReceiptHeaderHistory receiptHeaderHistory = new ReceiptHeaderHistory();
            BeanUtils.copyProperties(receiptHeader, receiptHeaderHistory);
            if (!receiptheaderhistoryService.save(receiptHeaderHistory)) {
                throw new ServiceException("新增历史头表失败");
            }
            for (ReceiptDetail receiptDetail: list) {
                receiptDetailIds.add(receiptDetail.getId());
                ReceiptDetailHistory receiptDetailHistory = new ReceiptDetailHistory();
                BeanUtils.copyProperties(receiptDetail, receiptDetailHistory);
                receiptDetailHistory.setReceiptId(receiptHeaderHistory.getId());
                receiptDetailHistoryList.add(receiptDetailHistory);
            }
            if(receiptDetailIds.size() > 0) {
                if (!receiptDetailService.removeByIds(receiptDetailIds)) {
                    throw new ServiceException("删除明细表失败");
                }
            }
            if(receiptDetailHistoryList.size() > 0) {
                if (!receiptDetailHistoryService.saveBatch(receiptDetailHistoryList)) {
                    throw new ServiceException("新增历史入库明细失败");
                }
            }
        }
        return AjaxResult.success("删除成功");
    }

    public List<ReceiptHeader> selectSIComplete() {
        return receiptHeaderMapper.selectSIComplete();
    }

    public boolean updateReceiptHeader(Integer id) {
        LambdaQueryWrapper<ReceiptDetail> receiptDetailLambdaQueryWrapper = com.baomidou.mybatisplus.core.toolkit.Wrappers.lambdaQuery();
        receiptDetailLambdaQueryWrapper.eq(ReceiptDetail::getReceiptId, id);
        List<ReceiptDetail> receiptDetailList = receiptDetailService.list(receiptDetailLambdaQueryWrapper);
        ReceiptHeader receiptHeader = receiptHeaderService.getById(id);
        if (receiptHeader == null) {
            return false;
        }
        BigDecimal totalQty = new BigDecimal(0);
        int totalLines = 0;
        for (ReceiptDetail receiptDetail : receiptDetailList) {
            totalLines++;
            totalQty = totalQty.add(receiptDetail.getQty());
        }
        receiptHeader = new ReceiptHeader();
        receiptHeader.setId(id);
        receiptHeader.setTotalQty(totalQty);
        receiptHeader.setTotalLines(totalLines);
        if (!receiptHeaderService.updateById(receiptHeader)) {
            return false;
        }
        return true;
    }

    public List<ReceiptHeader> getReceiptHeaderByReferCode(String referCode, String warehouseCode) {
        LambdaQueryWrapper<ReceiptHeader> LambdaQueryWrapper = new LambdaQueryWrapper<>();
        LambdaQueryWrapper.eq(ReceiptHeader::getReferCode, referCode);
        List<ReceiptHeader> receiptHeaders = list(LambdaQueryWrapper);
        return receiptHeaders;
    }
}