package com.zfire.mall.manager.logic.displace.order;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.date.DateTime;
import cn.hutool.core.date.DateUtil;
import com.alibaba.excel.util.StringUtils;
import com.baomidou.mybatisplus.core.toolkit.IdWorker;
import com.zfire.mall.manager.bean.admin.AdminUserCom;
import com.zfire.mall.manager.bean.displace.order.DisplaceBean;
import com.zfire.mall.manager.bean.displace.order.DisplaceNumBean;
import com.zfire.mall.manager.bean.retail.RetailOrderItemBean;
import com.zfire.mall.manager.bean.retail.RetailOrderRefundBean;
import com.zfire.mall.manager.bean.wallet.CustomerWalletAmountBean;
import com.zfire.mall.manager.commonmapper.InvoiceMapper;
import com.zfire.mall.manager.constant.Constant;
import com.zfire.mall.manager.enums.OrderOperationTypeEnum;
import com.zfire.mall.manager.enums.OrderTypeEnum;
import com.zfire.mall.manager.exception.RemoteServiceException;
import com.zfire.mall.manager.logic.common.CommonLogic;
import com.zfire.mall.manager.logic.engin.order.EnginOrderLogic;
import com.zfire.mall.manager.logic.retail.RetailOrderLogic;
import com.zfire.mall.manager.logic.saletype.SaleTypeLogic;
import com.zfire.mall.manager.logic.wallet.RebateOrderLogic;
import com.zfire.mall.manager.logic.wallet.WalletLogic;
import com.zfire.mall.manager.plus.entity.*;
import com.zfire.mall.manager.plus.service.*;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.integration.redis.util.RedisLockRegistry;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.util.*;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.locks.Lock;
import java.util.stream.Collectors;

@Service
public class DisplaceOrderV2Logic {

    @Autowired
    CommonLogic commonLogic;
    @Autowired
    RetailOrderService retailOrderService;
    @Autowired
    RetailOrderItemService retailOrderItemService;
    @Autowired
    EnginOrderService enginOrderService;
    @Autowired
    EnginOrderItemService enginOrderItemService;
    @Autowired
    OrderBaseService orderBaseService;
    @Autowired
    KingDeeMaterialService kingDeeMaterialService;
    @Autowired
    OrderDisplaceRecordService orderDisplaceRecordService;
    @Autowired
    InvoiceMapper invoiceMapper;
    @Autowired
    CustomerWalletService customerWalletService;
    @Autowired
    RedisLockRegistry redisLockRegistry;
    @Autowired
    RetailOrderLogic retailOrderLogic;
    @Autowired
    EnginOrderLogic enginOrderLogic;
    @Autowired
    WalletLogic walletLogic;
    @Resource
    OrderExecRecordService orderExecRecordService;
    @Autowired
    PriceTypeService priceTypeService;
    @Autowired
    SaleTypeService saleTypeService;
    @Autowired
    SaleTypeLogic saleTypeLogic;
    @Resource
    DepositManageService depositManageService;
    @Resource
    DepositManageItemService depositManageItemService;
    @Resource
    DepositManageItemCollectService depositManageItemCollectService;
    @Resource
    DepositManageItemBakService depositManageItemBakService;
    @Autowired
    RebateOrderLogic rebateOrderLogic;


    public List<List<OrderDisplaceRecord>> recordList(String orderId){
        if(orderId.indexOf("-") > -1) {
            orderId = orderId.substring(0, orderId.indexOf("-"));
        }

        List<OrderDisplaceRecord> list = orderDisplaceRecordService.lambdaQuery()
                .eq(OrderDisplaceRecord::getOrderId, orderId)
                .orderByDesc(OrderDisplaceRecord::getCreateTime).orderByAsc(OrderDisplaceRecord::getIsOld).list();

        List<List<OrderDisplaceRecord>> datas = new ArrayList<>();
        List<String> batchNos = list.stream().map(OrderDisplaceRecord::getBatchNo).distinct().collect(Collectors.toList());
        for(String batchNo : batchNos){
            List<OrderDisplaceRecord> records = list.stream().filter(v -> v.getBatchNo().equals(batchNo)).collect(Collectors.toList());
            datas.add(records);
        }
        return datas;
    }


    @Transactional
    public void add(DisplaceBean displaceBean) throws InterruptedException {

        //1.订单置换 2.批量置换
        Integer type = displaceBean.getType();
        if(type == 1){
            //第一种模式后续开发
            return;
        }
        //新机型
        List<String> newMaterialIds = displaceBean.getNewMaterialIds();

        if(CollectionUtils.isEmpty(displaceBean.getNewMaterialIds())){
            throw new RemoteServiceException("请选择新机型");
        }
        if(newMaterialIds.size() > 1){
            throw new RemoteServiceException("替换成多机型暂不支持");
        }
        //新机型id
        String newMaterialId = newMaterialIds.get(0);
        //被置换的订单 零售单政策单的订单号为主键id，工程单为orderNo
        List<DisplaceNumBean> orderItems = displaceBean.getOrderItems();
        List<String> orderIds = orderItems.stream().map(DisplaceNumBean::getOrderId).collect(Collectors.toList());
        List<OrderBase> list = orderBaseService.lambdaQuery().in(OrderBase::getOrderId, orderIds).list();
        if(list.size() == 0){
            throw new RemoteServiceException("请检查参数是否正确");
        }
        Map<String, String> orderTypeMap = list.stream().collect(Collectors.toMap(OrderBase::getOrderId, OrderBase::getOrderType));

        //开始置换
        for(DisplaceNumBean bean : displaceBean.getOrderItems()){
            String orderType = orderTypeMap.get(bean.getOrderId());
            if(StringUtils.equals(orderType,OrderTypeEnum.TRADE.getKey())){
                throw new RemoteServiceException("商用订单暂时不支持置换");
            }
            String redisKey = "";
            if(StringUtils.equals(orderType,OrderTypeEnum.RETAIL.getKey()) || StringUtils.equals(orderType,OrderTypeEnum.RETAIL_POLICY.getKey()))
                redisKey = Constant.RedisPrefix.LOCK_RETAIL + bean.getOrderId();
            else
                redisKey = Constant.RedisPrefix.ENGIN_ORDER + bean.getOrderId();

            Lock obtain = redisLockRegistry.obtain(redisKey);
            if(!obtain.tryLock(5,TimeUnit.SECONDS)){
                throw new RemoteServiceException("系统繁忙，请稍后再试");
            }
            try {
                this.displace(bean,displaceBean, orderType, newMaterialId);
            }finally {
                obtain.unlock();
            }
        }
    }

    /**
     * 置换
     */
    public void displace(DisplaceNumBean bean,DisplaceBean displaceBean,String orderType,String newMaterialId) throws InterruptedException {


        if(StringUtils.equals(orderType,OrderTypeEnum.RETAIL.getKey()) || StringUtils.equals(orderType,OrderTypeEnum.RETAIL_POLICY.getKey())) {
            this.displaceRetail(bean,displaceBean,orderType,newMaterialId);
        }else{
            this.displaceEngin(bean,displaceBean,orderType,newMaterialId);
        }

    }


    /**
     * 置换零售单，政策单
     */
    public void displaceRetail(DisplaceNumBean bean,DisplaceBean displaceBean,String orderType,String newMaterialId) throws InterruptedException {
        AdminUserCom adminUser = commonLogic.getAdminUser();

        //新机型
        KingDeeMaterial newMaterial = kingDeeMaterialService.getById(newMaterialId);
        //置换记录
        List<OrderDisplaceRecord> records = new ArrayList<>();
        //置换数量
        Integer displaceQty = bean.getDisplaceQty();
        //批次号
        String batchNo = IdWorker.getIdStr();
        String orderItemId = bean.getOrderItemId();
        //检测新机型是否已存在本订单中
        Integer count = retailOrderItemService.lambdaQuery().eq(RetailOrderItem::getMaterialId, newMaterialId)
                .eq(RetailOrderItem::getRetailOrderId, bean.getOrderId()).count();
//        if(count > 0){
//            throw new RemoteServiceException("检测到订单号【"+bean.getOrderId()+"】的置换机型已存在该订单中");
//        }
        RetailOrder oldOrder = retailOrderService.getById(bean.getOrderId());
        RetailOrderItem oldItem = retailOrderItemService.getById(orderItemId);
        RetailOrderItem oldItemBean = BeanUtil.copyProperties(oldItem, RetailOrderItem.class);
        if(StringUtils.isNotBlank(oldItem.getKingDeeEntryId()) || StringUtils.isNotBlank(oldItem.getKingDeeSeq())){
            throw new RemoteServiceException("检测到订单号【"+bean.getOrderId()+"】的置换机型已同步至金蝶");
        }
        if(oldItem.getIsDirectTransfer() && !oldItem.getDirectTransferStatus()){
            throw new RemoteServiceException("检测到订单号【"+bean.getOrderId()+"】正在直调中，请先直调完成");
        }
//        if (invoiceMapper.selectInvoice(oldItem.getId()) != 0 && retailOrder.getIsPlanOrder()){
//            throw new RemoteServiceException("检测到订单有申请发货，不可弃审");
//        }
//        if (oldItem.getOldQty() > oldItem.getRefundableQty() && retailOrder.getIsPlanOrder()) {
//            throw new RemoteServiceException("销售类型：" + oldItem.getSaleTypeName()  + " 名称：" + oldItem.getMaterialName() + "数量发生变更，不可弃审");
//        }
        //判断是否存在暂扣的发货单
        Integer tmpFhCount = invoiceMapper.selectInvoice(oldItem.getId());
        if(tmpFhCount > 0)
            throw new RemoteServiceException("机型【"+oldItem.getSpecification()+"】存在发货申请中的订单，请先处理完再置换");

        //可置换数量
        int kzhQty = oldItem.getRefundableQty();
        if(kzhQty <= 0){
            return;
        }
        //检查置换金额
//        if(oldItem.getPrice().doubleValue() > bean.getNewMaterialPrice().doubleValue()){
//            throw new RemoteServiceException("置换物料的单价不可小于被置换订单机型的单价");
//        }
        if(kzhQty < displaceQty.intValue()){
            throw new RemoteServiceException("机型【"+oldItem.getSpecification()+"】最多可置换"+kzhQty+"套");
        }
        //价格类型
        //PriceType priceType = priceTypeService.getById(displaceBean.getPriceTypeId());
        SaleType saleType = saleTypeService.getById(displaceBean.getSaleTypeId());
        //返利比例
        WalletRebateSaleType bySaleTypeRebateWallet = saleTypeLogic.getBySaleTypeRebateWallet(displaceBean.getWalletId2(), displaceBean.getSaleTypeId());
        BigDecimal rebateRate = bySaleTypeRebateWallet != null ? bySaleTypeRebateWallet.getRebateRate() : BigDecimal.valueOf(0);

        //置换数量
        BigDecimal qty = BigDecimal.valueOf(displaceQty);
        //新单价
        BigDecimal price = displaceBean.getNewPrice();
        //折扣金额
        BigDecimal discAmount = displaceBean.getNewDiscAmount();

        //flag : 1=同价置换 2=非同价置换
        if(bean.getFlag() != null && bean.getFlag() == 1){
            price = oldItem.getPrice();
            saleType = null;
            rebateRate = oldItem.getRebateRate();
            discAmount = oldItem.getDiscAmount();
        }
        //是否有红字未确认的返利单
        rebateOrderLogic.checkNeedAck(oldItem.getCustomerWalletId2());

        //置换扣新的金额
        BigDecimal payAmount = price.multiply(qty);
        //置换总折扣价格
        BigDecimal totalDiscAmount = discAmount.multiply(qty);
        payAmount = payAmount.subtract(totalDiscAmount);
        //置换总返利价格
        BigDecimal totalRebateAmount = new BigDecimal(0);
        if(rebateRate != null) {
            totalRebateAmount = rebateRate.multiply(payAmount);
        }
        payAmount = payAmount.subtract(totalRebateAmount);
        if(payAmount.doubleValue() < 0)
            payAmount = BigDecimal.valueOf(0);

        //1.退掉被置换的明细数量和金额
        RetailOrderRefundBean retailOrderRefundBean = new RetailOrderRefundBean();
        List<RetailOrderItemBean> refundList = new ArrayList<>();
        RetailOrderItemBean retailOrderItemBean = BeanUtil.copyProperties(oldItem, RetailOrderItemBean.class);
        retailOrderItemBean.setTdQty(displaceQty);
        retailOrderRefundBean.setId(oldOrder.getId());
        refundList.add(retailOrderItemBean);
        retailOrderRefundBean.setRetailOrderItemList(refundList);
        //1.2 此处只会退订1个，所以返回的退订信息也只有1个
        Map<String, Object> paramsMap = retailOrderLogic.tuiding(retailOrderRefundBean).get(0);

//        refundAmount = (BigDecimal) paramsMap.get("tdAmount");
        //2.生成新的置换明细
        RetailOrderItem newItem = new RetailOrderItem();
        //BeanUtils.copyProperties(oldItem,newItem);
        newItem.setAdminUserId(oldItem.getAdminUserId());
        newItem.setAdminWebsitId(oldItem.getAdminWebsitId());
        newItem.setRetailOrderId(oldItem.getRetailOrderId());
        //newItem.setPriceType(priceType.getPriceTypeName());
        newItem.setPriceType(oldItem.getPriceType());
        newItem.setOrgPrice(oldItem.getOrgPrice());
        newItem.setMaterialId(newMaterial.getId());
        newItem.setMaterialOldNumber(newMaterial.getOldNumber());
        newItem.setMaterialCode(newMaterial.getNumber());
        newItem.setMaterialName(newMaterial.getName());
        newItem.setSpecification(newMaterial.getSpecification());
        newItem.setK3CategoryId(newMaterial.getCategoryId());
        newItem.setK3CategoryNumber(newMaterial.getCategoryNumber());
        newItem.setK3CategoryName(newMaterial.getCategoryName());
        newItem.setServiceId(oldItem.getServiceId());
        newItem.setServiceName(oldItem.getServiceName());
        newItem.setUnit(newMaterial.getBaseUnitId());
        newItem.setWalletId1(oldItem.getWalletId1());
        newItem.setCustomerWalletId(oldItem.getCustomerWalletId());
        newItem.setCustomerWalletName(oldItem.getCustomerWalletName());
        newItem.setCustomerWalletNumber(oldItem.getCustomerWalletNumber());
        newItem.setSaleTypeId(oldItem.getSaleTypeId());
        newItem.setSaleTypeName(oldItem.getSaleTypeName());
        newItem.setSaleTypeCode(oldItem.getSaleTypeCode());
        //1=同价置换 2=非同价置换
        if (bean.getFlag() == 1) {
            newItem.setWalletId2(oldItem.getWalletId2());
            newItem.setSinglePayPrice(oldItem.getSinglePayPrice());
            newItem.setPayAmount(oldItem.getSinglePayPrice().multiply(qty));
            newItem.setOldPayAmount(newItem.getPayAmount());
            //查询经销商的返利钱包
            newItem.setCustomerWalletId2(oldItem.getCustomerWalletId2());
            newItem.setCustomerWalletName2(oldItem.getCustomerWalletName2());
            newItem.setIsUseRebate(oldItem.getIsUseRebate());
            newItem.setRebateRate(oldItem.getRebateRate());
            newItem.setSingleRebateAmount(oldItem.getSingleRebateAmount());
            newItem.setPayRebateAmount(oldItem.getSingleRebateAmount().multiply(qty));
            newItem.setRebateAmount(newItem.getPayRebateAmount());
        } else if (bean.getFlag() == 2) {
            if(saleType != null){
                newItem.setSaleTypeId(saleType.getId());
                newItem.setSaleTypeName(saleType.getSaleName());
                newItem.setSaleTypeCode(saleType.getSaleCode());
            }
            newItem.setWalletId2(displaceBean.getWalletId2());
            newItem.setOldPayAmount(payAmount);
            newItem.setPayAmount(payAmount);
            newItem.setSinglePayPrice(payAmount.divide(qty,2,BigDecimal.ROUND_HALF_DOWN));
            //查询经销商的返利钱包
            CustomerWallet customerWallet2 = walletLogic.queryCustomerWallet(oldOrder.getCustomerId(), displaceBean.getWalletId2());
            if(customerWallet2 != null) {
                newItem.setCustomerWalletId2(customerWallet2.getCustomerWalletId());
                newItem.setCustomerWalletName2(customerWallet2.getCustomerWalletName());
            }
            newItem.setIsUseRebate(true);
            newItem.setRebateRate(rebateRate);
            newItem.setSingleRebateAmount(totalRebateAmount.divide(qty, 2, BigDecimal.ROUND_HALF_DOWN));
            newItem.setPayRebateAmount(totalRebateAmount);
            newItem.setRebateAmount(totalRebateAmount);
        }

        newItem.setPrice(price);
        newItem.setQty(displaceQty);
        newItem.setOldQty(displaceQty);
        newItem.setRefundableQty(displaceQty);
        newItem.setDiscAmount(discAmount);
        newItem.setRetiredQty(0);
        newItem.setRefundProductQty(0);
        newItem.setRefundProductAmount(BigDecimal.valueOf(0));
        newItem.setTotalAmount(qty.multiply(price));
        newItem.setTotalDiscAmount(totalDiscAmount);
        newItem.setId(null);
        newItem.setCreateTime(null);
        newItem.setCreateBy(null);
        newItem.setProductPriceId(null);
        newItem.setPolicyId(null);
        newItem.setPolicyMaterialId(null);
        newItem.setPolicyConditionId(null);
        newItem.setPopType(null);
        newItem.setIsDisplaceOrder(true);


        RetailOrderItem execRecord = (RetailOrderItem) paramsMap.get("execRecord");

        //旧机
        OrderDisplaceRecord oldRecord = this.supplyRetailDisplaceRecord(bean, oldOrder, oldItemBean, orderType,true);
        oldRecord.setBatchNo(batchNo);
        oldRecord.setPayAmount(oldItem.getSinglePayPrice().multiply(BigDecimal.valueOf(bean.getDisplaceQty())));
        records.add(oldRecord);

        //新订单表头
        RetailOrder newOrder = BeanUtil.copyProperties(oldOrder, RetailOrder.class);

        //代表新置换的机型，已存在本单，需要生成新单
        if(count > 0){
            String newRetailOrderId = oldOrder.getId()+"-zh";
            //置换次数加1
            Integer zhcs = retailOrderService.lambdaQuery().eq(RetailOrder::getOldOrderId, oldOrder.getId()).count();
            newRetailOrderId += (zhcs + 1);
            //明细
            newItem.setId(null);
            newItem.setCreateTime(new Date());
            newItem.setCreateBy(adminUser.getNickName());
            newItem.setRetailOrderId(newRetailOrderId);
            newItem.setIsDisplaceOrder(true);

            //表头
            newOrder.setOldOrderId(newOrder.getId());
            newOrder.setId(newRetailOrderId);
            newOrder.setIsDisplaceOrder(true);
            newOrder.setTotalAmount(newItem.getTotalAmount());
            newOrder.setCreateTime(new Date());
            newOrder.setCreateBy(adminUser.getNickName());
            newOrder.insert();
        }
        newItem.insert();

        // 订单执行记录
        //newOrder.setCreateTime(oldOrder.getCreateTime());
        this.insertRetailOrderRecord(newOrder, execRecord, newItem, false);

        //新机
        OrderDisplaceRecord newRecord = this.supplyRetailDisplaceRecord(bean, newOrder, newItem, orderType,false);
        newRecord.setBatchNo(batchNo);
        newRecord.setPayAmount(newItem.getSinglePayPrice().multiply(BigDecimal.valueOf(bean.getDisplaceQty())));
        newRecord.setMaterialId(newMaterial.getId());
        newRecord.setMaterialNumber(newMaterial.getNumber());
        newRecord.setMaterialName(newMaterial.getName());
        newRecord.setSpecification(newMaterial.getSpecification());
        records.add(newRecord);

        //更新订单置换状态
        oldOrder.setIsDisplaceOrder(true);
        oldOrder.updateById();

        //保存置换记录
        orderDisplaceRecordService.saveBatch(records);

        //扣钱并记录台账
        List<CustomerWalletAmountBean> customerWalletAmountBeans = new ArrayList<>();
        customerWalletAmountBeans.add(new CustomerWalletAmountBean(newItem.getCustomerWalletId(), newItem.getPayAmount(), newItem.getRemark(),
                "置换单-扣款", new Date(), newOrder.getId(), 2, "sub"));
        customerWalletAmountBeans.add(new CustomerWalletAmountBean(newItem.getCustomerWalletId2(), newItem.getPayRebateAmount(), newItem.getRemark(),
                "置换单-扣返利", new Date(), newOrder.getId(), 2, "sub"));
        walletLogic.doWalletAmount(customerWalletAmountBeans);

    }

    private void insertRetailOrderRecord(RetailOrder order, RetailOrderItem oldRecord, RetailOrderItem newItem, boolean isAll) {
        List<OrderExecRecord> recordList = new ArrayList<>();
//        OrderExecRecord oldExecRecord = new OrderExecRecord();
//        BeanUtils.copyProperties(oldRecord, oldExecRecord);
//        recordList.add(oldExecRecord.setRefOrderId(order.getId())
//                .setCustomerId(order.getCustomerId())
//                .setCustomerName(order.getCustomerName())
//                .setCustomerNumber(order.getCustomerNumber())
//                .setAdminCompanyId(order.getAdminCompanyId())
//                .setOrderType(order.getType() == 1 ? OrderTypeEnum.RETAIL.getKey() : OrderTypeEnum.RETAIL_POLICY.getKey())
//                .setRefOrderItemId(oldRecord.getId())
//                .setTheTime(order.getTheTime())
//                .setPolicyId(order.getPolicyId())
//                .setPolicyCode(order.getPolicyCode())
//                .setPolicyTitle(order.getPolicyTitle())
//                .setPolicyRemark(order.getPolicyRemark())
//                .setK3ServiceId(order.getK3ServiceId())
//                .setK3ServiceName(order.getK3ServiceName())
//                .setAdminUserId(order.getAdminUserId())
//                .setAdminWebsitId(order.getAdminWebsitId())
//                .setOrderOperationType(OrderOperationTypeEnum.ORDER_DISPLACE.getKey())
//                .setDirection(-1)
//                .setCreateBy(null)
//                .setCreateTime(null));
        OrderExecRecord newExecRecord = new OrderExecRecord();
        BeanUtils.copyProperties(newItem, newExecRecord);
        recordList.add(newExecRecord.setRefOrderId(order.getId())
                .setCustomerId(order.getCustomerId())
                .setCustomerName(order.getCustomerName())
                .setCustomerNumber(order.getCustomerNumber())
                .setAdminCompanyId(order.getAdminCompanyId())
                .setOrderType(order.getType() == 1 ? OrderTypeEnum.RETAIL.getKey() : OrderTypeEnum.RETAIL_POLICY.getKey())
                .setRefOrderItemId(isAll ? oldRecord.getId() : newItem.getId())
                .setTheTime(DateUtil.date())
                .setPolicyId(order.getPolicyId())
                .setPolicyCode(order.getPolicyCode())
                .setPolicyTitle(order.getPolicyTitle())
                .setPolicyRemark(order.getPolicyRemark())
                .setK3ServiceId(order.getK3ServiceId())
                .setK3ServiceName(order.getK3ServiceName())
                .setAdminUserId(order.getAdminUserId())
                .setAdminWebsitId(order.getAdminWebsitId())
                .setOrderOperationType(OrderOperationTypeEnum.ORDER_DISPLACE.getKey())
                .setDirection(1)
                .setRefType("订单置换")
                .setOrderCreateTime(order.getCreateTime())
                .setCreateBy(null)
                .setCreateTime(null));

        orderExecRecordService.saveBatch(recordList);
    }

    private void insertEnginOrderRecord(EnginOrder oldOrder, EnginOrder newOrder, EnginOrderItem oldRecord, EnginOrderItem newItem, boolean isAll) {
        DateTime curDate = DateUtil.date();
        List<OrderExecRecord> recordList = new ArrayList<>();
        OrderExecRecord oldExecRecord = new OrderExecRecord();
        BeanUtils.copyProperties(oldRecord, oldExecRecord);
        recordList.add(oldExecRecord.setRefOrderId(oldOrder.getEnginOrderNo() + "T")
                .setCustomerId(oldOrder.getCustomerId())
                .setCustomerName(oldOrder.getCustomerName())
                .setCustomerNumber(oldOrder.getCustomerNumber())
                .setAdminCompanyId(oldOrder.getAdminCompanyId())
                .setTheTime(curDate)
                .setOrderType(oldOrder.getEnginOrderType())
                .setK3ServiceId(oldOrder.getServiceId())
                .setK3ServiceName(oldOrder.getServiceName())
                .setRefEnginRecordNo(oldOrder.getRefEnginRecordNo())
                .setMaterialCode(oldRecord.getMaterialNumber())
                .setRefOrderItemId(oldRecord.getId())
                .setAdminUserId(oldOrder.getAdminUserId())
                .setAdminWebsitId(oldOrder.getAdminWebsitId())
                .setOrderOperationType(OrderOperationTypeEnum.ORDER_DISPLACE.getKey())
                .setDirection(-1)
                .setRefType("订单置换")
                .setOrderCreateTime(oldOrder.getCreateTime())
                .setCreateBy(null)
                .setCreateTime(null));
        OrderExecRecord newExecRecord = new OrderExecRecord();
        BeanUtils.copyProperties(newItem, newExecRecord);
        recordList.add(newExecRecord.setRefOrderId(newOrder.getEnginOrderNo())
                .setCustomerId(newOrder.getCustomerId())
                .setCustomerName(newOrder.getCustomerName())
                .setCustomerNumber(newOrder.getCustomerNumber())
                .setAdminCompanyId(newOrder.getAdminCompanyId())
                .setTheTime(curDate)
                .setOrderType(newOrder.getEnginOrderType())
                .setK3ServiceId(newOrder.getServiceId())
                .setK3ServiceName(newOrder.getServiceName())
                .setRefEnginRecordNo(newOrder.getRefEnginRecordNo())
                .setMaterialCode(newItem.getMaterialNumber())
                .setRefOrderItemId(isAll ? oldRecord.getId() : newItem.getId())
                .setAdminUserId(newOrder.getAdminUserId())
                .setAdminWebsitId(newOrder.getAdminWebsitId())
                .setOrderOperationType(OrderOperationTypeEnum.ORDER_DISPLACE.getKey())
                .setDirection(1)
                .setRefType("订单置换")
                .setOrderCreateTime(oldOrder.getCreateTime())
                .setCreateBy(null)
                .setCreateTime(null));

        orderExecRecordService.saveBatch(recordList);
    }


    /**
     * 置换工程单
     */
    public void displaceEngin(DisplaceNumBean bean,DisplaceBean displaceBean,String orderType,String newMaterialId) throws InterruptedException {
        AdminUserCom adminUser = commonLogic.getAdminUser();
        //新机型
        KingDeeMaterial newMaterial = kingDeeMaterialService.getById(newMaterialId);
        //置换记录
        List<OrderDisplaceRecord> records = new ArrayList<>();
        //置换数量
        Integer displaceQty = bean.getDisplaceQty();
        String batchNo = IdWorker.getIdStr();
        String orderItemId = bean.getOrderItemId();

        //检测新机型是否已存在本订单中
        Integer count = enginOrderItemService.lambdaQuery().eq(EnginOrderItem::getMaterialId, newMaterialId)
                .eq(EnginOrderItem::getEnginOrderNo, bean.getOrderId()).count();
//        if(count > 0){
//            throw new RemoteServiceException("检测到订单号【"+bean.getOrderId()+"】的置换机型已存在该订单中");
//        }
        EnginOrder oldOrder = enginOrderService.lambdaQuery().eq(EnginOrder::getEnginOrderNo, bean.getOrderId()).one();
        EnginOrderItem oldItem = enginOrderItemService.getById(orderItemId);
        EnginOrderItem oldItemBean = BeanUtil.copyProperties(oldItem, EnginOrderItem.class);

        List<EnginOrderItem> orderItems = enginOrderItemService.lambdaQuery()
                .eq(EnginOrderItem::getParentId, oldOrder.getEnginOrderId())
                .list();

        long transferCount = orderItems.stream().filter(EnginOrderItem::getIsDirectTransfer).count();
        if (!oldOrder.getDirectTransferStatus() && transferCount > 0) {
            throw new RemoteServiceException("检测到订单直调未完结，不能做置换");
        }
        if(StringUtils.isNotBlank(oldItem.getKingDeeEntryId()) || StringUtils.isNotBlank(oldItem.getKingDeeSeq())){
            throw new RemoteServiceException("检测到订单号【"+bean.getOrderId()+"】的置换机型已同步至金蝶");
        }
        if(oldItem.getIsDirectTransfer() && !oldItem.getDirectTransferStatus()){
            throw new RemoteServiceException("检测到订单号【"+bean.getOrderId()+"】正在直调中，请先直调完成");
        }
        //检查置换金额
//        if(oldItem.getPrice().doubleValue() > bean.getNewMaterialPrice().doubleValue()){
//            throw new RemoteServiceException("置换物料的单价不可小于被置换订单机型的单价");
//        }
        //判断是否存在暂扣的发货单
        Integer tmpFhCount = invoiceMapper.selectInvoice(oldItem.getId());
        if(tmpFhCount > 0)
            throw new RemoteServiceException("机型【"+oldItem.getSpecification()+"】存在发货申请中的订单，请先处理完再置换");

        //可置换数量
        int kzhQty = oldItem.getRefundableQty();
        if(kzhQty < displaceQty.intValue()){
            throw new RemoteServiceException("机型【"+oldItem.getSpecification()+"】最多可置换"+kzhQty+"套");
        }

        //价格类型
//        PriceType priceType = priceTypeService.getById(displaceBean.getPriceTypeId());
//        SaleType saleType = saleTypeService.getById(displaceBean.getSaleTypeId());
        //返利比例
        WalletRebateSaleType bySaleTypeRebateWallet = saleTypeLogic.getBySaleTypeRebateWallet(displaceBean.getWalletId2(), displaceBean.getSaleTypeId());
        BigDecimal rebateRate = bySaleTypeRebateWallet != null ? bySaleTypeRebateWallet.getRebateRate() : BigDecimal.valueOf(0);

        //置换数量
        BigDecimal qty = BigDecimal.valueOf(displaceQty);
        //折扣金额
        BigDecimal discAmount = displaceBean.getNewDiscAmount();
        //新单价
        BigDecimal price = displaceBean.getNewPrice();
        //flag : 1=同价置换 2=非同价置换
        if(bean.getFlag() != null && bean.getFlag() == 1){
            price = oldItem.getPrice();
            rebateRate = oldItem.getRebateRate();
            discAmount = oldItem.getDiscAmount();
        }
        //置换总折扣价格
        BigDecimal totalDiscAmount = discAmount.multiply(qty);
        //置换扣新的金额
        BigDecimal payAmount = price.multiply(qty);
        payAmount = payAmount.subtract(totalDiscAmount);
        //置换总返利价格
        BigDecimal totalRebateAmount = new BigDecimal(0);
        if(rebateRate != null) {
            totalRebateAmount = rebateRate.multiply(payAmount);
        }
        payAmount = payAmount.subtract(totalRebateAmount);
        if(payAmount.doubleValue() < 0)
            payAmount = BigDecimal.valueOf(0);
        //TODO 如果是家用工程扣押金订单
        BigDecimal depositRate = enginOrderLogic.queryOrderTakeDeposit(oldOrder);
        int depositCompare = depositRate.compareTo(BigDecimal.ZERO);

        //是否有红字未确认的返利单
        rebateOrderLogic.checkNeedAck(oldItem.getCustomerWalletId2());

        //部分置换
        //1.退掉被置换的明细数量和金额
        Map<String, Object> paramsMap = enginOrderLogic.refundItem(oldItem, displaceQty);
        //2.生成新的置换明细
        EnginOrderItem newItem = new EnginOrderItem();
        //BeanUtils.copyProperties(oldItem,newItem);
        newItem.setParentId(oldItem.getParentId());
        newItem.setUseRefCount(oldOrder.getRefCount());
        newItem.setEnginOrderNo(oldItem.getEnginOrderNo());
        newItem.setRefEnginRecordNo(oldItem.getRefEnginRecordNo());
        newItem.setAdminUserId(oldItem.getAdminUserId());
        newItem.setAdminWebsitId(oldItem.getAdminWebsitId());
        newItem.setSaleTypeId(oldItem.getSaleTypeId());
        newItem.setSaleTypeName(oldItem.getSaleTypeName());
        newItem.setSaleTypeCode(oldItem.getSaleTypeCode());
        newItem.setMaterialId(newMaterial.getId());
        newItem.setMaterialOldNumber(newMaterial.getOldNumber());
        newItem.setMaterialNumber(newMaterial.getNumber());
        newItem.setMaterialName(newMaterial.getName());
        newItem.setSpecification(newMaterial.getSpecification());
        newItem.setRealMaterialId(newMaterial.getId());
        newItem.setRealMaterialName(newMaterial.getName());
        newItem.setRealMaterialNumber(newMaterial.getNumber());
        newItem.setRealMaterialOldNumber(newMaterial.getOldNumber());
        newItem.setRealSpecification(newMaterial.getSpecification());
        newItem.setUnit(newMaterial.getBaseUnitId());
        newItem.setK3CategoryId(newMaterial.getCategoryId());
        newItem.setK3CategoryNumber(newMaterial.getCategoryNumber());
        newItem.setK3CategoryName(newMaterial.getCategoryName());
//        newItem.setEnginPrice(oldItem.getEnginPrice());
//        newItem.setEnginTotality(oldItem.getEnginTotality());
//        newItem.setEnginNum(oldItem.getEnginNum());
        newItem.setPrice(price);
        newItem.setQty(displaceQty);
        newItem.setDiscAmount(discAmount);
        newItem.setDepositRate(oldItem.getDepositRate());
        newItem.setServiceId(oldItem.getServiceId());
        newItem.setServiceName(oldItem.getServiceName());
        newItem.setCustomerWalletId(oldItem.getCustomerWalletId());
        newItem.setCustomerWalletId2(oldItem.getCustomerWalletId2());
        newItem.setCustomerWalletName(oldItem.getCustomerWalletName());
        newItem.setCustomerWalletName2(oldItem.getCustomerWalletName2());
        newItem.setCustomerWalletNumber(oldItem.getCustomerWalletNumber());
        newItem.setSingleRebateAmount(oldItem.getSingleRebateAmount());
        newItem.setSinglePayPrice(payAmount.divide(qty,2,BigDecimal.ROUND_HALF_DOWN));
        newItem.setSingleDiscAmount(totalDiscAmount.divide(qty,2,BigDecimal.ROUND_HALF_DOWN));
        newItem.setSingleDepositAmount(depositCompare >= 0 ? newItem.getSinglePayPrice().multiply(depositRate).setScale(2, BigDecimal.ROUND_DOWN) : BigDecimal.ZERO);
        newItem.setTotalDepositAmount(depositCompare >= 0 ? newItem.getSingleDepositAmount().multiply(qty) : BigDecimal.ZERO);
        newItem.setTax(oldItem.getTax());
        newItem.setRemark(oldItem.getRemark());
        newItem.setHistoryHasOrderQty(oldItem.getHistoryHasOrderQty());
        newItem.setWalletId1(oldItem.getWalletId1());
        newItem.setWalletId2(oldItem.getWalletId2());
        newItem.setOldQty(displaceQty);
        newItem.setRefundableQty(displaceQty);
        newItem.setTotalAmount(qty.multiply(price));
        newItem.setPayRebateAmount(totalRebateAmount);
        newItem.setTotalDiscAmount(totalDiscAmount);
        newItem.setId(null);
        newItem.setCreateTime(null);
        newItem.setCreateBy(null);
        newItem.setIsDisplaceOrder(true);
        //1=同价置换 2=非同价置换
        if (bean.getFlag() == 1) {
            newItem.setWalletId2(oldItem.getWalletId2());
            newItem.setSinglePayPrice(oldItem.getSinglePayPrice());
            newItem.setPayAmount(newItem.getSinglePayPrice().multiply(qty));
            newItem.setOldPayAmount(newItem.getPayAmount());
            //查询经销商的返利钱包
            newItem.setCustomerWalletId2(oldItem.getCustomerWalletId2());
            newItem.setCustomerWalletName2(oldItem.getCustomerWalletName2());
            newItem.setRebateRate(oldItem.getRebateRate());
            newItem.setSingleRebateAmount(oldItem.getSingleRebateAmount());
            newItem.setPayRebateAmount(oldItem.getSingleRebateAmount().multiply(qty));
            newItem.setRebateAmount(newItem.getRebateAmount());
        } else if (bean.getFlag() == 2) {
            newItem.setWalletId2(displaceBean.getWalletId2());
            newItem.setOldPayAmount(payAmount);
            newItem.setPayAmount(payAmount);
            //查询经销商的返利钱包
            CustomerWallet customerWallet2 = walletLogic.queryCustomerWallet(oldOrder.getCustomerId(), displaceBean.getWalletId2());
            if(customerWallet2 != null) {
                newItem.setCustomerWalletId2(customerWallet2.getCustomerWalletId());
                newItem.setCustomerWalletName2(customerWallet2.getCustomerWalletName());
            }
            newItem.setRebateRate(rebateRate);
            newItem.setSingleRebateAmount(totalRebateAmount.divide(qty, 2, BigDecimal.ROUND_HALF_DOWN));
            newItem.setPayRebateAmount(totalRebateAmount);
            newItem.setRebateAmount(totalRebateAmount);
        }

        //新订单表头
        EnginOrder newOrder = BeanUtil.copyProperties(oldOrder, EnginOrder.class);

        //代表新置换的机型，已存在本单，需要生成新单
        if(count > 0){
            String newOrderNo = oldOrder.getEnginOrderNo()+"-zh";
            String newOrderId = IdWorker.getIdStr();
            //置换次数加1
            Integer zhcs = enginOrderService.lambdaQuery().eq(EnginOrder::getOldOrderId, oldOrder.getEnginOrderNo()).count();
            newOrderNo += (zhcs + 1);
            //明细
            newItem.setId(null);
            newItem.setCreateTime(new Date());
            newItem.setCreateBy(adminUser.getNickName());
            newItem.setParentId(newOrderId);
            newItem.setEnginOrderNo(newOrderNo);
            newItem.setIsDisplaceOrder(true);

            //表头
            newOrder.setOldOrderId(newOrder.getEnginOrderNo());
            newOrder.setEnginOrderId(newOrderId);
            newOrder.setEnginOrderNo(newOrderNo);
            newOrder.setIsDisplaceOrder(true);
            newOrder.setCreateTime(new Date());
            newOrder.setCreateBy(adminUser.getNickName());
            newOrder.insert();
        }

        newItem.insert();

        // 订单执行记录
        EnginOrderItem execRecord = (EnginOrderItem) paramsMap.get("execRecord");
        this.insertEnginOrderRecord(oldOrder, newOrder, execRecord, newItem, false);

        //旧机
        OrderDisplaceRecord oldRecord = this.supplyEnginDisplaceRecord(bean, oldOrder, oldItem, orderType,true);
        oldRecord.setBatchNo(batchNo);
        oldRecord.setPayAmount(oldItem.getSinglePayPrice().multiply(BigDecimal.valueOf(bean.getDisplaceQty())));
        records.add(oldRecord);
        //新机
        OrderDisplaceRecord newRecord = this.supplyEnginDisplaceRecord(bean, newOrder, newItem, orderType,false);
        newRecord.setBatchNo(batchNo);
        newRecord.setPayAmount(newItem.getPayAmount());
        newRecord.setMaterialId(newMaterial.getId());
        newRecord.setMaterialNumber(newMaterial.getNumber());
        newRecord.setMaterialName(newMaterial.getName());
        newRecord.setSpecification(newMaterial.getSpecification());
        records.add(newRecord);

        //更新订单置换状态
        oldOrder.setIsDisplaceOrder(true);
        oldOrder.updateById();

        //保存置换记录
        orderDisplaceRecordService.saveBatch(records);

        // 处理家用押金管理
        if (newOrder.getEnginOrderType().equals(OrderTypeEnum.HOME.getKey())) {
            this.handleDepositManage(newItem, oldItem);
        }

        //扣钱并记录台账
        EnginOrderItem refundOrderItem = (EnginOrderItem) paramsMap.get("refund");
        List<CustomerWalletAmountBean> customerWalletAmountBeans = enginOrderLogic.handleDisplaceRefundWalletMethod(oldOrder, refundOrderItem);
//        List<CustomerWalletAmountBean> customerWalletAmountBeans = new ArrayList<>();
        customerWalletAmountBeans.add(new CustomerWalletAmountBean(newItem.getCustomerWalletId(), newItem.getPayAmount(), newItem.getRemark(),
                "置换单-扣款", new Date(), newOrder.getEnginOrderNo() + "|" + newOrder.getRefEnginRecordNo(), 2, "sub"));
        customerWalletAmountBeans.add(new CustomerWalletAmountBean(newItem.getCustomerWalletId2(), newItem.getPayRebateAmount(), newItem.getRemark(),
                "置换单-扣返利", new Date(), newOrder.getEnginOrderNo() + "|" + newOrder.getRefEnginRecordNo(), 2, "sub"));
        walletLogic.doWalletAmount(customerWalletAmountBeans);
    }

    /**
     *
     * @param newItem
     * @param oldItem
     */
    private void handleDepositManage(EnginOrderItem newItem, EnginOrderItem oldItem) {
        DepositManage depositManage = depositManageService.lambdaQuery()
                .eq(DepositManage::getRefEnginRecordNo, oldItem.getRefEnginRecordNo())
                .one();
        DepositManageItem depositManageItem = depositManageItemService.lambdaQuery()
                .eq(DepositManageItem::getParentId, depositManage.getDepositManageId())
                .eq(DepositManageItem::getMaterialId, oldItem.getMaterialId())
                .eq(DepositManageItem::getRealMaterialId, oldItem.getRealMaterialId())
                .eq(DepositManageItem::getPrice, oldItem.getPrice())
                .one();
        if (Objects.isNull(depositManageItem)) {
            throw new RemoteServiceException("找不到押金明细记录");
        }
        depositManageItem.setQty(depositManageItem.getQty() - newItem.getQty())
                .setTotalAmount(depositManageItem.getPrice().multiply(BigDecimal.valueOf(depositManageItem.getQty())))
                .setSalesQty(depositManageItem.getSalesQty() - newItem.getQty())
                .setSalesAmount(depositManageItem.getPrice().multiply(BigDecimal.valueOf(depositManageItem.getSalesQty())))
                .setDataQty(depositManageItem.getDataQty() - newItem.getQty());

        if (depositManageItem.getQty() > 0) {
            depositManageItem.updateById();
        } else {
            DepositManageItemBak bakItem = new DepositManageItemBak();
            BeanUtils.copyProperties(depositManageItem,bakItem);
            bakItem.insert();
            depositManageItem.deleteById();
        }

        // 置换机型押金明细
        DepositManageItem newDepositManageItem = depositManageItemService.lambdaQuery()
                .eq(DepositManageItem::getParentId, depositManage.getDepositManageId())
                .eq(DepositManageItem::getMaterialId, newItem.getMaterialId())
                .eq(DepositManageItem::getRealMaterialId, newItem.getRealMaterialId())
                .eq(DepositManageItem::getPrice, newItem.getPrice())
                .one();

        if (Objects.nonNull(newDepositManageItem)) {
            newDepositManageItem.setQty(newDepositManageItem.getQty() + newItem.getQty())
                    .setTotalAmount(newDepositManageItem.getPrice().multiply(BigDecimal.valueOf(newDepositManageItem.getQty())))
                    .setSalesQty(newDepositManageItem.getSalesQty() + newItem.getQty())
                    .setSalesAmount(newDepositManageItem.getPrice().multiply(BigDecimal.valueOf(newDepositManageItem.getSalesQty())))
                    .setDataQty(newDepositManageItem.getDataQty() + newItem.getQty())
                    .updateById();
        } else {
            new DepositManageItem().setParentId(depositManage.getDepositManageId())
                    .setRefEnginRecordNo(depositManage.getRefEnginRecordNo())
                    .setMaterialId(newItem.getMaterialId())
                    .setMaterialName(newItem.getMaterialName())
                    .setMaterialNumber(newItem.getMaterialNumber())
                    .setMaterialOldNumber(newItem.getMaterialOldNumber())
                    .setSpecification(newItem.getSpecification())
                    .setK3CategoryId(newItem.getK3CategoryId())
                    .setK3CategoryName(newItem.getK3CategoryName())
                    .setK3CategoryNumber(newItem.getK3CategoryNumber())
                    .setUnit(newItem.getUnit())
                    .setEnginPrice(newItem.getEnginPrice())
                    .setEnginTotality(newItem.getEnginTotality())
                    .setEnginNum(newItem.getEnginNum())
                    .setPrice(newItem.getPrice())
                    .setQty(newItem.getQty())
                    .setTotalAmount(newItem.getTotalAmount())
                    .setCustomerWalletId(newItem.getCustomerWalletId())
                    .setCustomerWalletNumber(newItem.getCustomerWalletNumber())
                    .setCustomerWalletName(newItem.getCustomerWalletName())
                    .setTax(newItem.getTax())
                    .setDataQty(newItem.getQty())
                    .setRealMaterialId(newItem.getMaterialId())
                    .setRealMaterialName(newItem.getMaterialName())
                    .setRealMaterialNumber(newItem.getMaterialNumber())
                    .setRealMaterialOldNumber(newItem.getMaterialOldNumber())
                    .setRealSpecification(newItem.getRealSpecification())
                    .setSalesQty(newItem.getQty())
                    .setSalesAmount(newItem.getPayAmount())
                    .insert();
        }

        // 置换机型扣押明细
        DepositManageItemCollect depositManageItemCollect = depositManageItemCollectService.lambdaQuery()
                .eq(DepositManageItemCollect::getParentId, depositManage.getDepositManageId())
                .eq(DepositManageItemCollect::getMaterialId, newItem.getMaterialId())
                .eq(DepositManageItemCollect::getCustomerWalletId, newItem.getCustomerWalletId())
                .eq(DepositManageItemCollect::getPrice, newItem.getPrice())
                .one();
        if (Objects.isNull(depositManageItemCollect)) {
            new DepositManageItemCollect().setParentId(depositManage.getDepositManageId())
                    .setRefEnginRecordNo(depositManage.getRefEnginRecordNo())
                    .setMaterialId(newItem.getMaterialId())
                    .setMaterialName(newItem.getMaterialName())
                    .setMaterialNumber(newItem.getMaterialNumber())
                    .setMaterialOldNumber(newItem.getMaterialOldNumber())
                    .setSpecification(newItem.getSpecification())
                    .setK3CategoryId(newItem.getK3CategoryId())
                    .setK3CategoryName(newItem.getK3CategoryName())
                    .setK3CategoryNumber(newItem.getK3CategoryNumber())
                    .setUnit(newItem.getUnit())
                    .setPrice(newItem.getPrice())
                    .setCustomerWalletId(newItem.getCustomerWalletId())
                    .setCustomerWalletNumber(newItem.getCustomerWalletNumber())
                    .setCustomerWalletName(newItem.getCustomerWalletName())
                    .insert();
        }
    }

    /**
     * 组装零售订单置换记录
     * @param bean
     * @param retailOrder
     * @param retailOrderItem
     * @param orderType
     * @param isOld
     * @return
     */
    public OrderDisplaceRecord supplyRetailDisplaceRecord(DisplaceNumBean bean,RetailOrder retailOrder,RetailOrderItem retailOrderItem,String orderType,Boolean isOld){
        OrderDisplaceRecord record = new OrderDisplaceRecord();
        record.setOrderId(bean.getOrderId());
        record.setOrderItemId(bean.getOrderItemId());
        record.setOrderType(orderType);
        BeanUtils.copyProperties(retailOrderItem,record);
        record.setCustomerId(retailOrder.getCustomerId());
        record.setCustomerNumber(retailOrder.getCustomerNumber());
        record.setCustomerName(retailOrder.getCustomerName());
        record.setIsOld(isOld);
        record.setSaleTypeNumber(retailOrderItem.getSaleTypeCode());
        record.setMaterialNumber(retailOrderItem.getMaterialCode());
        record.setDisplaceQty(bean.getDisplaceQty());
        record.setCreateTime(null);
        record.setCreateBy(null);
        record.setId(null);
        record.setTotalDiscAmount(record.getDiscAmount().multiply(BigDecimal.valueOf(bean.getDisplaceQty())));
        return record;
    }


    /**
     * 组装工程订单置换记录
     * @param bean
     * @param enginOrder
     * @param enginOrderItem
     * @param orderType
     * @param isOld
     * @return
     */
    public OrderDisplaceRecord supplyEnginDisplaceRecord(DisplaceNumBean bean,EnginOrder enginOrder,EnginOrderItem enginOrderItem,String orderType,Boolean isOld){
        OrderDisplaceRecord record = new OrderDisplaceRecord();
        BeanUtils.copyProperties(enginOrderItem,record);
        record.setOrderId(bean.getOrderId());
        record.setOrderItemId(bean.getOrderItemId());
        record.setOrderType(orderType);
        record.setCustomerId(enginOrder.getCustomerId());
        record.setCustomerNumber(enginOrder.getCustomerNumber());
        record.setCustomerName(enginOrder.getCustomerName());
        record.setIsOld(isOld);
        record.setSaleTypeNumber(enginOrderItem.getSaleTypeCode());
        record.setDisplaceQty(bean.getDisplaceQty());
        record.setCreateTime(null);
        record.setCreateBy(null);
        record.setId(null);
        return record;
    }

}
