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.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.lang3.StringUtils;

import java.io.IOException;
import java.math.BigDecimal;
import java.math.RoundingMode;
import java.time.LocalDateTime;
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) {

        //如果页号为0, 就表示上次查完了, 这次要从总页数开始查, 如果页号 > 0, 就降序查, 防止漏单
        if (jobPointLog.getPageIndex() == 0) {
            jobPointLog.setPageIndex(requestBailunOrder(jobPointLog));
        }
        if (jobPointLog.getPageIndex() > 0) {
            do {
                requestBailunOrder(jobPointLog);
                jobPointLog.setPageIndex(jobPointLog.getPageIndex() - 1);
                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();
                    }
                }
            } while (0 < jobPointLog.getPageIndex());
        }
        if (jobPointLog.getPageIndex() == 0) {
            jobPointLog.setStartTime(jobPointLog.getEndTime());
            jobPointLog.setEndTime(jobPointLog.getEndTime().plusDays(jobPointLog.getIntervalTime()).isAfter(LocalDateTime.now()) ? LocalDateTime.now() : jobPointLog.getEndTime().plusDays(jobPointLog.getIntervalTime()));
        }
    }

    /**
     * 请求OMS接口
     *
     * @param jobPointLog
     * @return
     */
    private Integer requestBailunOrder(JobPointLog jobPointLog) {
        Integer totalPages = null;
        LinkedHashMap<String, String> map = new LinkedHashMap<>(4);
        map.put("pageIndex", jobPointLog.getPageIndex() == 0 ? "1" : jobPointLog.getPageIndex().toString());
        map.put("pageCount", jobPointLog.getPageSize().toString());
        //时间回退一点, 避免服务器时间不一致而漏单
        map.put("BailunLastUpdateTimeFrom", DateTimeFormatter.ofPattern(CommonConstant.TIME_FORMAT).format(jobPointLog.getStartTime().minusMinutes(5)));
        map.put("BailunLastUpdateTimeTo", DateTimeFormatter.ofPattern(CommonConstant.TIME_FORMAT).format(jobPointLog.getEndTime()));
        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();
                totalPages = omsResultInfo.getTotalPages();
                if (omsResultInfo.getResult() != null && omsResultInfo.getResult().size() > 0) {
                    analyseOmsOrder(omsResultInfo.getResult());
                }
            } else {
                throw new RuntimeException("调用OMS接口同步百伦订单失败, 响应200, 请求参数" + map.toString());
            }
        } else {
            throw new RuntimeException("调用OMS接口同步百伦订单失败, 响应200, 请求参数" + map.toString());
        }
        //如果PageIndex等于0取总页数, 否则取PageIndex
        return jobPointLog.getPageIndex() == 0 ? totalPages : jobPointLog.getPageIndex();
    }

    /**
     * 解析订单, 并处理费用信息
     *
     * @param bailunOrderList
     */
    public void analyseOmsOrder(List<OmsResult> bailunOrderList) {
        for (OmsResult omsResult : bailunOrderList)
            if (omsResult != null && omsResult.getBailunPaymentStatus() != null && omsResult.getBailunPaymentStatus().equals(Constant.PAYMENT_STATUS)) {
                DcBaseOmsOrder dcBaseOmsOrder = new DcBaseOmsOrder();
                assignmentOrderInfo(omsResult, dcBaseOmsOrder);
                deleteSku(dcBaseOmsOrder);//因为OMS可能改订单, 部分SKU有可能会被删除, 所以先删除, 再插入, 并且更新退款为未予订单关联
                log.warn(dcBaseOmsOrder.getOriginOrderId());
                Boolean isFbaFeeException = false;
                // 百伦sku信息, 有销售员和采购价, bailun_sku_order根据sku找对应销售员和采购价
                HashMap<String, String> saleItemHashMap = putSellerNameInMap(omsResult.getSaleItem());
                //获取汇率
                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);
                        }
                    }
                }

                //如果订单中存在百伦SKU, 去拿一些放在SKU里的信息
                Map<String, BailunSkuStructure> bailunSkuInfoMap = new HashMap<>();
                //拿仓库信息
                DcBaseWarehouse dcBaseWarehouse = getDcBaseWarehouse(omsResult);
                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();
                        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();
                        /*
                         * 赋值, 初始值避免null
                         */
                        assignmentSkuInfo(omsResult, dcBaseOmsOrder, dcBaseOmsSku, bailunSku, dcBaseWarehouse,saleItemHashMap, isFbaFeeException);
                        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, isFbaFeeException);
                        }
                        bailunSkuStructure.setDcBaseOmsSku(dcBaseOmsSku);
                        bailunSkuInfoMap.put(bailunSku.getBailunSku(), bailunSkuStructure);
                    }
                    //按规则计算处理费
                    caculateBailunHandleFee(dcBaseOmsOrder, bailunSkuCumulative, dcBaseWarehouse);
                }
                /*
                 * 配货单处理,
                 * 返回已发货的SKU总售价
                 */
                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.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);
                }
                // 是FBA异常订单
                dcBaseOmsOrder.setHasFbaException(isFbaFeeException);
                // 如果是亚马逊订单, 检查平台费是否超高
                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;
                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();
                            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);
                            //将总销售额按比例摊分到SKU-原币种, SKU可能有多个
                            BigDecimal skuAmountSales = bailunSkuStructure.getSkuCostRatio().multiply(totalAmountSale).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());
                                if (dcMidCostFirst != null) {
                                    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产品总售价 - 促销费
                            BigDecimal skuAmountSalesRMB = (skuAmountSales.subtract(skuCostPromotion)).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);
                            /*
                             * 将按比例摊分的费用算到单个SKU
                             * 摊分方法: 除以下单数
                             */
                            BigDecimal quantityOrderdDecimal = BigDecimal.valueOf(bailunSkuStructure.getSkuQuantityOrderd());

                            BigDecimal rmbCost;
                            if (quantityOrderdDecimal.compareTo(BigDecimal.ZERO) == 1) {
                                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));
                                //单个SKU的销售额
                                unitSkuAmountSalesRMB = skuAmountSalesRMB.divide(quantityOrderdDecimal, 3, RoundingMode.HALF_EVEN);
                                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.getCostTail())//尾程费
                                        .add(dcBaseOmsSku.getCostProduct())//采购成本
                                        .add(skuPaypalFeeRmb.divide(quantityOrderdDecimal, 3, RoundingMode.HALF_EVEN))//Paypal费
                                        .setScale(3, RoundingMode.HALF_EVEN);
                            } else {
                                dcBaseOmsSku.setAmountAdjustment(BigDecimal.ZERO);
                                dcBaseOmsSku.setAmountTax(BigDecimal.ZERO);
                                dcBaseOmsSku.setCostPromotion(BigDecimal.ZERO);
                                dcBaseOmsSku.setAmountGiftWrap(BigDecimal.ZERO);
                                dcBaseOmsSku.setCostPaypalFee(BigDecimal.ZERO);
                                dcBaseOmsSku.setCostHandleBailun(BigDecimal.ZERO);
                                dcBaseOmsSku.setCostPlatformFee(BigDecimal.ZERO);
                                dcBaseOmsSku.setCostHandlePlatform(BigDecimal.ZERO);
                                dcBaseOmsSku.setCostFbaFee(BigDecimal.ZERO);
                                dcBaseOmsSku.setCostFirst(BigDecimal.ZERO);
                                dcBaseOmsSku.setCostTail(BigDecimal.ZERO);
                                dcBaseOmsSku.setCostProduct(BigDecimal.ZERO);
                                dcBaseOmsSku.setAmountSales(BigDecimal.ZERO);
                                rmbCost = BigDecimal.ZERO;
                            }
                            //单个SKU的费用支出
                            dcBaseOmsSku.setCostTotal(rmbCost);
                            //利润都转为人民币计算
                            BigDecimal unitSkuProfit = unitSkuAmountSalesRMB.subtract(dcBaseOmsSku.getCostTotal());
                            //只有发货的SKU才去算订单维度利润
                            BigDecimal skuShippedProfit = unitSkuProfit.multiply(BigDecimal.valueOf(dcBaseOmsSku.getBailunSkuQuantityShipped()));
                            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);
                    /*
                     * OMS过来的详细费用不用动
                     * 这边处理新增了
                     *  利润 = 销售额 -退款 -操作费 - 平台费 -头程-尾程- 处理费-采购成本
                     */
                    //退款在匹配退款单的时候算
                    BigDecimal costTotal = dcBaseOmsOrder.getCostHandleBailun() //处理费
                            .add(costPlatformFeeRMB) //平台费
                            .add(dcBaseOmsOrder.getCostHandlePlatform())//第三方仓操作费
                            .add(totalCostFbaFeeRMB)//FBA操作费
                            .add(dcBaseOmsOrder.getCostFirst()) //头程费
                            .add(dcBaseOmsOrder.getCostTail()) //尾程费
                            .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);
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                    throw new RuntimeException("Mybatis操作DB失败", e);
                } finally {
                    SessionUtil.closeSession();
                }
            }
    }

    private void deleteSku(DcBaseOmsOrder dcBaseOmsOrder) {
        try {
            DcBaseOmsSkuMapper mapper = SessionUtil.getSession().getMapper(DcBaseOmsSkuMapper.class);
            mapper.deleteByExample(DcBaseOmsSkuExample.newAndCreateCriteria().andOriginOrderIdEqualTo(dcBaseOmsOrder.getOriginOrderId()).andBailunAccountIdEqualTo(dcBaseOmsOrder.getBailunAccountId()).example());
            DcBaseCrmRefundMapper crmRefundMapper = SessionUtil.getSession().getMapper(DcBaseCrmRefundMapper.class);
            crmRefundMapper.updateLinked(dcBaseOmsOrder.getOriginOrderId(), dcBaseOmsOrder.getBailunAccountId());
        } 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;
    }

    private DcBaseWarehouse getDcBaseWarehouse(OmsResult omsResult) {
        DcBaseWarehouse dcBaseWarehouse = null;
        try {
            DcBaseWarehouseMapper baseWarehouseMapper = SessionUtil.getSession().getMapper(DcBaseWarehouseMapper.class);
            if (PlatformType.FBA.value().equals(omsResult.getPlatformType())) {
                dcBaseWarehouse = baseWarehouseMapper.selectOneByExample(DcBaseWarehouseExample.newAndCreateCriteria().andBailunAccountIdEqualTo(omsResult.getSeller().getBailunAccountId()).example());
            } else if (omsResult.getBailunSku().size() > 0 && StringUtils.isNotBlank(omsResult.getBailunSku().get(0).getWarehouseCode())) {
                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());
                } else if (omsResult.getBailunSku() != null && omsResult.getBailunSku().size() > 0){
                    dcBaseWarehouse = baseWarehouseMapper.selectOneByExample(DcBaseWarehouseExample.newAndCreateCriteria().andWarehouseCodeEqualTo(omsResult.getBailunSku().get(0).getWarehouseCode()).example());
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
            throw new RuntimeException("MYBATIS操作DB失败", e);
        } finally {
            SessionUtil.closeSession();
        }
        return dcBaseWarehouse;
    }



    private HashMap<String, String> putSellerNameInMap(List<SaleItem> saleItemList) {
        HashMap<String, String> map = new HashMap<>(saleItemList.size());
        if (saleItemList != null && saleItemList.size() > 0) {
            for (SaleItem saleItem : saleItemList) {
                map.put(saleItem.getBailunSku(), saleItem.getSellerName());
            }
        }
        return map;
    }

    /**
     * 处理配货单, 多个配货单的SKU可能重复
     * 每个SKU 单独存放, 方便导数据
     * 返回已发货的SKU 总成本
     */
    private BigDecimal handPickingOrder(DcBaseOmsOrder dcBaseOmsOrder, OmsResult omsResult, Map<String, BailunSkuStructure> skuStructureMap) {
        List<PickingOrder> pickingOrderList = omsResult.getPickingOrder();
        BigDecimal totalShippedSkuPrice = BigDecimal.ZERO;
        BigDecimal totalCostPackaging = BigDecimal.ZERO;
        BigDecimal totalCostShipping = BigDecimal.ZERO;
        if (pickingOrderList != null && pickingOrderList.size() > 0) {
            try {
                DcBaseOmsPickMapper mapper = SessionUtil.getSession().getMapper(DcBaseOmsPickMapper.class);
                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) {
                        for (PickingItem pickingItem : pickingItems) {
                            DcBaseOmsPick dcBaseOmsPick = new DcBaseOmsPick();
                            totalShippedSkuPrice = totalShippedSkuPrice.add(skuStructureMap.get(pickingItem.getBailunSku()).getBailunSkuUnitPrice().multiply(pickingItem.getQuantityShipped() != null ? BigDecimal.valueOf(pickingItem.getQuantityShipped()) : BigDecimal.ZERO));
                            DcBaseOmsSku dcBaseOmsSku = skuStructureMap.get(pickingItem.getBailunSku()).getDcBaseOmsSku();
                            BigDecimal weightRatio = skuStructureMap.get(pickingItem.getBailunSku()) != null ? skuStructureMap.get(pickingItem.getBailunSku()).getSkuWeightRatio() : BigDecimal.ONE;
                            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));
                            dcBaseOmsPick.setBailunSkuOutboundWeight(outboundWeight.multiply(weightRatio).setScale(3, RoundingMode.HALF_EVEN));
                            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());

                            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());
                            mapper.upsertSelective(dcBaseOmsPick);
                        }
                    }
                }
            } catch (Exception e) {
                e.printStackTrace();
                throw new RuntimeException("MYBATIS操作DB失败");
            } finally {
                SessionUtil.closeSession();
            }
        }
        dcBaseOmsOrder.setCostHandlePlatform(totalCostPackaging);
        dcBaseOmsOrder.setCostTail(totalCostShipping);
        return totalShippedSkuPrice;
    }

    /**
     * 检查订单平台费用是否异常
     *
     * @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 dcBaseWarehouse
     * @param dcBaseOmsOrder
     * @param dcBaseOmsSku
     */
    public void skuOrderHandle(DcBaseWarehouse dcBaseWarehouse, DcBaseOmsOrder dcBaseOmsOrder, BailunSkuCumulative bailunSkuCumulative, Map<String, BailunSkuStructure> skuStructureMap, DcBaseOmsSku dcBaseOmsSku, OmsResult omsResult, BailunSku bailunSku, HashMap<String, String> saleItemHashMap, Boolean isFbaFeeException) {

        // -- end 调用产品库信息 skuProductInfo, 获取分类信息
        //处理SKU费用信息
        skuOrderFeeHandle(dcBaseOmsOrder, bailunSkuCumulative.getTotalWeight(), skuStructureMap, dcBaseOmsSku, omsResult);


    }

    /**
     * 拿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;
    }

    /**
     * SKU订单费用处理
     *
     * @param dcBaseOmsOrder
     * @param dcBaseOmsSku   costRatio   子SKU采购费用 与 订单所有SKU采购费用 比率
     */
    public void skuOrderFeeHandle(DcBaseOmsOrder dcBaseOmsOrder, BigDecimal totalWeight, Map<String, BailunSkuStructure> skuStructureMap, DcBaseOmsSku dcBaseOmsSku, OmsResult omsResult) {
        OrderCharge orderCharge = omsResult.getOrderCharge();
        //--begin 将采购单价 * 数量 / 总采购价 & SKU单个重量 * 数量 / 总重量   计算出来, 传递进费用计算
        BigDecimal costRatio = (orderCharge.getCostProduct() != null && orderCharge.getCostProduct().getAmount() != null && orderCharge.getCostProduct().getAmount().compareTo(BigDecimal.ZERO) != 0) ? dcBaseOmsSku.getBailunSkuUnitPrice().multiply(BigDecimal.valueOf(dcBaseOmsSku.getBailunSkuQuantityOrdered())).divide(orderCharge.getCostProduct().getAmount(), 4, RoundingMode.HALF_EVEN) : BigDecimal.ONE;
        BigDecimal weightRatio = (dcBaseOmsSku.getBailunSkuWeight() != null && totalWeight.compareTo(BigDecimal.ZERO) != 0) ? dcBaseOmsSku.getBailunSkuWeight().multiply(BigDecimal.valueOf(dcBaseOmsSku.getBailunSkuQuantityOrdered())).divide(totalWeight, 4, RoundingMode.HALF_EVEN) : BigDecimal.ONE;
        dcBaseOmsSku.setRatioPrice(costRatio);
        dcBaseOmsSku.setRatioWeight(weightRatio);
        skuStructureMap.put(dcBaseOmsSku.getBailunSku(), new BailunSkuStructure(dcBaseOmsSku.getBailunSku(), dcBaseOmsSku.getBailunSkuWeight(), dcBaseOmsSku.getBailunSkuUnitPrice() != null ? dcBaseOmsSku.getBailunSkuUnitPrice() : BigDecimal.ZERO, costRatio, weightRatio));
        //--end 将采购单价 * 数量 / 总采购价 & SKU单个重量 * 数量 / 总重量计算出来, 传递进费用计算
        //按重量比例摊分百伦处理费
        dcBaseOmsSku.setCostHandleBailun(dcBaseOmsOrder.getCostHandleBailun() != null ? dcBaseOmsOrder.getCostHandleBailun().multiply(skuStructureMap.get(dcBaseOmsSku.getBailunSku()).getSkuWeightRatio()).setScale(3, RoundingMode.HALF_EVEN) : BigDecimal.ZERO);
        dcBaseOmsSku.setCostHandlePlatform(BigDecimal.ZERO);
        //按采购价比例摊分百伦费用
        dcBaseOmsSku.setAmountTotal((orderCharge.getAmountTotal() != null && orderCharge.getAmountTotal().getAmount() != null) ? orderCharge.getAmountTotal().getAmount().multiply(costRatio).setScale(3, RoundingMode.HALF_EVEN) : BigDecimal.ZERO);
        dcBaseOmsSku.setAmountProduct((orderCharge.getAmountProduct() != null && orderCharge.getAmountProduct().getAmount() != null) ? orderCharge.getAmountProduct().getAmount().multiply(costRatio).setScale(3, RoundingMode.HALF_EVEN) : BigDecimal.ZERO);
        dcBaseOmsSku.setAmountTax((orderCharge.getAmountTax() != null && orderCharge.getAmountTax().getAmount() != null) ? orderCharge.getAmountTax().getAmount().multiply(costRatio).setScale(3, RoundingMode.HALF_EVEN) : BigDecimal.ZERO);
        dcBaseOmsSku.setAmountShipping((orderCharge.getAmountShipping() != null && orderCharge.getAmountShipping().getAmount() != null) ? orderCharge.getAmountShipping().getAmount().multiply(costRatio).setScale(3, RoundingMode.HALF_EVEN) : BigDecimal.ZERO);
        dcBaseOmsSku.setAmountAdjustment((orderCharge.getAmountAdjustment() != null && orderCharge.getAmountAdjustment().getAmount() != null) ? orderCharge.getAmountAdjustment().getAmount().multiply(costRatio).setScale(3, RoundingMode.HALF_EVEN) : BigDecimal.ZERO);
        dcBaseOmsSku.setAmountGiftWrap((orderCharge.getAmountGiftWrap() != null && orderCharge.getAmountGiftWrap().getAmount() != null) ? orderCharge.getAmountGiftWrap().getAmount().multiply(costRatio).setScale(3, RoundingMode.HALF_EVEN) : BigDecimal.ZERO);
        //产品成本 = 单价 * 数量
        dcBaseOmsSku.setCostPromotion((orderCharge.getCostPromotion() != null && orderCharge.getCostPromotion().getAmount() != null) ? orderCharge.getCostPromotion().getAmount().multiply(costRatio).setScale(3, RoundingMode.HALF_EVEN) : BigDecimal.ZERO);
        dcBaseOmsSku.setCostProduct(dcBaseOmsSku.getBailunSkuUnitPrice() != null && dcBaseOmsSku.getBailunSkuQuantityOrdered() != null ? dcBaseOmsSku.getBailunSkuUnitPrice().multiply(BigDecimal.valueOf(dcBaseOmsSku.getBailunSkuQuantityOrdered())).setScale(4, RoundingMode.HALF_EVEN) : BigDecimal.ZERO);
        //平台费
        dcBaseOmsSku.setCostPlatformFee((orderCharge.getCostPlatformFee() != null && orderCharge.getCostPlatformFee().getAmount() != null) ? orderCharge.getCostPlatformFee().getAmount().multiply(costRatio).setScale(3, RoundingMode.HALF_EVEN) : BigDecimal.ZERO);
        dcBaseOmsSku.setCostShipping((orderCharge.getCostShipping() != null && orderCharge.getCostShipping().getAmount() != null) ? orderCharge.getCostShipping().getAmount().multiply(costRatio).setScale(3, RoundingMode.HALF_EVEN) : BigDecimal.ZERO);
        dcBaseOmsSku.setCostPackage((orderCharge.getCostPackage() != null && orderCharge.getCostPackage().getAmount() != null) ? orderCharge.getCostPackage().getAmount().multiply(costRatio).setScale(3, RoundingMode.HALF_EVEN) : BigDecimal.ZERO);
        dcBaseOmsSku.setCostFbaFee((orderCharge.getCostFbaFee() != null && orderCharge.getCostFbaFee().getAmount() != null) ? orderCharge.getCostFbaFee().getAmount().multiply(costRatio).setScale(3, RoundingMode.HALF_EVEN) : BigDecimal.ZERO);
        dcBaseOmsSku.setCostPaypalFee((orderCharge.getCostPaypalFee() != null && orderCharge.getCostPaypalFee().getAmount() != null) ? orderCharge.getCostPaypalFee().getAmount().multiply(costRatio).setScale(3, RoundingMode.HALF_EVEN) : BigDecimal.ZERO);
    }

    /**
     * 检查FBA费用是否异常
     *
     * @param dcBaseOmsSku
     */
    private void checkFbaFee(DcBaseOmsSku dcBaseOmsSku, Boolean isFbaFeeException) {
        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);
                    isFbaFeeException = 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.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.setCostFirst(BigDecimal.ZERO);

    }

    /**
     * 把OMS订单中的一部分值赋值到百伦订单对象上
     *
     * @param dcBaseOmsSku
     * @param saleItemHashMap
     * @param isFbaFeeException
     * @return
     */
    public void assignmentSkuInfo(OmsResult omsResult, DcBaseOmsOrder dcBaseOmsOrder, DcBaseOmsSku dcBaseOmsSku, BailunSku bailunSku, DcBaseWarehouse dcBaseWarehouse, HashMap<String, String> saleItemHashMap, Boolean isFbaFeeException) {
        dcBaseOmsSku.setBailunInterceptionStatus(dcBaseOmsOrder.getBailunInterceptionStatus());
        dcBaseOmsSku.setBailunSku(bailunSku.getBailunSku());
        if (dcBaseWarehouse != null) {
            dcBaseOmsSku.setWarehouseCode(dcBaseWarehouse.getWarehouseCode());
            dcBaseOmsSku.setWarehouseName(dcBaseWarehouse.getWarehouseName());
        }
        dcBaseOmsSku.setAreaId(omsResult.getAreaId());
        dcBaseOmsSku.setHasCancle(omsResult.getHasCancle());
        dcBaseOmsSku.setSellerName(saleItemHashMap.get(bailunSku.getBailunSku()));
        // --begin 调用产品库信息 skuProductInfo, 获取分类信息
        DcBaseSku skuProductInfo = getDcBaseSku(bailunSku);
        if (skuProductInfo != null) {
            dcBaseOmsSku.setBailunCategoryId(skuProductInfo.getBailunCategoryId());
            dcBaseOmsSku.setBailunCategoryName(skuProductInfo.getBailunCategoryName());
        }
        //根据国家找物流规则
        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.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.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的情况
        //如果是 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);
                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());
                dcBaseOmsOrder.setFinanceOtherExchangeRate(otherFinanceExchangeRate);
                dcBaseOmsOrder.setSellerOtherExchangeRate(sellerOtherExchangeRate);
            }
        }
    }
}
