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.HashMap;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;

@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);
                        SessionUtil.getSession().commit();
                    } 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());
            }
        }
        //如果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)) {
                log.warn(omsResult.getOriginOrderId());
                BigDecimal orderSaleAmount = BigDecimal.ZERO;
                BigDecimal orderOriginal = BigDecimal.ZERO;
                String currency = null;
                if (omsResult.getOrderCharge() != null && omsResult.getOrderCharge().getAmountTotal() != null && omsResult.getOrderCharge().getAmountTotal().getCurrencyCode() != null) {
                    BigDecimal exchangeRate = CallBailunSystem.getExchangeRate(omsResult.getOrderCharge().getAmountTotal().getCurrencyCode(), "USD", omsResult.getCreateTime());
                    currency = omsResult.getOrderCharge().getAmountTotal().getCurrencyCode();
                    orderOriginal = omsResult.getOrderCharge().getAmountTotal().getAmount();
                    orderSaleAmount = exchangeRate != null ? exchangeRate.multiply(omsResult.getOrderCharge().getAmountTotal().getAmount()) : omsResult.getOrderCharge().getAmountTotal().getAmount();
                }
                TOrderOriginalWithBLOBs tOrderOriginal = new TOrderOriginalWithBLOBs();
                HashMap<String, BailunSkuStructure> skuStructureMap = new HashMap<>();
                DcBaseWarehouse dcBaseWarehouse = null;
                Integer totalSkuQuantity = 0;
                if (omsResult.getBailunSku() != null && omsResult.getBailunSku().size() > 0) {
                    //拿仓库信息
                    dcBaseWarehouse = getDcBaseWarehouse(omsResult);
                    for (BailunSku bailunSku : omsResult.getBailunSku()) {
                        BailunSkuStructure bailunSkuStructure = new BailunSkuStructure();
                        TOrderProduct tOrderProduct = new TOrderProduct();
                        tOrderProduct.setOriginalcurrency(currency);
                        tOrderProduct.setOriginaltotal(orderOriginal);
                        tOrderProduct.setOrdersaleamount(orderSaleAmount);
                        tOrderProduct.setShipwarehousecode(bailunSku.getWarehouseCode());
                        assignmentSkuInfo(bailunSku, omsResult, tOrderProduct);
                        bailunSkuStructure.setSkuQuantityOrderd(bailunSku.getBailunSkuQuantityOrdered() != null ? bailunSku.getBailunSkuQuantityOrdered() : 0);
                        bailunSkuStructure.setTOrderProduct(tOrderProduct);
                        skuStructureMap.put(bailunSku.getBailunSku(), bailunSkuStructure);
                        totalSkuQuantity += bailunSku.getBailunSkuQuantityOrdered() != null ? bailunSku.getBailunSkuQuantityOrdered() : 0;
                    }
                }
                /*
                 * 配货单处理
                 */
                BigDecimal totalWeight = handPickingOrder(omsResult, tOrderOriginal, skuStructureMap, totalSkuQuantity);

                /*
                 * 对订单维度字段进行赋值处理
                 */
                tOrderOriginal.setOrderamount(orderSaleAmount);
                tOrderOriginal.setOriginalcurrency(currency);
                tOrderOriginal.setOriginaltotal(orderOriginal);
                assignmentOrderInfo(omsResult, tOrderOriginal, dcBaseWarehouse,totalWeight);

                try {
                    TOrderProductMapper productMapper = SessionUtil.getSession().getMapper(TOrderProductMapper.class);
                    TOrderOriginalMapper mapper = SessionUtil.getSession().getMapper(TOrderOriginalMapper.class);
                    skuStructureMap.forEach((s, bailunSkuStructure) -> {
                        bailunSkuStructure.getTOrderProduct().setOrderSystem(Constant.ORDER_SYSTEM);
                        int i = productMapper.updateByExampleSelective(bailunSkuStructure.getTOrderProduct(), TOrderProductExample.newAndCreateCriteria().andOrdernoEqualTo(bailunSkuStructure.getTOrderProduct().getOrderno()).andPlatformEqualTo(bailunSkuStructure.getTOrderProduct().getPlatform()).andProductcodeEqualTo(bailunSkuStructure.getTOrderProduct().getProductcode()).example());
                        if (i == 0) {
                            productMapper.insertSelective(bailunSkuStructure.getTOrderProduct());
                        }
                        
                    });
                    tOrderOriginal.setOrderSystem(Constant.ORDER_SYSTEM);
                    int i = mapper.updateByExampleSelective(tOrderOriginal, TOrderOriginalExample.newAndCreateCriteria().andOrdernosystemEqualTo(tOrderOriginal.getOrdernosystem()).andOrdersourceEqualTo(tOrderOriginal.getOrdersource()).example());
                    if (i == 0) {
                        mapper.insertSelective(tOrderOriginal);
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                    throw new RuntimeException("MYBATIS操作db失败" + omsResult.getOriginOrderId(), e);
                } finally {
                    SessionUtil.closeSession();
                }
            }
        }
    }



    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())) {
                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(OmsResult omsResult, TOrderOriginalWithBLOBs tOrderOriginal, HashMap<String, BailunSkuStructure> skuStructureMap, Integer totalSkuOrderedQuantity) {
        BigDecimal totalOutWeight = BigDecimal.ZERO;
        try {
            TOrderShippingMapper tOrderShippingMapper = SessionUtil.getSession().getMapper(TOrderShippingMapper.class);
            TOrderShippingsMapper tOrderShippingsMapper = SessionUtil.getSession().getMapper(TOrderShippingsMapper.class);
            List<PickingOrder> pickingOrderList = omsResult.getPickingOrder();
            TOrderShippingWithBLOBs tOrderShipping = new TOrderShippingWithBLOBs();
            assignmentShippingInfo(omsResult, tOrderShipping);
            if (pickingOrderList != null && pickingOrderList.size() > 0) {
                Integer totalShippedCount = 0;
                Integer totalPickedCount = 0;
                for (PickingOrder pickingOrder : pickingOrderList) {
                    if (pickingOrder.getPickingItems() != null && pickingOrder.getPickingItems().size() > 0) {
                        totalOutWeight = totalOutWeight.add(pickingOrder.getOutboundWeight()  != null? pickingOrder.getOutboundWeight() : BigDecimal.ZERO);
                        TOrderShippingsWithBLOBs tOrderShippings = new TOrderShippingsWithBLOBs();
                        Integer pickFlag = -1;
                        Integer shipFlag = -1;
                        //优先级  未发货 完全发货 部分发货
                        for (PickingItem pickingItem : pickingOrder.getPickingItems()) {
                            totalShippedCount += pickingItem.getQuantityShipped();
                            totalPickedCount += pickingItem.getQuantityPicked();
                            BailunSkuStructure bailunSkuStructure = skuStructureMap.get(pickingItem.getBailunSku());
                            if (bailunSkuStructure != null && pickingOrder.getWarehouse() != null) {
                                bailunSkuStructure.getTOrderProduct().setShiptime(pickingOrder.getShippingTime());
                                bailunSkuStructure.getTOrderProduct().setShipwarehousecode(pickingOrder.getWarehouse().getWarehouseCode());
                            }
                            if (pickingItem.getQuantityPicked() == bailunSkuStructure.getSkuQuantityOrderd()) {
                                //完全配货
                                if (shipFlag < 1) {
                                    pickFlag = 1;
                                }
                            } else if (pickingItem.getQuantityPicked() == 0) {
                                //未配货
                                if (pickFlag < 2) {
                                    pickFlag = 2;
                                }
                            } else if (pickingItem.getQuantityPicked() < bailunSkuStructure.getSkuQuantityOrderd()) {
                                //部分配货
                                if (pickFlag < 3) {
                                    pickFlag = 3;
                                }
                            }
                            if (pickingItem.getQuantityPicked() == pickingItem.getQuantityShipped()) {
                                //完全发货
                                if (shipFlag < 1) {
                                    shipFlag = 1;
                                }
                            } else if (pickingItem.getQuantityShipped() == 0) {
                                //未发货
                                if (shipFlag < 2) {
                                    shipFlag = 2;
                                }
                            } else if (pickingItem.getQuantityPicked() > pickingItem.getQuantityShipped()) {
                                //部分发货
                                if (shipFlag < 3) {
                                    shipFlag = 3;
                                }
                            }
                        }
                        assignmentShippingsInfo(omsResult, tOrderShippings, pickingOrder, pickFlag, shipFlag);
                        tOrderShippings.setOrderSystem(Constant.ORDER_SYSTEM);
                        int i = tOrderShippingsMapper.updateByExampleSelective(tOrderShippings, TOrderShippingsExample.newAndCreateCriteria().andOrdernosystemEqualTo(tOrderShippings.getOrdernosystem()).andPeihuonoEqualTo(tOrderShippings.getPeihuono()).example());
                        if (i == 0) {
                            tOrderShippingsMapper.insert(tOrderShippings);
                        }
                    }

                }

                if (totalPickedCount.compareTo(totalSkuOrderedQuantity) == 0) {
                    tOrderShipping.setPeihuostatus("完全配货");
                } else if (totalPickedCount.compareTo(totalSkuOrderedQuantity) == -1) {
                    tOrderShipping.setPeihuostatus("部分配货");
                } else if (totalPickedCount.equals(0)) {
                    tOrderShipping.setPeihuostatus("未配货");
                }
                if (totalShippedCount.compareTo(totalSkuOrderedQuantity) == 0) {
                    tOrderShipping.setShipstatus("完全发货");
                } else if (totalShippedCount.compareTo(totalSkuOrderedQuantity) == -1) {
                    tOrderShipping.setShipstatus("部分发货");
                } else if (totalShippedCount.equals(0)) {
                    tOrderShipping.setShipstatus(" 未发货 ");
                }
                if (pickingOrderList.get(0).getWarehouse() != null) {
                    tOrderShipping.setShipwarehouse(pickingOrderList.get(0).getWarehouse().getWarehouseCode());
                }
                tOrderShipping.setOutweight(totalOutWeight);
                if (omsResult.getLogisticsItems() != null && omsResult.getLogisticsItems().size() > 0 && omsResult.getLogisticsItems().get(0).getLogisticsMethod() != null) {
                    tOrderShipping.setAssignlogistics(omsResult.getLogisticsItems().get(0).getLogisticsMethod().getLogisticsCode());
                }
                if (pickingOrderList.get(0).getLogistics() != null) {
                    tOrderShipping.setShiplogistics(pickingOrderList.get(0).getLogistics().getLogisticsCode());
                }
                tOrderShipping.setLogisticsno(pickingOrderList.get(0).getTrackingOrderId());
                tOrderShipping.setCreatetime(pickingOrderList.get(0).getCreateTime());
            } else {
                tOrderShipping.setPeihuostatus("未配货");
                tOrderShipping.setShipstatus(" 未发货 ");
            }
            tOrderShipping.setOrderSystem(Constant.ORDER_SYSTEM);
            int i = tOrderShippingMapper.updateByExampleSelective(tOrderShipping, TOrderShippingExample.newAndCreateCriteria().andOrdernosystemEqualTo(tOrderShipping.getOrdernosystem()).andOrdersourceEqualTo(tOrderShipping.getOrdersource()).example());
            if (i == 0) {
                tOrderShippingMapper.insert(tOrderShipping);
            }
            
        } catch (Exception e) {
            e.printStackTrace();
            throw new RuntimeException("MYBATIS操作DB失败");
        } finally {
            SessionUtil.closeSession();
        }
        return totalOutWeight;
    }

    private void assignmentShippingInfo(OmsResult omsResult, TOrderShippingWithBLOBs tOrderShipping) {
        tOrderShipping.setOrdernoplatform(omsResult.getOriginOrderId());
        tOrderShipping.setOrdernosystem(omsResult.getBailunOrderId());
        tOrderShipping.setOrdersource(omsResult.getPlatformType());
        tOrderShipping.setOrderexceptionstatus("没问题");
        tOrderShipping.setIsshipagain(0);
        tOrderShipping.setIsassignlogistics(0);
        tOrderShipping.setIsfaraway(0);
        tOrderShipping.setUpdatetime(LocalDateTime.now());
        if (omsResult.getReceiptAddress() != null) {
            tOrderShipping.setShipcountry(omsResult.getReceiptAddress().getReceiptCountry());
            tOrderShipping.setShipaddress(omsResult.getReceiptAddress().getReceiptAddress());
        }
    }


    /**
     * 检查订单平台费用是否异常
     *
     * @param dcBaseOmsOrder
     */
    private void checkPlatformFee(DcBaseOmsOrder dcBaseOmsOrder) {
        BigDecimal value = dcBaseOmsOrder.getAmountProduct().subtract(dcBaseOmsOrder.getCostPromotion());
        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 = CallBailunSystem.getSkuInfo(bailunSku.getBailunSku());
        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);
    }




    /**
     * 把OMS订单中的一部分值赋值到百伦订单对象上
     *
     * @return
     */
    public void assignmentOrderInfo(OmsResult omsResult, TOrderOriginalWithBLOBs tOrderOriginal, DcBaseWarehouse dcBaseWarehouse, BigDecimal totalWeight) {
        tOrderOriginal.setIssystemship(1);
        tOrderOriginal.setOrdernoplatform(omsResult.getOriginOrderId());
        tOrderOriginal.setEbaytransactionid(omsResult.getTransactionId());
        if (omsResult.getPlatformType().toUpperCase().equals(PlatformType.FBA.value())) {
            tOrderOriginal.setIssystemship(0);
        }
        tOrderOriginal.setOrdernosystem(omsResult.getBailunOrderId());
        tOrderOriginal.setOrdersource(omsResult.getPlatformType());
        tOrderOriginal.setOrderstatus("处理中");
        if(omsResult.getBailunOrderStatus() != null) {
            switch (omsResult.getBailunOrderStatus()) {
                case "Canceled" :  tOrderOriginal.setOrderstatus("已取消");
                    break;
                case "Finished" :  tOrderOriginal.setOrderstatus("完结");
                    break;
                case "Handling" :  tOrderOriginal.setOrderstatus("处理中");
                    break;
            }
        }
        tOrderOriginal.setOrdersite(omsResult.getWebsite());
        tOrderOriginal.setInterceptstatus(0);
        if (omsResult.getBailunInterceptionStatus() != null && !omsResult.getBailunInterceptionStatus().equals("未拦截")) {
            tOrderOriginal.setInterceptstatus(1);
        }
        if (omsResult.getSeller() != null) {
            tOrderOriginal.setSellaccount(omsResult.getSeller().getSellerAccount());
        }

        if (omsResult.getPickingOrder() != null && omsResult.getPickingOrder().size() > 0 && omsResult.getPickingOrder().get(0).getWarehouse() != null) {
            tOrderOriginal.setShipwarehouse(omsResult.getPickingOrder().get(0).getWarehouse().getWarehouseCode());
        }
        //ProductTitle
        tOrderOriginal.setOrdertime(omsResult.getCreateTime());
        tOrderOriginal.setPaytime(omsResult.getPaidTime());
        if (omsResult.getPayment() != null) {
            tOrderOriginal.setPaypalinaccount(omsResult.getPayment().getCollectionAccount());
            tOrderOriginal.setPaypaloutaccount(omsResult.getPayment().getPayAccount());
        }
        if (omsResult.getBuyer() != null) {
            tOrderOriginal.setBuyerid(omsResult.getBuyer().getBuyerId());
            tOrderOriginal.setBuyername(omsResult.getBuyer().getBuyerName());
            tOrderOriginal.setEmail(omsResult.getBuyer().getBuyerEmail());
        }
        //根据国家找物流规则
        if (omsResult.getReceiptAddress() != null) {
            tOrderOriginal.setCountry(omsResult.getReceiptAddress().getReceiptCountry());
            tOrderOriginal.setAddress1(omsResult.getReceiptAddress().getReceiptAddress());
            tOrderOriginal.setAddress2(omsResult.getReceiptAddress().getReceiptAddress2());
            tOrderOriginal.setCity(omsResult.getReceiptAddress().getReceiptCity());
            tOrderOriginal.setProvince(omsResult.getReceiptAddress().getReceiptArea());
            tOrderOriginal.setPostcode(omsResult.getReceiptAddress().getReceiptPostalCode());
            tOrderOriginal.setPhonenumber(omsResult.getReceiptAddress().getReceiverPhone());
            tOrderOriginal.setCountryEnName(omsResult.getReceiptAddress().getReceiptCountry());
//            tOrderOriginal.setMobilenumber(null);
            //Email在上面omsResult.getBuyer()
        }

        tOrderOriginal.setCreatetime(LocalDateTime.now());
        tOrderOriginal.setUpdatetime(LocalDateTime.now());
//        tOrderOriginal.setHid();
//        tOrderOriginal.setItemid();
//        tOrderOriginal.setSkuinfo();
        tOrderOriginal.setFreight(totalWeight);
        tOrderOriginal.setOmscreatetime(omsResult.getCreateTime());
        tOrderOriginal.setOmsupdatetime(omsResult.getOrderUpdateTime());
        tOrderOriginal.setMatchtime(omsResult.getCreateTime());
//        originalcurrency在上面
//        originaltotal在上面
//        IsRefund在上面
//        Ebaytransactionid在上面
        tOrderOriginal.setBjpaytime(omsResult.getPaidTime());
        tOrderOriginal.setInterceptstatus(omsResult.getBailunInterceptionStatus().equals("None") ? 0 : 1);
        tOrderOriginal.setPlatformnosources(omsResult.getTransactionId());
//        tOrderOriginal.setTs();
        if (dcBaseWarehouse != null && dcBaseWarehouse.getHqType() != null) {
            tOrderOriginal.setIsAbroad(dcBaseWarehouse.getHqType().equals(CommonConstant.DOMESTIC_WAREHOUSE) ? 0 : 1);
        }
        //CountryEnName
    }

    /**
     * 把OMS订单中的一部分值赋值到百伦订单对象上
     *
     * @return
     */
    public void assignmentSkuInfo(BailunSku bailunSku, OmsResult omsResult, TOrderProduct tOrderProduct) {
        tOrderProduct.setPlatformorderno(omsResult.getOriginOrderId());
        tOrderProduct.setOrderno(omsResult.getBailunOrderId());
        tOrderProduct.setPlatform(omsResult.getPlatformType());
        tOrderProduct.setPlatformsite(omsResult.getWebsite());
//        tOrderProduct.setPlatformsku();
        tOrderProduct.setProductcode(bailunSku.getBailunSku());
        tOrderProduct.setTitle(bailunSku.getBailunSkuTitleCn());
        tOrderProduct.setProductshipcount(bailunSku.getBailunSkuQuantityOrdered());
        tOrderProduct.setProductweight(bailunSku.getBailunSkuWeight());
        tOrderProduct.setProductsaleamount(bailunSku.getBailunSkuUnitPrice() != null ? bailunSku.getBailunSkuUnitPrice().getAmount() : BigDecimal.ZERO);
        // --begin 调用产品库信息 skuProductInfo, 获取分类信息
        DcBaseSku skuProductInfo = getDcBaseSku(bailunSku);
        if (skuProductInfo != null) {
            tOrderProduct.setDeveloper(skuProductInfo.getSuppliersName());
            tOrderProduct.setBuyer(skuProductInfo.getBuyerName());
            tOrderProduct.setSeller(skuProductInfo.getSellerName());
            tOrderProduct.setCategoryid(skuProductInfo.getCategoryId());
            tOrderProduct.setCategoryname(skuProductInfo.getCategoryName());
//            tOrderProduct.setMainimageurl();
            tOrderProduct.setSupplierid(skuProductInfo.getSuppliersId());
            tOrderProduct.setSuppliername(skuProductInfo.getSuppliersName());
            tOrderProduct.setBuyprice(skuProductInfo.getUnitPrice());
            tOrderProduct.setDeveloptime(skuProductInfo.getCreateTime());
        }

        tOrderProduct.setPaytime(omsResult.getPaidTime());
        if (bailunSku.getBailunSkuUnitPrice() != null) {
            tOrderProduct.setCurrency(bailunSku.getBailunSkuUnitPrice().getCurrencyCode());
        }
//        tOrderProduct.setOrderstatus();
//        tOrderProduct.setHid();
        tOrderProduct.setBjpaytime(omsResult.getPaidTime());
        tOrderProduct.setIsdelete(omsResult.getHasCancle() ? 1 : 0);
        tOrderProduct.setTs(LocalDateTime.now());
        tOrderProduct.setCreatetime(omsResult.getCreateTime());
        tOrderProduct.setUpdatetime(LocalDateTime.now());
    }

    /**
     * 把OMS订单中的一部分值赋值到百伦订单对象上
     *
     * @return
     */
    public void assignmentShippingsInfo(OmsResult omsResult, TOrderShippingsWithBLOBs tOrderShippings, PickingOrder pickingOrder,  Integer pickFlag,Integer shipFlag) {
        tOrderShippings.setOrdernoplatform(omsResult.getOriginOrderId());
        tOrderShippings.setOrdernosystem(omsResult.getBailunOrderId());
        tOrderShippings.setOrdersource(omsResult.getPlatformType());
        if (pickingOrder.getWarehouse() != null) {
            tOrderShippings.setShipwarehouse(pickingOrder.getWarehouse().getWarehouseCode());
        }
        tOrderShippings.setOrderexceptionstatus("没问题");
        tOrderShippings.setIsshipagain(0);
        tOrderShippings.setOutwarehousetime(pickingOrder.getShippingTime());
        tOrderShippings.setOutweight(pickingOrder.getOutboundWeight());
//        tOrderShippings.setOriginalsku();
//        tOrderShippings.setHaspeihuosku();
//        tOrderShippings.setNopeihuosku();
        tOrderShippings.setPeihuono(pickingOrder.getPickOrderId());
        tOrderShippings.setPeihuotime(pickingOrder.getCreateTime());
        switch (shipFlag) {
            case 1:
                tOrderShippings.setShipstatus("完全发货");
                break;
            case 2:
                tOrderShippings.setShipstatus("未发货");
                break;
            case 3:
                tOrderShippings.setShipstatus(" 部分发货");
                break;
        }
        switch (pickFlag) {
            case 1:
                tOrderShippings.setPeihuostatus("完全配货");
                break;
            case 2:
                tOrderShippings.setPeihuostatus("未配货");
                break;
            case 3:
                tOrderShippings.setPeihuostatus("部分配货");
                break;
        }
//        tOrderShippings.setHasshipsku();
//        tOrderShippings.setNoshipsku();
        tOrderShippings.setOutwarehousetime(pickingOrder.getShippingTime());
        tOrderShippings.setOutweight(pickingOrder.getOutboundWeight());
//        tOrderShippings.setPackageno();
        tOrderShippings.setIsassignlogistics(0);
        tOrderShippings.setShiplogistics(pickingOrder.getTrackingProvider());
        tOrderShippings.setIsfaraway(0);
        tOrderShippings.setLogisticsno(pickingOrder.getTrackingOrderId());
        tOrderShippings.setCreatetime(pickingOrder.getCreateTime());
        tOrderShippings.setUpdatetime(LocalDateTime.now());
//        tOrderShippings.setHid();
//        tOrderShippings.setPlatformexpress();
//        tOrderShippings.setShipaddress();
//        tOrderShippings.setShipcountry();
        tOrderShippings.setShipfee(pickingOrder.getCostShipping());
//        tOrderShippings.setPickorderinfo();
//        tOrderShippings.setShiporderinfo();
    }


    /**
     * 获取汇率
     *
     * @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);
        if (orderCharge != null) {
            if (orderCharge.getAmountTotal() != null && !StringUtils.isEmpty(orderCharge.getAmountTotal().getCurrencyCode())) {
                String orderCurrency = orderCharge.getAmountTotal().getCurrencyCode();
                BigDecimal sellerOrderExchangeRate = orderCharge.getAmountTotal().getExchangeRate();
                BigDecimal orderFinanceExchangeRate = CallBailunSystem.getMonthExchangeRate(orderCurrency, Constant.RMB_CURRENCY, omsResult.getPaidTime() != null ? omsResult.getPaidTime() : omsResult.getCreateTime());
                dcBaseOmsOrder.setOrderCurrency(orderCurrency);
                dcBaseOmsOrder.setFinanceOrderExchangeRate(orderFinanceExchangeRate != null ? orderFinanceExchangeRate : BigDecimal.ZERO);
                dcBaseOmsOrder.setSellerOrderExchangeRate(sellerOrderExchangeRate != null ? sellerOrderExchangeRate : BigDecimal.ZERO);
            }
            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 = orderCharge.getCostPlatformFee().getExchangeRate();
                BigDecimal otherFinanceExchangeRate = CallBailunSystem.getMonthExchangeRate(otherCurrency, Constant.RMB_CURRENCY, omsResult.getPaidTime() != null ? omsResult.getPaidTime() : omsResult.getCreateTime());
                dcBaseOmsOrder.setOtherCurrency(otherCurrency);
                dcBaseOmsOrder.setFinanceOtherExchangeRate(otherFinanceExchangeRate != null ? otherFinanceExchangeRate : BigDecimal.ZERO);
                dcBaseOmsOrder.setSellerOtherExchangeRate(sellerOtherExchangeRate != null ? sellerOtherExchangeRate : BigDecimal.ZERO);
            }
        }
    }
}
