ReceiptDetailServiceImpl.java 32.7 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
package com.huaheng.pc.receipt.receiptDetail.service;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.huaheng.common.exception.BusinessException;
import com.huaheng.common.utils.Wrappers;
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.security.ShiroUtils;
import com.huaheng.framework.web.domain.AjaxResult;
import com.huaheng.mobile.receipt.ReceiptBill;
import com.huaheng.pc.check.checkHeader.domain.CheckHeader;
import com.huaheng.pc.check.checkHeader.service.CheckHeaderService;
import com.huaheng.pc.config.company.domain.Company;
import com.huaheng.pc.config.company.service.CompanyService;
import com.huaheng.pc.config.configValue.domain.ConfigValue;
import com.huaheng.pc.config.configValue.service.ConfigValueService;
import com.huaheng.pc.config.material.domain.Material;
import com.huaheng.pc.config.material.service.MaterialService;
import com.huaheng.pc.config.materialType.domain.MaterialType;
import com.huaheng.pc.config.materialType.service.MaterialTypeService;
import com.huaheng.pc.config.receiptPreference.domain.ReceiptPreference;
import com.huaheng.pc.config.receiptPreference.service.ReceiptPreferenceService;
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.statusFlow.service.StatusFlowDetailService;
import com.huaheng.pc.receipt.receiptContainerDetail.domain.ReceiptContainerDetail;
import com.huaheng.pc.receipt.receiptHeader.domain.ReceiptHeader;
import com.huaheng.pc.receipt.receiptHeader.service.ReceiptHeaderService;
import com.huaheng.pc.system.config.domain.Config;
import com.huaheng.pc.system.dict.domain.DictData;
import com.huaheng.pc.system.dict.service.IDictDataService;
import com.huaheng.pc.task.taskDetail.domain.TaskDetail;
import io.swagger.models.auth.In;
import org.aspectj.weaver.loadtime.Aj;
import org.springframework.stereotype.Service;
import javax.annotation.Resource;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Set;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.huaheng.pc.receipt.receiptDetail.domain.ReceiptDetail;
import com.huaheng.pc.receipt.receiptDetail.mapper.ReceiptDetailMapper;
import com.huaheng.pc.receipt.receiptDetail.service.ReceiptDetailService;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

@Service
public class ReceiptDetailServiceImpl extends ServiceImpl<ReceiptDetailMapper, ReceiptDetail> implements ReceiptDetailService{

    @Resource
    private MaterialService materialService;
    @Resource
    private ReceiptHeaderService receiptHeaderService;
    @Resource
    private ReceiptTypeService receiptTypeService;
    @Resource
    private StatusFlowDetailService statusFlowDetailService;
    @Resource
    private MaterialTypeService materialTypeService;
    @Resource
    private ReceiptPreferenceService receiptPreferenceService;
    @Resource
    private IDictDataService dictDataService;
    @Resource
    private CheckHeaderService checkHeaderService;
    @Resource
    private ConfigValueService configValueService;
    @Resource
    private ReceiptDetailMapper receiptDetailMapper;
    @Resource
    private CompanyService companyService;

    /**
     * 新增入库明细
     * @param receiptDetail
     * @return
     */
    @Transactional(rollbackFor = Exception.class)
    @Override
    public AjaxResult saveReceiptDetaial(ReceiptDetail receiptDetail){
        /* 判断入库头表状态*/
        LambdaQueryWrapper<ReceiptHeader> lambdaReceiptHeader = Wrappers.lambdaQuery();
        lambdaReceiptHeader.eq(ReceiptHeader::getId, receiptDetail.getReceiptId());
        ReceiptHeader receiptHeader = receiptHeaderService.getOne(lambdaReceiptHeader);

        //判断入库头表状态
        if (receiptHeader == null ){
            throw new ServiceException("找不到主单据");
        } else if (receiptHeader.getFirstStatus() > QuantityConstant.RECEIPT_HEADER_POOL){
            throw new ServiceException("单据进入订单池后,不允许新增明细");
        } else if (receiptHeader.getFirstStatus() == 20) {
            throw new ServiceException("单据已作废");
        }
        receiptDetail.setReceiptCode(receiptHeader.getCode());

        /* 判断物料编码*/
        LambdaQueryWrapper<Material> lambdaQueryWrapper = Wrappers.lambdaQuery();
        lambdaQueryWrapper.eq(Material::getCode, receiptDetail.getMaterialCode());
        lambdaQueryWrapper.eq(Material::getWarehouseCode, ShiroUtils.getWarehouseCode());
        Material material = materialService.getOne(lambdaQueryWrapper);
        if (material == null) {
            throw new ServiceException("物料不存在");
        }
        receiptDetail.setCompanyCode(receiptHeader.getCompanyCode());
        receiptDetail.setMaterialCode(material.getCode());
        receiptDetail.setMaterialName(material.getName());
        receiptDetail.setMaterialSpec(material.getSpec());
        receiptDetail.setMaterialUnit(material.getUnit());

        receiptDetail.setInventorySts(QuantityConstant.GOOD);
        receiptDetail.setCreatedBy(ShiroUtils.getLoginName());
        receiptDetail.setLastUpdatedBy(ShiroUtils.getLoginName());
        receiptDetail.setWarehouseCode(ShiroUtils.getWarehouseCode());

        //根据流程配置更新入库明细下一流程
        ReceiptDetail receiptDetail1 = queryflow(receiptDetail);

        if (this.save(receiptDetail1)) {
//            receiptHeader.setTotalQty(receiptHeader.getTotalQty().add(receiptDetail1.getTotalQty()));
//            receiptHeader.setTotalLines(receiptHeader.getTotalLines()+1);
//            receiptHeaderService.updateById(receiptHeader);
            updateReceiptHeader(receiptHeader);
            return AjaxResult.success("新增单据明细成功");
        } else {
            return AjaxResult.error("新增单据明细失败!");
        }

    }

    /**
     * 修改入库明细
     * @param receiptDetail
     * @return
     */
    @Override
    @Transactional
    public AjaxResult updateReceiptDetaial(ReceiptDetail receiptDetail) {
        /* 先修改入库头表中的总数量和总行数,再更新记录,完成后更新入库头表中总数量和总行数*/

        //查询原记录
        ReceiptDetail originalReceiptDetail= this.getById(receiptDetail.getId());
        ReceiptHeader receiptHeader = receiptHeaderService.getById(receiptDetail.getReceiptId());
        //判断物料编码是否被修改
        if (!originalReceiptDetail.getMaterialCode().equals(receiptDetail.getMaterialCode())){
            LambdaQueryWrapper<Material> lambdaMaterial = Wrappers.lambdaQuery();
            lambdaMaterial.eq(Material::getCode,receiptDetail.getMaterialCode());
            Material material = materialService.getOne(lambdaMaterial);
            if (material == null) {
                throw new ServiceException("该物料编码不存在");

            }else {
                receiptDetail.setMaterialName(material.getName());
                receiptDetail.setMaterialSpec(material.getSpec());
                receiptDetail.setMaterialUnit(material.getUnit());
//                receiptDetail.setProcessStamp("0");
//                receiptHeader.setTotalQty(receiptHeader.getTotalQty().subtract(originalReceiptDetail.getTotalQty()));
//                receiptHeader.setTotalLines(receiptHeader.getTotalLines()-1);
//                if ( !receiptHeaderService.updateById(receiptHeader)){
//                    return AjaxResult.error("入库头表更新失败");
//                }
            }
        }
        //如果单据状态为驳回则设置状态为提交审核
        if ("10".equals(receiptDetail.getProcessStamp())){
            receiptDetail.setProcessStamp("5");
        }
        receiptDetail.setLastUpdatedBy(ShiroUtils.getLoginName());
        if ( !this.updateById(receiptDetail) ){
            return AjaxResult.error("入库明细更新失败");
        } else {

            updateReceiptHeader(receiptHeader);
            return AjaxResult.success("修改单据明细成功");
        }
    }

    /**
     * 更新入库单头表状态
     * @param receiptHeader 入库单按头表
     * @return
     */
    @Override
    public AjaxResult updateReceiptHeader(ReceiptHeader receiptHeader) {
        BigDecimal totalQty = new BigDecimal(0);
        int totalLines = 0;
        LambdaQueryWrapper<ReceiptDetail> receiptDetailLambdaQueryWrapper = Wrappers.lambdaQuery();
        receiptDetailLambdaQueryWrapper.eq(ReceiptDetail::getReceiptId,receiptHeader.getId());
        List<ReceiptDetail> receiptDetailList =  list(receiptDetailLambdaQueryWrapper);
        for(ReceiptDetail receiptDetail : receiptDetailList) {
            totalLines++;
            totalQty = totalQty.add(receiptDetail.getQty());
        }
        receiptHeader.setTotalQty(totalQty);
        receiptHeader.setTotalLines(totalLines);
        if (!receiptHeaderService.updateById(receiptHeader)){
            return AjaxResult.error("入库头表更新失败");
        }
        return AjaxResult.success("入库头表更新成功");
    }

    @Override
    public List<ReceiptDetail> findByReceiptId(Integer id) {
        LambdaQueryWrapper<ReceiptDetail> queryWrapper = Wrappers.lambdaQuery();
        queryWrapper.eq(ReceiptDetail::getReceiptId, id);
        return list(queryWrapper);
    }

    /**
     * 根据流程配置更新入库明细下一流程
     * 1.先查询入库子表要没有设置入库流程
     * 2.查询入库主表的入库单据流程
     * 3.物料是否有入库流程
     * 4.物料类别是否有入库流程
     * 5.入库首选项的入库流程
     * @param receiptDetail
     * @return
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public ReceiptDetail queryflow(ReceiptDetail receiptDetail){
        //当单据状态为驳回或作废时不更新状态
        if (QuantityConstant.RECEIPT_HEADER_REJECTED.toString().equals(receiptDetail.getProcessStamp()) || QuantityConstant.RECEIPT_HEADER_OBSOLETE.toString().equals(receiptDetail.getProcessStamp())){
            return receiptDetail;
        }

        //如果入库明细绑定了入库流程则从入库明细中选择流程
        if ( StringUtils.isNotEmpty(receiptDetail.getStatusFlowCode())){
            List<StatusFlowDetail> statusFlowDetails = statusFlowDetailService.queryStatusFlowDetail(receiptDetail.getStatusFlowCode());
            String status = nextStatusFlow(statusFlowDetails, receiptDetail.getProcessStamp());
            //在状态到达时候是判断是否要质检
            if (QuantityConstant.RECEIPT_HEADER_RECEIVING.toString().equals(status) && inspection(receiptDetail)){
                receiptDetail.setProcessStamp(QuantityConstant.RECEIPT_HEADER_CHECK.toString());
            } else {
                receiptDetail.setProcessStamp(status);
            }
            return receiptDetail;
        }
        //查询头表信息
        LambdaQueryWrapper<ReceiptHeader> lambdaReceiptHeader = Wrappers.lambdaQuery();
        lambdaReceiptHeader.eq(ReceiptHeader::getCode, receiptDetail.getReceiptCode());
        lambdaReceiptHeader.last("limit 1");
        ReceiptHeader receiptHeader = receiptHeaderService.getOne(lambdaReceiptHeader);

        //查询明细表中入库物料信息
        LambdaQueryWrapper<Material> lambdaMaterial = Wrappers.lambdaQuery();
        lambdaMaterial.eq(Material::getCode, receiptDetail.getMaterialCode());
        lambdaMaterial.eq(Material::getWarehouseCode, ShiroUtils.getWarehouseCode());
        lambdaMaterial.last("limit 1");
        Material material = materialService.getOne(lambdaMaterial);

        //查询头表中绑定的入库类型中的入库流程
        LambdaQueryWrapper<ReceiptType> lambdaReceiptType = Wrappers.lambdaQuery();
        lambdaReceiptType.eq(ReceiptType::getCode,  receiptHeader.getReceiptType())
                .eq(ReceiptType::getWarehouseCode,ShiroUtils.getWarehouseCode())
                .eq(ReceiptType::getCompanyCode, receiptDetail.getCompanyCode());
        lambdaReceiptType.last("limit 1");
        ReceiptType receiptType = receiptTypeService.getOne(lambdaReceiptType);


        if (receiptType.getReceiptFlow() != null){
            //物料是否有入库流程
            List<StatusFlowDetail> statusFlowDetails = statusFlowDetailService.queryStatusFlowDetail(receiptType.getReceiptFlow());
            String status = nextStatusFlow(statusFlowDetails, receiptDetail.getProcessStamp());
            //在状态到达时候是判断是否要质检
            if (QuantityConstant.RECEIPT_HEADER_RECEIVING.toString().equals(status) && inspection(receiptDetail)){
                receiptDetail.setProcessStamp(QuantityConstant.RECEIPT_HEADER_CHECK.toString());
            } else {
                receiptDetail.setProcessStamp(status);
            }
            return receiptDetail;
        } else if (material.getReceivingFlow() != null){
            //物料是否有入库流程
            List<StatusFlowDetail> statusFlowDetails = statusFlowDetailService.queryStatusFlowDetail(material.getReceivingFlow());
            String status = nextStatusFlow(statusFlowDetails, receiptDetail.getProcessStamp());
            //在状态到达时候是判断是否要质检
            if (QuantityConstant.RECEIPT_HEADER_RECEIVING.toString().equals(status) && inspection(receiptDetail)){
                receiptDetail.setProcessStamp(QuantityConstant.RECEIPT_HEADER_CHECK.toString());
            } else {
                receiptDetail.setProcessStamp(status);
            }
            return receiptDetail;
        } else {
            //该物料类别是否有入库流程
            LambdaQueryWrapper<MaterialType> lambdaMaterialType = Wrappers.lambdaQuery();
            lambdaMaterialType.eq(MaterialType::getCode, material.getType());
            MaterialType materialType = materialTypeService.getOne(lambdaMaterialType);
            if (materialType.getReceivingFlow() != null) {
                List<StatusFlowDetail> statusFlowDetails = statusFlowDetailService.queryStatusFlowDetail(materialType.getReceivingFlow());
                String status = nextStatusFlow(statusFlowDetails, receiptDetail.getProcessStamp());
                //在状态到达时候是判断是否要质检
                if (QuantityConstant.RECEIPT_HEADER_RECEIVING.toString().equals(status) && inspection(receiptDetail)){
                    receiptDetail.setProcessStamp(QuantityConstant.RECEIPT_HEADER_CHECK.toString());
                } else {
                    receiptDetail.setProcessStamp(status);
                }
                return receiptDetail;
            } else {
                //以上都没有的情况下查询入库首选项中的入库流程
                LambdaQueryWrapper<ConfigValue> lambdaQueryWrapper = Wrappers.lambdaQuery();
                lambdaQueryWrapper.eq(ConfigValue::getModuleType, "receipt");
                ConfigValue configValue = configValueService.getOne(lambdaQueryWrapper);

                LambdaQueryWrapper<ReceiptPreference> lambda = Wrappers.lambdaQuery();
                lambda.eq(ReceiptPreference::getCode, configValue.getValue());
                ReceiptPreference receiptPreference = receiptPreferenceService.getOne(lambda);
                List<StatusFlowDetail> statusFlowDetails = statusFlowDetailService.queryStatusFlowDetail(receiptPreference.getReceivingFlow());
                String status = nextStatusFlow(statusFlowDetails, receiptDetail.getProcessStamp());
                //在状态到达时候是判断是否要质检
                if (QuantityConstant.RECEIPT_HEADER_RECEIVING.toString().equals(status) && inspection(receiptDetail)){
                    receiptDetail.setProcessStamp(QuantityConstant.RECEIPT_HEADER_CHECK.toString());
                } else {
                    receiptDetail.setProcessStamp(status);
                }
                return receiptDetail;
            }
        }
    }

    /**
     * 获取配置流程中下一状态
     * @param statusFlowDetails 流程列表
     * @param status 当前状态
     */
    public String nextStatusFlow(List<StatusFlowDetail> statusFlowDetails, String status){
        //判断当前状态是否为最后状态,若为最后状态返回当前状态
        if (StringUtils.isEmpty(status)){
            status = "0";
        }
        if (status.equals(statusFlowDetails.get(statusFlowDetails.size()-1).getFlowCode())){
            return status;
        } else {
            for (int i = 0; i < statusFlowDetails.size(); i++){
                if (Integer.parseInt(statusFlowDetails.get(i).getFlowCode()) > Integer.parseInt(status)){
                    return statusFlowDetails.get(i).getFlowCode();
                }
            }
            return status;
        }
    }

    @Override
    public List<StatusFlowDetail> queryflow(){
        LambdaQueryWrapper<ConfigValue> lambdaQueryWrapper = Wrappers.lambdaQuery();
        lambdaQueryWrapper.eq(ConfigValue::getModuleType, "receipt");
        ConfigValue configValue = configValueService.getOne(lambdaQueryWrapper);

        LambdaQueryWrapper<ReceiptPreference> lambda = Wrappers.lambdaQuery();
        lambda.eq(ReceiptPreference::getCode, configValue.getValue());
        ReceiptPreference receiptPreference = receiptPreferenceService.getOne(lambda);
        List<StatusFlowDetail> statusFlowDetails = statusFlowDetailService.queryStatusFlowDetail(receiptPreference.getReceivingFlow());
        return statusFlowDetails;
    }

    /**
     * @description 更新头表尾状态
     * 每次明细表更新后调用该方法
     * 当所有明细表到达该状态时,更新头表状态
     * @param id 头表id
     */
    @Override
    public void updateReceiptHeaderLastStatus(Integer id){
        LambdaQueryWrapper<ReceiptDetail> lambdaDetails = Wrappers.lambdaQuery();
        lambdaDetails.eq(ReceiptDetail::getReceiptId, id);
        List<ReceiptDetail> receiptDetails = this.list(lambdaDetails);
        //查询出头表信息
        ReceiptHeader receiptHeader = receiptHeaderService.getById(id);
        int minStatus;
        int maxStatus;
        // 判断入库明细是否为空, 为空时入库单头表状态为新建
        if (receiptDetails.isEmpty()){
            minStatus = 0;
            maxStatus = 0;
        } else {
            minStatus = Integer.parseInt(receiptDetails.get(0).getProcessStamp());
            maxStatus = Integer.parseInt(receiptDetails.get(0).getProcessStamp());
            //遍历明细状态得出最小状态值
            for (int i = 1; i<receiptDetails.size(); i++){
                if ( minStatus > Integer.parseInt(receiptDetails.get(i).getProcessStamp())) {
                    minStatus = Integer.parseInt(receiptDetails.get(i).getProcessStamp());
                }
                if ( maxStatus < Integer.parseInt(receiptDetails.get(i).getProcessStamp())) {
                    maxStatus = Integer.parseInt(receiptDetails.get(i).getProcessStamp());
                }
            }
        }
        //若更新状态值小于头状态,更新尾状态否则更新头尾状态
        receiptHeader.setFirstStatus(maxStatus);
        receiptHeader.setLastStatus(minStatus);
        if (!receiptHeaderService.updateById(receiptHeader)) {
            throw new ServiceException("更新状态失败");
        }
    }
    /**
     * @description 更新头表尾状态
     * 每次明细表更新后调用该方法
     * 当所有明细表到达该状态时,更新头表状态
     * @param receiptHeaderIdSet 头表id
     */
    @Override
    public void updateReceiptHeaderLastStatusV2(Set<Integer> receiptHeaderIdSet){
        for (Integer id:receiptHeaderIdSet){
            LambdaQueryWrapper<ReceiptDetail> lambdaDetails = Wrappers.lambdaQuery();
            lambdaDetails.eq(ReceiptDetail::getReceiptId, id);
            lambdaDetails.orderByDesc(ReceiptDetail::getProcessStamp);
            lambdaDetails.last("limit 1");
            List<ReceiptDetail> receiptDetails = this.list(lambdaDetails);
            //查询出头表信息
            ReceiptHeader receiptHeader = receiptHeaderService.getById(id);
            int minStatus=0;
            int maxStatus=0;
            if(receiptDetails!=null&&receiptDetails.size()>0){
                minStatus = Integer.parseInt(receiptDetails.get(0).getProcessStamp());
                maxStatus = Integer.parseInt(receiptDetails.get(0).getProcessStamp());
                //遍历明细状态得出最小状态值
                for (int i = 1; i<receiptDetails.size(); i++){
                    if ( minStatus > Integer.parseInt(receiptDetails.get(i).getProcessStamp())) {
                        minStatus = Integer.parseInt(receiptDetails.get(i).getProcessStamp());
                    }
                    if ( maxStatus < Integer.parseInt(receiptDetails.get(i).getProcessStamp())) {
                        maxStatus = Integer.parseInt(receiptDetails.get(i).getProcessStamp());
                    }
                }
            }
            //若更新状态值小于头状态,更新尾状态否则更新头尾状态
            receiptHeader.setFirstStatus(maxStatus);
            receiptHeader.setLastStatus(minStatus);
            if (!receiptHeaderService.updateById(receiptHeader)) {
                throw new ServiceException("更新状态失败");
            }
        }
    }
    /**
     * 入库单审核
     * @param ids
     * @param approval
     * @return
     */
    @Override
    public AjaxResult approval(String ids, Integer approval) {
        ReceiptHeader receiptHeader = new ReceiptHeader();
        if (StringUtils.isEmpty(ids)){
            return AjaxResult.error("id不能为空");
        }
        Integer[] idArray = Convert.toIntArray(ids);
        for (Integer id: idArray) {
            receiptHeader.setId(id);
            receiptHeader.setLastStatus(approval);
            receiptHeader.setFirstStatus(approval);
            receiptHeader.setLastUpdatedBy(ShiroUtils.getLoginName());
            if (!receiptHeaderService.updateById(receiptHeader)){
                throw new ServiceException("更新头表失败");
            } else {
                LambdaQueryWrapper<ReceiptDetail> lambda = Wrappers.lambdaQuery();
                lambda.eq(ReceiptDetail::getReceiptId, id);
                List<ReceiptDetail> receiptDetails = this.list(lambda);
                for (ReceiptDetail receiptDetail : receiptDetails){
                    receiptDetail.setProcessStamp(QuantityConstant.RECEIPT_HEADER_POOL.toString());
                    receiptDetail = this.queryflow(receiptDetail);
                    if (!this.updateById(receiptDetail)){
                        throw new ServiceException("更新入库明细表失败");
                    }
                }
            }
            this.updateReceiptHeaderLastStatus(id);
        }
        return AjaxResult.success("审核完成");
    }

    @Override
    public List<TaskDetail> getReceiptQtyLast7Days() {
        return receiptDetailMapper.getReceiptQtyLast7Days();
    }

    @Override
    public List<TaskDetail> getWarehouseReceipt() {
        return receiptDetailMapper.getWarehouseReceipt();
    }

    @Override
    public List<TaskDetail> getCompanyReceipt() {
        return receiptDetailMapper.getCompanyReceipt();
    }


    /**
     * 判断明细中是否质检
     */
    public boolean inspection(ReceiptDetail receiptDetail){
        //如果明细中需要质检,则判断是否已经生成质检单
        if ("0".equals(receiptDetail.getQcCheck())){
            LambdaQueryWrapper<CheckHeader> lambda = Wrappers.lambdaQuery();
            lambda.eq(CheckHeader::getCode, receiptDetail.getReceiptCode());
            CheckHeader checkHeader = checkHeaderService.getOne(lambda);
            if (checkHeader == null){
                return true;
            }
        }
        return false;
    }

    /**
     //     * 移动端收货
     //     *
     //     * @param code
     //     * @return
     //     */
    @Override
    public AjaxResult scanReceiptCode(String code, String type, String companyCode) {
        LambdaQueryWrapper<ReceiptHeader> lambdaQueryWrapper = Wrappers.lambdaQuery();
        lambdaQueryWrapper.eq(ReceiptHeader::getReferCode, code)
                .eq(ReceiptHeader::getReceiptType, type);
        ReceiptHeader receiptHeader = receiptHeaderService.getOne(lambdaQueryWrapper);
        if (receiptHeader == null) {
            LambdaQueryWrapper<Company> companyLambdaQueryWrapper = Wrappers.lambdaQuery();
            companyLambdaQueryWrapper.eq(Company::getCode,companyCode);
            Company company = companyService.getOne(companyLambdaQueryWrapper);
            return AjaxResult.success("");
            //    return receiptHeaderService.findErpReceipt(String.valueOf(company.getId()), receiptHeader.getReferType(), receiptHeader.getReferCode());
        } else {
            LambdaQueryWrapper<ReceiptDetail> queryWrapper = Wrappers.lambdaQuery();
            queryWrapper.eq(ReceiptDetail::getReceiptCode, receiptHeader.getCode());
            List<ReceiptDetail> receiptDetailList = list(queryWrapper);
            return AjaxResult.success(receiptDetailList);
        }

    }

    @Override
    public List<Integer> insertTodayReceiptDetail(int headerId, List<ReceiptBill> receiptBills, boolean isCompletedQty, String companyCode) {
        List<Integer> mReceiptDetailIds = new ArrayList<>();
        ReceiptHeader receiptHeader = receiptHeaderService.getById(headerId);

        for(ReceiptBill receiptBill : receiptBills) {
            ReceiptDetail receiptDetail = new ReceiptDetail();
            receiptDetail.setId(null);
            receiptDetail.setWarehouseCode(ShiroUtils.getWarehouseCode());
			receiptDetail.setCompanyCode(companyCode);
            receiptDetail.setReceiptId(receiptHeader.getId());
            receiptDetail.setReceiptCode(receiptHeader.getCode());
            receiptDetail.setMaterialCode(receiptBill.getMaterialCode());
            receiptDetail.setMaterialName(receiptBill.getMaterialName());
            receiptDetail.setInventorySts("good");
            receiptDetail.setQty(receiptBill.getQty());
            if(isCompletedQty) {
                receiptDetail.setTaskQty(receiptBill.getQty());
            }
            receiptDetail.setCreatedBy(ShiroUtils.getLoginName());
            receiptDetail.setLastUpdatedBy(ShiroUtils.getLoginName());
            receiptDetail.setDeleted(false);
            receiptDetail.setBatch(receiptBill.getBatch());
            save(receiptDetail);
            mReceiptDetailIds.add(receiptDetail.getId());
        }
        return mReceiptDetailIds;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public String insertExcelData(List<ReceiptDetail> list, boolean updateSupport, String operName) {
        if (StringUtils.isNull(list) || list.size() == 0) {
            throw new ServiceException("导入数据不能为空!");
        }
        //新增入库头表
        ReceiptHeader receiptHeader=createHeader(operName,list);
        int successNum = 0;
        int failureNum = 0;
        StringBuilder successMsg = new StringBuilder();
        StringBuilder failureMsg = new StringBuilder();
        for (ReceiptDetail importData : list) {
            /*if(StringUtils.isEmpty(importData.getWarehouseCode())){
                failureNum++;
                String msg = "<br/>" + failureNum + "、仓库编码为空 导入失败:";
                failureMsg.append(msg );
                continue;
            }
            if(StringUtils.isEmpty(importData.getCompanyCode())){
                failureNum++;
                String msg = "<br/>" + failureNum + "、货主编码为空 导入失败:";
                failureMsg.append(msg );
                continue;
            }*/
            if(StringUtils.isNull(importData.getQty())){
                failureNum++;
                String msg = "<br/>" + failureNum + "、数量为空 导入失败:";
                failureMsg.append(msg );
                continue;
            }
            try {
                importData.setReceiptId(receiptHeader.getId());
                importData.setReceiptCode(receiptHeader.getCode());
                Material material = materialService.getMaterialByCode(importData.getMaterialCode());
                importData.setMaterialName(material.getName());
                importData.setMaterialSpec(material.getSpec());
                importData.setMaterialUnit(material.getUnit());
                importData.setWarehouseCode(ShiroUtils.getWarehouseCode());
                importData.setCompanyCode(QuantityConstant.COMPANY_CS);
                importData.setInventorySts(QuantityConstant.GOOD);
                this.save(importData);
                successNum++;
                successMsg.append("<br/>" + successNum + "、数据 " + importData.getMaterialCode() + " 导入成功");

            } catch (Exception e) {
                failureNum++;
                String msg = "<br/>" + failureNum + "、物料编码 " + importData.getMaterialCode() + " 导入失败:";
                failureMsg.append(msg + e.getMessage());
            }
        }
        if (failureNum > 0) {
            failureMsg.insert(0, "很抱歉,导入失败!共 " + failureNum + " 条数据格式不正确,错误如下:");
            throw new ServiceException(failureMsg.toString());
        } else {
            successMsg.insert(0, "恭喜您,数据已全部导入成功!共 " + successNum + " 条,数据如下:");
        }
        return successMsg.toString();
    }

    public ReceiptHeader createHeader(String operName,List<ReceiptDetail> list){
        ReceiptHeader receiptHeader=new ReceiptHeader();
        String code =receiptHeaderService.createCode(QuantityConstant.RECEIPT_TYPE_PPI);
        receiptHeader.setId(null);
        receiptHeader.setLastUpdated(null);
        receiptHeader.setLastUpdatedBy(operName);
        receiptHeader.setCreated(null);
        receiptHeader.setCreatedBy(operName);
        receiptHeader.setWarehouseCode(ShiroUtils.getWarehouseCode());
        receiptHeader.setCompanyCode(QuantityConstant.COMPANY_CS);
        receiptHeader.setCode(code);
        receiptHeader.setReceiptType(QuantityConstant.RECEIPT_TYPE_PPI);
        receiptHeader.setTotalLines(list.size());
        receiptHeader.setFirstStatus(QuantityConstant.RECEIPT_HEADER_BUILD);
        receiptHeader.setLastStatus(QuantityConstant.RECEIPT_HEADER_BUILD);
        BigDecimal bigDecimal = list.stream().map(ReceiptDetail::getQty).reduce(BigDecimal::add).orElse(BigDecimal.ZERO);
        receiptHeader.setTotalQty(bigDecimal);
        if (!receiptHeaderService.save(receiptHeader)) {
            throw new ServiceException("导入失败,添加入库单头表失败");
        }
        return receiptHeader;
    }

    @Override
    public String getWorkNo(Integer id) {
        LambdaQueryWrapper<ReceiptDetail> detailLambda = Wrappers.lambdaQuery();
        detailLambda.eq(ReceiptDetail::getId, id);
        detailLambda.last("limit 1");
        ReceiptDetail receiptDetail= this.getOne(detailLambda);
        if(receiptDetail!=null){
            return receiptDetail.getMoCode();
        }
        return null;
    }

    @Override
    public List<ReceiptDetail> getByHeaderCode(String code){
        LambdaQueryWrapper<ReceiptDetail> detailLambda = Wrappers.lambdaQuery();
        detailLambda.eq(ReceiptDetail::getReceiptCode,code);
        List<ReceiptDetail> list=this.list(detailLambda);
        return list;
    }
    @Override
    public List<ReceiptDetail> selectListEntityByLike(ReceiptDetail receiptDetail){
        LambdaQueryWrapper<ReceiptDetail> detailLambda = Wrappers.lambdaQuery();
        detailLambda.eq(StringUtils.isNotEmpty(receiptDetail.getReceiptCode()),ReceiptDetail::getReceiptCode,receiptDetail.getReceiptCode());
        detailLambda.eq(StringUtils.isNotNull(receiptDetail.getReceiptId()),ReceiptDetail::getReceiptId,receiptDetail.getReceiptId());
        detailLambda.eq(ReceiptDetail::getDeleted,false);

        List<ReceiptDetail> list=this.list(detailLambda);
        return list;
    }
    @Override
    public ReceiptDetail selectFirstEntity(ReceiptDetail receiptDetail){
        LambdaQueryWrapper<ReceiptDetail> detailLambda = Wrappers.lambdaQuery();
        detailLambda.eq(StringUtils.isNotNull(receiptDetail.getId()),ReceiptDetail::getReceiptCode,receiptDetail.getReceiptCode());
        detailLambda.eq(ReceiptDetail::getDeleted,false);
        detailLambda.last("limit 1");
        return this.getOne(detailLambda);
    }
    @Override
    public List<Map<String, Object>> selectList(String code, String goodsShelfNo) {
        String warehouseCode=ShiroUtils.getWarehouseCode();
        String shelfNo=goodsShelfNo.substring(1,5);
        return receiptDetailMapper.selectLists(code,shelfNo,warehouseCode);
    }
}