package cn.superdesk.uniorder.service.thirdpart.qchjc.account.impl;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.StrUtil;
import cn.superdesk.uniorder.common.HttpUtil;
import cn.superdesk.uniorder.common.enums.accounting.AccountingOrderBackAccountStatusEnum;
import cn.superdesk.uniorder.common.enums.accounting.AccountingOrderDimCreateByEnum;
import cn.superdesk.uniorder.common.enums.accounting.AccountingOrderIsSendEmailEnum;
import cn.superdesk.uniorder.common.enums.accounting.AccountingOrderTypeDimEnum;
import cn.superdesk.uniorder.common.enums.accounting.customer.AccountingOrderCustomerAccountingStatusEnum;
import cn.superdesk.uniorder.common.enums.common.*;
import cn.superdesk.uniorder.common.enums.invoice.customer.InvoiceApplyCustomerInvoiceProgressingStatusEnum;
import cn.superdesk.uniorder.common.enums.invoice.customer.InvoiceApplyCustomerMakeInvoiceStatusEnum;
import cn.superdesk.uniorder.common.enums.invoice.customer.InvoiceApplyCustomerReceiveInvoiceStatusEnum;
import cn.superdesk.uniorder.common.enums.order.UnifiedOrderCreditBackAccountStatusEnum;
import cn.superdesk.uniorder.common.enums.order.UnifiedOrderCreditInvoiceApplyStatusEnum;
import cn.superdesk.uniorder.common.enums.order.UnifiedOrderCreditInvoiceMakeStatusEnum;
import cn.superdesk.uniorder.common.enums.order.UnifiedOrderCreditTypeDefaultEnum;
import cn.superdesk.uniorder.common.enums.thirdpart.qchjc.QchjcOrgEnum;
import cn.superdesk.uniorder.common.enums.thirdpart.qchjc.QchjcStorageStatusEnum;
import cn.superdesk.uniorder.common.exception.OpenApiException;
import cn.superdesk.uniorder.common.json.AnJsonUtils;
import cn.superdesk.uniorder.common.lamda.AnLamdaUtils;
import cn.superdesk.uniorder.common.numerical.AnBeanUtils;
import cn.superdesk.uniorder.common.numerical.AnCollectionUtils;
import cn.superdesk.uniorder.common.numerical.AnStringUtils;
import cn.superdesk.uniorder.common.rest.response.R;
import cn.superdesk.uniorder.common.security.JwtUtil;
import cn.superdesk.uniorder.common.security.dto.LoginSysUser;
import cn.superdesk.uniorder.dao.entity.accounting.score.customer.AccountingScoreCustomer;
import cn.superdesk.uniorder.dao.entity.accounting.score.customer.AccountingScoreCustomerExample;
import cn.superdesk.uniorder.dao.entity.base.*;
import cn.superdesk.uniorder.dao.entity.invoice.common.InvoiceBankInfo;
import cn.superdesk.uniorder.dao.entity.invoice.customer.InvoiceApply;
import cn.superdesk.uniorder.dao.entity.operation.UnifiedOrderIssuesFlowing;
import cn.superdesk.uniorder.dao.entity.sys.SysUser;
import cn.superdesk.uniorder.dao.entity.thirdpart.qchjc.accounting.*;
import cn.superdesk.uniorder.dao.entity.thirdpart.qchjc.invoice.QchjcInvoiceApplyEntity;
import cn.superdesk.uniorder.dao.entity.thirdpart.qchjc.invoice.QchjcInvoiceApplyEntityExample;
import cn.superdesk.uniorder.dao.entity.thirdpart.qchjc.invoice.QchjcInvoiceApplyRelationEntity;
import cn.superdesk.uniorder.dao.entity.thirdpart.qchjc.invoice.QchjcInvoiceApplyRelationEntityExample;
import cn.superdesk.uniorder.dao.entity.thirdpart.qchjc.organisation.QchjcEnterpriseEntity;
import cn.superdesk.uniorder.dao.entity.thirdpart.qchjc.organisation.QchjcSupplierEntity;
import cn.superdesk.uniorder.dao.mapper.accounting.score.customer.AccountingScoreCustomerMapper;
import cn.superdesk.uniorder.dao.mapper.base.*;
import cn.superdesk.uniorder.dao.mapper.organisation.SysEnterpriseMapper;
import cn.superdesk.uniorder.dao.mapper.thirdpart.qchjc.accounting.*;
import cn.superdesk.uniorder.dao.mapper.thirdpart.qchjc.invoice.QchjcInvoiceApplyEntityMapper;
import cn.superdesk.uniorder.dao.mapper.thirdpart.qchjc.invoice.QchjcInvoiceApplyRelationEntityMapper;
import cn.superdesk.uniorder.dao.mapper.thirdpart.qchjc.organisation.QchjcEnterpriseEntityMapper;
import cn.superdesk.uniorder.dao.mapper.thirdpart.qchjc.organisation.QchjcSupplierEntityMapper;
import cn.superdesk.uniorder.dto.param.accounting.qchjc.QchjcCustomerAccountingListRequest;
import cn.superdesk.uniorder.dto.param.accounting.score.customer.AccountingOrderScoreCustomerCreateParam;
import cn.superdesk.uniorder.dto.param.accounting.score.customer.AccountingOrderScoreCustomerCreateSelectedCreditParam;
import cn.superdesk.uniorder.dto.param.accounting.score.customer.AccountingOrderScoreCustomerNotYetDimCreditScene2QueryCriteria;
import cn.superdesk.uniorder.dto.param.invoice.common.InvoiceBankInfoQueryCriteria;
import cn.superdesk.uniorder.dto.param.invoice.customer.InvoiceApplyFocusScoreOpApplyFormV2_1;
import cn.superdesk.uniorder.dto.param.invoice.customer.InvoiceApplyOpCreateSelectedCreditParams;
import cn.superdesk.uniorder.dto.param.invoice.customer.status.OpBackAccountStatusForm;
import cn.superdesk.uniorder.dto.param.invoice.customer.status.OpChangeStatusBaseItem;
import cn.superdesk.uniorder.dto.param.setting.UnifiedServicePartGoodsTransportParam;
import cn.superdesk.uniorder.dto.param.thirdpart.qchjc.accounting.QchjcAccountingScoreCustomerParam;
import cn.superdesk.uniorder.dto.param.thirdpart.qchjc.accounting.QchjcCustomerStorageParam;
import cn.superdesk.uniorder.dto.param.thirdpart.qchjc.accounting.QchjcOrderGoodsParam;
import cn.superdesk.uniorder.dto.param.thirdpart.qchjc.accounting.QchjcOrderParam;
import cn.superdesk.uniorder.dto.param.thirdpart.qchjc.api.QchjcResponse;
import cn.superdesk.uniorder.dto.param.thirdpart.qchjc.api.customer.QchjcCustomerCancelStatementParam;
import cn.superdesk.uniorder.dto.param.thirdpart.qchjc.api.customer.QchjcCustomerMakeInvoiceStatusParam;
import cn.superdesk.uniorder.dto.param.thirdpart.qchjc.api.customer.QchjcCustomerReceivePaymentStatusParam;
import cn.superdesk.uniorder.dto.vo._function.select.SelectOptionVirt;
import cn.superdesk.uniorder.dto.vo.invoice.customer.InvoiceApplyDetailDimCreditItemVo;
import cn.superdesk.uniorder.dto.vo.thirdpart.qchjc.accounting.QchjcCustomerStatementVo;
import cn.superdesk.uniorder.dto.vo.thirdpart.qchjc.accounting.QchjcOrderGoodsVo;
import cn.superdesk.uniorder.dto.vo.thirdpart.qchjc.accounting.QchjcOrderVo;
import cn.superdesk.uniorder.dto.vo.thirdpart.qchjc.invoice.QchjcApplyResVo;
import cn.superdesk.uniorder.dto.vo.thirdpart.qchjc.invoice.QchjcInvoiceApplyVo;
import cn.superdesk.uniorder.service.accounting.score.customer.AccountingScoreCustomerService;
import cn.superdesk.uniorder.service.order.base.CommonOrderProcessService;
import cn.superdesk.uniorder.service.order.base.CommonOrderTransportProcessService;
import cn.superdesk.uniorder.service.order.base.ScoreOrderService;
import cn.superdesk.uniorder.service.invoice.common.InvoiceBankInfoService;
import cn.superdesk.uniorder.service.invoice.customer.InvoiceApplyCustomerOpCreateService;
import cn.superdesk.uniorder.service.invoice.customer.InvoiceApplyCustomerService;
import cn.superdesk.uniorder.service.invoice.customer.state.InvoiceApplyCustomerFieldBackAccountStatusService;
import cn.superdesk.uniorder.service.setting.UnifiedServiceService;
import cn.superdesk.uniorder.service.sys.SysUserService;
import cn.superdesk.uniorder.service.thirdpart.qchjc.account.QchjcCustomerStatementService;
import cn.superdesk.uniorder.service.thirdpart.qchjc.log.QchjcLogService;
import com.alibaba.fastjson2.JSON;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.function.Predicate;
import java.util.stream.Collectors;

/**
 * @author xc
 * @description
 * @date 2022/4/1 11:43
 */
@Slf4j
@Service
@RequiredArgsConstructor
public class QchjcCustomerStatementServiceImpl implements QchjcCustomerStatementService {


    private final QchjcAccountingScoreCustomerEntityMapper          qchjcAccountingCustomerMapper;
    private final QchjcUserEntityMapper                             qchjcUserEntityMapper;
    private final SysUserService                                    sysUserService;
    private final QchjcOrderGoodsEntityMapper                       qchOrderGoodsEntityMapper;
    private final QchjcOrderEntityMapper                            qchOrderEntityMapper;
    private final SysEnterpriseMapper                               sysEnterpriseMapper;
    private final CommonOrderTransportProcessService                commonOrderTransportProcessService;
    private final CommonOrderProcessService                         commonOrderProcessService;
    private final UnifiedOrderMapper                                unifiedOrderMapper;
    private final UnifiedOrderCreditMapper                          unifiedOrderCreditMapper;
    private final UnifiedOrderCreditMapperEx                        unifiedOrderCreditMapperEx;
    private final UnifiedOrderGoodsMapper                           unifiedOrderGoodsMapper;
    private final UnifiedOrderGoodsMapperEx                         unifiedOrderGoodsMapperEx;
    private final InvoiceBankInfoService                            invoiceBankInfoService;
    private final ScoreOrderService                                 scoreOrderService;
    private final QchjcInvoiceApplyEntityMapper                     qchjcInvoiceApplyEntityMapper;
    private final InvoiceApplyCustomerOpCreateService               invoiceApplyCustomerOpCreateService;
    private final AccountingScoreCustomerMapper                     accountingScoreCustomerMapper;
    private final QchjcEnterpriseEntityMapper                       qchjcEnterpriseEntityMapper;
    private final QchjcSupplierEntityMapper                         qchjcSupplierEntityMapper;
    private final QchjcCustomerBackAccountEntityMapper              qchjcCustomerBackAccountEntityMapper;
    private final InvoiceApplyCustomerService                       invoiceApplyCustomerService;
    private final AccountingScoreCustomerService                    accountingScoreCustomerService;
    private final InvoiceApplyCustomerFieldBackAccountStatusService invoiceApplyCustomerFieldBackAccountStatusService;
    private final UnifiedServiceService                             unifiedServiceService;
    private final QchjcLogService                                   qchjcLogService;
    private final QchjcInvoiceApplyRelationEntityMapper             qchjcInvoiceApplyRelationEntityMapper;

    @Value(value = "${qchjc.domain}")
    private String  domain;
    @Value(value = "${qchjc.customer.makeInvoiceStatusSyncApi}")
    private String  makeInvoiceStatusSyncApi;
    @Value(value = "${qchjc.customer.receivePaymentStatusSyncApi}")
    private String  receiveInvoiceStatusSyncApi;
    @Value(value = "${qchjc.customer.statementCancelApi}")
    private String  statementCancelApi;
    @Value(value = "${qchjc.push.enable}")
    private boolean pushEnabled;


    @Override
    public int insertSelective(QchjcAccountingScoreCustomerEntity qchjcAccountingScoreCustomerEntity) {
        return qchjcAccountingCustomerMapper.insertSelective(qchjcAccountingScoreCustomerEntity);
    }

    @Override
    public int updateByPrimaryKeySelective(QchjcAccountingScoreCustomerEntity qchjcAccountingScoreCustomerEntity) {
        return qchjcAccountingCustomerMapper.updateByPrimaryKeySelective(qchjcAccountingScoreCustomerEntity);
    }

    @Override
    public void deleteObj(Long id) {
        qchjcAccountingCustomerMapper.deleteByPrimaryKey(id);
    }

    @Override
    public QchjcAccountingScoreCustomerEntity findById(Long id) {
        return qchjcAccountingCustomerMapper.selectByPrimaryKey(id);
    }

    @Override
    public List<QchjcAccountingScoreCustomerEntity> findAll(Map<String, Object> queryMap) {
        return null;
    }

    @Override
    public PageInfo<QchjcAccountingScoreCustomerEntity> findByPaging(Map<String, Object> params, Integer pageNo, Integer pageSize) {
        return null;
    }

    /**
     * 采购单位对账单状态同步 集采 -> 结算中心
     *
     * @param toJSONString
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public void syncStatus(String toJSONString) {
        QchjcCustomerBackAccountEntity entity = AnJsonUtils.toObject(toJSONString, QchjcCustomerBackAccountEntity.class);
        //数据库留存一份
        entity.setSyncTime(DateUtil.date());
        qchjcCustomerBackAccountEntityMapper.insertSelective(entity);

        if (entity.getBackAccountStatus() != 2) {
            throw new OpenApiException(500, "只接收全部回款");
        }
        String                             accountingOrderSn                  = entity.getAccountingOrderSn();
        QchjcAccountingScoreCustomerEntity qchjcAccountingScoreCustomerEntity = qchjcAccountingCustomerMapper.selectByAccountingOrderSn(accountingOrderSn);
        if (qchjcAccountingScoreCustomerEntity == null) {
            throw new OpenApiException(500, "对账单信息未同步，请先同步对账单");
        }

        //构造参数
        //对账单不存在
        AccountingScoreCustomer accountingScoreCustomer = accountingScoreCustomerService.findByAccountingOrderSn(accountingOrderSn);
        if (accountingScoreCustomer == null) {
            throw new OpenApiException(500, "该对账单不存在，请检查");
        }
        //对账单状态为已取消
        if (AccountingOrderCustomerAccountingStatusEnum.已取消.getKey().equals(accountingScoreCustomer.getAccountingStatus())) {
            throw new OpenApiException(500, "该对账单已取消，请检查");
        }

        /**
         * 检查对账单有效的开票申请是否全部为"待回款" （有效的开票申请 不包含 已红冲/已作废/已删除 状态的开票申请）
         */
        //所有开票申请
        List<InvoiceApply> entitysExistDb = invoiceApplyCustomerService.findByAccountingOrderSn(accountingOrderSn, AccountingOrderTypeDimEnum.积分订单);

        if (CollUtil.isEmpty(entitysExistDb)) {
            throw new OpenApiException(500, "数据异常，对账单下没有开票申请");
        }
        //过滤掉已红冲和已作废的开票申请
        List<InvoiceApply> collect = entitysExistDb.stream().filter(invoiceApply ->
                !InvoiceApplyCustomerInvoiceProgressingStatusEnum.已红冲.getKey().equals(invoiceApply.getInvoiceStatus())
                        && !InvoiceApplyCustomerInvoiceProgressingStatusEnum.已作废.getKey().equals(invoiceApply.getInvoiceStatus())
        ).collect(Collectors.toList());

        if (CollectionUtils.isEmpty(collect)) {
            throw new OpenApiException(500, "该对账单非回款流程节点，请检查");
        }
        //判断是否有处于非待回款节点的开票申请
        List<InvoiceApply> inconformity = collect.stream().filter(i -> !InvoiceApplyCustomerInvoiceProgressingStatusEnum.待回款.getKey().equals(i.getInvoiceStatus())).collect(Collectors.toList());
        if (CollectionUtils.isNotEmpty(inconformity)) {
            throw new OpenApiException(500, "该对账单非回款流程节点，请检查");
        }

        //所有待回款节点的开票申请
        List<InvoiceApply> conformity = collect.stream().filter(i -> InvoiceApplyCustomerInvoiceProgressingStatusEnum.待回款.getKey().equals(i.getInvoiceStatus())).collect(Collectors.toList());
        if (CollectionUtils.isEmpty(conformity)) {
            throw new OpenApiException(500, "该对账单非回款流程节点，请检查");
        }

        //处理用户
        handle(entity.getBackAccountUserId(), entity.getBackAccountUserName());
        try {

            OpBackAccountStatusForm      form       = new OpBackAccountStatusForm();
            List<OpChangeStatusBaseItem> submitList = new ArrayList<>();
            //构造表单参数- 待回款的
            for (InvoiceApply invoiceApply : conformity) {
                OpChangeStatusBaseItem item = new OpChangeStatusBaseItem();
                item.setAccountingOrderId(accountingScoreCustomer.getId());
                item.setAccountingOrderSn(accountingScoreCustomer.getAccountingOrderSn());
                item.setInvoiceApplyId(invoiceApply.getId());
                item.setInvoiceApplySn(invoiceApply.getInvoiceApplySn());
                submitList.add(item);
            }
            form.setSubmitList(submitList);
            //调用方法，更改状态
            Long         unifiedId = qchjcUserEntityMapper.selectByOutId(entity.getBackAccountUserId()).getUnifiedId();
            LoginSysUser login     = LoginSysUser.builder().sysUserId(unifiedId).sysUserName(entity.getBackAccountUserName()).build();
            invoiceApplyCustomerFieldBackAccountStatusService.opComplete(entitysExistDb, form, login);
        } catch (Exception e) {
            log.info("结算中心采购单位回款状态同步失败，异常信息：{}", e.getLocalizedMessage());
            throw new OpenApiException(500, "结算中心回款状态同步失败");
        }
        //更新中间表状态
        qchjcAccountingScoreCustomerEntity.setBackAccountStatus(AccountingOrderBackAccountStatusEnum.全部回款.getKey());//已收款
        qchjcAccountingScoreCustomerEntity.setReceiveInvoiceStatus(InvoiceApplyCustomerReceiveInvoiceStatusEnum.已领票.getKey());//已收票
        qchjcAccountingScoreCustomerEntity.setUpdateTime(entity.getBackAccountTime());
        qchjcAccountingScoreCustomerEntity.setUpdateUserId(entity.getBackAccountUserId());
        qchjcAccountingScoreCustomerEntity.setUpdateUserName(entity.getBackAccountUserName());
        qchjcAccountingCustomerMapper.updateByPrimaryKeySelective(qchjcAccountingScoreCustomerEntity);
    }

    /**
     * 采购单位开票状态推送 结算中心 -> 集采
     *
     * @param param
     * @return
     */
    @Override
    @Async
    public void makeInvoiceStatusSync(QchjcCustomerMakeInvoiceStatusParam param) {
        if (!pushEnabled) {
            //推送未启用
            return;
        }
        QchjcResponse response = null;
        try {
            String result = HttpUtil.post(JSON.toJSONString(param), domain + makeInvoiceStatusSyncApi);
            log.info("集采开票状态同步返回结果：{}", result);
            response = JSON.parseObject(result, QchjcResponse.class);
        } catch (Exception e) {
            log.info("集采开票状态同步异常：{}", e.getMessage());
            response = QchjcResponse.builder()
                    .success(false)
                    .resultMessage("集采开票状态同步异常").build();
        } finally {
            if (response != null) {
                qchjcLogService.record(response.isSuccess() ? 1 : 0, "采购单位开票状态推送", JSON.toJSONString(param), JSON.toJSONString(response));
            }
        }

        //中间表处理
        QchjcAccountingScoreCustomerEntity qchjcAccountingScoreCustomerEntity = qchjcAccountingCustomerMapper.selectByAccountingOrderSn(param.getReconciliationBuyerCode());
        if (qchjcAccountingScoreCustomerEntity != null) {
            //修改中间表开票状态
            qchjcAccountingScoreCustomerEntity.setInvoiceStatus(InvoiceApplyCustomerMakeInvoiceStatusEnum.已开票.getKey());//已开票
            qchjcAccountingScoreCustomerEntity.setUpdateTime(DateUtil.date());
            qchjcAccountingScoreCustomerEntity.setUpdateUserId(param.getOperatorId());
            qchjcAccountingScoreCustomerEntity.setUpdateUserName(param.getOperatorName());
            qchjcAccountingCustomerMapper.updateByPrimaryKeySelective(qchjcAccountingScoreCustomerEntity);
        }
        //保存发票号
        Map<String, String> invoiceNumberMap = param.getInvoiceNumberMap();
        if (invoiceNumberMap != null && invoiceNumberMap.size() > 0) {
            for (Map.Entry<String, String> entry : invoiceNumberMap.entrySet()) {
                String key   = entry.getKey();//开票申请编号
                String value = entry.getValue();//发票号,多个用`,`分隔

                QchjcInvoiceApplyRelationEntityExample example = new QchjcInvoiceApplyRelationEntityExample();
                example.createCriteria().andInvoiceApplySnEqualTo(key);
                List<QchjcInvoiceApplyRelationEntity> qchjcInvoiceApplyRelationEntities = qchjcInvoiceApplyRelationEntityMapper.selectByExample(example);
                if (CollectionUtils.isNotEmpty(qchjcInvoiceApplyRelationEntities)) {
                    QchjcInvoiceApplyRelationEntity qchjcInvoiceApplyRelationEntity = qchjcInvoiceApplyRelationEntities.get(0);
                    QchjcInvoiceApplyEntity         qchjcInvoiceApplyEntity         = qchjcInvoiceApplyEntityMapper.selectByPrimaryKey(qchjcInvoiceApplyRelationEntity.getQchjcInvoiceApplyId());
                    String                          invoiceNumber                   = qchjcInvoiceApplyEntity.getInvoiceNumber();
                    if (StringUtils.isNotEmpty(invoiceNumber)) {
                        if (!invoiceNumber.contains(value)) {
                            qchjcInvoiceApplyEntity.setInvoiceNumber(invoiceNumber + "," + value);
                        }
                    } else {
                        qchjcInvoiceApplyEntity.setInvoiceNumber(value);
                    }
                    qchjcInvoiceApplyEntityMapper.updateByPrimaryKeySelective(qchjcInvoiceApplyEntity);
                }
            }
        }
    }

    /**
     * 采购单位收款状态同步 结算中心 -> 集采
     *
     * @param param
     * @return
     */
    @Override
    @Async
    public void receivePaymentStatusSync(QchjcCustomerReceivePaymentStatusParam param) {
        if (!pushEnabled) {
            //推送未启用
            return;
        }
        QchjcResponse response = null;
        try {
            String result = HttpUtil.post(JSON.toJSONString(param), domain + receiveInvoiceStatusSyncApi);
            log.info("集采收款状态同步返回结果：{}", result);
            response = JSON.parseObject(result, QchjcResponse.class);
        } catch (Exception e) {
            log.info("集采收款状态同步异常：{}", e.getMessage());
            response = QchjcResponse.builder()
                    .success(false)
                    .resultMessage("集采收款状态同步异常")
                    .build();
        } finally {
            if (response != null) {
                qchjcLogService.record(response.isSuccess() ? 1 : 0, "采购单位收款状态推送", JSON.toJSONString(param), JSON.toJSONString(response));
            }
        }

        //中间表处理
        QchjcAccountingScoreCustomerEntity qchjcAccountingScoreCustomerEntity = qchjcAccountingCustomerMapper.selectByAccountingOrderSn(param.getReconciliationBuyerCode());
        if (qchjcAccountingScoreCustomerEntity != null) {
            //修改中间表开票状态
            qchjcAccountingScoreCustomerEntity.setBackAccountStatus(AccountingOrderBackAccountStatusEnum.全部回款.getKey());//已收款
            qchjcAccountingScoreCustomerEntity.setReceiveInvoiceStatus(InvoiceApplyCustomerReceiveInvoiceStatusEnum.已领票.getKey());
            qchjcAccountingScoreCustomerEntity.setUpdateTime(DateUtil.date());
            qchjcAccountingScoreCustomerEntity.setUpdateUserId(param.getOperatorId());
            qchjcAccountingScoreCustomerEntity.setUpdateUserName(param.getOperatorName());
            qchjcAccountingCustomerMapper.updateByPrimaryKeySelective(qchjcAccountingScoreCustomerEntity);
        }
    }

    /**
     * 采购单位对账单作废接口 结算中心 -> 集采
     *
     * @param param
     * @return
     */
    @Override
    @Async
    public void statementCancelSync(QchjcCustomerCancelStatementParam param) {
        if (!pushEnabled) {
            //推送未启用
            return;
        }
        QchjcResponse response = null;
        try {
            String result = HttpUtil.post(JSON.toJSONString(param), domain + statementCancelApi);
            log.info("集采对账单作废接口返回结果：{}", result);
            response = JSON.parseObject(result, QchjcResponse.class);
        } catch (Exception e) {
            log.info("集采对账单作废接口异常：{}", e.getMessage());
            response = QchjcResponse.builder()
                    .success(false)
                    .resultMessage("集采对账单作废接口异常")
                    .build();
        } finally {
            if (response != null) {
                qchjcLogService.record(response.isSuccess() ? 1 : 0, "采购单位对账单作废接口推送", JSON.toJSONString(param), JSON.toJSONString(response));
            }
        }

        //中间表处理
        QchjcAccountingScoreCustomerEntity qchjcAccountingScoreCustomerEntity = qchjcAccountingCustomerMapper.selectByAccountingOrderSn(param.getReconciliationBuyerCode());
        if (qchjcAccountingScoreCustomerEntity != null) {
            //修改中间表开票状态
            qchjcAccountingScoreCustomerEntity.setAccountingStatus(AccountingOrderCustomerAccountingStatusEnum.已取消.getKey());//已取消
            qchjcAccountingScoreCustomerEntity.setUpdateTime(DateUtil.date());
            qchjcAccountingScoreCustomerEntity.setUpdateUserId(param.getOperatorId());
            qchjcAccountingScoreCustomerEntity.setUpdateUserName(param.getOperatorName());
            qchjcAccountingCustomerMapper.updateByPrimaryKeySelective(qchjcAccountingScoreCustomerEntity);
            /**
             * 20220609 取消订单、商品中间表中和对账单的关联关系
             */
            QchjcOrderEntityExample qchjcOrderEntityExample = new QchjcOrderEntityExample();
            //根据采购单位对账单sn字段把对账单与订单的关联关系取消
            qchjcOrderEntityExample.createCriteria().andCustomerAccountingOrderSnEqualTo(param.getReconciliationBuyerCode());
            QchjcOrderEntity qchjcOrderEntity = new QchjcOrderEntity();
            qchjcOrderEntity.setCustomerAccountingOrderSn("");
            qchOrderEntityMapper.updateByExampleSelective(qchjcOrderEntity, qchjcOrderEntityExample);
            //根据采购单位对账单sn字段把对账单与商品的关联关系 & 发票单的关联取消 & 采购单位对账状态改为未对账
            QchjcOrderGoodsEntityExample updateOrderGoodsExample = new QchjcOrderGoodsEntityExample();
            updateOrderGoodsExample.createCriteria().andCustomerAccountingOrderSnEqualTo(param.getReconciliationBuyerCode());
            QchjcOrderGoodsEntity qchjcOrderGoodsEntity = new QchjcOrderGoodsEntity();
            qchjcOrderGoodsEntity.setCustomerAccountingOrderSn("");
            qchjcOrderGoodsEntity.setQchCustomerInvoiceApplyId(0L);
            qchjcOrderGoodsEntity.setAccountingStateCustomer(CommonAccountingStateEnum.未对账.getKey());
            qchOrderGoodsEntityMapper.updateByExampleSelective(qchjcOrderGoodsEntity, updateOrderGoodsExample);

        }
    }

    /**
     * 企业商城账单-采购单位账单列表查询
     *
     * @param request
     * @return
     */
    @Override
    public R<List<QchjcCustomerStatementVo>> queryQchjcCustomerStatementList(QchjcCustomerAccountingListRequest request) {
        PageHelper.startPage(request.getPageNumber(), request.getPageSize());
        List<QchjcCustomerStatementVo>     qchjcCustomerStatementVos = qchjcAccountingCustomerMapper.queryQchjcCustomerStatementList(request);
        PageInfo<QchjcCustomerStatementVo> page                      = new PageInfo<>(qchjcCustomerStatementVos);
        return new R<List<QchjcCustomerStatementVo>>(page.getPageNum(), page.getPageSize(), (int) page.getTotal(), qchjcCustomerStatementVos);
    }

    @Override
    public R<String> updateRemark(Long id, String remark, String token) {
        QchjcAccountingScoreCustomerEntity qchjcAccountingScoreCustomerEntity = qchjcAccountingCustomerMapper.selectByPrimaryKey(id);
        if (qchjcAccountingScoreCustomerEntity == null) {
            return new R<>("500", "未查询到对应的记录", false);
        }
        qchjcAccountingScoreCustomerEntity.setRemark(remark);
        qchjcAccountingScoreCustomerEntity.setUpdateTime(DateUtil.date());

        LoginSysUser loginSysUser = JwtUtil.getLoginSysUser(token);
        qchjcAccountingScoreCustomerEntity.setUpdateUserId(loginSysUser.getSysUserId().toString());
        qchjcAccountingScoreCustomerEntity.setUpdateUserName(loginSysUser.getFullName());
        qchjcAccountingCustomerMapper.updateByPrimaryKeySelective(qchjcAccountingScoreCustomerEntity);
        return new R<>("200", "更新成功", true);
    }

    /**
     * 根据id查询账单详情，包含对账单信息+发票单信息
     *
     * @param id
     * @return
     */
    @Override
    public R<QchjcCustomerStatementVo> queryQchjcCustomerStatementVoById(Long id) {
        QchjcAccountingScoreCustomerEntity qchjcAccountingScoreCustomerEntity = qchjcAccountingCustomerMapper.selectByPrimaryKey(id);
        if (qchjcAccountingScoreCustomerEntity == null) {
            return new R<>("500", "未查询到对应的记录", false);
        }
        //对账单主体信息
        QchjcCustomerStatementVo vo = qchjcAccountingCustomerMapper.queryQchjcCustomerStatementVoById(id);
        //发票单信息
        List<QchjcInvoiceApplyVo> invoiceApplyVoList = qchjcInvoiceApplyEntityMapper.queryQchjcInvoiceApplyVoListByAccountingOrderSn(vo.getAccountingOrderSn());

        //从关系表查询统一订单的 开票申请sn 和明细数、申请金额数据
        invoiceApplyVoList.forEach(invoiceApplyVo -> {
            List<QchjcApplyResVo> applyList = qchjcInvoiceApplyRelationEntityMapper.selectQchjcApplyResByInvoiceSn(invoiceApplyVo.getInvoiceSn());
            invoiceApplyVo.setApplyList(applyList);
        });
        vo.setInvoiceApplyVoList(invoiceApplyVoList);
        return new R<>(vo);
    }

    @Override
    public List<Long> getTodoIdList() {
        return qchjcAccountingCustomerMapper.getTodoIdList();
    }

    @Override
    public void putInvoiceApplyIntoStorage(Long id, AccountingScoreCustomer scoreAccountingCustomer) {

        QchjcCustomerStatementVo vo = getTodoList(id);

        QchjcInvoiceApplyEntityExample qchjcInvoiceApplyEntityExample = new QchjcInvoiceApplyEntityExample();
        qchjcInvoiceApplyEntityExample.createCriteria()
                .andAccountingOrderSnEqualTo(vo.getAccountingOrderSn());
        //查询对账单对应的发票单
        List<QchjcInvoiceApplyEntity> qchjcInvoiceApplyEntities = qchjcInvoiceApplyEntityMapper.selectByExample(qchjcInvoiceApplyEntityExample);

        /**
         * 调用一键分票,发票单入库
         */

        for (QchjcInvoiceApplyEntity qchjcInvoiceApplyEntity : qchjcInvoiceApplyEntities) {
            //构造表单
            InvoiceApplyFocusScoreOpApplyFormV2_1 form = new InvoiceApplyFocusScoreOpApplyFormV2_1();
            //form.setJcUnAccountingAmount(qchjcInvoiceApplyEntity.getJcUnAccountingAmount());//集采发票单不对账金额
            //form.setJcRealAmount(qchjcInvoiceApplyEntity.getRealAmount());//集采发票单实际金额
            form.setAccountingOrderSn(scoreAccountingCustomer.getAccountingOrderSn());//对账单编号
            form.setAccountingOrderId(scoreAccountingCustomer.getId());//对账单id

            form.setInvoiceTypeId(qchjcInvoiceApplyEntity.getInvoiceType());//发票类型
            form.setInvoiceMode(qchjcInvoiceApplyEntity.getInvoiceMode());//开票方式

            form.setRemark(qchjcInvoiceApplyEntity.getRemark());//备注
            form.setSysEnterpriseExtInvoiceId(qchjcInvoiceApplyEntity.getSysEnterpriseExtInvoiceId());//系统企业扩展发票id
            List<InvoiceApplyOpCreateSelectedCreditParams> creditSelected = new ArrayList<>();
            //查询发票单下所有商品
            List<QchjcOrderGoodsEntity> qchjcOrderGoodsEntities = qchOrderGoodsEntityMapper.selectByInvoiceApplyId(qchjcInvoiceApplyEntity.getId());
            if (CollectionUtils.isEmpty(qchjcOrderGoodsEntities)) {
                log.error("发票单下没有商品，发票单id：{}", qchjcInvoiceApplyEntity.getId());
                throw new OpenApiException(500, "发票单下没有商品");
            }
            for (QchjcOrderGoodsEntity qchjcOrderGoodsEntity : qchjcOrderGoodsEntities) {
                InvoiceApplyOpCreateSelectedCreditParams param = new InvoiceApplyOpCreateSelectedCreditParams();
                param.setUnifiedOrderId(qchjcOrderGoodsEntity.getUnifiedOrderId());//统一订单id
                param.setUnifiedOrderGoodsId(qchjcOrderGoodsEntity.getUnifiedId());//统一订单商品id
                param.setUnifiedOrderCreditId(qchjcOrderGoodsEntity.getUnifiedCreditId());//统一订单流水id
                creditSelected.add(param);
            }
            form.setCreditSelected(creditSelected);

            form.setSourceFrom(CommonSourceFromEnum.企业商城_侨城汇.getSourceFromCode());// 操作来源
            form.setServiceNo(CommonServiceNoEnum.企业商城_侨城汇.getServiceNo());// 订单来源

            LoginSysUser invoiceLoginUser = new LoginSysUser();
            invoiceLoginUser.setSysUserName(qchjcInvoiceApplyEntity.getApplyUserName());
            QchjcUserEntity qchjcUserEntity1 = qchjcUserEntityMapper.selectByOutId(qchjcInvoiceApplyEntity.getApplyUserId());
            invoiceLoginUser.setSysUserId(qchjcUserEntity1.getUnifiedId());
            //调用一键分票
            invoiceApplyCustomerOpCreateService.opInvoiceApplyV2_1(form, invoiceLoginUser);
            //把统一订单开票申请编号/订单数/开票申请金额更新到中间表的invoice_apply_sn字段，格式 开票申请编号-订单数（实际是明细数量）-开票申请金额，多个开票申请时用,分隔
            //List<String> res = qchjcInvoiceApplyEntityMapper.selectInvoiceApplyResByQchjcApplyId(qchjcInvoiceApplyEntity.getId());

            //把集采发票单-结算中心开票申请关系保存到中间表
            List<QchjcInvoiceApplyRelationEntity> list = qchjcInvoiceApplyRelationEntityMapper.selectInvoiceApplyResByQchjcApplyId(qchjcInvoiceApplyEntity.getId());
            if (CollectionUtils.isNotEmpty(list)) {
                for (QchjcInvoiceApplyRelationEntity qchjcInvoiceApplyRelationEntity : list) {
                    qchjcInvoiceApplyRelationEntity.setQchjcInvoiceApplyId(qchjcInvoiceApplyEntity.getId());
                    qchjcInvoiceApplyRelationEntityMapper.insert(qchjcInvoiceApplyRelationEntity);
                }
                //String collect = String.join(",", res);
                //qchjcInvoiceApplyEntity.setInvoiceApplySn(collect);
                //qchjcInvoiceApplyEntityMapper.updateByPrimaryKeySelective(qchjcInvoiceApplyEntity);
            }

        }
    }

    /**
     * 查询所有待入库状态对账单
     *
     * @return
     */
    @Override
    public QchjcCustomerStatementVo getTodoList(Long id) {
        return qchjcAccountingCustomerMapper.getTodoList(id);

    }

    @Override
    public QchjcAccountingScoreCustomerEntity selectByAccountingOrderSn(String accountingOrderSn) {
        QchjcAccountingScoreCustomerEntityExample example = new QchjcAccountingScoreCustomerEntityExample();
        example.createCriteria()
                .andAccountingOrderSnEqualTo(accountingOrderSn);
        List<QchjcAccountingScoreCustomerEntity> entities = qchjcAccountingCustomerMapper.selectByExample(example);
        if (CollectionUtils.isNotEmpty(entities)) {
            return entities.get(0);
        } else {
            throw new OpenApiException(500, "对账单不存在, accountOrderSn : " + accountingOrderSn);
        }

    }

    @Override
    public QchjcAccountingScoreCustomerEntity selectByPrimaryKey(Long id) {
        return qchjcAccountingCustomerMapper.selectByPrimaryKey(id);
    }

    /**
     * 对账单入库统一订单
     *
     * @param todoId
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public QchjcCustomerStorageParam doSaveDetail(Long todoId) {

        //校验是否有发票单，如果没有跳过任务
        QchjcCustomerStatementVo vo = getTodoList(todoId);

        Integer invoiceCount = vo.getInvoiceCount();

        QchjcInvoiceApplyEntityExample qchjcInvoiceApplyEntityExample = new QchjcInvoiceApplyEntityExample();
        qchjcInvoiceApplyEntityExample
                .createCriteria()
                .andAccountingOrderSnEqualTo(vo.getAccountingOrderSn());
        //查询对账单对应的发票单
        List<QchjcInvoiceApplyEntity> qchjcInvoiceApplyEntities = qchjcInvoiceApplyEntityMapper.selectByExample(qchjcInvoiceApplyEntityExample);

        if (CollectionUtils.isEmpty(qchjcInvoiceApplyEntities) || qchjcInvoiceApplyEntities.size() != invoiceCount) {
            log.info("对账单编号：{}，发票申请共应 : {} 条， 已同步：{}条，任务跳过", vo.getAccountingOrderSn(), invoiceCount, qchjcInvoiceApplyEntities.size());
            return null;
        }

        AccountingScoreCustomerExample accountingScoreCustomerExample = new AccountingScoreCustomerExample();
        accountingScoreCustomerExample
                .createCriteria()
                .andAccountingOrderSnEqualTo(vo.getAccountingOrderSn());
        List<AccountingScoreCustomer> accountingScoreCustomers = accountingScoreCustomerMapper.selectByExample(accountingScoreCustomerExample);
        if (CollectionUtils.isNotEmpty(accountingScoreCustomers)) {
            log.info("该对账单已存在，请勿重复入库，accountingOrderSn : {}", vo.getAccountingOrderSn());
            return null;
        }


        log.info("集采-采购单位对账单入库，param : {}", JSON.toJSONString(vo.getAccountingOrderSn()));

        /**
         * step_1 对账单明细数据构造
         */
        //未对账流水集合 -> 对应前端页面勾选的所有未对账流水, 用于生成对账单的表单参数
        List<AccountingOrderScoreCustomerCreateSelectedCreditParam> selectCredits = new ArrayList<>();

        for (QchjcOrderVo qchjcOrderVo : vo.getOrderSelected()) {
            //处理订单
            UnifiedOrder unifiedOrderEntity = new UnifiedOrder();
            //集采订单vo转换为统一订单实体
            convertQchOrderParam2Entity(qchjcOrderVo, unifiedOrderEntity);
            //处理商品
            List<UnifiedOrderGoods>            processUnifiedOrderGoodsList = new ArrayList<>();
            List<QchjcOrderGoodsVo>            orderGoodsSelected           = qchjcOrderVo.getOrderGoodsSelected();
            List<Predicate<QchjcOrderGoodsVo>> predicates                   = new ArrayList<>();
            predicates.add(r -> null != r.getSellingPrice() && r.getSellingPrice().compareTo(BigDecimal.ZERO) > 0);
            predicates.add(r -> null != r.getCostPrice() && r.getCostPrice().compareTo(BigDecimal.ZERO) > 0);
            List<QchjcOrderGoodsVo> scoreOrderGoodsReceiveParamFilterList = AnLamdaUtils.filters(orderGoodsSelected, predicates);
            if (CollectionUtils.isEmpty(scoreOrderGoodsReceiveParamFilterList)) {
                log.info("scoreOrderGoodsReceiveParamFilterList is empty, orderSn : {}", qchjcOrderVo.getOrderSn());
                throw new OpenApiException(500, "过滤后商品列表为空，入库失败");
            }
            //订单商品vo转换为统一订单商品实体,并构造流水
            List<UnifiedOrderCredit> processUnifiedOrderCreditList = new ArrayList<>();
            scoreOrderGoodsReceiveParamFilterList.forEach(goodsVo -> {
                //转为商品实体
                UnifiedOrderGoods unifiedOrderGoods = new UnifiedOrderGoods();
                convertQchOrderGoodsVo2Entity(goodsVo, unifiedOrderGoods);
                unifiedOrderGoods.setOrderSn(unifiedOrderEntity.getOrderSn());
                unifiedOrderGoods.setQchjcGoodsId(goodsVo.getId());
                processUnifiedOrderGoodsList.add(unifiedOrderGoods);
                //构造流水
                UnifiedOrderCredit scoreOrderCredit = new UnifiedOrderCredit();
                convertQchOrderGoods2CreditEntity(goodsVo, scoreOrderCredit, qchjcOrderVo);
                scoreOrderCredit.setOrderSn(unifiedOrderEntity.getOrderSn());
                scoreOrderCredit.setQchGoodsId(goodsVo.getId());
                processUnifiedOrderCreditList.add(scoreOrderCredit);
            });

            //运费由集采处理 拆分成商品
            //commonOrderTransportProcessService.processTransport(unifiedOrderEntity, processUnifiedOrderGoodsList);
            UnifiedOrderIssuesFlowing unifiedOrderIssuesFlowing = commonOrderProcessService.processOrderAmount(unifiedOrderEntity, processUnifiedOrderGoodsList, AnStringUtils.getUUID());
            log.info("集采-采购单位对账单入库，unifiedOrderIssuesFlowing : {}", JSON.toJSONString(unifiedOrderIssuesFlowing));

            //流水、商品、订单入库
            // 没有商品 没有流水 不保存订单数据
            if (AnCollectionUtils.isNotEmpty(processUnifiedOrderGoodsList) && AnCollectionUtils.isNotEmpty(processUnifiedOrderCreditList)) {
                //订单
                UnifiedOrderExample unifiedOrderExample = new UnifiedOrderExample();
                unifiedOrderExample.createCriteria().andOrderSnEqualTo(unifiedOrderEntity.getOrderSn());
                List<UnifiedOrder> unifiedOrders = unifiedOrderMapper.selectByExample(unifiedOrderExample);
                UnifiedOrder       unifiedOrder  = null;
                if (CollectionUtils.isNotEmpty(unifiedOrders) && (unifiedOrder = unifiedOrders.get(0)) != null) {
                    /**
                     * 订单已存在，加行锁 再行处理
                     */
                    unifiedOrder = unifiedOrderMapper.selectByPrimaryKeyForUpdate(unifiedOrder.getId());
                    //判断订单下的明细是否已经对过账，如果已经对过账，则不允许再次对账
                    UnifiedOrderCreditExample unifiedOrderCreditExample = new UnifiedOrderCreditExample();
                    unifiedOrderCreditExample.createCriteria().andOrderSnEqualTo(unifiedOrderEntity.getOrderSn())
                            .andAccountingStateCustomerEqualTo(CommonAccountingStateEnum.已对账.getKey());
                    List<UnifiedOrderCredit> unifiedOrderCredits = unifiedOrderCreditMapper.selectByExample(unifiedOrderCreditExample);
                    if (CollectionUtils.isNotEmpty(unifiedOrderCredits)) {
                        throw new OpenApiException(500, "订单sn:" + unifiedOrder.getOrderSn() + "存在已对账流水，不允许重复对账");
                    }
                    /**
                     * 更新订单表，商品，流水数据，这里用了福利的重推单做法
                     * public UnifiedOrderIssuesFlowingParam kafkaScoreOrderReceive(ScoreOrderReceiveParam receiveParam)
                     */

                    /**
                     * 重推订单处理
                     *
                     * 这里用已有的订单覆盖供应商对账单的标志，因为下一步要进行采购单位对账单创建，供应商对账单状态保持不变，采购单位为未对账
                     */
                    unifiedOrderEntity.setId(unifiedOrder.getId());
                    unifiedOrderEntity.setUpdateTime(DateUtil.date());
                    unifiedOrderEntity.setAccountingStateSupplier(unifiedOrder.getAccountingStateSupplier());
                    unifiedOrderMapper.updateByPrimaryKeySelective(unifiedOrderEntity);
                    //把统一订单id更新到中间表
                    QchjcOrderEntity qchjcOrderEntity = new QchjcOrderEntity();
                    qchjcOrderEntity.setId(qchjcOrderVo.getId());
                    qchjcOrderEntity.setUnifiedId(unifiedOrderEntity.getId());
                    qchOrderEntityMapper.updateByPrimaryKeySelective(qchjcOrderEntity);

                    /**
                     * 最终入库的商品数据和流水数据
                     */
                    List<UnifiedOrderGoods>  finalUnifiedOrderGoodsList  = new ArrayList<>();
                    List<UnifiedOrderCredit> finalUnifiedOrderCreditList = new ArrayList<>();
                    /**
                     * 重推商品处理
                     */
                    processUnifiedOrderGoodsFromQchjc(unifiedOrderEntity, processUnifiedOrderGoodsList, finalUnifiedOrderGoodsList);
                    /**
                     * 重推流水处理
                     */
                    processUnifiedOrderCreditFromQchjc(unifiedOrderEntity, processUnifiedOrderCreditList, finalUnifiedOrderCreditList);
                    //id类字段回写到中间表
                    for (UnifiedOrderGoods unifiedOrderGoods : finalUnifiedOrderGoodsList) {
                        Long id           = unifiedOrderGoods.getId();//统一订单商品id
                        Long qchjcGoodsId = unifiedOrderGoods.getQchjcGoodsId();//中间表商品id
                        //更新中间表商品id
                        QchjcOrderGoodsEntity qchjcOrderGoodsEntity = qchOrderGoodsEntityMapper.selectByPrimaryKey(qchjcGoodsId);
                        qchjcOrderGoodsEntity.setUnifiedId(id);
                        qchjcOrderGoodsEntity.setUnifiedOrderId(unifiedOrderEntity.getId());
                        qchjcOrderGoodsEntity.setAccountingStateCustomer(CommonAccountingStateEnum.已对账.getKey());
                        qchOrderGoodsEntityMapper.updateByPrimaryKeySelective(qchjcOrderGoodsEntity);
                    }
                    //构造流水参数
                    for (UnifiedOrderCredit unifiedOrderCredit : finalUnifiedOrderCreditList) {
                        //生成流水后把流水添加到未对账流水集合中，用于生成对账单
                        AccountingOrderScoreCustomerCreateSelectedCreditParam param = new AccountingOrderScoreCustomerCreateSelectedCreditParam();
                        param.setUnifiedOrderCreditId(unifiedOrderCredit.getId());//统一订单流水id
                        param.setUnifiedOrderId(unifiedOrderEntity.getId());//统一订单id

                        finalUnifiedOrderGoodsList.forEach(unifiedOrderGoods -> {
                            if (unifiedOrderGoods.getQchjcGoodsId().equals(unifiedOrderCredit.getQchGoodsId())) {
                                param.setUnifiedOrderGoodsId(unifiedOrderGoods.getId());//统一订单商品id
                                Long qchjcGoodsId = unifiedOrderGoods.getQchjcGoodsId();
                                //把统一订单流水id更新到商品中间表
                                QchjcOrderGoodsEntity qchjcOrderGoodsEntity = qchOrderGoodsEntityMapper.selectByPrimaryKey(qchjcGoodsId);
                                qchjcOrderGoodsEntity.setUnifiedCreditId(unifiedOrderCredit.getId());
                                qchOrderGoodsEntityMapper.updateByPrimaryKeySelective(qchjcOrderGoodsEntity);
                            }
                        });
                        selectCredits.add(param);
                    }

                }
                /** 新推送订单 */
                else {
                    //订单不存在,直接插入订单、商品、流水记录
                    unifiedOrderMapper.insertSelective(unifiedOrderEntity);
                    //把统一订单id更新到中间表
                    QchjcOrderEntity qchjcOrderEntity = new QchjcOrderEntity();
                    qchjcOrderEntity.setId(qchjcOrderVo.getId());
                    qchjcOrderEntity.setUnifiedId(unifiedOrderEntity.getId());
                    qchOrderEntityMapper.updateByPrimaryKeySelective(qchjcOrderEntity);
                    //商品
                    for (UnifiedOrderGoods unifiedOrderGoods : processUnifiedOrderGoodsList) {
                        unifiedOrderGoodsMapper.insert(unifiedOrderGoods);
                        Long id           = unifiedOrderGoods.getId();//统一订单商品id
                        Long qchjcGoodsId = unifiedOrderGoods.getQchjcGoodsId();//中间表商品id
                        //更新中间表商品id
                        QchjcOrderGoodsEntity qchjcOrderGoodsEntity = qchOrderGoodsEntityMapper.selectByPrimaryKey(qchjcGoodsId);
                        qchjcOrderGoodsEntity.setUnifiedId(id);
                        qchjcOrderGoodsEntity.setUnifiedOrderId(unifiedOrderEntity.getId());
                        qchjcOrderGoodsEntity.setAccountingStateCustomer(CommonAccountingStateEnum.已对账.getKey());
                        qchOrderGoodsEntityMapper.updateByPrimaryKeySelective(qchjcOrderGoodsEntity);
                    }
                    //流水
                    for (UnifiedOrderCredit unifiedOrderCredit : processUnifiedOrderCreditList) {
                        unifiedOrderCreditMapper.insert(unifiedOrderCredit);
                        //生成流水后把流水添加到未对账流水集合中，用于生成对账单
                        AccountingOrderScoreCustomerCreateSelectedCreditParam param = new AccountingOrderScoreCustomerCreateSelectedCreditParam();
                        param.setUnifiedOrderCreditId(unifiedOrderCredit.getId());//统一订单流水id
                        param.setUnifiedOrderId(unifiedOrderEntity.getId());//统一订单id
                        processUnifiedOrderGoodsList.forEach(unifiedOrderGoods -> {
                            if (unifiedOrderGoods.getQchjcGoodsId().equals(unifiedOrderCredit.getQchGoodsId())) {
                                param.setUnifiedOrderGoodsId(unifiedOrderGoods.getId());//统一订单商品id
                                Long qchjcGoodsId = unifiedOrderGoods.getQchjcGoodsId();
                                //把统一订单流水id更新到商品中间表
                                QchjcOrderGoodsEntity qchjcOrderGoodsEntity = qchOrderGoodsEntityMapper.selectByPrimaryKey(qchjcGoodsId);
                                qchjcOrderGoodsEntity.setUnifiedCreditId(unifiedOrderCredit.getId());
                                qchOrderGoodsEntityMapper.updateByPrimaryKeySelective(qchjcOrderGoodsEntity);
                            }
                        });
                        selectCredits.add(param);
                    }
                }


            }
        }

        /**
         * step_2 构造伪表单，对账单入库
         */
        //创建对账单表单参数
        AccountingOrderScoreCustomerCreateParam accountingOrderScoreCustomerCreateParam = new AccountingOrderScoreCustomerCreateParam();
        accountingOrderScoreCustomerCreateParam.setCreditSelected(selectCredits);
        //销方信息
        LoginSysUser    loginSysUser    = new LoginSysUser();
        QchjcUserEntity qchjcUserEntity = qchjcUserEntityMapper.selectByOutId(vo.getCreateUserId());
        if (qchjcUserEntity != null) {
            loginSysUser.setSysUserId(qchjcUserEntity.getUnifiedId());
            loginSysUser.setSysUserName(qchjcUserEntity.getUserName());
        }
        List<InvoiceBankInfo> query           = invoiceBankInfoService.query(new InvoiceBankInfoQueryCriteria(), loginSysUser);
        InvoiceBankInfo       invoiceBankInfo = query.get(0);//获取默认或id最小的抬头信息
        accountingOrderScoreCustomerCreateParam.setBankInfoId(invoiceBankInfo.getId());//销方信息id

        accountingOrderScoreCustomerCreateParam.setServiceNo(CommonServiceNoEnum.企业商城_侨城汇.getServiceNo());
        accountingOrderScoreCustomerCreateParam.setSourceFrom(CommonSourceFromEnum.企业商城_侨城汇.getSourceFromCode());//订单来源
        accountingOrderScoreCustomerCreateParam.setIsSendEmail(AccountingOrderIsSendEmailEnum.未发送.getKey());
        //组装参数
        handleCreateParam(accountingOrderScoreCustomerCreateParam, vo);
        //得出未对账流水
        List<InvoiceApplyDetailDimCreditItemVo> resultListCredit = scoreOrderService.getScoreOrderReconciliationNotYetScene2(
                AccountingOrderScoreCustomerNotYetDimCreditScene2QueryCriteria
                        .builder()
                        .creditSelected(selectCredits)
                        .autoComplete(AccountingOrderDimCreateByEnum.流水.getKey())
                        .build(),
                loginSysUser
        );

        /**
         * 返回创建对账单的参数
         */
        return QchjcCustomerStorageParam.builder()
                .resultListCredit(resultListCredit)
                .accountingOrderScoreCustomerCreateParam(accountingOrderScoreCustomerCreateParam)
                .loginSysUser(loginSysUser).build();
    }

    /**
     * 集采重推账单 流水处理
     *
     * @param unifiedOrderEntity
     * @param processUnifiedOrderCreditList
     */
    private void processUnifiedOrderCreditFromQchjc(UnifiedOrder unifiedOrderEntity, List<UnifiedOrderCredit> processUnifiedOrderCreditList, List<UnifiedOrderCredit> finalUnifiedOrderCreditList) {
        UnifiedOrderCreditExample orderCreditExample4SaveOrUpdate = new UnifiedOrderCreditExample();
        orderCreditExample4SaveOrUpdate.createCriteria().andOrderSnEqualTo(unifiedOrderEntity.getOrderSn());

        List<UnifiedOrderCredit> existsDatabaseUnifiedOrderCreditList = unifiedOrderCreditMapper.selectByExample(orderCreditExample4SaveOrUpdate);

        log.info("\n\n\nOrderCredit: \n已存在数据 : \n{}\n过来的数据 : \n{}\n\n\n",
                AnJsonUtils.toJson(existsDatabaseUnifiedOrderCreditList),
                AnJsonUtils.toJson(processUnifiedOrderCreditList)
        );


        for (UnifiedOrderCredit processOrderCredit : processUnifiedOrderCreditList) {

            // 新过来的数据在老的是不是存在
            List<UnifiedOrderCredit> findByManyOrderCreditList = null;

            // 查询条件 如果 goods_id 为 0 条数大于 1 是会有问题 0 默认只有运费 , 如果 附件与赠品过来的情况 就会有问题,具体的问题再写吧
            List<Predicate<UnifiedOrderCredit>> predicatesByMany = new ArrayList<>();
            // 20201016 add start 从数据上看,是会有可能 同样的 orderId 不同的 orderSn
            predicatesByMany.add(
                    r -> r.getOrderSn().equals(processOrderCredit.getOrderSn())
                            && r.getOrderId().equals(processOrderCredit.getOrderId())
                            && r.getGoodsId().equals(processOrderCredit.getGoodsId())
                            && r.getCreditType().equals(processOrderCredit.getCreditType())
                            && r.getCreditName().equals(processOrderCredit.getCreditName())
                            && r.getBalance().compareTo(processOrderCredit.getBalance()) == 0
                            && r.getBatchs().equals(processOrderCredit.getBatchs())
            );
            // 20201016 add end
            // 新过来的数据在老的是不是存在
            findByManyOrderCreditList = AnLamdaUtils.filters(existsDatabaseUnifiedOrderCreditList, predicatesByMany);


            if (CollectionUtils.isNotEmpty(findByManyOrderCreditList)) {

                UnifiedOrderCredit findedOrderCredit = findByManyOrderCreditList.get(0);

                overWriteCreditField(processOrderCredit, findedOrderCredit);

                findedOrderCredit.setUpdateUserId(3L);
                findedOrderCredit.setUpdateTime(DateUtil.date());

                finalUnifiedOrderCreditList.add(findedOrderCredit);
            }
            // 两种情况都不存 才会作为新数据插入
            else {
                finalUnifiedOrderCreditList.add(processOrderCredit);
            }

            unifiedOrderCreditMapper.deleteByExample(orderCreditExample4SaveOrUpdate);
            for (UnifiedOrderCredit unifiedOrderCredit : finalUnifiedOrderCreditList) {
                if (unifiedOrderCredit.getId() == null || unifiedOrderCredit.getId() == 0) {
                    unifiedOrderCreditMapper.insertSelective(unifiedOrderCredit);
                } else {
                    unifiedOrderCreditMapperEx.insertSelectiveWithoutReturnId(unifiedOrderCredit);
                }
            }
        }
    }

    /**
     * 集采重推账单 流水处理
     *
     * @param processOrderCredit
     * @param findedOrderCredit
     */
    private void overWriteCreditField(UnifiedOrderCredit processOrderCredit, UnifiedOrderCredit findedOrderCredit) {
        findedOrderCredit.setOrderSn(processOrderCredit.getOrderSn());

        findedOrderCredit.setCreditType(processOrderCredit.getCreditType());
        findedOrderCredit.setCreditName(processOrderCredit.getCreditName());
        findedOrderCredit.setOutSnapshotOrderCreditId(processOrderCredit.getOutSnapshotOrderCreditId());
        findedOrderCredit.setGoodsId(processOrderCredit.getGoodsId());
        findedOrderCredit.setDailyAccountType(processOrderCredit.getDailyAccountType());
        findedOrderCredit.setBatchs(processOrderCredit.getBatchs());
        findedOrderCredit.setBalance(processOrderCredit.getBalance());
        findedOrderCredit.setEnterpriseId(processOrderCredit.getEnterpriseId());
        findedOrderCredit.setMemberId(processOrderCredit.getMemberId());
        findedOrderCredit.setPayStatus(processOrderCredit.getPayStatus());
        findedOrderCredit.setPayType(processOrderCredit.getPayType());
        // 采购单位对账单标志位
        findedOrderCredit.setCreditLockingCustomer(CommonAccountingLockingEnum.正常.getKey());
        findedOrderCredit.setAccountingStateCustomer(CommonAccountingStateEnum.未对账.getKey());

        findedOrderCredit.setQchGoodsId(processOrderCredit.getQchGoodsId());

    }

    /**
     * 集采重推账单 商品处理
     *
     * @param unifiedOrderEntity
     * @param processUnifiedOrderGoodsList
     */
    private void processUnifiedOrderGoodsFromQchjc(UnifiedOrder unifiedOrderEntity, List<UnifiedOrderGoods> processUnifiedOrderGoodsList, List<UnifiedOrderGoods> finalUnifiedOrderGoodsList) {
        UnifiedOrderGoodsExample orderGoodsExample4SaveOrUpdate = new UnifiedOrderGoodsExample();
        orderGoodsExample4SaveOrUpdate.createCriteria().andOrderSnEqualTo(unifiedOrderEntity.getOrderSn());
        //结算中心数据库中已存在的商品
        List<UnifiedOrderGoods> existsUnifiedOrderGoodsList = unifiedOrderGoodsMapper.selectByExample(orderGoodsExample4SaveOrUpdate);
        log.info("\n\n\nOrderGoods: \n已存在数据 : \n{}\n过来的数据 : \n{}\n\n\n",
                AnJsonUtils.toJson(existsUnifiedOrderGoodsList),
                AnJsonUtils.toJson(processUnifiedOrderGoodsList)
        );


        // 拿着过来的数据 去 查 数据库的
        for (UnifiedOrderGoods processOrderGoods : processUnifiedOrderGoodsList) {

            // 查询数据库中是否存在
            UnifiedOrderGoodsExample unifiedOrderGoodsExample = new UnifiedOrderGoodsExample();
            unifiedOrderGoodsExample.createCriteria().andOrderSnEqualTo(unifiedOrderEntity.getOrderSn())
                    .andOutSnapshotOrderGoodsIdEqualTo(processOrderGoods.getOutSnapshotOrderGoodsId());//goods_id直接用集采的
            List<UnifiedOrderGoods> findByOutSnapshotIdOrderGoodsList = unifiedOrderGoodsMapper.selectByExample(unifiedOrderGoodsExample);


            //如果该商品已存在，则更新该商品数据
            if (CollectionUtils.isNotEmpty(findByOutSnapshotIdOrderGoodsList)) {
                UnifiedOrderGoods findedBySnapshotIdOrderGoods = findByOutSnapshotIdOrderGoodsList.get(0);

                overWriteGoodsField(processOrderGoods, findedBySnapshotIdOrderGoods);
                finalUnifiedOrderGoodsList.add(findedBySnapshotIdOrderGoods);
            } else {
                finalUnifiedOrderGoodsList.add(processOrderGoods);
            }
        }
        // 删除后重新插入数据
        unifiedOrderGoodsMapper.deleteByExample(orderGoodsExample4SaveOrUpdate);
        for (UnifiedOrderGoods unifiedOrderGoods : finalUnifiedOrderGoodsList) {
            if (unifiedOrderGoods.getId() == null || unifiedOrderGoods.getId() == 0) {
                unifiedOrderGoodsMapper.insertSelective(unifiedOrderGoods);
            } else {
                unifiedOrderGoodsMapperEx.insertSelectiveWithoutReturnId(unifiedOrderGoods);
            }
        }
        //unifiedOrderGoodsMapperEx.insertBatch(finalUnifiedOrderGoodsList);

        log.info("\n\n\n\nOrderGoods Final:\n{}\n\n\n\n", AnJsonUtils.toJson(finalUnifiedOrderGoodsList));
    }

    /**
     * 集采重推采购单位账单 商品覆写处理
     *
     * @param processOrderGoods
     * @param findedBySnapshotIdOrderGoods
     */
    private void overWriteGoodsField(UnifiedOrderGoods processOrderGoods, UnifiedOrderGoods findedBySnapshotIdOrderGoods) {

        findedBySnapshotIdOrderGoods.setOrderSn(processOrderGoods.getOrderSn());

        //采购单位对账标志位改为未对账
        findedBySnapshotIdOrderGoods.setGoodsLockingCustomer(CommonAccountingLockingEnum.正常.getKey());
        findedBySnapshotIdOrderGoods.setAccountingStateCustomer(CommonAccountingStateEnum.未对账.getKey());

        findedBySnapshotIdOrderGoods.setGoodsName(processOrderGoods.getGoodsName());
        findedBySnapshotIdOrderGoods.setGoodsAlias(processOrderGoods.getGoodsAlias());

        findedBySnapshotIdOrderGoods.setGoodsId(processOrderGoods.getGoodsId());
        findedBySnapshotIdOrderGoods.setOutSnapshotOrderGoodsId(processOrderGoods.getOutSnapshotOrderGoodsId());

        findedBySnapshotIdOrderGoods.setQuantity(processOrderGoods.getQuantity());
        findedBySnapshotIdOrderGoods.setUnit(StrUtil.isBlank(processOrderGoods.getUnit()) ? CommonOrderGoodsUnitEnum.项.getDesc() : processOrderGoods.getUnit());
        findedBySnapshotIdOrderGoods.setPrice(processOrderGoods.getPrice());
        findedBySnapshotIdOrderGoods.setCostPrice(processOrderGoods.getCostPrice());

        findedBySnapshotIdOrderGoods.setGoodsParams(processOrderGoods.getGoodsParams());

        //findedBySnapshotIdOrderGoods.setFiscalCode(processOrderGoods.getFiscalCode());
        //findedBySnapshotIdOrderGoods.setTaxCode(processOrderGoods.getTaxCode());
        //findedBySnapshotIdOrderGoods.setTaxRate(processOrderGoods.getTaxRate());

        // 商户税率
        //findedBySnapshotIdOrderGoods.setMerchTaxId(processOrderGoods.getMerchTaxId());
        findedBySnapshotIdOrderGoods.setMerchTaxCode(processOrderGoods.getMerchTaxCode());
        findedBySnapshotIdOrderGoods.setMerchTaxRate(processOrderGoods.getMerchTaxRate());

        // 平台税率
        //findedBySnapshotIdOrderGoods.setOperationTaxId(processOrderGoods.getOperationTaxId());
        findedBySnapshotIdOrderGoods.setOperationTaxCode(processOrderGoods.getOperationTaxCode());
        findedBySnapshotIdOrderGoods.setOperationTaxRate(processOrderGoods.getOperationTaxRate());

        //findedBySnapshotIdOrderGoods.setCateIdLv1(processOrderGoods.getCateIdLv1());
        //findedBySnapshotIdOrderGoods.setCateIdLv1(processOrderGoods.getCateIdLv2());
        //findedBySnapshotIdOrderGoods.setCateIdLv3(processOrderGoods.getCateIdLv3());

        findedBySnapshotIdOrderGoods.setCateNameLv1(processOrderGoods.getCateNameLv1());
        findedBySnapshotIdOrderGoods.setCateNameLv2(processOrderGoods.getCateNameLv2());
        findedBySnapshotIdOrderGoods.setCateNameLv3(processOrderGoods.getCateNameLv3());

        findedBySnapshotIdOrderGoods.setSelfOption(processOrderGoods.getSelfOption() == null ? "" : processOrderGoods.getSelfOption());

        findedBySnapshotIdOrderGoods.setGoodsType(processOrderGoods.getGoodsType());


        findedBySnapshotIdOrderGoods.setUpdateTime(DateUtil.date());
        findedBySnapshotIdOrderGoods.setUpdateUserId(1L);
        findedBySnapshotIdOrderGoods.setQchjcGoodsId(processOrderGoods.getQchjcGoodsId());

    }

    @Override
    public void recordFailLog(QchjcAccountingScoreCustomerEntity entity, String s) {
        entity.setStorageStatus(QchjcStorageStatusEnum.FAIL.getStatus());
        entity.setStorageTime(DateUtil.date());
        entity.setStorageReason(s);
        qchjcAccountingCustomerMapper.updateByPrimaryKeySelective(entity);
    }

    @Override
    public R<List<SelectOptionVirt>> queryCustomerList() {
        return new R<>(sysEnterpriseMapper.queryQchjcCustomerList());
    }


    private void handleCreateParam(AccountingOrderScoreCustomerCreateParam param, QchjcCustomerStatementVo vo) {

        param.setBatchs(CommonServiceNoEnum.企业商城_侨城汇.getServiceNo());
        param.setJcAccountingOrderSn(vo.getAccountingOrderSn());//集采的原始sn

        //param.setCreditName(UnifiedOrderCreditTypeDefaultEnum.积分支付.getDesc());
        //param.setCreditType(UnifiedOrderCreditTypeDefaultEnum.积分支付.getKey());
        ArrayList<String> nameList = new ArrayList<>();
        nameList.add(UnifiedOrderCreditTypeDefaultEnum.积分支付.getDesc());
        param.setCreditNameList(nameList);
        List<Integer> creditTypeList = new ArrayList<>();
        creditTypeList.add(UnifiedOrderCreditTypeDefaultEnum.积分支付.getKey());
        param.setCreditTypeList(creditTypeList);

        param.setEmailAddress(vo.getPurchaseEmail());

        param.setDateType(vo.getDateType());
        SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        param.setEndTime(format.format(vo.getEndTime()));
        param.setStartTime(format.format(vo.getStartTime()));

        param.setPurchasePhone(vo.getPurchasePhone());
        param.setPurchaseUserName(vo.getPurchaseUserName());
        QchjcUserEntity qchjcUserEntity = qchjcUserEntityMapper.selectByOutId(vo.getPurchaseUserId());
        if (qchjcUserEntity != null) {
            param.setPurchaseUserId(qchjcUserEntity.getUnifiedId());
        } else {
            param.setPurchaseUserId(null);
        }

        param.setServiceNo(CommonServiceNoEnum.企业商城_侨城汇.getServiceNo());
        param.setSourceFrom(CommonSourceFromEnum.企业商城_侨城汇.getSourceFromCode());

        param.setStatisticsTotalAmount(vo.getStatisticsTotalAmount());//订单金额
        param.setUnAccountingAmount(vo.getUnAccountingAmount());//不对帐金额 集采默认为0.00
        //param.setJcUnAccountingAmount(vo.getJcUnAccountingAmount());//集采不对帐金额
    }

    private void handleScoreAccountingCustomer(AccountingScoreCustomer scoreAccountingCustomer, QchjcCustomerStatementVo vo) {

    }

    //商品vo转换为统一订单流水实体
    private void convertQchOrderGoods2CreditEntity(QchjcOrderGoodsVo vo, UnifiedOrderCredit unifiedOrderCreditEntity, QchjcOrderVo qchjcOrderVo) {

        unifiedOrderCreditEntity.setDirection(vo.getDirection());

        //unifiedOrderCreditEntity.setOutSnapshotOrderCreditId(scoreOrderCreditReceiveParam.getOrderCreditId());

        unifiedOrderCreditEntity.setOrderId(qchjcOrderVo.getId());
        /**
         * goods_id直接用集采的
         */
        unifiedOrderCreditEntity.setGoodsId(Long.parseLong(vo.getGoodsId()));

        unifiedOrderCreditEntity.setCreditType(UnifiedOrderCreditTypeDefaultEnum.积分支付.getKey());
        unifiedOrderCreditEntity.setCreditName(UnifiedOrderCreditTypeDefaultEnum.积分支付.getDesc());

        /* 积分变动类型(1充值 2消费 3退款) */
        unifiedOrderCreditEntity.setDailyAccountType(vo.getDirection() == 1 ? 2 : 3);//1-正单 -1退单 ，对应2消费，3退款
        unifiedOrderCreditEntity.setBatchs(CommonServiceNoEnum.企业商城_侨城汇.getServiceNo());//固定值
        if (vo.getDirection() == 1) {
            unifiedOrderCreditEntity.setBalance(vo.getSellingPrice().multiply(new BigDecimal(vo.getQuantity())));
        } else {
            unifiedOrderCreditEntity.setBalance(vo.getSellingPrice().multiply(new BigDecimal(vo.getQuantity())).negate());
        }

        QchjcEnterpriseEntity qchjcEnterpriseEntity = qchjcEnterpriseEntityMapper.selectByOutId(qchjcOrderVo.getPurchaseVirtId());
        QchjcUserEntity       qchjcUser             = qchjcUserEntityMapper.selectByOutId(qchjcOrderVo.getPurchaseUserId());
        unifiedOrderCreditEntity.setEnterpriseId(qchjcEnterpriseEntity.getId());//所属企业,enterprise_id 取中间表的id，非统一订单表的自增id
        if (qchjcUser != null) {
            unifiedOrderCreditEntity.setMemberId(qchjcUser.getUnifiedId());//买家id
        } else {
            unifiedOrderCreditEntity.setMemberId(0L);//买家id
        }

        unifiedOrderCreditEntity.setPayStatus(1);//固定已支付
        unifiedOrderCreditEntity.setPayType(qchjcOrderVo.getPayType());

        unifiedOrderCreditEntity.setCreditLockingCustomer(CommonAccountingLockingEnum.正常.getKey());
        unifiedOrderCreditEntity.setCreditLockingSupplier(CommonAccountingLockingEnum.正常.getKey());

        unifiedOrderCreditEntity.setAccountingStateCustomer(CommonAccountingStateEnum.未对账.getKey());
        unifiedOrderCreditEntity.setAccountingStateSupplier(CommonAccountingStateEnum.不对账.getKey());

        unifiedOrderCreditEntity.setInvoiceApplyStatus(UnifiedOrderCreditInvoiceApplyStatusEnum.待申请.getKey());
        unifiedOrderCreditEntity.setInvoiceMakeStatus(UnifiedOrderCreditInvoiceMakeStatusEnum.待开票.getKey());
        unifiedOrderCreditEntity.setBackStatus(UnifiedOrderCreditBackAccountStatusEnum.未回款.getKey());


        unifiedOrderCreditEntity.setCreateTime(qchjcOrderVo.getCreateTime());
        QchjcUserEntity qchjcCreateUserEntity = qchjcUserEntityMapper.selectByOutId(qchjcOrderVo.getCreateUserId());
        if (qchjcCreateUserEntity != null) {
            unifiedOrderCreditEntity.setCreateUserId(qchjcCreateUserEntity.getUnifiedId());
        }
        unifiedOrderCreditEntity.setUpdateTime(qchjcOrderVo.getUpdateTime());
        QchjcUserEntity qchjcUpdateUserEntity = qchjcUserEntityMapper.selectByOutId(qchjcOrderVo.getUpdateUserId());
        if (qchjcUpdateUserEntity != null) {
            unifiedOrderCreditEntity.setUpdateUserId(qchjcUpdateUserEntity.getUnifiedId());
        }

    }

    /**
     * 接收并保存集采采购单位对账单数据
     *
     * @param data
     * @throws OpenApiException
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public void receive(String data) throws OpenApiException {
        QchjcAccountingScoreCustomerParam param = AnJsonUtils.toObject(data, QchjcAccountingScoreCustomerParam.class);
        //校验参数
        String                purchaseVirtId        = param.getPurchaseVirtId();
        QchjcEnterpriseEntity qchjcEnterpriseEntity = qchjcEnterpriseEntityMapper.selectByOutId(purchaseVirtId);
        if (qchjcEnterpriseEntity == null) {
            throw new OpenApiException(500, "企业ID在企业数据库中不存在，请先同步企业");
        }
        QchjcAccountingScoreCustomerEntityExample customerEntityExample = new QchjcAccountingScoreCustomerEntityExample();
        customerEntityExample.createCriteria()
                .andAccountingOrderSnEqualTo(param.getAccountingOrderSn());
        List<QchjcAccountingScoreCustomerEntity> entities = qchjcAccountingCustomerMapper.selectByExample(customerEntityExample);
        QchjcAccountingScoreCustomerEntity       origin   = null;
        if (CollectionUtils.isNotEmpty(entities)) {
            origin = entities.get(0);
            if (QchjcStorageStatusEnum.PROCESSING.getStatus().equals(origin.getStorageStatus())
                    || QchjcStorageStatusEnum.SUCCESS.getStatus().equals(origin.getStorageStatus())) {
                throw new OpenApiException(500, "该对账单已存在，处于入库中或入库成功，请勿重复推送对账单");
            }
        }
        //1.保存操作人员信息
        handleUser(param);
        //2.保存商品、订单信息
        Integer count = handleGoodsAndOrder(param, origin);
        //3.保存对账单主体信息
        param.setOrderGoodsCount(count);
        handleCustomerStatement(param, origin);
    }

    @Override
    public List<QchjcCustomerStatementVo> getTodoList() {
        return null;
    }


    /**
     * 保存采购单位对账单主体信息
     *
     * @param param
     * @param origin
     */
    private void handleCustomerStatement(QchjcAccountingScoreCustomerParam param, QchjcAccountingScoreCustomerEntity origin) {
        if (origin != null) {
            //重复推送的对账单，更新
            QchjcAccountingScoreCustomerEntity copy = AnBeanUtils.copy(param, origin);
            copy.setSyncTime(DateUtil.date());
            copy.setStorageStatus(QchjcStorageStatusEnum.TODO.getStatus());//重新推送的对账单改为待入库状态
            copy.setStorageReason("重新推送");
            qchjcAccountingCustomerMapper.updateByPrimaryKeySelective(copy);
        } else {
            //新增
            QchjcAccountingScoreCustomerEntity customerStatementEntity = AnBeanUtils.copy(param, QchjcAccountingScoreCustomerEntity.class);
            customerStatementEntity.setSyncTime(DateUtil.date());
            qchjcAccountingCustomerMapper.insertSelective(customerStatementEntity);
        }
    }

    /**
     * 保存对账单的订单、商品明细
     *
     * @param param
     * @param origin
     */
    private Integer handleGoodsAndOrder(QchjcAccountingScoreCustomerParam param, QchjcAccountingScoreCustomerEntity origin) {
        Integer count = 0;

        //修改已有的商品，订单信息，新增不存在的订单和商品 需要注意并发问题
        List<QchjcOrderParam> orderSelected = param.getOrderSelected();

        String accountingOrderSn = param.getAccountingOrderSn();
        for (QchjcOrderParam orderParam : orderSelected) {
            QchjcOrderEntityExample qchjcOrderEntityExample = new QchjcOrderEntityExample();
            qchjcOrderEntityExample.createCriteria().andOrderSnEqualTo(orderParam.getOrderSn());
            List<QchjcOrderEntity> qchjcOrderEntities = qchOrderEntityMapper.selectByExample(qchjcOrderEntityExample);
            if (CollectionUtils.isNotEmpty(qchjcOrderEntities) && qchjcOrderEntities.get(0) != null) {
                QchjcOrderEntity qchjcOrderEntity = qchjcOrderEntities.get(0);
                //订单已存在,修改订单信息和商品信息，订单表加行锁
                QchjcOrderEntity orderEntity = qchOrderEntityMapper.selectByIdForUpdate(qchjcOrderEntity.getId());
                QchjcOrderEntity order       = convertQchParam2QchEntity(orderParam, orderEntity, accountingOrderSn);
                qchOrderEntityMapper.updateByPrimaryKeySelective(order);

                //修改订单商品明细，存在的商品修改，不存在的商品新增
                List<QchjcOrderGoodsParam> orderGoodsSelected = orderParam.getOrderGoodsSelected();
                for (QchjcOrderGoodsParam qchjcOrderGoodsParam : orderGoodsSelected) {
                    QchjcOrderGoodsEntityExample qchjcOrderGoodsEntityExample = new QchjcOrderGoodsEntityExample();
                    qchjcOrderGoodsEntityExample.createCriteria().andOrderSnEqualTo(orderParam.getOrderSn())
                            .andOutSnapshotOrderGoodsIdEqualTo(qchjcOrderGoodsParam.getOutSnapshotOrderGoodsId());
                    List<QchjcOrderGoodsEntity> qchjcOrderGoodsEntities = qchOrderGoodsEntityMapper.selectByExample(qchjcOrderGoodsEntityExample);
                    if (CollectionUtils.isNotEmpty(qchjcOrderGoodsEntities) && qchjcOrderGoodsEntities.get(0) != null) {
                        QchjcOrderGoodsEntity qchjcOrderGoodsEntity = qchjcOrderGoodsEntities.get(0);
                        // 校验是否重复推送的商品
                        if (CommonAccountingStateEnum.已对账.getKey().equals(qchjcOrderGoodsEntity.getAccountingStateCustomer())) {
                            throw new OpenApiException(500, "订单" + orderParam.getOrderSn() + "已对账，所属对账单编号为：" + qchjcOrderEntity.getCustomerAccountingOrderSn() + ",不能重复对账");
                        }
                        //商品已存在，修改商品信息
                        qchjcOrderGoodsEntity = convertQchGoodsParam2Entity(qchjcOrderGoodsParam, qchjcOrderGoodsEntity, accountingOrderSn, qchjcOrderGoodsParam.getOrderSn());
                        qchOrderGoodsEntityMapper.updateByPrimaryKeySelective(qchjcOrderGoodsEntity);
                    } else {
                        //商品不存在，新增商品
                        QchjcOrderGoodsEntity orderGoods = convertQchGoodsParam2Entity(qchjcOrderGoodsParam, null, accountingOrderSn, qchjcOrderGoodsParam.getOrderSn());
                        qchOrderGoodsEntityMapper.insertSelective(orderGoods);
                    }
                    count += 1;
                }

                //todo 删除表里已经存在，但是新推送参数中不存在的商品 ?
                //List<String> collect = orderGoodsSelected.stream().map(QchjcOrderGoodsParam::getOutSnapshotOrderGoodsId).collect(Collectors.toList());
                //QchjcOrderGoodsEntityExample qchjcOrderGoodsEntityExample = new QchjcOrderGoodsEntityExample();
                //qchjcOrderGoodsEntityExample.createCriteria().andOrderSnEqualTo(orderParam.getOrderSn())
                //        .andOutSnapshotOrderGoodsIdNotIn(collect);
                //qchOrderGoodsEntityMapper.deleteByExample(qchjcOrderGoodsEntityExample);


            } else {
                //订单不存在，新增
                QchjcOrderEntity order = convertQchParam2QchEntity(orderParam, null, accountingOrderSn);
                qchOrderEntityMapper.insertSelective(order);
                //新增商品
                List<QchjcOrderGoodsParam> orderGoodsSelected = orderParam.getOrderGoodsSelected();
                String                     orderSn            = orderParam.getOrderSn();
                //遍历保存商品
                for (QchjcOrderGoodsParam goodsParam : orderGoodsSelected) {
                    QchjcOrderGoodsEntity orderGoods = convertQchGoodsParam2Entity(goodsParam, null, accountingOrderSn, orderSn);
                    qchOrderGoodsEntityMapper.insertSelective(orderGoods);
                    count += 1;
                }
            }
        }
        return count;
    }

    private QchjcOrderGoodsEntity convertQchGoodsParam2Entity(QchjcOrderGoodsParam qchjcOrderGoodsParam, QchjcOrderGoodsEntity qchjcOrderGoodsEntity, String accountingOrderSn, String orderSn) {
        if (qchjcOrderGoodsEntity == null) {
            qchjcOrderGoodsEntity = AnBeanUtils.copy(qchjcOrderGoodsParam, QchjcOrderGoodsEntity.class);
        } else {
            qchjcOrderGoodsEntity = AnBeanUtils.copy(qchjcOrderGoodsParam, qchjcOrderGoodsEntity);
        }
        qchjcOrderGoodsEntity.setOrderSn(orderSn);
        qchjcOrderGoodsEntity.setSyncTime(DateUtil.date());
        qchjcOrderGoodsEntity.setCustomerAccountingOrderSn(accountingOrderSn);
        return qchjcOrderGoodsEntity;
    }

    private QchjcOrderEntity convertQchParam2QchEntity(QchjcOrderParam orderParam, QchjcOrderEntity orderEntity, String accountingOrderSn) {
        if (orderEntity == null) {
            orderEntity = AnBeanUtils.copy(orderParam, QchjcOrderEntity.class);
        } else {
            orderEntity = AnBeanUtils.copy(orderParam, orderEntity);
        }
        orderEntity.setServiceNo(CommonServiceNoEnum.企业商城_侨城汇.getServiceNo());
        //order.setAccountingOrderSn(accountingOrderSn); 弃用
        orderEntity.setCustomerAccountingOrderSn(accountingOrderSn);
        orderEntity.setSaleId(orderParam.getSupplierId());
        orderEntity.setSaleName(orderParam.getSupplierName());
        orderEntity.setSyncTime(DateUtil.date());
        orderEntity.setAmount(orderParam.getOrderAmount());
        orderEntity.setCostAmount(orderParam.getOrderCostAmount());
        orderEntity.setTransportAmount(orderParam.getTransportAmount());
        orderEntity.setTransportMerchantAssumeAmount(orderParam.getTransportMerchantAssumeAmount());
        return orderEntity;
    }

    /**
     * 外部用户入库统一订单，保存映射关系
     *
     * @param param
     */
    private void handleUser(QchjcAccountingScoreCustomerParam param) {
        String createUserId   = param.getCreateUserId();
        String createUserName = param.getCreateUserName();
        String updateUserId   = param.getUpdateUserId();
        String updateUserName = param.getUpdateUserName();

        handle(createUserId, createUserName);
        handle(updateUserId, updateUserName);

    }

    private void handle(String userId, String userName) {
        QchjcUserEntityExample example = new QchjcUserEntityExample();
        example.createCriteria()
                .andOutIdEqualTo(userId);
        List<QchjcUserEntity> creator = qchjcUserEntityMapper.selectByExample(example);
        QchjcUserEntity       createUser;
        if (CollectionUtils.isEmpty(creator) || null == creator.get(0)) {
            createUser = QchjcUserEntity.builder()
                    .outId(userId)
                    .userName(userName).build();
            qchjcUserEntityMapper.insertSelective(createUser);
        } else {
            createUser = creator.get(0);
        }
        if (createUser.getUnifiedId() == null) {
            //用户入库统一订单
            SysUser sysUser4Qchjc = sysUserService.createSysUser4Qchjc(userId, userName);
            if (sysUser4Qchjc == null) {
                createUser.setStorageStatus(QchjcStorageStatusEnum.FAIL.getStatus());
                qchjcUserEntityMapper.updateByPrimaryKeySelective(createUser);
                throw new OpenApiException(500, "同步失败,用户入库异常");
            }
            //保存统一订单用户id
            createUser.setUnifiedId(sysUser4Qchjc.getId());
            createUser.setStorageStatus(QchjcStorageStatusEnum.SUCCESS.getStatus());
            createUser.setStorageTime(DateUtil.date());
            qchjcUserEntityMapper.updateByPrimaryKeySelective(createUser);
        }
    }

    /**
     * 集采商品vo转换为统一订单商品实体
     *
     * @param vo
     * @param unifiedOrderGoods
     */
    private void convertQchOrderGoodsVo2Entity(QchjcOrderGoodsVo vo, UnifiedOrderGoods unifiedOrderGoods) {
        if (CommonOrderGoodsTypeEnum.运费.getKey().equals(vo.getGoodsType())) {

            UnifiedServicePartGoodsTransportParam defaultGoodsTransport = unifiedServiceService.getUnifiedServicePartGoodsTransport(CommonServiceNoEnum.企业商城_侨城汇.getServiceNo());

            //运费处理，集采的运费为双向结算
            unifiedOrderGoods.setOrderSn(vo.getOrderSn());
            unifiedOrderGoods.setGoodsLockingCustomer(CommonAccountingLockingEnum.正常.getKey());
            unifiedOrderGoods.setGoodsLockingSupplier(CommonAccountingLockingEnum.正常.getKey());

            unifiedOrderGoods.setAccountingStateCustomer(CommonAccountingStateEnum.未对账.getKey());
            unifiedOrderGoods.setAccountingStateSupplier(CommonAccountingStateEnum.不对账.getKey());

            unifiedOrderGoods.setOutSnapshotOrderGoodsId(vo.getId());//集采的订单快照id是uuid，这里用中间表id替换

            unifiedOrderGoods.setGoodsType(CommonOrderGoodsTypeEnum.运费.getKey());
            unifiedOrderGoods.setDirection(CommonDirectionEnum.正向.getKey());

            /**
             * goods_id直接用集采的
             */
            unifiedOrderGoods.setGoodsId(Long.parseLong(vo.getGoodsId()));
            unifiedOrderGoods.setOutSnapshotOrderGoodsId(Long.parseLong(vo.getOutSnapshotOrderGoodsId()));

            unifiedOrderGoods.setGoodsName(CommonOrderGoodsIdEnum.运费.getDesc());
            unifiedOrderGoods.setUnit(CommonOrderGoodsUnitEnum.项.getDesc());

            unifiedOrderGoods.setQuantity(1);
            unifiedOrderGoods.setPrice(vo.getSellingPrice());
            unifiedOrderGoods.setCostPrice(vo.getCostPrice());

//			defaultGoodsTransport
            unifiedOrderGoods.setFiscalCode(defaultGoodsTransport.getGoodsTransportFiscalCode());
            unifiedOrderGoods.setTaxCode(defaultGoodsTransport.getGoodsTransportTaxCode());
            unifiedOrderGoods.setTaxRate(defaultGoodsTransport.getGoodsTransportTaxRate());

            // 商户税率
            unifiedOrderGoods.setMerchTaxId(0L);
            unifiedOrderGoods.setMerchTaxCode(vo.getMerchTaxCode());
            unifiedOrderGoods.setMerchTaxRate(vo.getMerchTaxRate());

            // 平台税率
            unifiedOrderGoods.setOperationTaxId(0L);
            unifiedOrderGoods.setOperationTaxCode(vo.getOperationTaxCode());
            unifiedOrderGoods.setOperationTaxRate(vo.getOperationTaxRate());

            unifiedOrderGoods.setCreateTime(DateUtil.date());
            unifiedOrderGoods.setCreateUserId(1L);
            unifiedOrderGoods.setUpdateTime(DateUtil.date());
            unifiedOrderGoods.setUpdateUserId(1L);

        } else {
            //商品处理
            unifiedOrderGoods.setGoodsType(vo.getGoodsType());//商品类型
            unifiedOrderGoods.setDirection(vo.getDirection());//商品方向

            unifiedOrderGoods.setGoodsLockingCustomer(CommonAccountingLockingEnum.正常.getKey());
            unifiedOrderGoods.setGoodsLockingSupplier(CommonAccountingLockingEnum.正常.getKey());

            unifiedOrderGoods.setAccountingStateCustomer(CommonAccountingStateEnum.未对账.getKey());
            unifiedOrderGoods.setAccountingStateSupplier(CommonAccountingStateEnum.不对账.getKey());
            /**
             * goods_id直接用集采的
             */
            unifiedOrderGoods.setGoodsId(Long.parseLong(vo.getGoodsId()));
            unifiedOrderGoods.setOutSnapshotOrderGoodsId(Long.parseLong(vo.getOutSnapshotOrderGoodsId()));

//		scoreOrderGoodsEntity.setOrderSn();
            unifiedOrderGoods.setGoodsName(vo.getGoodsName());
            unifiedOrderGoods.setQuantity(vo.getQuantity());
            unifiedOrderGoods.setUnit(StrUtil.isBlank(vo.getUnit()) ? CommonOrderGoodsUnitEnum.项.getDesc() : vo.getUnit());
            unifiedOrderGoods.setPrice(vo.getSellingPrice());
            // add costprice 成本价
            unifiedOrderGoods.setCostPrice(vo.getCostPrice());

            unifiedOrderGoods.setGoodsParams(vo.getGoodsParams());//商品参数

            unifiedOrderGoods.setSelfOption(vo.getSelfOption() == null ? "" : vo.getSelfOption());

            /************************************** update by linjinjy 20200727 20200723_林志鹏_税率,退款格式.docx 将要弃用 20210413 mark by linjinyu **************************************/

            //unifiedOrderGoods.setFiscalCode(vo.getFiscalCode());
            //unifiedOrderGoods.setTaxCode(vo.getTaxCode());
            //unifiedOrderGoods.setTaxRate(vo.getTaxRate());

            /************************************** update by linjinjy 20200727 20200723_林志鹏_税率,退款格式.docx 将要弃用 20210413 mark by linjinyu **************************************/


            /****************************************** 税率修改 20210413 mark by linjinyu start ******************************************/

            // 商户税率
            //unifiedOrderGoods.setMerchTaxId(vo.getMerchTaxId());
            unifiedOrderGoods.setMerchTaxCode(vo.getMerchTaxCode());
            unifiedOrderGoods.setMerchTaxRate(vo.getMerchTaxRate());

            // 平台税率
            //unifiedOrderGoods.setOperationTaxId(vo.getOperationTaxId());
            unifiedOrderGoods.setOperationTaxCode(vo.getOperationTaxCode());
            unifiedOrderGoods.setOperationTaxRate(vo.getOperationTaxRate());

            /****************************************** 税率修改 20210413 mark by linjinyu   end ******************************************/


            /****************************************** 三级分类 20200904 by linjinyu 20200904_林志鹏_三极分类 ******************************************/

            //unifiedOrderGoods.setCateIdLv1(vo.getCateIdLv1());
            //unifiedOrderGoods.setCateIdLv2(vo.getCateIdLv2());
            //unifiedOrderGoods.setCateIdLv3(vo.getCateIdLv3());
            unifiedOrderGoods.setCateNameLv1(vo.getCateNameLv1());
            unifiedOrderGoods.setCateNameLv2(vo.getCateNameLv2());
            unifiedOrderGoods.setCateNameLv3(vo.getCateNameLv3());

            /****************************************** 三级分类 20200904 by linjinyu 20200904_林志鹏_三极分类 ******************************************/


            unifiedOrderGoods.setCreateTime(DateUtil.date());
            // TODO 写死
            unifiedOrderGoods.setCreateUserId(1L);
            unifiedOrderGoods.setUpdateTime(DateUtil.date());
            // TODO 写死
            unifiedOrderGoods.setUpdateUserId(1L);
        }
    }

    /**
     * 集采订单vo转换为统一订单实体
     *
     * @param vo
     * @param unifiedOrderEntity
     */
    private void convertQchOrderParam2Entity(QchjcOrderVo vo, UnifiedOrder unifiedOrderEntity) {

        unifiedOrderEntity.setOrderType(vo.getOrderType());//正单/退单
        unifiedOrderEntity.setOrderSn(vo.getOrderSn());//订单sn
        unifiedOrderEntity.setOrderSnOutTrade(vo.getOrderSn());//外部订单号 唯一值

        unifiedOrderEntity.setServiceNo(CommonServiceNoEnum.企业商城_侨城汇.getServiceNo());//服务编号，固定值
        unifiedOrderEntity.setServiceName(CommonServiceNoEnum.企业商城_侨城汇.getServiceName());

        unifiedOrderEntity.setProjectId(QchjcOrgEnum.CUSTOMER.getOrgId());//项目ID 固定值
        unifiedOrderEntity.setProjectName(QchjcOrgEnum.CUSTOMER.getServiceNoName());//项目名称 固定值

        QchjcEnterpriseEntity qchjcEnterpriseEntity = qchjcEnterpriseEntityMapper.selectByOutId(vo.getPurchaseVirtId());
        unifiedOrderEntity.setPurchaseVirtId(qchjcEnterpriseEntity.getId());//采购单位ID, 中间表的id，集采的id统一+10万
        unifiedOrderEntity.setPurchaseVirtName(vo.getPurchaseVirtName());//采购单位名称
        unifiedOrderEntity.setPurchaseDepartmentName(vo.getPurchaseDepartmentName());//采购单位部门名称


        QchjcUserEntity qchjcUserEntity1 = qchjcUserEntityMapper.selectByOutId(vo.getPurchaseUserId());
        if (qchjcUserEntity1 != null) {
            unifiedOrderEntity.setPurchaseUserId(qchjcUserEntity1.getUnifiedId());//采购单位用户ID
        }
        unifiedOrderEntity.setPurchaseUserName(vo.getPurchaseUserName());//采购单位用户名称
        unifiedOrderEntity.setPurchasePhone(vo.getPurchasePhone());//采购单位用户电话

        QchjcSupplierEntity qchjcSupplierEntity = qchjcSupplierEntityMapper.selectByOutId(vo.getSupplierId());
        if (qchjcSupplierEntity != null) {
            unifiedOrderEntity.setSaleId(qchjcSupplierEntity.getId());//销售单位ID,中间表id，集采id统一+10万
        }
        unifiedOrderEntity.setSaleName(vo.getSupplierName());//销售单位名称

        // 商城 dispatchPrice + grprice = price scoreOrderReceiveParam.getPrice()
        unifiedOrderEntity.setAmount(vo.getOrderAmount());//订单金额
        unifiedOrderEntity.setCostAmount(vo.getOrderCostAmount());//订单成本金额

        /**
         * 20220425修改 集采运费已经拆成商品，运费都填0
         */
        unifiedOrderEntity.setTransportAmount(BigDecimal.ZERO);//运费
        unifiedOrderEntity.setTransportMerchantAssumeAmount(BigDecimal.ZERO);//运费商品承担金额

        /**
         * 20220416新增
         *
         * 20220425 因为集采过来的订单都是正单，所以退单字段没用了
         */
        unifiedOrderEntity.setRefundGoodsAmount(BigDecimal.ZERO);//退货金额
        unifiedOrderEntity.setRefundGoodsCostAmount(BigDecimal.ZERO);//退货成本金额

        unifiedOrderEntity.setPayType(vo.getPayType());
        unifiedOrderEntity.setOrderState(vo.getOrderState());//订单状态
        unifiedOrderEntity.setOrderStateName(vo.getOrderStateName());//订单状态名称

        unifiedOrderEntity.setCompletState(vo.getCompletState());//订单完成状态

        unifiedOrderEntity.setOrderLockingCustomer(CommonAccountingLockingEnum.正常.getKey());
        unifiedOrderEntity.setOrderLockingSupplier(CommonAccountingLockingEnum.正常.getKey());


        unifiedOrderEntity.setAccountingStateCustomer(CommonAccountingStateEnum.未对账.getKey());
        unifiedOrderEntity.setAccountingStateSupplier(CommonAccountingStateEnum.不对账.getKey());


        // TODO 写死
        unifiedOrderEntity.setPayState(2);
        // TODO 写死
        unifiedOrderEntity.setSettlementType(2);
        // TODO 写死
        unifiedOrderEntity.setAppraiseState(2);
        // TODO 写死
        unifiedOrderEntity.setSourceChannel(1);

        unifiedOrderEntity.setOtherParams(vo.getOtherParams());//其他参数

        QchjcUserEntity qchjcUserEntity = qchjcUserEntityMapper.selectByOutId(vo.getCreateUserId());
        if (qchjcUserEntity != null) {
            // 这个是可以用于记录 谁创建的 20200611
            unifiedOrderEntity.setCreateUserId(qchjcUserEntity.getUnifiedId());
        }
        unifiedOrderEntity.setCreateTime(vo.getCreateTime());

        unifiedOrderEntity.setPayTime(vo.getPayTime());
        unifiedOrderEntity.setSendTime(vo.getSendTime());
        unifiedOrderEntity.setFinishTime(vo.getFinishTime());

        // TODO 结算时间逻辑 添加 mark by linjinyu at 20211112
        // |---- 1. kafka 正向通道,触发点 订单已完成 产生 结算时间(订单完成时间填充) right
        // |---- 2. kafka 负向通道,解发点 退单已完成 解锁正负单时 产生结算时间(退单完成时间填充)
        // |---- 3. 供应商结算 未对账商品 list 逻辑 不变(没说明) 看样子是 加了个 结算时间 筛选逻辑
        //if (UnifiedOrderCompletStateEnum.已完成.getKey().equals(unifiedOrderEntity.getCompletState())
        //        && ObjectUtil.isNotNull(unifiedOrderEntity.getFinishTime())) {
        //unifiedOrderEntity.setAccountingTime(unifiedOrderEntity.getFinishTime());
        unifiedOrderEntity.setAccountingTime(vo.getAccountingTime());//结算时间
        //}


        // TODO 写死
        unifiedOrderEntity.setUserType("2");
        // TODO 写死
        unifiedOrderEntity.setUserName("系统");

        unifiedOrderEntity.setUpdateTime(vo.getUpdateTime());

        QchjcUserEntity updateUser = qchjcUserEntityMapper.selectByOutId(vo.getUpdateUserId());
        if (updateUser != null) {
            unifiedOrderEntity.setUpdateUserId(updateUser.getUnifiedId());
        }

        // 原本代码也是注释了
//		unifiedOrderEntity.setRecUserId();
        unifiedOrderEntity.setRecUserName(vo.getRecUserName());
        unifiedOrderEntity.setRecUserPhone(vo.getRecUserPhone());
        unifiedOrderEntity.setRecAddress(vo.getRecAddress());


        unifiedOrderEntity.setExpress(vo.getExpress());
        unifiedOrderEntity.setExpressCompany(vo.getExpressCompany());
        unifiedOrderEntity.setExpressSn(vo.getExpressSn());


        unifiedOrderEntity.setRemarks(vo.getRemarks());
    }

}
