package com.trade.service.trade.salesorder.service.impl;

import cn.hutool.core.collection.CollectionUtil;
import com.alibaba.fastjson2.JSON;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.trade.common.constant.HttpStatus;
import com.trade.common.exception.ServiceException;
import com.trade.common.redis.RedisCache;
import com.trade.common.text.Convert;
import com.trade.common.utils.ConstantUtil;
import com.trade.common.utils.DateUtils;
import com.trade.common.utils.StringUtils;
import com.trade.common.utils.uuid.SnowflakeIdGenerator;
import com.trade.service.DictConstants;
import com.trade.service.TransStruct;
import com.trade.service.enterprise.companyrelated.domain.ImporterEntity;
import com.trade.service.enterprise.companyrelated.service.IImporterEntityService;
import com.trade.service.enterprise.customer.domain.Enterprise;
import com.trade.service.enterprise.customer.service.EnterpriseBaseService;
import com.trade.service.filestorage.dto.FileAbstractDto;
import com.trade.service.filestorage.service.TFileStorageService;
import com.trade.service.finance.disbursement.service.BillingDisbursementService;
import com.trade.service.finance.paymentcollection.domain.OrderIncomeAssociation;
import com.trade.service.finance.paymentcollection.domain.OrderReceivePaymentAssociation;
import com.trade.service.finance.paymentcollection.service.BillingIncomeService;
import com.trade.service.finance.paymentcollection.service.OrderIncomeAssociationService;
import com.trade.service.finance.paymentcollection.service.OrderReceivePaymentAssociationService;
import com.trade.service.trade.salescontract.domain.ContractTerms;
import com.trade.service.trade.salescontract.dto.SalesContractDto;
import com.trade.service.trade.salescontract.service.ContractTermsService;
import com.trade.service.trade.salescontract.service.SalesContractService;
import com.trade.service.trade.salesorder.constant.SaleOrderConstant;
import com.trade.service.trade.salesorder.domain.SalesOrderGoods;
import com.trade.service.trade.salesorder.domain.SalesOrderLogistics;
import com.trade.service.trade.salesorder.dto.*;
import com.trade.service.trade.salesorder.mapper.SalesOrderMapper;
import com.trade.service.trade.salesorder.service.*;
import com.trade.service.trade.salesorder.vo.*;
import com.trade.service.trade.salesorder.domain.SalesOrder;
import com.trade.service.trade.salesorder.domain.SalesOrderInvoice;
import com.trade.service.tradingplatform.domain.TradingPlatform;
import com.trade.service.tradingplatform.service.TradingPlatformBaseService;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Optional;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;

/**
 * <p>
 * 销售订单表 服务实现类
 * </p>
 *
 * @author zhangchenm
 * @since 2024-09-06
 */
@Service
public class SalesOrderServiceImpl extends ServiceImpl<SalesOrderMapper, SalesOrder> implements ISalesOrderService {

    private final ISalesOrderGoodsService salesOrderGoodsService;
    private final ISalesOrderInvoiceService salesOrderInvoiceService;
    private final ISalesOrderLogisticsService salesOrderLogisticsService;
    private final ISalesOrderContainerService salesOrderContainerService;
    @Resource
    private TransStruct transStruct;
    @Resource
    private SalesContractService salesContractService;
    @Resource
    private ContractTermsService contractTermsService;
    @Resource
    private IImporterEntityService importerEntityService;
    @Resource
    private TFileStorageService tFileStorageService;
    @Resource
    private EnterpriseBaseService enterpriseBaseService;
    @Resource
    private RedisCache redisCache;
    @Resource
    private OrderIncomeAssociationService orderIncomeAssociationService;
    @Resource
    private BillingIncomeService billingIncomeService;
    @Resource
    private TradingPlatformBaseService tradingPlatformBaseService;
    @Resource
    private BillingDisbursementService billingDisbursementService;
    @Resource
    private OrderReceivePaymentAssociationService orderReceivePaymentAssociationService;

    public SalesOrderServiceImpl(ISalesOrderGoodsService salesOrderGoodsService,
            ISalesOrderInvoiceService salesOrderInvoiceService, ISalesOrderLogisticsService salesOrderLogisticsService,
            ISalesOrderContainerService salesOrderContainerService){
        this.salesOrderGoodsService = salesOrderGoodsService;
        this.salesOrderInvoiceService = salesOrderInvoiceService;
        this.salesOrderLogisticsService = salesOrderLogisticsService;
        this.salesOrderContainerService = salesOrderContainerService;
    }

    @Override
    public PageInfo<SalesOrderVO> queryListBySearch(SalesOrderSearch search) {
        PageHelper.startPage(search.getPage(), search.getRows());
        List<SalesOrderVO> list = this.baseMapper.queryListBySearch(search);
        for (SalesOrderVO salesOrderVO : list) {
            SalesOrderLogistics salesOrderLogistics = salesOrderLogisticsService.getByOrderId(salesOrderVO.getId());
            if (salesOrderLogistics != null && salesOrderLogistics.getLadingDate() != null
                    && salesOrderVO.getSettlementCycle() != null) {
                salesOrderVO.setExpectedPaymentDueDate(
                        salesOrderLogistics.getLadingDate().plusDays(salesOrderVO.getSettlementCycle()));
            }
            String value = Convert.toStr(redisCache.getCacheObject(salesOrderVO.getId().toString()));
            if (StringUtils.isNotEmpty(value)) {
                SalesGoodsReceivePaymentDto salesOrderReceivePaymentDto = JSON.parseObject(value,
                        SalesGoodsReceivePaymentDto.class);
                if (salesOrderReceivePaymentDto != null) {
                    salesOrderVO.setSelectGoodAmount(salesOrderReceivePaymentDto.getGoodsAmount());
                    salesOrderVO.setSelectType(salesOrderReceivePaymentDto.getSelectType());
                }
            }
            if (search.getPoint()) {
                if (salesOrderVO.getStatus().equals(SaleOrderConstant.ORDER_STATUS_PARTIAL_COLLECTION)
                        || salesOrderVO.getStatus()
                                .equals(SaleOrderConstant.ORDER_STATUS_PARTIAL_REPAYMENT_UNDER_REVIEW)
                        || salesOrderVO.getStatus().equals(SaleOrderConstant.ORDER_STATUS_REPAYMENT_UNDER_REVIEW)
                        || salesOrderVO.getStatus().equals(SaleOrderConstant.ORDER_STATUS_RECEIVED)) {
                    salesOrderVO.setStatus(SaleOrderConstant.ORDER_STATUS_DELIVERING);
                }
            }
        }
        return new PageInfo<>(list);
    }

    @Override
    public SalesOrderDtlVO getDetail(Long id, boolean is4Update) {
        Optional<SalesOrder> salesOrderOpt = Optional.ofNullable(this.getById(id));
        salesOrderOpt.orElseThrow(() -> new ServiceException("订单不存在", HttpStatus.BAD_REQUEST));
        SalesOrderDtlVO salesOrderDtlVO = new SalesOrderDtlVO();
        SalesOrder salesOrder = salesOrderOpt.get();
        SalesOrderVO salesOrderVO = transStruct.transSalesOrder2SalesOrderVO(salesOrder);
        SalesContractDto salesContract = salesContractService.getSalesContractById(salesOrder.getSaleContractId());
        salesOrderVO.setFromPort(salesContract.getPortDeparture());
        salesOrderVO.setDestPort(salesContract.getPortDestination());
        salesOrderVO.setAgencyEnterpriseName(salesContract.getAgencyEnterpriseName());
        salesOrderVO.setSalesContractName(salesContract.getContractName());
        salesOrderVO.setSalesContractNo(salesContract.getContractNo());
        Optional<ImporterEntity> importerEntity = Optional
                .ofNullable(importerEntityService.getByEntityId(salesOrder.getImporterId()));
        salesOrderDtlVO.setSalesOrderVO(salesOrderVO);
        importerEntity.ifPresent(e -> salesOrderVO.setImporterName(e.getEntityName()));
        List<SalesOrderGoodsVO> salesOrderGoodsList = salesOrderGoodsService.listByOrderId(id);
        salesOrderDtlVO.setSalesOrderGoodsList(salesOrderGoodsList);
        if (is4Update) {
            return salesOrderDtlVO;
        }
        Optional<SalesOrderLogisticsDtlVO> orderLogisticsOptional = Optional
                .ofNullable(salesOrderLogisticsService.getDetailByOrderNo(salesOrder.getOrderNo()));
        if (orderLogisticsOptional.isPresent()) {
            SalesOrderLogisticsDtlVO orderLogistics = orderLogisticsOptional.get();
            salesOrderDtlVO.setSalesOrderLogistics(orderLogistics);
            List<SalesOrderContainerVO> containers = salesOrderContainerService
                    .listByLogisticsId(orderLogistics.getId());
            containers.forEach(item -> item
                    .setFile(new FileAbstractDto(tFileStorageService.getFileStorageById(item.getFileId()))));
            salesOrderDtlVO.setSalesOrderContainerList(containers);
        }
        Optional<SalesOrderInvoice> orderInvoiceOptional = Optional
                .ofNullable(salesOrderInvoiceService.getByOrderId(salesOrder.getId()));
        if (orderInvoiceOptional.isPresent()) {
            SalesOrderInvoice orderInvoice = orderInvoiceOptional.get();
            SalesOrderInvoiceVO orderInvoiceVO = new SalesOrderInvoiceVO();
            orderInvoiceVO.setInvoiceNo(orderInvoice.getInvoiceNo());
            orderInvoiceVO.setGmtCreate(DateUtils.parseDate2LocalDate(orderInvoice.getGmtCreate()));
            orderInvoiceVO
                    .setFile(new FileAbstractDto(tFileStorageService.getFileStorageById(orderInvoice.getFileId())));
            salesOrderDtlVO.setSalesOrderInvoice(orderInvoiceVO);
        }
        Optional<ContractTerms> contractTermsOpt = Optional.ofNullable(contractTermsService
                .getByContractIdAndType(salesContract.getId(), ConstantUtil.SALES_CONTRACT_NO_PREFIX));
        contractTermsOpt.ifPresent(e -> {
            salesOrderDtlVO.setSalesOrderPayInfoVO(transStruct.transContractTerms2SalesOrderPayInfoVO(e));
            salesOrderVO.setPaymentWay(e.getPaymentWay());
            salesOrderVO.setSettlementCycle(e.getSettlementCycle());
        });
        Optional<Enterprise> enterpriseBaseOpt = Optional
                .ofNullable(enterpriseBaseService.getEnterpriseByCustomerId(salesOrder.getCustomerUserId()));
        enterpriseBaseOpt.ifPresent(e -> {
            salesOrderVO.setCustomerIdentifierNo(e.getCustomerIdentifierNo());
            salesOrderVO.setEnterpriseName(e.getName());
        });
        return salesOrderDtlVO;
    }

    @Override
    public Long saveSalesOrder(SalesOrder salesOrder) {
        this.save(salesOrder);
        return salesOrder.getId();
    }

    @Override
    public boolean existSalesOrderByImporterId(Long importerId) {
        return this.lambdaQuery().eq(SalesOrder::getImporterId, importerId).count() > 0;
    }

    @Override
    public List<SalesOrder4CustomsDeclarationVO> queryOrderNo4GetCustomsDeclaration() {
        return this.baseMapper.queryOrderNo4GetCustomsDeclaration();
    }

    @Override
    public void updateCustomsDeclarationStatusFinishedByOrderNo(String orderNo) {
        this.baseMapper.updateCustomsDeclarationStatusFinishedByOrderNo(orderNo);
    }

    @Override
    public SalesOrder getByOrderNo(String orderNo) {
        return this.lambdaQuery().eq(SalesOrder::getOrderNo, orderNo).one();
    }

    @Override
    public List<SalesOrder> queryBySaleContractId(Long saleContractId) {
        return this.lambdaQuery().eq(SalesOrder::getSaleContractId, saleContractId).list();
    }

    @Override
    public Boolean processGoodsReceivePayment(SalesGoodsReceivePaymentDto salesOrderReceivePayment) {
        String value = JSON.toJSONString(salesOrderReceivePayment);
        redisCache.setCacheObject(salesOrderReceivePayment.getSalesOrderId().toString(), value, 30, TimeUnit.MINUTES);
        return true;
    }

    @Override
    public List<ReceivePaymentExtendDto> processOrderReceivePaymentList(
            List<ReceivePaymentExtendDto> receivePaymentExtendDtos, boolean source) {
        if (CollectionUtil.isEmpty(receivePaymentExtendDtos)) {
            return null;
        }
        List<ReceivePaymentExtendDto> result = new ArrayList<>();
        Map<Long, List<ReceivePaymentExtendDto>> groupBy = receivePaymentExtendDtos.stream()
                .collect(Collectors.groupingBy(ReceivePaymentExtendDto::getSaleContractId));
        groupBy.forEach((k, v) -> {
            ReceivePaymentExtendDto extendDto = new ReceivePaymentExtendDto();
            extendDto.setSaleContractId(k);
            ReceivePaymentExtendDto extendDtoOne = v.get(0);
            extendDto.setSalesContractNo(extendDtoOne.getSalesContractNo());
            extendDto.setOriginalCurrency(extendDtoOne.getOriginalCurrency());
            extendDto.setCustomerUserId(extendDtoOne.getCustomerUserId());
            BigDecimal total = v.stream().filter(e -> e.getOriginalReceivePayment() != null)
                    .map(ReceivePaymentExtendDto::getOriginalReceivePayment).reduce(BigDecimal.ZERO, BigDecimal::add);
            extendDto.setOriginalReceivePayment(total);
            List<SalesOrderReceiveExtendDto> salesOrderReceiveExtendDtos = new ArrayList<>();
            for (ReceivePaymentExtendDto receivePaymentExtendDto : v) {
                for (SalesOrderReceiveExtendDto salesOrderReceiveExtendDto : receivePaymentExtendDto
                        .getSalesOrderInfo()) {
                    checkOrderReceivePayment(salesOrderReceiveExtendDto.getSalesOrderId(), k, source);
                }
                salesOrderReceiveExtendDtos.addAll(receivePaymentExtendDto.getSalesOrderInfo());
            }
            extendDto.setSalesOrderInfo(salesOrderReceiveExtendDtos);
            result.add(extendDto);
        });
        return result;
    }

    @Override
    public List<OrderListInfoDto> queryOrderListInfoByOrderIds(List<SalesOrderReceiveExtendDto> salesOrderInfo) {
        if (CollectionUtil.isEmpty(salesOrderInfo)) {
            throw new ServiceException("数据传参异常");
        }
        List<OrderListInfoDto> list = new ArrayList<>();
        for (SalesOrderReceiveExtendDto salesOrderReceiveExtendDto : salesOrderInfo) {
            OrderListInfoDto orderListInfoDto = new OrderListInfoDto();
            SalesOrder salesOrder = this.baseMapper.selectById(salesOrderReceiveExtendDto.getSalesOrderId());
            if (salesOrder == null) {
                throw new ServiceException("订单id(" + salesOrderReceiveExtendDto.getSalesOrderId() + ")订单不存在");
            }
            orderListInfoDto.setOrderNo(salesOrder.getOrderNo());
            orderListInfoDto.setAmount(salesOrder.getAmount());
            if (salesOrderReceiveExtendDto.getSelectType() == 2) {
                String value = Convert
                        .toStr(redisCache.getCacheObject(salesOrderReceiveExtendDto.getSalesOrderId().toString()));
                if (StringUtils.isNotEmpty(value)) {
                    SalesGoodsReceivePaymentDto salesOrderReceivePaymentDto = JSON.parseObject(value,
                            SalesGoodsReceivePaymentDto.class);
                    orderListInfoDto.setActualAmount(salesOrderReceivePaymentDto.getGoodsAmount());
                }
            } else {
                orderListInfoDto.setActualAmount(salesOrder.getAmount());
            }
            orderListInfoDto.setId(salesOrderReceiveExtendDto.getSalesOrderId());
        }
        return list;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public OrderPaymentAmountDto submitOrderListInfo(List<OrderListInfoDto> salesOrderInfo, int source) {
        OrderPaymentAmountDto orderPaymentAmountDto = new OrderPaymentAmountDto();
        String businessBatchNumber = new SnowflakeIdGenerator(1).nextUniqueId();
        orderPaymentAmountDto.setBusinessBatchNumber(businessBatchNumber);
        BigDecimal actualReceivedAmount = BigDecimal.ZERO;
        for (OrderListInfoDto orderListInfoDto : salesOrderInfo) {
            SalesOrder salesOrder = this.baseMapper.selectById(orderListInfoDto.getId());
            if (salesOrder == null) {
                throw new ServiceException("订单id(" + orderListInfoDto.getOrderNo() + ")订单不存在");
            }
            if (orderListInfoDto.getActualAmount().compareTo(orderListInfoDto.getAmount()) != 0
                    && orderListInfoDto.getFileId() == null) {
                throw new ServiceException("订单id(" + orderListInfoDto.getOrderNo() + ")需要上传补充协议");
            }
            OrderReceivePaymentAssociation orderReceivePaymentAssociation = new OrderReceivePaymentAssociation();
            orderReceivePaymentAssociation.setCustomerUserId(salesOrder.getCustomerUserId());
            orderReceivePaymentAssociation.setOrderId(orderListInfoDto.getId());
            orderReceivePaymentAssociation.setFileId(orderListInfoDto.getFileId());
            orderReceivePaymentAssociation.setOrderNo(orderListInfoDto.getOrderNo());
            orderReceivePaymentAssociation.setActualReceivedAmount(orderListInfoDto.getActualAmount());
            orderReceivePaymentAssociation.setActualReceivedCurrency(orderListInfoDto.getCurrency());
            orderReceivePaymentAssociation.setGoodsAmount(orderListInfoDto.getAmount());
            orderReceivePaymentAssociation.setGoodsCurrency(orderListInfoDto.getCurrency());
            orderReceivePaymentAssociation.setRemark(orderListInfoDto.getRemark());
            orderReceivePaymentAssociation.setBusinessBatchNumber(businessBatchNumber);
            orderReceivePaymentAssociationService.save(orderReceivePaymentAssociation);
            actualReceivedAmount = actualReceivedAmount.add(orderListInfoDto.getActualAmount());
        }
        orderPaymentAmountDto.setActualReceivedAmount(actualReceivedAmount);
        return orderPaymentAmountDto;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public Boolean processOrderReceivePayment(ReceivePaymentSubDto receivePaymentSubDto, boolean source) {
        receivePaymentSubDto.getReceivePaymentDtoList().stream().forEach(e -> {
            OrderIncomeAssociation orderIncomeAssociation = new OrderIncomeAssociation();
            orderIncomeAssociation.setRemark(e.getRemark());
            orderIncomeAssociation.setVoucherNo(e.getVoucherNo());
            orderIncomeAssociation.setCustomerUserId(e.getCustomerUserId());
            orderIncomeAssociation.setSalesContractNo(e.getSalesContractNo());
            orderIncomeAssociation.setSaleContractId(e.getSaleContractId());
            orderIncomeAssociation.setBusinessBatchNumber(e.getBusinessBatchNumber());
            orderIncomeAssociation.setSaleContractId(e.getSaleContractId());
            orderIncomeAssociation.setReceivePayment(e.getModifyAmount());
            orderIncomeAssociation.setCurrency(e.getModifyCurrency());
            orderIncomeAssociation.setOriginalReceivePayment(e.getOriginalReceivePayment());
            orderIncomeAssociation.setOriginalCurrency(e.getOriginalCurrency());
            orderIncomeAssociation.setAccountNumber(receivePaymentSubDto.getAccountNumber());
            orderIncomeAssociation.setPaymentType(receivePaymentSubDto.getPaymentType());
            orderIncomeAssociation.setExpectedPaymentDueDate(receivePaymentSubDto.getExpectedPaymentDueDate());
            orderIncomeAssociation.setSource(source ? 1 : 2);
            orderIncomeAssociation.setPromptReceivingCurrency(receivePaymentSubDto.getPromptReceivingCurrency());
            if (orderIncomeAssociation.getSource() == 2 && StringUtils.isEmpty(e.getVoucherNo())) {
                throw new ServiceException("销售合同编号" + e.getSalesContractNo() + "凭证号不能为空");
            }
            if (orderIncomeAssociation.getSource() == 2 && CollectionUtil.isEmpty(e.getFileIds())) {
                throw new ServiceException("销售合同编号" + e.getSalesContractNo() + "收款凭证不能为空");
            }
            int flag = 1;
            for (SalesOrderReceiveExtendDto salesOrderReceiveExtendDto : e.getSalesOrderInfo()) {
                // checkOrderReceivePayment(salesOrderReceiveExtendDto.getSalesOrderId(), e.getSaleContractId(),
                // source);
                int goodsStatus = SaleOrderConstant.GOODS_STATUS_IN_REVIEW;
                if (!source) {
                    goodsStatus = SaleOrderConstant.GOODS_STATUS_RECEIVED;
                }
                if (salesOrderReceiveExtendDto.getSelectType() == 2) {
                    String value = Convert
                            .toStr(redisCache.getCacheObject(salesOrderReceiveExtendDto.getSalesOrderId().toString()));
                    if (StringUtils.isNotEmpty(value)) {
                        SalesGoodsReceivePaymentDto salesOrderReceivePaymentDto = JSON.parseObject(value,
                                SalesGoodsReceivePaymentDto.class);
                        salesOrderReceiveExtendDto
                                .setSalesOrderGoodsIds(salesOrderReceivePaymentDto.getSalesOrderGoodsIds());
                        // 在订单详情里面如果勾选了所有未收款商品
                        Long count = salesOrderGoodsService.countBySaleOrderId(
                                salesOrderReceiveExtendDto.getSalesOrderId(),
                                SaleOrderConstant.GOODS_STATUS_UNCOLLECTED);
                        int orderStatus = SaleOrderConstant.ORDER_STATUS_PARTIAL_REPAYMENT_UNDER_REVIEW;
                        if (!source) {
                            orderStatus = SaleOrderConstant.ORDER_STATUS_PARTIALLY_COMPLETED;
                            flag = 2;
                        }
                        if (count.equals(salesOrderReceivePaymentDto.getSalesOrderGoodsIds().size())) {
                            orderStatus = SaleOrderConstant.ORDER_STATUS_REPAYMENT_UNDER_REVIEW;
                            if (!source) {
                                orderStatus = SaleOrderConstant.ORDER_STATUS_END;
                                flag = 2;
                            }
                        }
                        updateSalesOrderAndGoodsStatus(salesOrderReceiveExtendDto, orderStatus, goodsStatus, flag);
                    }
                } else {
                    List<Long> goodIds = salesOrderGoodsService
                            .listByOrderId(salesOrderReceiveExtendDto.getSalesOrderId()).stream()
                            .filter(s -> s.getReceivePaymentStatus() == SaleOrderConstant.GOODS_STATUS_UNCOLLECTED)
                            .map(s -> s.getId()).collect(Collectors.toList());
                    salesOrderReceiveExtendDto.setSalesOrderGoodsIds(goodIds);
                    int orderStatus = SaleOrderConstant.ORDER_STATUS_REPAYMENT_UNDER_REVIEW;
                    if (!source) {
                        orderStatus = SaleOrderConstant.ORDER_STATUS_END;
                        flag = 2;
                    }
                    updateSalesOrderAndGoodsStatus(salesOrderReceiveExtendDto, orderStatus, goodsStatus, flag);
                }
            }
            orderIncomeAssociation.setOrderInfo(JSON.toJSONString(e.getSalesOrderInfo()));
            Long billingIncomeId;
            if (source) {
                billingIncomeId = billingIncomeService.saveOrderIncome(orderIncomeAssociation);
            } else {
                billingIncomeId = billingDisbursementService.saveOrderDisbursement(orderIncomeAssociation);
            }
            orderIncomeAssociation.setBillingIncomeId(billingIncomeId);
            if (CollectionUtil.isNotEmpty(e.getFileIds())) {
                orderIncomeAssociation.setFileIds(JSON.toJSONString(e.getFileIds()));
            }
            orderIncomeAssociationService.save(orderIncomeAssociation);
        });
        return true;
    }

    @Override
    public boolean updateSalesOrderAndGoodsStatus(SalesOrderReceiveExtendDto salesOrderReceiveExtendDto,
            int orderStatus, int goodsStatus, int flag) {
        SalesOrder salesOrder = this.baseMapper.selectById(salesOrderReceiveExtendDto.getSalesOrderId());
        salesOrder.setStatus(orderStatus);
        salesOrderReceiveExtendDto.getSalesOrderGoodsIds().forEach(id -> {
            SalesOrderGoods salesGoods = salesOrderGoodsService.getById(id);
            salesGoods.setReceivePaymentStatus(goodsStatus);
            salesOrderGoodsService.updateById(salesGoods);
        });
        if (flag == 2 || flag == 3) {
            List<SalesOrderGoodsVO> orderGoodsVOS = salesOrderGoodsService
                    .listByOrderId(salesOrderReceiveExtendDto.getSalesOrderId()).stream()
                    .filter(s -> s.getReceivePaymentStatus() == SaleOrderConstant.GOODS_STATUS_UNCOLLECTED)
                    .collect(Collectors.toList());
            if (CollectionUtil.isNotEmpty(orderGoodsVOS)) {
                BigDecimal amountGoods = orderGoodsVOS.stream().filter(o -> o.getPriceTotal() != null)
                        .map(SalesOrderGoodsVO::getPriceTotal).reduce(BigDecimal.ZERO, BigDecimal::add);
                salesOrder.setPendingReceivedAmount(amountGoods);
            }
        }
        return this.baseMapper.updateById(salesOrder) > 0;
    }

    /**
     * 校验收款支付信息
     * 
     * @param salesOrderId
     * @param saleContractId
     * @param source
     */
    private void checkOrderReceivePayment(Long salesOrderId, Long saleContractId, boolean source) {
        SalesContractDto salesContractDto = salesContractService.getSalesContractById(saleContractId);
        if (source) {
            if (StringUtils.isEmpty(salesContractDto.getAgencyCertNo())) {
                throw new ServiceException("订单订单id" + salesOrderId + "为非“中国大陆”公司代理出口的销售订单");
            } else {
                TradingPlatform tradingPlatform = tradingPlatformBaseService
                        .findByCertNo(salesContractDto.getAgencyCertNo());
                if (!DictConstants.DISTRICT_CN_MAINLAND.equals(tradingPlatform.getDistrictCode())) {
                    throw new ServiceException("订单订单id" + salesOrderId + "为非“中国大陆”公司代理出口的销售订单");
                }
            }
        } else {
            if (StringUtils.isNotEmpty(salesContractDto.getAgencyCertNo())) {
                TradingPlatform tradingPlatform = tradingPlatformBaseService
                        .findByCertNo(salesContractDto.getAgencyCertNo());
                if (DictConstants.DISTRICT_CN_MAINLAND.equals(tradingPlatform.getDistrictCode())) {
                    throw new ServiceException("订单订单id" + salesOrderId + "“中国大陆”公司代理出口的销售订单，不能勾选");
                }
            }
        }
        SalesOrder salesOrder = this.baseMapper.selectById(salesOrderId);
        if (salesOrder.getStatus().equals(SaleOrderConstant.ORDER_STATUS_INIT)
                || salesOrder.getStatus().equals(SaleOrderConstant.ORDER_STATUS_WAIT_DELIVERY)
                || salesOrder.getStatus().equals(SaleOrderConstant.ORDER_STATUS_REPAYMENT_UNDER_REVIEW)
                || salesOrder.getStatus().equals(SaleOrderConstant.ORDER_STATUS_RECEIVED)
                || salesOrder.getStatus().equals(SaleOrderConstant.ORDER_STATUS_END)) {
            throw new ServiceException("订单订单id为" + salesOrderId + "的订单状态不允许提示收款");
        }
    }
}
