package com.bailuntec.job;

import com.alibaba.fastjson.JSON;
import com.bailuntec.domain.constant.CommonConstant;
import com.bailuntec.domain.constant.Constant;
import com.bailuntec.domain.entity.*;
import com.bailuntec.domain.enumerate.OrderExceptionType;
import com.bailuntec.domain.enumerate.PlatformType;
import com.bailuntec.domain.example.*;
import com.bailuntec.domain.pojo.*;
import com.bailuntec.mapper.*;
import com.bailuntec.support.CallBailunSystem;
import com.bailuntec.support.PointJob;
import com.bailuntec.utils.OkHttpUtil;
import com.bailuntec.utils.PropertiesUtil;
import com.bailuntec.utils.SessionUtil;
import com.dangdang.ddframe.job.api.ShardingContext;
import lombok.extern.slf4j.Slf4j;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;
import org.apache.commons.beanutils.BeanUtils;
import org.apache.commons.lang3.StringUtils;

import java.io.IOException;
import java.math.BigDecimal;
import java.math.RoundingMode;
import java.time.LocalDateTime;
import java.time.ZoneId;
import java.time.format.DateTimeFormatter;
import java.util.*;

@Slf4j
public class OrderSyncJob extends PointJob {
    private OkHttpClient okHttpClient = OkHttpUtil.getInstance();
    private PropertiesUtil propertiesUtil = PropertiesUtil.getInstance("const");

    @Override
    public void executeJob(ShardingContext shardingContext, JobPointLog jobPointLog) {
        LinkedHashMap<String, String> map = new LinkedHashMap<>(4);
        map.put("pageCount", jobPointLog.getPageSize().toString());
        //时间回退一点, 避免服务器时间不一致而漏单
        map.put("BailunLastUpdateTimeFrom", DateTimeFormatter.ofPattern(CommonConstant.TIME_FORMAT).format(jobPointLog.getStartTime().minusMinutes(3)));
        map.put("BailunLastUpdateTimeTo", DateTimeFormatter.ofPattern(CommonConstant.TIME_FORMAT).format(jobPointLog.getEndTime()));
        do {
            map.put("pageIndex", jobPointLog.getPageIndex().equals(0) ? "1" : jobPointLog.getPageIndex().toString());
            Response response = null;
            String omsResultStr = null;
            try {
                Request request = new Request.Builder()
                        .get()
                        .url(OkHttpUtil.attachHttpGetParams(propertiesUtil.getPropertyAsString("BAILUNORDER_URL"), map))
                        .addHeader("Content-Type", "application/json")
                        .build();
                response = okHttpClient.newCall(request).execute();
                omsResultStr = response.body().string();
            } catch (IOException e) {
                throw new RuntimeException(map + "请求OMS接口同步百伦接口失败" + response, e);
            } finally {
                if (response != null) {
                    response.close();
                }
            }
            if (StringUtils.isNoneBlank(omsResultStr)) {
                OmsResultRoot omsResultRoot = JSON.parseObject(omsResultStr, OmsResultRoot.class);
                if (omsResultRoot != null && omsResultRoot.getSuccess().booleanValue()) {
                    OmsResultInfo omsResultInfo = omsResultRoot.getResult();
                    if (jobPointLog.getPageIndex().equals(0)) {
                        jobPointLog.setPageIndex(omsResultInfo.getTotalPages() + 1);
                    }
                    if (omsResultInfo.getResult() != null && omsResultInfo.getResult().size() > 0) {
                        analyseOmsOrder(omsResultInfo.getResult());
                    }
                } else {
                    throw new RuntimeException("调用OMS接口同步百伦订单失败, 响应200, 请求参数" + map.toString());
                }
            } else {
                throw new RuntimeException("调用OMS接口同步百伦订单失败, 响应为null, 请求参数" + map.toString());
            }
            if (jobPointLog.getPageIndex() % 10 == 0) {
                try {
                    JobPointLogMapper mapper = SessionUtil.getSession().getMapper(JobPointLogMapper.class);
                    mapper.upsertSelective(jobPointLog);
                } catch (Exception e) {
                    e.printStackTrace();
                    throw new RuntimeException("Mybatis操作DB插入任务记录失败", e);
                } finally {
                    SessionUtil.closeSession();
                }
            }
            jobPointLog.setPageIndex(jobPointLog.getPageIndex() - 1);
        } while (0 < jobPointLog.getPageIndex());
        jobPointLog.setPageIndex(0);
        jobPointLog.setStartTime(jobPointLog.getEndTime());
        jobPointLog.setEndTime(jobPointLog.getEndTime().plusDays(jobPointLog.getIntervalTime()).isAfter(LocalDateTime.now()) ? LocalDateTime.now() : jobPointLog.getEndTime().plusDays(jobPointLog.getIntervalTime()));
    }

    /**
     * 解析订单, 并处理费用信息
     *
     * @param bailunOrderList
     */
    public void analyseOmsOrder(List<OmsResult> bailunOrderList) {
        for (OmsResult omsResult : bailunOrderList) {
            log.warn(omsResult.getOriginOrderId());
            if (omsResult != null && omsResult.getBailunPaymentStatus() != null && omsResult.getBailunPaymentStatus().equals(Constant.PAYMENT_STATUS)) {
                DcBaseOmsOrder dcBaseOmsOrder = new DcBaseOmsOrder();
                assignmentOrderInfo(omsResult, dcBaseOmsOrder);
                deleteSku(dcBaseOmsOrder);//因为OMS可能改订单, 部分SKU有可能会被删除, 所以先删除, 再插入, 并且更新退款为未予订单关联
                //判断是否刷单订单
                listOrderExceptions(omsResult, dcBaseOmsOrder);
                //获取汇率
                getExchangeRate(omsResult, dcBaseOmsOrder);
                //遍历平台SKU拿销售额
                BigDecimal totalAmountSale = BigDecimal.ZERO;
                if (omsResult.getPlatformSku() != null && omsResult.getPlatformSku().size() > 0) {
                    for (PlatformSku platformSku : omsResult.getPlatformSku()) {
                        if (platformSku.getPlatformSkuUnitPrice() != null && platformSku.getPlatformSkuUnitPrice().getAmount() != null && platformSku.getPlatformSkuQuantityOrdered() != null) {
                            BigDecimal platformSkuUnitPrice = platformSku.getPlatformSkuUnitPrice().getAmount().compareTo(BigDecimal.ZERO) == 1 ? platformSku.getPlatformSkuUnitPrice().getAmount() : BigDecimal.ZERO;
                            totalAmountSale = platformSkuUnitPrice.multiply(BigDecimal.valueOf(platformSku.getPlatformSkuQuantityOrdered())).add(totalAmountSale).setScale(2, RoundingMode.HALF_EVEN);
                        }
                    }
                }
                //这个MAP, key放仓库. value放线物流路
                HashMap<String, Logistics> logisticsHashMap = new HashMap<>();
                //由LMS线路计算的物流费
                BigDecimal totalCostLogistics = getTotalCostLogistics(omsResult.getLogisticsItems(), logisticsHashMap);
                //如果订单中存在百伦SKU, 去拿一些放在SKU里的信息
                Map<String, BailunSkuStructure> bailunSkuInfoMap = new HashMap<>();
                BigDecimal totalCostFirst = BigDecimal.ZERO;
                if (omsResult.getBailunSku() != null && omsResult.getBailunSku().size() > 0) {
                    /*
                     * 遍历所有百伦SKU(omsResult.getBailunSku())
                     * 拿到SKU累计信息, 自发货运费按SKU重量比重取
                     */
                    BailunSkuCumulative bailunSkuCumulative = getBailunSkuCumulative(omsResult);
                    //SKU总个数
                    dcBaseOmsOrder.setQuantityBailunSku(bailunSkuCumulative.getTotalQuantity());
                    //计算每个SKU采购价占总采购价比重(用于摊分SKU售价之类) 以及 每个SKU重量价占总重量的比重
                    for (BailunSku bailunSku : omsResult.getBailunSku()) {
                        BailunSkuStructure bailunSkuStructure = new BailunSkuStructure();
                        /*
                         * 拿每个SKU的发货仓库信息
                         * 如果是FBA库存, 要看是否共享库存
                         */
                        DcBaseWarehouse dcBaseWarehouse = getDcBaseWarehouse(bailunSku, omsResult);
                        bailunSkuStructure.setDcBaseWarehouse(dcBaseWarehouse);
                        if (PlatformType.FBA.value().equals(omsResult.getPlatformType()) && dcBaseWarehouse != null) {
                            switch (dcBaseWarehouse.getAreaId()) {
                                case 6:
                                case 8:
                                case 10:
                                case 11:
                                case 12:
                                    DcBaseStockFbaShareMapper dcBaseStockFbaShareMapper = SessionUtil.getSession().getMapper(DcBaseStockFbaShareMapper.class);
                                    DcBaseStockConfigFbaMapper dcBaseStockConfigFbaMapper = SessionUtil.getSession().getMapper(DcBaseStockConfigFbaMapper.class);
                                    DcBaseWarehouseMapper baseWarehouseMapper = SessionUtil.getSession().getMapper(DcBaseWarehouseMapper.class);
                                    DcBaseStockFbaShare dcBaseStockFbaShare = dcBaseStockFbaShareMapper.selectOneByExample(DcBaseStockFbaShareExample.newAndCreateCriteria().andBailunSkuEqualTo(bailunSku.getBailunSku()).example());
                                    if (dcBaseStockFbaShare != null) { //说明是共享库存, 读仓库配置
                                        DcBaseStockConfigFba dcBaseStockConfigFba = dcBaseStockConfigFbaMapper.selectOneByExample(DcBaseStockConfigFbaExample.newAndCreateCriteria().andBailunSkuEqualTo(dcBaseStockFbaShare.getBailunSku()).example());
                                        if (dcBaseStockConfigFba != null) {
                                            DcBaseWarehouse dcBaseWarehouseFba = baseWarehouseMapper.selectOneByExample(DcBaseWarehouseExample.newAndCreateCriteria().andWarehouseCodeEqualTo(dcBaseStockConfigFba.getWarehouseCode()).example());
                                            bailunSkuStructure.setDcBaseWarehouse(dcBaseWarehouseFba);
                                        } else {
                                            bailunSkuStructure.setDcBaseWarehouse(null);
                                        }
                                    } //其他的不是共享库存, 就不管了.
                                    break;
                            }
                        }
                        bailunSkuStructure.setBailunSku(bailunSku.getBailunSku());
                        bailunSkuStructure.setBailunSkuUnitPrice((bailunSku.getBailunSkuUnitPrice() != null && bailunSku.getBailunSkuUnitPrice().getAmount() != null) ? bailunSku.getBailunSkuUnitPrice().getAmount() : BigDecimal.ZERO);
                        bailunSkuStructure.setBailunSkuWeight(bailunSku.getBailunSkuWeight() != null ? bailunSku.getBailunSkuWeight() : BigDecimal.ZERO);
                        bailunSkuStructure.setSkuCostRatio(dcBaseOmsOrder.getCostProduct().compareTo(BigDecimal.ZERO) == 1 ? bailunSkuStructure.getBailunSkuUnitPrice().multiply(BigDecimal.valueOf(bailunSku.getBailunSkuQuantityOrdered())).divide(dcBaseOmsOrder.getCostProduct(), 3, RoundingMode.HALF_EVEN) : BigDecimal.ONE);
                        bailunSkuStructure.setSkuWeightRatio(bailunSkuCumulative.getTotalWeight().compareTo(BigDecimal.ZERO) == 1 ? bailunSkuStructure.getBailunSkuWeight().multiply(BigDecimal.valueOf(bailunSku.getBailunSkuQuantityOrdered())).divide(bailunSkuCumulative.getTotalWeight(), 3, RoundingMode.HALF_EVEN) : BigDecimal.ONE);
                        bailunSkuStructure.setSkuQuantityOrderd(bailunSku.getBailunSkuQuantityOrdered() != null ? bailunSku.getBailunSkuQuantityOrdered() : 0);
                        DcBaseOmsSku dcBaseOmsSku = new DcBaseOmsSku();
                        if (PlatformType.FBA.value().equals(omsResult.getPlatformType())) {
                            dcBaseOmsSku.setWarehouseCodeFba(dcBaseWarehouse.getWarehouseCode());
                        }
                        dcBaseOmsSku.setHasDelete(false);
                        dcBaseOmsSku.setHasScalp(dcBaseOmsOrder.getHasScalp());
                        /*
                         * 赋值, 初始值避免null
                         */
                        assignmentSkuInfo(omsResult, dcBaseOmsOrder, dcBaseOmsSku, bailunSku, dcBaseWarehouse, logisticsHashMap);
                        if (PlatformType.FBA.value().equals(omsResult.getPlatformType().toUpperCase())) {
                            //FBA费用
                            BigDecimal skuCostFbaFee = bailunSkuStructure.getSkuWeightRatio().multiply(dcBaseOmsOrder.getCostFbaFee()).setScale(3, RoundingMode.HALF_EVEN);
                            dcBaseOmsSku.setCostFbaFee(skuCostFbaFee);
                            //FBA的发货数不用从配货单信息拿, FBA只要下单亚马逊就发货
                            dcBaseOmsSku.setBailunSkuQuantityShipped(bailunSku.getBailunSkuQuantityOrdered());
                            checkFbaFee(dcBaseOmsSku, dcBaseOmsOrder);
                        }
                        bailunSkuStructure.setDcBaseOmsSku(dcBaseOmsSku);
                        bailunSkuInfoMap.put(bailunSku.getBailunSku(), bailunSkuStructure);
                    }
                    /*
                     * 按规则计算百伦处理费
                     * 处理费算到订单维度
                     */
                    caculateBailunHandleFee(dcBaseOmsOrder, bailunSkuCumulative, bailunSkuInfoMap.get(omsResult.getBailunSku().get(0).getBailunSku()).getDcBaseWarehouse());
                }
                /*
                 * 配货单处理,
                 */
                handPickingOrder(dcBaseOmsOrder, omsResult, bailunSkuInfoMap);
                /*
                 * Order费用处理
                 */
                //促销费
                dcBaseOmsOrder.setCostPromotion((omsResult.getOrderCharge().getCostPromotion() != null && omsResult.getOrderCharge().getCostPromotion().getAmount() != null) ? omsResult.getOrderCharge().getCostPromotion().getAmount() : BigDecimal.ZERO);
                //手工单销售额 = 平台SKU产品总售价 - 促销费, 手工单没有SKU售价, 只能拿订单收入
                if (StringUtils.isNotBlank(omsResult.getPlatformOrderType()) && omsResult.getPlatformOrderType().equals(Constant.MANUAL_ORDER) && omsResult.getOrderCharge().getAmountTotal() != null) {
                    totalAmountSale = omsResult.getOrderCharge().getAmountTotal().getAmount();
                    dcBaseOmsOrder.setAmountProduct(omsResult.getOrderCharge().getAmountTotal().getAmount());
                }
                //销售额
                dcBaseOmsOrder.setAmountSales(totalAmountSale.add(dcBaseOmsOrder.getAmountShipping()).add(dcBaseOmsOrder.getAmountGiftWrap()).subtract(dcBaseOmsOrder.getCostPromotion()));
                //平台渠道费
                dcBaseOmsOrder.setCostPlatformFee((omsResult.getOrderCharge().getCostPlatformFee() != null && omsResult.getOrderCharge().getCostPlatformFee().getAmount() != null) ? omsResult.getOrderCharge().getCostPlatformFee().getAmount() : BigDecimal.ZERO);
                //平台渠道费人民币 - Ebay的平台费币种不一样
                BigDecimal costPlatformFeeRMB;
                if (PlatformType.Ebay.value().equals(dcBaseOmsOrder.getPlatformType().toUpperCase())) {
                    costPlatformFeeRMB = dcBaseOmsOrder.getCostPlatformFee().multiply(dcBaseOmsOrder.getSellerOtherExchangeRate()).setScale(3, RoundingMode.HALF_EVEN);
                } else {
                    costPlatformFeeRMB = dcBaseOmsOrder.getCostPlatformFee().multiply(dcBaseOmsOrder.getSellerOrderExchangeRate()).setScale(3, RoundingMode.HALF_EVEN);
                }
                // 如果是亚马逊订单, 检查平台费是否超高
                if (dcBaseOmsOrder.getPlatformType().toUpperCase().equals(PlatformType.Amazon.value())) {
                    checkPlatformFee(dcBaseOmsOrder);
                }
                //--begin 插入DB
                // 利润 = 销售额 -退款 -操作费 - 平台费 -头程-尾程(FBA费)- 处理费-采购成本
                BigDecimal totalAmountSalesRMB = dcBaseOmsOrder.getAmountSales().multiply(dcBaseOmsOrder.getSellerOrderExchangeRate()).setScale(3, RoundingMode.HALF_EVEN);
                BigDecimal totalCostFbaFeeRMB = dcBaseOmsOrder.getCostFbaFee().multiply(dcBaseOmsOrder.getSellerOrderExchangeRate()).setScale(3, RoundingMode.HALF_EVEN);
                BigDecimal totalCostPaypalFeeRMB = dcBaseOmsOrder.getCostPaypalFee().multiply(dcBaseOmsOrder.getSellerOrderExchangeRate()).setScale(3, RoundingMode.HALF_EVEN);
                BigDecimal totalAmountPrepaid = BigDecimal.ZERO;
                BigDecimal totalProfit = BigDecimal.ZERO;
                BigDecimal totalOrderCostLogistics = BigDecimal.ZERO;
                try {
                    DcBaseOmsSkuMapper omsSkuMapper = SessionUtil.getSession().getMapper(DcBaseOmsSkuMapper.class);
                    if (bailunSkuInfoMap.size() > 0) {
                        /*
                         * OMS过来的详细费用不用动
                         *  按比例算出SKU的售价
                         *  利润 = 销售额 -退款 -操作费 - 平台费 -头程-尾程- 处理费-采购成本
                         *  FBA费用相当于FBA订单的尾程费
                         *  跟重量有关的费用按重量分摊
                         */
                        for (BailunSkuStructure bailunSkuStructure : bailunSkuInfoMap.values()) {
                            DcBaseOmsSku dcBaseOmsSku = bailunSkuStructure.getDcBaseOmsSku();
                            DcBaseWarehouse dcBaseWarehouse = bailunSkuStructure.getDcBaseWarehouse();
                            dcBaseOmsSku.setRatioPrice(bailunSkuStructure.getSkuCostRatio());
                            dcBaseOmsSku.setRatioWeight(bailunSkuStructure.getSkuWeightRatio());
                            //总收入
                            BigDecimal skuAmountTotal = bailunSkuStructure.getSkuCostRatio().multiply(dcBaseOmsOrder.getAmountTotal()).setScale(3, RoundingMode.HALF_EVEN);
                            //商品收入
                            BigDecimal skuAmountProduct = bailunSkuStructure.getSkuCostRatio().multiply(dcBaseOmsOrder.getAmountProduct()).setScale(3, RoundingMode.HALF_EVEN);
                            //礼品包装收入
                            BigDecimal skuGiftAmountFee = bailunSkuStructure.getSkuCostRatio().multiply(dcBaseOmsOrder.getAmountGiftWrap()).setScale(3, RoundingMode.HALF_EVEN);
                            //调整收入
                            BigDecimal skuAmountAdjustment = bailunSkuStructure.getSkuCostRatio().multiply(dcBaseOmsOrder.getAmountAdjustment()).setScale(3, RoundingMode.HALF_EVEN);
                            //税费收入
                            BigDecimal skuAmountTax = bailunSkuStructure.getSkuCostRatio().multiply(dcBaseOmsOrder.getAmountTax()).setScale(3, RoundingMode.HALF_EVEN);
                            //运费收入
                            BigDecimal skuAmountShipping = bailunSkuStructure.getSkuWeightRatio().multiply(dcBaseOmsOrder.getAmountShipping()).setScale(3, RoundingMode.HALF_EVEN);
                            //将总销售额按比例摊分到SKU-原币种, SKU可能有多个
                            BigDecimal skuAmountSales = bailunSkuStructure.getSkuCostRatio().multiply(dcBaseOmsOrder.getAmountSales()).setScale(3, RoundingMode.HALF_EVEN);
                            //单个SKU售价-原币种
                            BigDecimal skuSalesPrice = bailunSkuStructure.getSkuQuantityOrderd() > 0 ? skuAmountSales.divide(BigDecimal.valueOf(bailunSkuStructure.getSkuQuantityOrderd()), 3, RoundingMode.HALF_EVEN) : BigDecimal.ZERO;
                            //平台费-原币种
                            BigDecimal skuCostPlatformFee = bailunSkuStructure.getSkuCostRatio().multiply(dcBaseOmsOrder.getCostPlatformFee()).setScale(3, RoundingMode.HALF_EVEN);
                            BigDecimal skuCostPlatformFeeRMB = bailunSkuStructure.getSkuCostRatio().multiply(costPlatformFeeRMB).setScale(3, RoundingMode.HALF_EVEN);
                            // Paypal费
                            BigDecimal skuPaypalFee = bailunSkuStructure.getSkuCostRatio().multiply(dcBaseOmsOrder.getCostPaypalFee()).setScale(3, RoundingMode.HALF_EVEN);
                            BigDecimal skuPaypalFeeRmb = bailunSkuStructure.getSkuCostRatio().multiply(totalCostPaypalFeeRMB).setScale(3, RoundingMode.HALF_EVEN);
                            //如果不是国内仓并且发货了 就需要去拿头程费
                            if (dcBaseWarehouse != null && !dcBaseWarehouse.getHqType().equals(Constant.DOMESTIC_WAREHOUSE) && dcBaseOmsSku.getBailunSkuQuantityShipped() > 0) {
                                DcMidCostFirstMapper mapper = SessionUtil.getSession().getMapper(DcMidCostFirstMapper.class);
                                DcMidCostFirst dcMidCostFirst = mapper.selectOneByExample(DcMidCostFirstExample.newAndCreateCriteria().andBailunSkuEqualTo(dcBaseOmsSku.getBailunSku()).andWarehouseCodeEqualTo(dcBaseWarehouse.getWarehouseCode()).example());
                                //如果查不到,铭哥那边商量好了，头程0的，先跑调拨单，若是真是之前的SKU无法找到的，那就取值38元1KG来计算。
                                if (dcMidCostFirst == null) {
                                    dcMidCostFirst = new DcMidCostFirst();
                                    dcMidCostFirst.setCostFirst(bailunSkuStructure.getBailunSkuWeight().multiply(Constant.COST_FIRST_PRICE));
                                }
                                dcBaseOmsSku.setCostFirst(dcMidCostFirst.getCostFirst());
                                totalCostFirst = totalCostFirst.add(dcMidCostFirst.getCostFirst().multiply(BigDecimal.valueOf(dcBaseOmsSku.getBailunSkuQuantityShipped())));
                            }
                            //下单数大于发货数, 判定为预收费-人民币
                            if (dcBaseOmsSku.getBailunSkuQuantityOrdered() != null && dcBaseOmsSku.getBailunSkuQuantityOrdered() > dcBaseOmsSku.getBailunSkuQuantityShipped()) {
                                BigDecimal quantityPrepared = BigDecimal.valueOf(dcBaseOmsSku.getBailunSkuQuantityOrdered() - dcBaseOmsSku.getBailunSkuQuantityShipped());
                                //这是未发货(预收)部分占的平台费
                                BigDecimal skuCostPlatformFeePreparedRMB = skuCostPlatformFeeRMB.multiply(quantityPrepared).divide(BigDecimal.valueOf(dcBaseOmsSku.getBailunSkuQuantityOrdered()), 3, RoundingMode.HALF_EVEN);
                                BigDecimal amountPrepaid = (skuSalesPrice.multiply(quantityPrepared).multiply(dcBaseOmsOrder.getSellerOrderExchangeRate()).subtract(skuCostPlatformFeePreparedRMB)).divide(quantityPrepared, 3, RoundingMode.HALF_EVEN);
                                dcBaseOmsSku.setAmountPrepaid(amountPrepaid.compareTo(BigDecimal.ZERO) == 1 ? amountPrepaid : BigDecimal.ZERO);
                                totalAmountPrepaid = totalAmountPrepaid.add(dcBaseOmsSku.getAmountPrepaid());
                            }
                            //促销费-原币种
                            BigDecimal skuCostPromotion = bailunSkuStructure.getSkuCostRatio().multiply(dcBaseOmsOrder.getCostPromotion()).setScale(3, RoundingMode.HALF_EVEN);
                            //销售额 = 平台SKU产品总售价 - 促销费(如果不是FBA, 还要加上运费收入),这个费用在订单维度已经算好,按比例摊到SKU
                            BigDecimal skuAmountSalesRMB = skuAmountSales.multiply(dcBaseOmsOrder.getSellerOrderExchangeRate()).setScale(3, RoundingMode.HALF_EVEN);
                            BigDecimal unitSkuAmountSalesRMB = BigDecimal.ZERO;
                            //FBA费-人民币
                            BigDecimal skuCostFbaFeeRMB = dcBaseOmsSku.getCostFbaFee().multiply(dcBaseOmsOrder.getSellerOrderExchangeRate()).setScale(3, RoundingMode.HALF_EVEN);
                            //百伦处理费
                            BigDecimal skuCostHandleBailun = bailunSkuStructure.getSkuWeightRatio().multiply(dcBaseOmsOrder.getCostHandleBailun()).setScale(3, RoundingMode.HALF_EVEN);
                            //百伦LMS物流费-在CostTail(尾程费-真实费用)拿不到之前就用它
                            BigDecimal skuCostLogistics = bailunSkuStructure.getSkuWeightRatio().multiply(totalCostLogistics).setScale(3, RoundingMode.HALF_EVEN);
                            /*
                             * 将按比例摊分的费用算到单个SKU
                             * 摊分方法: 除以下单数
                             */
                            BigDecimal quantityOrderdDecimal = BigDecimal.valueOf(bailunSkuStructure.getSkuQuantityOrderd());
                            BigDecimal rmbCost = BigDecimal.ZERO;
                            if (quantityOrderdDecimal.compareTo(BigDecimal.ZERO) == 1) {
                                dcBaseOmsSku.setCostLogistics(skuCostLogistics.divide(quantityOrderdDecimal, 3, RoundingMode.HALF_EVEN));
                                dcBaseOmsSku.setAmountTotal(skuAmountTotal.divide(quantityOrderdDecimal, 3, RoundingMode.HALF_EVEN));
                                dcBaseOmsSku.setAmountProduct(skuAmountProduct.divide(quantityOrderdDecimal, 3, RoundingMode.HALF_EVEN));
                                dcBaseOmsSku.setAmountAdjustment(skuAmountAdjustment.divide(quantityOrderdDecimal, 3, RoundingMode.HALF_EVEN));
                                dcBaseOmsSku.setAmountTax(skuAmountTax.divide(quantityOrderdDecimal, 3, RoundingMode.HALF_EVEN));
                                dcBaseOmsSku.setAmountGiftWrap(skuGiftAmountFee.divide(quantityOrderdDecimal, 3, RoundingMode.HALF_EVEN));
                                dcBaseOmsSku.setCostPaypalFee(skuPaypalFee.divide(quantityOrderdDecimal, 3, RoundingMode.HALF_EVEN));
                                dcBaseOmsSku.setCostHandleBailun(skuCostHandleBailun.divide(quantityOrderdDecimal, 3, RoundingMode.HALF_EVEN));
                                dcBaseOmsSku.setCostPlatformFee(skuCostPlatformFee.divide(quantityOrderdDecimal, 3, RoundingMode.HALF_EVEN));
                                dcBaseOmsSku.setCostHandlePlatform(dcBaseOmsSku.getCostHandlePlatform().divide(quantityOrderdDecimal, 3, RoundingMode.HALF_EVEN));
                                dcBaseOmsSku.setCostFbaFee(dcBaseOmsSku.getCostFbaFee().divide(quantityOrderdDecimal, 3, RoundingMode.HALF_EVEN));
                                dcBaseOmsSku.setCostTail(dcBaseOmsSku.getCostTail().divide(quantityOrderdDecimal, 3, RoundingMode.HALF_EVEN));
                                dcBaseOmsSku.setCostProduct(bailunSkuStructure.getBailunSkuUnitPrice());
                                dcBaseOmsSku.setCostPromotion(skuCostPromotion.divide(quantityOrderdDecimal, 3, RoundingMode.HALF_EVEN));
                                dcBaseOmsSku.setAmountSales(skuAmountSales.subtract(skuCostPromotion).divide(quantityOrderdDecimal, 3, RoundingMode.HALF_EVEN));
                                dcBaseOmsSku.setAmountShipping(skuAmountShipping.divide(quantityOrderdDecimal, 3, RoundingMode.HALF_EVEN));
                                //单个SKU的销售额
                                unitSkuAmountSalesRMB = skuAmountSalesRMB.divide(quantityOrderdDecimal, 3, RoundingMode.HALF_EVEN);
                                //单个SKU的支出
                                rmbCost = dcBaseOmsSku.getCostHandleBailun()//处理费
                                        .add(skuCostPlatformFeeRMB.divide(quantityOrderdDecimal, 3, RoundingMode.HALF_EVEN))//平台费
                                        .add(dcBaseOmsSku.getCostHandlePlatform())//第三方仓操作费
                                        .add(skuCostFbaFeeRMB.divide(quantityOrderdDecimal, 3, RoundingMode.HALF_EVEN))//FBA费
                                        .add(dcBaseOmsSku.getCostFirst())//头程费
                                        .add(dcBaseOmsSku.getCostLogistics())//百伦LMS物流费
                                        .add(dcBaseOmsSku.getCostProduct())//采购成本
                                        .add(skuPaypalFeeRmb.divide(quantityOrderdDecimal, 3, RoundingMode.HALF_EVEN))//Paypal费
                                        .setScale(3, RoundingMode.HALF_EVEN);
                            }
                            //单个SKU的费用支出
                            dcBaseOmsSku.setCostTotal(rmbCost);
                            //利润都转为人民币计算
                            BigDecimal unitSkuProfit = unitSkuAmountSalesRMB.subtract(dcBaseOmsSku.getCostTotal());
                            //只有发货的SKU才去算订单维度利润
                            BigDecimal bailunSkuQuantityShippedDecimal = BigDecimal.valueOf(dcBaseOmsSku.getBailunSkuQuantityShipped());
                            BigDecimal skuShippedProfit = unitSkuProfit.multiply(bailunSkuQuantityShippedDecimal);
                            totalOrderCostLogistics = totalOrderCostLogistics.add(dcBaseOmsSku.getCostLogistics().multiply(bailunSkuQuantityShippedDecimal));
                            totalProfit = totalProfit.add(skuShippedProfit);
                            //SKU只放单个利润
                            dcBaseOmsSku.setProfitTotal(unitSkuProfit);
                            if (skuAmountSalesRMB.compareTo(BigDecimal.ZERO) == 0) {
                                dcBaseOmsSku.setProfitRate(BigDecimal.ZERO);
                            } else {
                                dcBaseOmsSku.setProfitRate(dcBaseOmsSku.getProfitTotal().divide(skuAmountSalesRMB, 5, RoundingMode.HALF_EVEN));
                            }
                            dcBaseOmsSku.setGmtModified(LocalDateTime.now());
                            int i = omsSkuMapper.updateByExampleSelective(dcBaseOmsSku, DcBaseOmsSkuExample.newAndCreateCriteria().andBailunSkuEqualTo(dcBaseOmsSku.getBailunSku()).andOriginOrderIdEqualTo(dcBaseOmsSku.getOriginOrderId()).andBailunAccountIdEqualTo(dcBaseOmsSku.getBailunAccountId()).example());
                            if (i == 0) {
                                omsSkuMapper.insertSelective(dcBaseOmsSku);
                            }
                        }
                    }
                    //预付款-预收金额-人民币
                    dcBaseOmsOrder.setAmountPrepaid(totalAmountPrepaid);
                    dcBaseOmsOrder.setCostFirst(totalCostFirst);
                    dcBaseOmsOrder.setCostLogistics(totalOrderCostLogistics);
                    /*
                     * OMS过来的详细费用不用动
                     * 这边处理新增了
                     *  利润 = 销售额 -退款 -操作费 - 平台费 -头程-尾程- 处理费-采购成本
                     */
                    //退款在匹配退款单的时候算
                    BigDecimal costTotal = dcBaseOmsOrder.getCostHandleBailun() //处理费
                            .add(costPlatformFeeRMB) //平台费
                            .add(dcBaseOmsOrder.getCostHandlePlatform())//第三方仓操作费
                            .add(totalCostFbaFeeRMB)//FBA操作费
                            .add(dcBaseOmsOrder.getCostFirst()) //头程费
                            .add(dcBaseOmsOrder.getCostLogistics())//LMS物流费用
                            .add(dcBaseOmsOrder.getCostProduct())//采购成本
                            .add(totalCostPaypalFeeRMB)//Paypal费
                            .setScale(3, RoundingMode.HALF_EVEN);
                    dcBaseOmsOrder.setCostTotal(costTotal);
                    //非OMS部分的利润直接减法运算
                    dcBaseOmsOrder.setProfitTotal(totalProfit);
                    //计算利润率
                    if (totalAmountSalesRMB.compareTo(BigDecimal.ZERO) == 0) {
                        dcBaseOmsOrder.setProfitRate(BigDecimal.ZERO);
                    } else {
                        dcBaseOmsOrder.setProfitRate(dcBaseOmsOrder.getProfitTotal().divide(totalAmountSalesRMB, 5, RoundingMode.HALF_EVEN));
                    }
                    dcBaseOmsOrder.setGmtModified(LocalDateTime.now());
                    DcBaseOmsOrderMapper omsOrderMapper = SessionUtil.getSession().getMapper(DcBaseOmsOrderMapper.class);
                    int i = omsOrderMapper.updateByExampleSelective(dcBaseOmsOrder, DcBaseOmsOrderExample.newAndCreateCriteria().andOriginOrderIdEqualTo(dcBaseOmsOrder.getOriginOrderId()).andBailunAccountIdEqualTo(dcBaseOmsOrder.getBailunAccountId()).example());
                    if (i == 0) {
                        omsOrderMapper.insertSelective(dcBaseOmsOrder);
                    }
                    List<PlatformSku> platformSkuList = omsResult.getPlatformSku();
                    DcBaseOmsPlatformSku dcBaseOmsPlatformSku = new DcBaseOmsPlatformSku();
                    DcBaseOmsPlatformSkuMapper mapper = SessionUtil.getSession().getMapper(DcBaseOmsPlatformSkuMapper.class);
                    if (platformSkuList != null && platformSkuList.size() > 0) {
                        for (PlatformSku platformSkuInfo : platformSkuList) {
                            BeanUtils.copyProperties(dcBaseOmsPlatformSku, dcBaseOmsOrder);
                            dcBaseOmsPlatformSku.setPlatformSku(platformSkuInfo.getPlatformSku());
                            dcBaseOmsPlatformSku.setItemId(platformSkuInfo.getPlatformSkuItemId());
                            dcBaseOmsPlatformSku.setPlatformSkuUnitPrice(platformSkuInfo.getPlatformSkuUnitPrice() != null ? platformSkuInfo.getPlatformSkuUnitPrice().getAmount() : BigDecimal.ZERO);
                            dcBaseOmsPlatformSku.setPlatformSkuQuantityOrdered(platformSkuInfo.getPlatformSkuQuantityOrdered());
                            dcBaseOmsPlatformSku.setPlatformSkuQuantityShipped(platformSkuInfo.getPlatformSkuQuantityShipped());
                            dcBaseOmsPlatformSku.setPlatformSkuTitleCn(platformSkuInfo.getPlatformSkuTitleCn());
                            dcBaseOmsPlatformSku.setPlatformSkuTitleEn(platformSkuInfo.getPlatformSkuTitleEn());
                            String site = dcBaseOmsOrder.getWebsite().toUpperCase().replaceAll(" ", "");
                            dcBaseOmsPlatformSku.setCreateTimeSite(timeZoneChange(site, dcBaseOmsOrder.getCreateTime()));
                            dcBaseOmsPlatformSku.setPaidTimeSite(timeZoneChange(site, dcBaseOmsOrder.getPaidTime()));
                            dcBaseOmsPlatformSku.setPayTimeSite(timeZoneChange(site, dcBaseOmsOrder.getPayTime()));
                            int ii = mapper.updateByExampleSelective(dcBaseOmsPlatformSku,DcBaseOmsPlatformSkuExample.newAndCreateCriteria().andPlatformSkuEqualTo(dcBaseOmsPlatformSku.getPlatformSku()).andOriginOrderIdEqualTo(dcBaseOmsPlatformSku.getOriginOrderId()).andBailunAccountIdEqualTo(dcBaseOmsPlatformSku.getBailunAccountId()).example());
                            if (ii == 0) {
                                mapper.insertSelective(dcBaseOmsPlatformSku);
                            }
                        }
                    }
                } catch (Exception e) {
                    throw new RuntimeException("Mybatis操作DB失败", e);
                } finally {
                    SessionUtil.closeSession();
                }
            }
        }
    }

    private LocalDateTime timeZoneChange(String site, LocalDateTime localDateTime) {
        LocalDateTime timeZoneChangeTime = null;
        if (localDateTime != null) {
            switch (site) {
                case "AU"://澳大利亚
                    timeZoneChangeTime = localDateTime.atZone(ZoneId.of(ZoneId.SHORT_IDS.get("CTT")))
                            .withZoneSameInstant(ZoneId.of(ZoneId.SHORT_IDS.get("AET"))).toLocalDateTime();
                    break;
                case "DE"://德国
                case "ES"://西班牙
                case "FR"://法国
                case "IT"://意大利
                case "UK"://英国
                case "IE"://爱尔兰
                    timeZoneChangeTime = localDateTime.atZone(ZoneId.of(ZoneId.SHORT_IDS.get("CTT")))
                            .withZoneSameInstant(ZoneId.of("GMT")).toLocalDateTime();
                    break;
                case "JP"://日本
                    timeZoneChangeTime = localDateTime.atZone(ZoneId.of(ZoneId.SHORT_IDS.get("CTT")))
                            .withZoneSameInstant(ZoneId.of(ZoneId.SHORT_IDS.get("JST"))).toLocalDateTime();
                    break;
                case "IN"://印度
                    timeZoneChangeTime = localDateTime.atZone(ZoneId.of(ZoneId.SHORT_IDS.get("CTT")))
                            .withZoneSameInstant(ZoneId.of(ZoneId.SHORT_IDS.get("IST"))).toLocalDateTime();
                    break;
                case "BR"://巴西
                    timeZoneChangeTime = localDateTime.atZone(ZoneId.of(ZoneId.SHORT_IDS.get("CTT")))
                            .withZoneSameInstant(ZoneId.of(ZoneId.SHORT_IDS.get("AGT"))).toLocalDateTime();
                    break;
                case "RU"://俄罗斯
                    timeZoneChangeTime = localDateTime.atZone(ZoneId.of(ZoneId.SHORT_IDS.get("CTT")))
                            .withZoneSameInstant(ZoneId.of(ZoneId.SHORT_IDS.get("EAT"))).toLocalDateTime();
                    break;
                case "SE"://瑞典
                case "PL"://波兰
                case "CH"://瑞士
                case "NL"://荷兰
                case "BED"://比利时(荷兰)
                case "BEF"://比利时(法)
                case "AT"://奥地利
                    timeZoneChangeTime = localDateTime.atZone(ZoneId.of(ZoneId.SHORT_IDS.get("CTT")))
                            .withZoneSameInstant(ZoneId.of(ZoneId.SHORT_IDS.get("ECT"))).toLocalDateTime();
                    break;
                //东盟统一偏移UTC+8
                case "ID"://印尼
                case "TW"://台湾
                case "HK"://香港
                case "SG"://新加坡
                case "CN"://中国
                case "MY"://马来西亚
                case "PH"://菲律宾
                    timeZoneChangeTime = localDateTime;
                    break;
                case "":
                case "CA"://加拿大
                case "CAFR"://法属加拿大
                case "MX"://墨西哥
                case "US"://美国
                case "EBAYMOTORS"://美国
                case "GLOBAL"://全球的统一选美国
                default:
                    timeZoneChangeTime = localDateTime.atZone(ZoneId.of(ZoneId.SHORT_IDS.get("CTT")))
                            .withZoneSameInstant(ZoneId.of(ZoneId.SHORT_IDS.get("PST"))).toLocalDateTime();
            }

        }
        return timeZoneChangeTime;
    }

    private void listOrderExceptions(OmsResult omsResult, DcBaseOmsOrder dcBaseOmsOrder) {
        dcBaseOmsOrder.setHasScalp(false);
        List<OrderException> orderExceptions = omsResult.getOrderExceptions();
        if (orderExceptions != null && orderExceptions.size() > 0) {
            for (OrderException orderException : orderExceptions) {
                if (StringUtils.isNotBlank(orderException.getExceptionType()) && orderException.getExceptionType().equals(OrderExceptionType.Scalp.value())) {
                    dcBaseOmsOrder.setHasScalp(true);
                }
            }
        }
    }

    private BigDecimal getTotalCostLogistics(List<LogisticsItem> logisticsItems, HashMap<String, Logistics> logisticsHashMap) {
        BigDecimal totalCostLogistics = BigDecimal.ZERO;
        if (logisticsItems != null && logisticsItems.size() > 0) {
            for (LogisticsItem logisticsItem : logisticsItems) {
                if (logisticsItem.getLogisticsCost() != null && logisticsItem.getLogisticsCost().getAmount() != null) {
                    totalCostLogistics = totalCostLogistics.add(logisticsItem.getLogisticsCost().getAmount());
                }
                if (logisticsItem.getWarehouse() != null && StringUtils.isNotBlank(logisticsItem.getWarehouse().getWarehouseCode())) {
                    logisticsHashMap.put(logisticsItem.getWarehouse().getWarehouseCode(), logisticsItem.getLogisticsMethod());
                }
            }
        }
        return totalCostLogistics;
    }

    private void deleteSku(DcBaseOmsOrder dcBaseOmsOrder) {
        try {
            DcBaseOmsOrderMapper mapper = SessionUtil.getSession().getMapper(DcBaseOmsOrderMapper.class);
            mapper.logicDeleteOmsSku(dcBaseOmsOrder);
            mapper.logicDeleteOmsPick(dcBaseOmsOrder);
            DcBaseCrmRefundMapper crmRefundMapper = SessionUtil.getSession().getMapper(DcBaseCrmRefundMapper.class);
            crmRefundMapper.updateLinked(dcBaseOmsOrder.getOriginOrderId(), dcBaseOmsOrder.getBailunAccountId());
            dcBaseOmsOrder.setAmountRefund(BigDecimal.ZERO);
        } catch (Exception e) {
            throw new RuntimeException("Mybatis操作DB失败", e);
        } finally {
            SessionUtil.closeSession();
        }
    }

    /**
     * 计算百伦的处理费用
     * 阶梯计费
     *
     * @param dcBaseOmsOrder
     * @param bailunSkuCumulative
     * @param dcBaseWarehouse
     */
    private void caculateBailunHandleFee(DcBaseOmsOrder dcBaseOmsOrder, BailunSkuCumulative bailunSkuCumulative, DcBaseWarehouse dcBaseWarehouse) {
        if (dcBaseWarehouse != null) {
            if (dcBaseWarehouse.getHqType().equals(Constant.FBA_WAREHOUSE) || dcBaseWarehouse.getHqType().equals(Constant.OVERSEAS_WAREHOUSE)) {
                dcBaseOmsOrder.setCostHandleBailun(Constant.NO_DOMESTIC_HANDLE_FEE);
            } else if (dcBaseWarehouse.getHqType().equals(Constant.DOMESTIC_WAREHOUSE)) {
                if (bailunSkuCumulative.isHasGeneral()) {
                    dcBaseOmsOrder.setCostHandleBailun(Constant.GENERAL_DOMESTIC_HANDLE_FEE);
                } else {
                    switch (bailunSkuCumulative.getTotalQuantity()) {
                        case 1:
                            dcBaseOmsOrder.setCostHandleBailun(BigDecimal.valueOf(2));
                            break;
                        case 2:
                            dcBaseOmsOrder.setCostHandleBailun(BigDecimal.valueOf(3));
                            break;
                        case 3:
                            dcBaseOmsOrder.setCostHandleBailun(BigDecimal.valueOf(4));
                            break;
                        case 4:
                            dcBaseOmsOrder.setCostHandleBailun(BigDecimal.valueOf(5));
                            break;
                        case 5:
                            dcBaseOmsOrder.setCostHandleBailun(BigDecimal.valueOf(6));
                            break;
                        case 6:
                            dcBaseOmsOrder.setCostHandleBailun(BigDecimal.valueOf(6.5));
                            break;
                        case 7:
                            dcBaseOmsOrder.setCostHandleBailun(BigDecimal.valueOf(7));
                            break;
                        case 8:
                            dcBaseOmsOrder.setCostHandleBailun(BigDecimal.valueOf(7.5));
                            break;
                        case 9:
                            dcBaseOmsOrder.setCostHandleBailun(BigDecimal.valueOf(8));
                            break;
                        case 10:
                            dcBaseOmsOrder.setCostHandleBailun(BigDecimal.valueOf(8.5));
                            break;
                        default:
                            dcBaseOmsOrder.setCostHandleBailun(BigDecimal.valueOf(8.5));
                    }
                }
            }
        }
    }

    private BailunSkuCumulative getBailunSkuCumulative(OmsResult omsResult) {
        BailunSkuCumulative bailunSkuCumulative = new BailunSkuCumulative();
        bailunSkuCumulative.setMaxSkuLong(BigDecimal.ZERO);
        bailunSkuCumulative.setMaxSkuWidth(BigDecimal.ZERO);
        bailunSkuCumulative.setMaxSkuHight(BigDecimal.ZERO);
        bailunSkuCumulative.setTotalWeight(BigDecimal.ZERO);
        bailunSkuCumulative.setTotalQuantity(0);
        for (BailunSku bailunSku : omsResult.getBailunSku()) {
            if (bailunSku.getBailunSkuWeight() == null) {
                bailunSku.setBailunSkuWeight(BigDecimal.ZERO);
            }
            bailunSkuCumulative.setTotalWeight(bailunSkuCumulative.getTotalWeight() != null ?
                    bailunSku.getBailunSkuWeight().multiply(BigDecimal.valueOf(bailunSku.getBailunSkuQuantityOrdered())).add(bailunSkuCumulative.getTotalWeight())
                    : bailunSku.getBailunSkuWeight().multiply(BigDecimal.valueOf(bailunSku.getBailunSkuQuantityOrdered())));
            bailunSkuCumulative.setTotalQuantity(bailunSkuCumulative.getTotalQuantity() != null ? bailunSku.getBailunSkuQuantityOrdered() + bailunSkuCumulative.getTotalQuantity() : bailunSku.getBailunSkuQuantityOrdered());
            if (PlatformType.FBA.value().equals(omsResult.getPlatformType().toUpperCase())) {
                if (!StringUtils.isEmpty(bailunSku.getBailunSkuSize())) {
                    // 该正则表达式可以匹配所有的数字 包括负数
                    String[] split = bailunSku.getBailunSkuSize().split(",");
                    BigDecimal skuLong = BigDecimal.ZERO;
                    BigDecimal skuWidth = BigDecimal.ZERO;
                    BigDecimal skuHeight = BigDecimal.ZERO;
                    if (split.length >= 3) {
                        if (!StringUtils.isEmpty(split[0]) && CommonConstant.NUMBER_AND_DECIMAL.matcher(split[0]).matches()) {
                            skuLong = new BigDecimal(split[0]);
                        }
                        if (!StringUtils.isEmpty(split[1]) && CommonConstant.NUMBER_AND_DECIMAL.matcher(split[1]).matches()) {
                            skuWidth = new BigDecimal(split[1]);
                        }
                        if (!StringUtils.isEmpty(split[2]) && CommonConstant.NUMBER_AND_DECIMAL.matcher(split[2]).matches()) {
                            skuHeight = new BigDecimal(split[2]);
                        }
                    }
                    if (skuLong.compareTo(bailunSkuCumulative.getMaxSkuLong()) >= 0)
                        bailunSkuCumulative.setMaxSkuLong(skuLong);
                    if (skuWidth.compareTo(bailunSkuCumulative.getMaxSkuWidth()) >= 0)
                        bailunSkuCumulative.setMaxSkuWidth(skuWidth);
                    if (skuHeight.compareTo(bailunSkuCumulative.getMaxSkuHight()) >= 0)
                        bailunSkuCumulative.setMaxSkuLong(skuHeight);
                }
            }
        }
        try {
            DcBaseOmsHandleMapper mapper = SessionUtil.getSession().getMapper(DcBaseOmsHandleMapper.class);
            DcBaseOmsHandle orderBailunCatagory = mapper.getOrderBailunCatagory(omsResult.getBailunSku().get(0).getBailunSku());
            bailunSkuCumulative.setHasGeneral(true);
            if (orderBailunCatagory != null) {//如果没有在这个表, 说明是普货类
                bailunSkuCumulative.setHasGeneral(false);
            }
        } catch (Exception e) {
            e.printStackTrace();
            throw new RuntimeException("MYBATIS操作DB失败", e);
        } finally {
            SessionUtil.closeSession();
        }
        return bailunSkuCumulative;
    }

    /**
     * 拿订单仓库信息
     * 如果是FBA, 就根据accountId查仓库
     * 不是FBA, 先从订单SKU里取, 取不到就去物流信息里拿
     *
     * @param bailunSku
     * @param omsResult
     * @return
     */
    private DcBaseWarehouse getDcBaseWarehouse(BailunSku bailunSku, OmsResult omsResult) {
        DcBaseWarehouse dcBaseWarehouse = null;
        try {
            DcBaseWarehouseMapper baseWarehouseMapper = SessionUtil.getSession().getMapper(DcBaseWarehouseMapper.class);
            /*
             * 如果是FBA订单, 先要看这个SKU是不是共享库存
             * 再看SKU在配置表dc_base_stock_config_fba,是否有配置
             * 配置
             */
            if (PlatformType.FBA.value().equals(omsResult.getPlatformType())) {
                dcBaseWarehouse = baseWarehouseMapper.selectOneByExample(DcBaseWarehouseExample.newAndCreateCriteria().andBailunAccountIdEqualTo(omsResult.getSeller().getBailunAccountId()).example());
            } else {
                if (StringUtils.isNotBlank(bailunSku.getWarehouseCode())) {
                    dcBaseWarehouse = baseWarehouseMapper.selectOneByExample(DcBaseWarehouseExample.newAndCreateCriteria().andWarehouseCodeEqualTo(bailunSku.getWarehouseCode()).example());
                } else if (omsResult.getLogisticsItems() != null && omsResult.getLogisticsItems().size() > 0 && omsResult.getLogisticsItems().get(0).getWarehouse() != null && omsResult.getLogisticsItems().get(0).getWarehouse().getWarehouseCode() != null) {
                    dcBaseWarehouse = baseWarehouseMapper.selectOneByExample(DcBaseWarehouseExample.newAndCreateCriteria().andWarehouseCodeEqualTo(omsResult.getLogisticsItems().get(0).getWarehouse().getWarehouseCode()).example());
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
            throw new RuntimeException("MYBATIS操作DB查询仓库信息失败", e);
        } finally {
            SessionUtil.closeSession();
        }
        return dcBaseWarehouse;
    }


    /**
     * 处理配货单, 多个配货单的SKU可能重复
     * 每个SKU 单独存放, 方便导数据
     * 返回已发货的SKU 总成本
     */
    private void handPickingOrder(DcBaseOmsOrder dcBaseOmsOrder, OmsResult omsResult, Map<String, BailunSkuStructure> skuStructureMap) {
        List<PickingOrder> pickingOrderList = omsResult.getPickingOrder();
        BigDecimal totalCostPackaging = BigDecimal.ZERO;
        BigDecimal totalCostShipping = BigDecimal.ZERO;
        if (pickingOrderList != null && pickingOrderList.size() > 0) {
            for (PickingOrder pickingOrder : pickingOrderList) {
                BigDecimal skuCostShipping = pickingOrder.getCostShipping() != null ? pickingOrder.getCostShipping() : BigDecimal.ZERO;
                BigDecimal skuCostPackaging = pickingOrder.getCostPackaging() != null ? pickingOrder.getCostPackaging() : BigDecimal.ZERO;
                BigDecimal outboundWeight = pickingOrder.getOutboundWeight() != null ? pickingOrder.getOutboundWeight() : BigDecimal.ZERO;
                totalCostPackaging = totalCostPackaging.add(skuCostPackaging);//总的第三方操作费
                totalCostShipping = totalCostShipping.add(skuCostShipping);//总的第三方发货费用
                List<PickingItem> pickingItems = pickingOrder.getPickingItems();
                if (pickingItems != null && pickingItems.size() > 0) {
                    BigDecimal pickOrderTotalWeight = BigDecimal.ZERO;
                    for (PickingItem pickingItem : pickingItems) {
                        BailunSkuStructure bailunSkuStructure = skuStructureMap.get(pickingItem.getBailunSku());
                        if (bailunSkuStructure != null) {
                            pickOrderTotalWeight = pickOrderTotalWeight.add(bailunSkuStructure.getBailunSkuWeight().multiply(BigDecimal.valueOf(pickingItem.getQuantityPicked())));
                        }
                    }
                    for (PickingItem pickingItem : pickingItems) {
                        BigDecimal quantityPickedBigDecimal = BigDecimal.valueOf(pickingItem.getQuantityPicked());
                        DcBaseOmsPick dcBaseOmsPick = new DcBaseOmsPick();
                        BailunSkuStructure bailunSkuStructure = skuStructureMap.get(pickingItem.getBailunSku());
                        BigDecimal weightRatio = bailunSkuStructure != null && pickOrderTotalWeight.compareTo(BigDecimal.ZERO) == 1? bailunSkuStructure.getBailunSkuWeight().multiply(quantityPickedBigDecimal).divide(pickOrderTotalWeight, 5, RoundingMode.HALF_EVEN) : BigDecimal.ONE;
                        dcBaseOmsPick.setHasDelete(false);
                        dcBaseOmsPick.setCostPackaging(skuCostPackaging);
                        dcBaseOmsPick.setCostShipping(skuCostShipping);
                        dcBaseOmsPick.setOutboundWeight(outboundWeight);
                        dcBaseOmsPick.setBailunSkuCostPackaging(skuCostPackaging.multiply(weightRatio).setScale(3, RoundingMode.HALF_EVEN));
                        dcBaseOmsPick.setBailunSkuCostShipping(skuCostShipping.multiply(weightRatio).setScale(3, RoundingMode.HALF_EVEN));
                        //从千克转为克, 且放单位SKU重量
                        dcBaseOmsPick.setBailunSkuOutboundWeight(pickingItem.getQuantityPicked() > 0?outboundWeight.multiply(weightRatio).multiply(Constant.RATE_1000).divide(quantityPickedBigDecimal, 3, RoundingMode.HALF_EVEN) : BigDecimal.ZERO);
                        dcBaseOmsPick.setBailunSku(pickingItem.getBailunSku());
                        dcBaseOmsPick.setQuantityPicked(pickingItem.getQuantityPicked());
                        dcBaseOmsPick.setQuantityShipped(pickingItem.getQuantityShipped());
                        dcBaseOmsPick.setDeclarePrice(pickingItem.getDeclarePrice());
                        dcBaseOmsPick.setOriginOrderId(omsResult.getOriginOrderId());
                        dcBaseOmsPick.setBailunAccountId(omsResult.getSeller().getBailunAccountId());
                        dcBaseOmsPick.setBailunOrderId(omsResult.getBailunOrderId());
                        if (pickingOrder.getLogistics() != null) {
                            dcBaseOmsPick.setLogisticsOrderId(pickingOrder.getLogistics().getLogisticsCode());
                            dcBaseOmsPick.setLogisticsOrderName(pickingOrder.getLogistics().getLogisticsName());
                        }
                        dcBaseOmsPick.setCreateTime(pickingOrder.getCreateTime());
                        dcBaseOmsPick.setShippingTime(pickingOrder.getShippingTime());
                        if (pickingOrder.getWarehouse() != null) {
                            dcBaseOmsPick.setWarehouseCode(pickingOrder.getWarehouse().getWarehouseCode());
                            dcBaseOmsPick.setWarehouseName(pickingOrder.getWarehouse().getWarehouseName());
                        }
                        dcBaseOmsPick.setPickOrderId(pickingOrder.getPickOrderId());
                        dcBaseOmsPick.setShippingStatus(pickingOrder.getShippingStatus());
                        dcBaseOmsPick.setTrackingOrderId(pickingOrder.getTrackingOrderId());
                        dcBaseOmsPick.setTrackingProvider(pickingOrder.getTrackingProvider());

                        if (bailunSkuStructure != null) {
                            DcBaseOmsSku dcBaseOmsSku = bailunSkuStructure.getDcBaseOmsSku();
                            dcBaseOmsSku.setBailunSkuQuantityShipped(dcBaseOmsSku.getBailunSkuQuantityShipped() != null ? dcBaseOmsSku.getBailunSkuQuantityShipped() + dcBaseOmsPick.getQuantityShipped() : dcBaseOmsPick.getQuantityShipped());
                            dcBaseOmsSku.setBailunSkuQuantityPicked(dcBaseOmsSku.getBailunSkuQuantityPicked() != null ? dcBaseOmsSku.getBailunSkuQuantityPicked() + dcBaseOmsPick.getQuantityPicked() : dcBaseOmsPick.getQuantityPicked());
                            dcBaseOmsSku.setCostHandlePlatform(dcBaseOmsSku.getCostHandlePlatform() != null ? dcBaseOmsSku.getCostHandlePlatform().add(dcBaseOmsPick.getBailunSkuCostPackaging()) : dcBaseOmsPick.getBailunSkuCostPackaging());
                            dcBaseOmsSku.setCostTail(dcBaseOmsSku.getCostTail() != null ? dcBaseOmsSku.getCostTail().add(dcBaseOmsPick.getBailunSkuCostShipping()) : dcBaseOmsPick.getBailunSkuCostShipping());
                        }
                        try {
                            DcBaseOmsPickMapper mapper = SessionUtil.getSession().getMapper(DcBaseOmsPickMapper.class);
                            int i = mapper.updateByExampleSelective(dcBaseOmsPick, DcBaseOmsPickExample.newAndCreateCriteria().andOriginOrderIdEqualTo(dcBaseOmsPick.getOriginOrderId())
                                    .andBailunAccountIdEqualTo(dcBaseOmsPick.getBailunAccountId()).andPickOrderIdEqualTo(dcBaseOmsPick.getPickOrderId()).andBailunSkuEqualTo(dcBaseOmsPick.getBailunSku()).example());
                            if (i == 0) {
                                mapper.insertSelective(dcBaseOmsPick);
                            }
                        } catch (Exception e) {
                            e.printStackTrace();
                            throw new RuntimeException("MYBATIS操作DB失败", e);
                        } finally {
                            SessionUtil.closeSession();
                        }
                    }
                }
            }

        }
        dcBaseOmsOrder.setCostHandlePlatform(totalCostPackaging);
        dcBaseOmsOrder.setCostTail(totalCostShipping);
    }

    /**
     * 检查订单平台费用是否异常
     *
     * @param dcBaseOmsOrder
     */
    private void checkPlatformFee(DcBaseOmsOrder dcBaseOmsOrder) {
        DcBaseOrderCommissonMapper mapper = SessionUtil.getSession().getMapper(DcBaseOrderCommissonMapper.class);
//        mapper.selectByExample(DcBaseOrderCommissonExample.newAndCreateCriteria().andBailunCategoryIdEqualTo().example());
        //TODO 待补充
        BigDecimal value = dcBaseOmsOrder.getAmountTotal();
        BigDecimal theoryPlatformFee = value.multiply(Constant.AMAZON_PLATFORM_FEE_RATE).setScale(0, RoundingMode.UP);
        //如果 理论平台费 小于实际平台费 或者 平台费为0, 标记异常
        if (theoryPlatformFee.compareTo(dcBaseOmsOrder.getCostPlatformFee()) == -1 || dcBaseOmsOrder.getCostPlatformFee().equals(BigDecimal.ZERO)) {
            dcBaseOmsOrder.setHasPlatformException(true);
        }
    }


    /**
     * 拿SkU基础信息
     *
     * @param bailunSku
     * @return
     */
    private DcBaseSku getDcBaseSku(BailunSku bailunSku) {
        DcBaseSku skuProductInfo = null;
        try {
            DcBaseSkuMapper dcBaseSkuMapper = SessionUtil.getSession().getMapper(DcBaseSkuMapper.class);
            skuProductInfo = dcBaseSkuMapper.selectOneByExample(DcBaseSkuExample.newAndCreateCriteria().andBailunSkuEqualTo(bailunSku.getBailunSku()).example());
        } catch (Exception e) {
            e.printStackTrace();
            throw new RuntimeException("MYBATIS查询DB失败");
        } finally {
            SessionUtil.closeSession();
        }
        return skuProductInfo;
    }


    /**
     * 检查FBA费用是否异常
     *
     * @param dcBaseOmsSku
     */
    private void checkFbaFee(DcBaseOmsSku dcBaseOmsSku, DcBaseOmsOrder dcBaseOmsOrder) {
        if (dcBaseOmsSku.getBailunSkuQuantityOrdered() > 0 && dcBaseOmsSku.getCostFbaFee().compareTo(BigDecimal.ZERO) == 1) {
            DcMidFbaFeeAvgMapper dcMidFbaFeeAvgMapper = SessionUtil.getSession().getMapper(DcMidFbaFeeAvgMapper.class);
            DcMidFbaFeeAvg dcMidFbaFeeAvg = dcMidFbaFeeAvgMapper.selectOneByExample(DcMidFbaFeeAvgExample.newAndCreateCriteria().andWebsiteEqualTo(dcBaseOmsSku.getWebsite()).andBailunSkuEqualTo(dcBaseOmsSku.getBailunSku()).example());
            if (dcMidFbaFeeAvg != null && dcBaseOmsSku.getBailunSkuQuantityOrdered() != 0) {
                BigDecimal fbaFeeRmb = dcBaseOmsSku.getCostFbaFee().multiply(dcBaseOmsSku.getFinanceOrderExchangeRate()).divide(BigDecimal.valueOf(dcBaseOmsSku.getBailunSkuQuantityOrdered()), 3, RoundingMode.HALF_EVEN);
                if (fbaFeeRmb.compareTo(dcMidFbaFeeAvg.getMaxFbaFee()) == 1) {
                    dcBaseOmsSku.setHasFbaException(true);
                    dcBaseOmsOrder.setHasFbaException(true);
                }
            }
        }
    }


    /**
     * 把OMS订单中的一部分值赋值到百伦订单对象上
     *
     * @param dcBaseOmsOrder
     * @return
     */
    public void assignmentOrderInfo(OmsResult omsResult, DcBaseOmsOrder dcBaseOmsOrder) {
        dcBaseOmsOrder.setAreaId(omsResult.getAreaId());
        dcBaseOmsOrder.setHasCancle(omsResult.getHasCancle());
        if (omsResult.getLogisticsItems() != null && omsResult.getLogisticsItems().size() > 0) {
            Warehouse warehouse = omsResult.getLogisticsItems().get(0).getWarehouse();
            Logistics logisticsMethod = omsResult.getLogisticsItems().get(0).getLogisticsMethod();
            if (warehouse != null) {
                dcBaseOmsOrder.setLogisticsWarehouseCode(warehouse.getWarehouseCode());
                dcBaseOmsOrder.setLogisticsWarehouseName(warehouse.getWarehouseName());
            }
            if (logisticsMethod != null) {
                dcBaseOmsOrder.setLogisticsMethodCode(logisticsMethod.getLogisticsCode());
                dcBaseOmsOrder.setLogisticsMethodName(logisticsMethod.getLogisticsName());
            }
        }
        //根据国家找物流规则
        if (omsResult.getReceiptAddress() != null) {
            dcBaseOmsOrder.setReceiptCountry(omsResult.getReceiptAddress().getReceiptCountry());
            dcBaseOmsOrder.setReceiptCity(omsResult.getReceiptAddress().getReceiptCity());
            dcBaseOmsOrder.setReceiptAddress(omsResult.getReceiptAddress().getReceiptAddress());
            dcBaseOmsOrder.setReceiptAddress2(omsResult.getReceiptAddress().getReceiptAddress2());
            dcBaseOmsOrder.setReceiptArea(omsResult.getReceiptAddress().getReceiptArea());
            dcBaseOmsOrder.setReceiptPostalCode(omsResult.getReceiptAddress().getReceiptPostalCode());
            dcBaseOmsOrder.setReceiverPhone(omsResult.getReceiptAddress().getReceiverPhone());
            dcBaseOmsOrder.setReceiver(omsResult.getReceiptAddress().getReceiver());
        }
        if (omsResult.getBuyer() != null) {
            dcBaseOmsOrder.setBuyerId(omsResult.getBuyer().getBuyerId());
            dcBaseOmsOrder.setBuyerEmail(omsResult.getBuyer().getBuyerEmail());
            dcBaseOmsOrder.setBuyerName(omsResult.getBuyer().getBuyerName());
        }
        if (omsResult.getSeller() != null) {
            dcBaseOmsOrder.setBailunAccountId(omsResult.getSeller().getBailunAccountId());
            dcBaseOmsOrder.setSellerAccount(omsResult.getSeller().getSellerAccount());
            dcBaseOmsOrder.setSellerId(omsResult.getSeller().getSellerId());
            dcBaseOmsOrder.setHqAccount(omsResult.getSeller().getHqAccount());
            dcBaseOmsOrder.setSellerOrderId(omsResult.getSeller().getSellerOrderId());
            dcBaseOmsOrder.setSellerEmail(omsResult.getSeller().getSellerEmail());
        }
        if (omsResult.getPayment() != null) {
            if (omsResult.getPayment().getPayTime() != null) {
                dcBaseOmsOrder.setPayTime(LocalDateTime.parse(omsResult.getPayment().getPayTime(), DateTimeFormatter.ofPattern("M/d/yy h:m:s a", Locale.US)));
            }
            dcBaseOmsOrder.setPayMethod(omsResult.getPayment().getPayMethod());
            dcBaseOmsOrder.setPayAccount(omsResult.getPayment().getPayAccount());
            dcBaseOmsOrder.setPayStatus(omsResult.getPayment().getPayStatus());
            dcBaseOmsOrder.setCollectionAccount(omsResult.getPayment().getCollectionAccount());
        }
        dcBaseOmsOrder.setTransactionId(omsResult.getTransactionId());
        dcBaseOmsOrder.setOriginOrderId(omsResult.getOriginOrderId());
        dcBaseOmsOrder.setBailunOrderId(omsResult.getBailunOrderId());
        dcBaseOmsOrder.setPlatformType(omsResult.getPlatformType());
        dcBaseOmsOrder.setWebsite(omsResult.getWebsite());
        dcBaseOmsOrder.setPlatformOrderType(omsResult.getPlatformOrderType());
        dcBaseOmsOrder.setCreateTime(omsResult.getCreateTime());
        dcBaseOmsOrder.setPaidTime(omsResult.getPaidTime() != null ? omsResult.getPaidTime() : omsResult.getCreateTime());
        dcBaseOmsOrder.setPlatformOrderStatus(omsResult.getPlatformOrderStatus());
        dcBaseOmsOrder.setBailunOrderStatus(omsResult.getBailunOrderStatus());
        dcBaseOmsOrder.setBailunInterceptionStatus(omsResult.getBailunInterceptionStatus());
        dcBaseOmsOrder.setBailunMergeStatus(omsResult.getBailunMergeStatus());
        dcBaseOmsOrder.setBailunShippingStatus(omsResult.getBailunShippingStatus());
        dcBaseOmsOrder.setBailunPaymentStatus(omsResult.getBailunPaymentStatus());
        dcBaseOmsOrder.setOrderUpdateTime(omsResult.getOrderUpdateTime());
        dcBaseOmsOrder.setBailunPickingStatus(omsResult.getBailunPickingStatus());
        dcBaseOmsOrder.setBailunRequireLogistics(omsResult.getBailunRequireLogistics());
        dcBaseOmsOrder.setAmountGiftWrap((omsResult.getOrderCharge().getAmountGiftWrap() != null && omsResult.getOrderCharge().getAmountGiftWrap().getAmount() != null) ? omsResult.getOrderCharge().getAmountGiftWrap().getAmount() : BigDecimal.ZERO);
        dcBaseOmsOrder.setAmountTotal((omsResult.getOrderCharge().getAmountTotal() != null && omsResult.getOrderCharge().getAmountTotal().getAmount() != null) ? omsResult.getOrderCharge().getAmountTotal().getAmount() : BigDecimal.ZERO);
        dcBaseOmsOrder.setAmountShipping((omsResult.getOrderCharge().getAmountShipping() != null && omsResult.getOrderCharge().getAmountShipping().getAmount() != null) ? omsResult.getOrderCharge().getAmountShipping().getAmount() : BigDecimal.ZERO);
        dcBaseOmsOrder.setAmountProduct((omsResult.getOrderCharge().getAmountProduct() != null && omsResult.getOrderCharge().getAmountProduct().getAmount() != null) ? omsResult.getOrderCharge().getAmountProduct().getAmount() : BigDecimal.ZERO);
        dcBaseOmsOrder.setAmountTax((omsResult.getOrderCharge().getAmountTax() != null && omsResult.getOrderCharge().getAmountTax().getAmount() != null) ? omsResult.getOrderCharge().getAmountTax().getAmount() : BigDecimal.ZERO);
        dcBaseOmsOrder.setAmountAdjustment((omsResult.getOrderCharge().getAmountAdjustment() != null && omsResult.getOrderCharge().getAmountAdjustment().getAmount() != null) ? omsResult.getOrderCharge().getAmountAdjustment().getAmount() : BigDecimal.ZERO);
        dcBaseOmsOrder.setCostShipping((omsResult.getOrderCharge().getCostShipping() != null && omsResult.getOrderCharge().getCostShipping().getAmount() != null) ? omsResult.getOrderCharge().getCostShipping().getAmount() : BigDecimal.ZERO);
        dcBaseOmsOrder.setCostFbaFee((omsResult.getOrderCharge().getCostFbaFee() != null && omsResult.getOrderCharge().getCostFbaFee().getAmount() != null) ? omsResult.getOrderCharge().getCostFbaFee().getAmount() : BigDecimal.ZERO);
        dcBaseOmsOrder.setCostPaypalFee((omsResult.getOrderCharge().getCostPaypalFee() != null && omsResult.getOrderCharge().getCostPaypalFee().getAmount() != null) ? omsResult.getOrderCharge().getCostPaypalFee().getAmount() : BigDecimal.ZERO);
        dcBaseOmsOrder.setCostProduct((omsResult.getOrderCharge().getCostProduct() != null && omsResult.getOrderCharge().getCostProduct().getAmount() != null) ? omsResult.getOrderCharge().getCostProduct().getAmount() : BigDecimal.ZERO);
        dcBaseOmsOrder.setCostHandleBailun(BigDecimal.ZERO);
        dcBaseOmsOrder.setCostHandlePlatform(BigDecimal.ZERO);
        dcBaseOmsOrder.setCostTail(BigDecimal.ZERO);
        dcBaseOmsOrder.setCostFirst(BigDecimal.ZERO);

    }

    /**
     * 把OMS订单中的一部分值赋值到百伦订单对象上
     *
     * @param dcBaseOmsSku
     * @param logisticsHashMap
     * @return
     */
    public void assignmentSkuInfo(OmsResult omsResult, DcBaseOmsOrder dcBaseOmsOrder, DcBaseOmsSku dcBaseOmsSku, BailunSku bailunSku, DcBaseWarehouse dcBaseWarehouse, HashMap<String, Logistics> logisticsHashMap) {
        dcBaseOmsSku.setBailunSkuQuantityShipped(0);
        dcBaseOmsSku.setBailunSkuQuantityPicked(0);
        dcBaseOmsSku.setCostHandlePlatform(BigDecimal.ZERO);
        dcBaseOmsSku.setCostTail(BigDecimal.ZERO);
        dcBaseOmsSku.setBailunInterceptionStatus(dcBaseOmsOrder.getBailunInterceptionStatus());
        dcBaseOmsSku.setBailunSku(bailunSku.getBailunSku());
        if (dcBaseWarehouse != null) {
            dcBaseOmsSku.setWarehouseCode(dcBaseWarehouse.getWarehouseCode());
            dcBaseOmsSku.setWarehouseName(dcBaseWarehouse.getWarehouseName());
            Logistics logistics = logisticsHashMap.get(dcBaseWarehouse.getWarehouseCode());
            if (logistics != null) {
                dcBaseOmsSku.setLogisticsMethodCode(logistics.getLogisticsCode());
                dcBaseOmsSku.setLogisticsMethodName(logistics.getLogisticsName());
            }
        }
        dcBaseOmsSku.setAreaId(omsResult.getAreaId());
        dcBaseOmsSku.setHasCancle(omsResult.getHasCancle());

        // --begin 调用产品库信息 skuProductInfo, 获取分类信息
        DcBaseSku skuProductInfo = getDcBaseSku(bailunSku);
        if (skuProductInfo != null) {
            dcBaseOmsSku.setBailunCategoryId(skuProductInfo.getBailunCategoryId());
            dcBaseOmsSku.setBailunCategoryName(skuProductInfo.getBailunCategoryName());
            dcBaseOmsSku.setSellerName(skuProductInfo.getSellerName());
        }
        //根据国家找物流规则
        if (omsResult.getReceiptAddress() != null) {
            dcBaseOmsSku.setReceiptCountry(omsResult.getReceiptAddress().getReceiptCountry());
            dcBaseOmsSku.setReceiptCity(omsResult.getReceiptAddress().getReceiptCity());
            dcBaseOmsSku.setReceiptAddress(omsResult.getReceiptAddress().getReceiptAddress());
            dcBaseOmsSku.setReceiptAddress2(omsResult.getReceiptAddress().getReceiptAddress2());
            dcBaseOmsSku.setReceiptArea(omsResult.getReceiptAddress().getReceiptArea());
            dcBaseOmsSku.setReceiptPostalCode(omsResult.getReceiptAddress().getReceiptPostalCode());
            dcBaseOmsSku.setReceiverPhone(omsResult.getReceiptAddress().getReceiverPhone());
            dcBaseOmsSku.setReceiver(omsResult.getReceiptAddress().getReceiver());
        }
        if (omsResult.getBuyer() != null) {
            dcBaseOmsSku.setBuyerId(omsResult.getBuyer().getBuyerId());
            dcBaseOmsSku.setBuyerEmail(omsResult.getBuyer().getBuyerEmail());
            dcBaseOmsSku.setBuyerName(omsResult.getBuyer().getBuyerName());
        }
        if (omsResult.getSeller() != null) {
            dcBaseOmsSku.setBailunAccountId(omsResult.getSeller().getBailunAccountId());
            dcBaseOmsSku.setSellerAccount(omsResult.getSeller().getSellerAccount());
            dcBaseOmsSku.setSellerId(omsResult.getSeller().getSellerId());
            dcBaseOmsSku.setHqAccount(omsResult.getSeller().getHqAccount());
            dcBaseOmsSku.setSellerOrderId(omsResult.getSeller().getSellerOrderId());
            dcBaseOmsSku.setSellerEmail(omsResult.getSeller().getSellerEmail());
        }
        if (omsResult.getPayment() != null) {
            if (omsResult.getPayment().getPayTime() != null) {
                dcBaseOmsSku.setPayTime(LocalDateTime.parse(omsResult.getPayment().getPayTime(), DateTimeFormatter.ofPattern("M/d/yy h:m:s a", Locale.US)));
            }
            dcBaseOmsSku.setPayMethod(omsResult.getPayment().getPayMethod());
            dcBaseOmsSku.setPayAccount(omsResult.getPayment().getPayAccount());
            dcBaseOmsSku.setPayStatus(omsResult.getPayment().getPayStatus());
            dcBaseOmsSku.setCollectionAccount(omsResult.getPayment().getCollectionAccount());
        }
        dcBaseOmsSku.setTransactionId(omsResult.getTransactionId());
        dcBaseOmsSku.setOriginOrderId(omsResult.getOriginOrderId());
        dcBaseOmsSku.setBailunOrderId(omsResult.getBailunOrderId());
        dcBaseOmsSku.setPlatformType(omsResult.getPlatformType());
        dcBaseOmsSku.setWebsite(omsResult.getWebsite());
        dcBaseOmsSku.setPlatformOrderType(omsResult.getPlatformOrderType());
        dcBaseOmsSku.setCreateTime(omsResult.getCreateTime());
        dcBaseOmsSku.setPaidTime(omsResult.getPaidTime() != null ? omsResult.getPaidTime() : omsResult.getCreateTime());
        dcBaseOmsSku.setPlatformOrderStatus(omsResult.getPlatformOrderStatus());
        dcBaseOmsSku.setBailunOrderStatus(omsResult.getBailunOrderStatus());
        dcBaseOmsSku.setShippingStatus(omsResult.getBailunShippingStatus());
        dcBaseOmsSku.setBailunPaymentStatus(omsResult.getBailunPaymentStatus());
        dcBaseOmsSku.setOrderUpdateTime(omsResult.getOrderUpdateTime());
        dcBaseOmsSku.setBailunPickingStatus(omsResult.getBailunPickingStatus());
        dcBaseOmsSku.setBailunRequireLogistics(omsResult.getBailunRequireLogistics());

        //币种和汇率
        dcBaseOmsSku.setOrderCurrency(dcBaseOmsOrder.getOrderCurrency());
        dcBaseOmsSku.setOtherCurrency(dcBaseOmsOrder.getOtherCurrency());
        dcBaseOmsSku.setFinanceOrderExchangeRate(dcBaseOmsOrder.getFinanceOrderExchangeRate() != null ? dcBaseOmsOrder.getFinanceOrderExchangeRate() : BigDecimal.ZERO);
        dcBaseOmsSku.setSellerOrderExchangeRate(dcBaseOmsOrder.getSellerOrderExchangeRate() != null ? dcBaseOmsOrder.getSellerOrderExchangeRate() : BigDecimal.ZERO);
        dcBaseOmsSku.setFinanceOtherExchangeRate(dcBaseOmsOrder.getFinanceOtherExchangeRate() != null ? dcBaseOmsOrder.getFinanceOtherExchangeRate() : BigDecimal.ZERO);
        dcBaseOmsSku.setSellerOtherExchangeRate(dcBaseOmsOrder.getSellerOtherExchangeRate() != null ? dcBaseOmsOrder.getSellerOtherExchangeRate() : BigDecimal.ZERO);
        dcBaseOmsSku.setOrderToUsdExchangeRate(dcBaseOmsOrder.getOrderToUsdExchangeRate() != null ? dcBaseOmsOrder.getOrderToUsdExchangeRate() : BigDecimal.ZERO);
        dcBaseOmsSku.setCnyToUsdExchangeRate(dcBaseOmsOrder.getCnyToUsdExchangeRate() != null ? dcBaseOmsOrder.getCnyToUsdExchangeRate() : BigDecimal.ZERO);
        dcBaseOmsSku.setOtherToUsdExchangeRate(dcBaseOmsOrder.getOtherToUsdExchangeRate() != null ? dcBaseOmsOrder.getOtherToUsdExchangeRate() : BigDecimal.ZERO);
        dcBaseOmsSku.setBailunSkuSize(bailunSku.getBailunSkuSize());
        dcBaseOmsSku.setBailunSkuWeight(bailunSku.getBailunSkuWeight());
        dcBaseOmsSku.setBailunSkuQuantityOrdered(bailunSku.getBailunSkuQuantityOrdered());
        dcBaseOmsSku.setBailunSkuUnitPrice(bailunSku.getBailunSkuUnitPrice().getAmount() != null ? bailunSku.getBailunSkuUnitPrice().getAmount() : BigDecimal.ZERO);
        dcBaseOmsSku.setBailunSkuTitleCn(bailunSku.getBailunSkuTitleCn());
        dcBaseOmsSku.setCostHandlePlatform(BigDecimal.ZERO);
        dcBaseOmsSku.setCostHandleBailun(BigDecimal.ZERO);
        dcBaseOmsSku.setCostTail(BigDecimal.ZERO);
        dcBaseOmsSku.setCostFirst(BigDecimal.ZERO);
        dcBaseOmsSku.setCostFbaFee(BigDecimal.ZERO);
        dcBaseOmsSku.setCostPaypalFee(BigDecimal.ZERO);
        dcBaseOmsSku.setAmountPrepaid(BigDecimal.ZERO);//更新旧数据中都已经发货,但是预付费>0的情况
        dcBaseOmsSku.setCostLogistics(BigDecimal.ZERO);
        //如果是 FBA订单1.检查FBA费用是否异常 2.
        dcBaseOmsSku.setBailunSkuQuantityShipped(0);

    }

    /**
     * 获取汇率
     *
     * @param dcBaseOmsOrder
     * @throws Exception
     */
    public void getExchangeRate(OmsResult omsResult, DcBaseOmsOrder dcBaseOmsOrder) {
        OrderCharge orderCharge = omsResult.getOrderCharge();
        //财务需要月初的汇率,  销售需要订单支付时期的汇率(从OMS直接取)
        dcBaseOmsOrder.setFinanceOrderExchangeRate(BigDecimal.ZERO);
        dcBaseOmsOrder.setFinanceOtherExchangeRate(BigDecimal.ZERO);
        dcBaseOmsOrder.setSellerOrderExchangeRate(BigDecimal.ZERO);
        dcBaseOmsOrder.setSellerOtherExchangeRate(BigDecimal.ZERO);
        /*
         * OMS的汇率问题很大
         * 自己取汇率
         */
        if (orderCharge != null) {
            LocalDateTime exchangeDate = omsResult.getPaidTime() != null ? omsResult.getPaidTime() : omsResult.getCreateTime();
            if (orderCharge.getAmountTotal() != null) {
                BigDecimal sellerOrderExchangeRate = null;
                String orderCurrency = orderCharge.getAmountTotal().getCurrencyCode();
                if (StringUtils.isEmpty(orderCharge.getAmountTotal().getCurrencyCode()) || orderCurrency.equals(Constant.RMB_CURRENCY_RMB)) {
                    orderCurrency = Constant.RMB_CURRENCY;
                    sellerOrderExchangeRate = BigDecimal.ONE;
                } else {
                    sellerOrderExchangeRate = CallBailunSystem.getExchangeRate(orderCurrency, Constant.RMB_CURRENCY, exchangeDate);
                }
                dcBaseOmsOrder.setOrderCurrency(orderCurrency);
                BigDecimal orderFinanceExchangeRate = CallBailunSystem.getMonthExchangeRate(orderCurrency, Constant.RMB_CURRENCY, exchangeDate);
                //Order币种转美元汇率
                BigDecimal orderToUsdExchangeRate = CallBailunSystem.getMonthExchangeRate(orderCurrency, Constant.USD_CURRENCY, exchangeDate);
                //人民币转美元汇率
                BigDecimal cnyToUsdFinanceExchangeRate = CallBailunSystem.getMonthExchangeRate(Constant.RMB_CURRENCY, Constant.USD_CURRENCY, exchangeDate);
                dcBaseOmsOrder.setOrderToUsdExchangeRate(orderToUsdExchangeRate);
                dcBaseOmsOrder.setCnyToUsdExchangeRate(cnyToUsdFinanceExchangeRate);
                dcBaseOmsOrder.setFinanceOrderExchangeRate(orderFinanceExchangeRate);
                dcBaseOmsOrder.setSellerOrderExchangeRate(sellerOrderExchangeRate);
            }
            /**
             * EBAY的平台费币种与订单币种可能不一致
             */
            if (omsResult.getPlatformType() != null && PlatformType.Ebay.value().equals(omsResult.getPlatformType().toUpperCase()) && orderCharge.getCostPlatformFee() != null && !StringUtils.isEmpty(orderCharge.getCostPlatformFee().getCurrencyCode())) {
                String otherCurrency = orderCharge.getCostPlatformFee().getCurrencyCode();
                BigDecimal sellerOtherExchangeRate = null;
                if (StringUtils.isEmpty(orderCharge.getCostPlatformFee().getCurrencyCode()) || otherCurrency.equals(Constant.RMB_CURRENCY_RMB)) {
                    otherCurrency = Constant.RMB_CURRENCY;
                    sellerOtherExchangeRate = BigDecimal.ONE;
                } else {
                    sellerOtherExchangeRate = CallBailunSystem.getExchangeRate(otherCurrency, Constant.RMB_CURRENCY, exchangeDate);
                }
                dcBaseOmsOrder.setOtherCurrency(otherCurrency);
                BigDecimal otherFinanceExchangeRate = CallBailunSystem.getMonthExchangeRate(otherCurrency, Constant.RMB_CURRENCY, omsResult.getPaidTime() != null ? omsResult.getPaidTime() : omsResult.getCreateTime());
                //Other币种转美元汇率
                BigDecimal otherToUsdExchangeRate = CallBailunSystem.getMonthExchangeRate(otherCurrency, Constant.USD_CURRENCY, omsResult.getPaidTime() != null ? omsResult.getPaidTime() : omsResult.getCreateTime());
                dcBaseOmsOrder.setOtherToUsdExchangeRate(otherToUsdExchangeRate);
                dcBaseOmsOrder.setFinanceOtherExchangeRate(otherFinanceExchangeRate);
                dcBaseOmsOrder.setSellerOtherExchangeRate(sellerOtherExchangeRate);
            }
        }
    }
}
