package com.freemud.application.sdk.api.ordercenter.adapter;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.TypeReference;
import com.freemud.application.sdk.api.ordercenter.entities.extinfo.OrderProductExtInfo;
import com.freemud.application.sdk.api.ordercenter.entities.v1.*;
import com.freemud.application.sdk.api.ordercenter.enums.AfterSalesStatus;
import com.freemud.application.sdk.api.ordercenter.enums.OrderSettlementType;
import com.freemud.application.sdk.api.ordercenter.enums.ProductTypeEnum;
import com.freemud.application.sdk.api.ordercenter.enums.RefundModeEnum;
import com.freemud.application.sdk.api.ordercenter.enums.orderv1.*;
import com.freemud.application.sdk.api.ordercenter.request.AfterOrderExtInfoDto;
import com.freemud.application.sdk.api.ordercenter.request.OrderExtendedReq;
import com.freemud.application.sdk.api.ordercenter.response.orderInfo.OrderPayItemResp;
import com.freemud.application.sdk.api.ordercenter.response.orderInfo.*;
import com.freemud.application.sdk.api.ordercenter.util.ClassUtils;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang.ObjectUtils;
import org.apache.commons.lang.StringUtils;
import org.springframework.stereotype.Component;

import java.math.BigDecimal;
import java.util.*;
import java.util.stream.Collectors;

@Component
public class OrderCenterSdkAdapter {


    /**
     * 新订单信息 转化成 老订单信息
     */
    public OrderBeanV1 convent2NEWOrderInfo(OrderInfoReqs orderInfoReqs) {
        OrderBeanV1 data = new OrderBeanV1();
        if (Objects.nonNull(orderInfoReqs.getEstimateDeliveryCompleteTime())) {
            data.setEstimateDeliveryCompleteTime(Long.parseLong(orderInfoReqs.getEstimateDeliveryCompleteTime()));
        }
        data.setOrderClient(orderInfoReqs.getOrderClient().toString());
        data.setCompanyId(orderInfoReqs.getPartnerId());
        data.setShopId(orderInfoReqs.getStoreId());
        data.setShopName(orderInfoReqs.getStoreName());
        data.setOid(orderInfoReqs.getOrderCode());
        data.setAmount(orderInfoReqs.getSettlementAmount() == null ? 0L : orderInfoReqs.getSettlementAmount().longValue());
        data.setSettlementAmount(orderInfoReqs.getSettlementAmount() == null ? 0L : orderInfoReqs.getSettlementAmount().longValue());
        data.setActualPayAmount(orderInfoReqs.getActualPayAmount() == null ? 0L : orderInfoReqs.getActualPayAmount().longValue());
        data.setUserId(orderInfoReqs.getUserId());
        data.setUserName(orderInfoReqs.getUserName());
//        data.setType(getOldOrderType(orderInfoReqs.getOrderType()));
        data.setOrderType(getOldOrderType(orderInfoReqs.getOrderType()));
        data.setNewOrderType(orderInfoReqs.getOrderType());
        data.setNeedInvoice(orderInfoReqs.getIsNeedInvoice());
        data.setOriginalAmount(orderInfoReqs.getOriginalAmount());
        AddDeliveryInfoV1 addInfo = new AddDeliveryInfoV1();
        addInfo.setExpress(orderInfoReqs.getExpressChannelName());
        data.setExtInfo(orderInfoReqs.getExtInfo());
        data.setBarCounter(orderInfoReqs.getBarCounter());
        data.setThirdOrderCode(orderInfoReqs.getThirdOrderCode());
        data.setDinersNumber(orderInfoReqs.getDinersNumber());
        data.setThirdShopId(orderInfoReqs.getThirdStoreId());
        data.setDownstreamPosCode(orderInfoReqs.getDownstreamPosCode());
        data.setDownstreamThirdOrderCode(orderInfoReqs.getDownstreamThirdOrderCode());
        data.setAppId(orderInfoReqs.getAppId());

        //20201222 新增配送类型 ->【ID1021986】
        //【订单开放平台】订单详情查询接口增加配送类型字段
        data.setExpressType(orderInfoReqs.getExpressType());


        if (orderInfoReqs.getOrderExtended() != null) {
            // 围餐门店英文名称
            data.setShopNameEn(orderInfoReqs.getOrderExtended().getStoreNameEn());
            data.setSpellGroupCode(orderInfoReqs.getOrderExtended().getSpellGroupCode());
        }

        if (orderInfoReqs.getAfterSalesOrderList() != null && orderInfoReqs.getAfterSalesOrderList().size() >= 1) {
            data.setAfterSalesOrderResp(orderInfoReqs.getAfterSalesOrderList().get(0));
        }

        if (orderInfoReqs.getDeliveryContactInfoList() != null && orderInfoReqs.getDeliveryContactInfoList().size() != 0) {
            for (DeliveryContactInfoResp deliveryContactInfoResp : orderInfoReqs.getDeliveryContactInfoList()) {
                //地址类型 1:订单地址 2:售后单地址 3:配送员信息
                if (deliveryContactInfoResp.getRelateObjectType() == 1) {
                    data.setReceiveProvince(orderInfoReqs.getDeliveryContactInfoList().get(0).getProvince());
                    data.setReceiveCity(orderInfoReqs.getDeliveryContactInfoList().get(0).getCity());
                    data.setReceiveRegion(orderInfoReqs.getDeliveryContactInfoList().get(0).getRegion());
                    data.setContactsName(orderInfoReqs.getDeliveryContactInfoList().get(0).getContactsName());
                    data.setAddress(orderInfoReqs.getDeliveryContactInfoList().get(0).getAddressDetail());
                    data.setPhone(orderInfoReqs.getDeliveryContactInfoList().get(0).getMobile());
                    addInfo.setExtInfo(deliveryContactInfoResp.getExtInfo());
                    if (orderInfoReqs.getDeliveryContactInfoList().get(0).getLatitude() != null
                            && orderInfoReqs.getDeliveryContactInfoList().get(0).getLongitude() != null) {
                        data.setLatitude(orderInfoReqs.getDeliveryContactInfoList().get(0).getLatitude().doubleValue());
                        data.setLongitude(orderInfoReqs.getDeliveryContactInfoList().get(0).getLongitude().doubleValue());
                        data.setTakeAddress(orderInfoReqs.getDeliveryContactInfoList().get(0).getAddressDetail());
                    }
                }
                if (deliveryContactInfoResp.getRelateObjectType() == 3) {
                    data.setRiderName(deliveryContactInfoResp.getContactsName());
                    data.setRiderPhone(deliveryContactInfoResp.getMobile());
                    addInfo.setDeliveryId(deliveryContactInfoResp.getThirdDeliveryId());
                    addInfo.setExpressNo(deliveryContactInfoResp.getExpressNo());
                    addInfo.setDeliveryType(deliveryContactInfoResp.getAddressDetail());
                    addInfo.setExpress(orderInfoReqs.getExpressChannelName());
                    addInfo.setDeliverStatus(orderInfoReqs.getDeliveryState());
                    addInfo.setRiderName(deliveryContactInfoResp.getContactsName());
                    addInfo.setRiderPhone(deliveryContactInfoResp.getMobile());
                    data.setAddInfo(addInfo);
                }
            }
        }
        data.setOperator(orderInfoReqs.getOperator());
        data.setOperateTime(orderInfoReqs.getUpdateTimestamp());
        if (CollectionUtils.isNotEmpty(orderInfoReqs.getOrderOperationHistoryList())) {
            List<OrderOperationHistoryResp> historyList = orderInfoReqs.getOrderOperationHistoryList();
            OrderOperationHistoryResp historyResp = historyList.get(historyList.size() - 1);
            data.setOperator(historyResp.getOperator());
            data.setOperateTime(historyResp.getUpdateTime());
        }
        data.setArriveShopTime("");
        data.setCancelReason(orderInfoReqs.getCancelReason());
        data.setRemark(orderInfoReqs.getNote());

        data.setShopAddress("");
        data.setShopPhone("");
        data.setCourierName("");
        data.setCourierPhone("");
        data.setCreateUser("");
        data.setCustomerOrder(orderInfoReqs.getThirdOrderCode());
        data.setEvaluateStatus(0);

        try {
            if (orderInfoReqs.getAcceptTime() != null) {
                data.setGmtAccept(Long.parseLong(orderInfoReqs.getAcceptTime()));
            }
            if (orderInfoReqs.getCreateTime() != null) {
                data.setGmtCreate(Long.parseLong(orderInfoReqs.getCreateTime()));
            }
            if (orderInfoReqs.getExpectTime() != null) {
                data.setGmtExpect(Long.parseLong(orderInfoReqs.getExpectTime()));
            }
            if (orderInfoReqs.getUpdateTime() != null) {
                data.setGmtModified(Long.parseLong(orderInfoReqs.getUpdateTime()));
            }
            if (orderInfoReqs.getPayTime() != null) {
                data.setGmtPay(Long.parseLong(orderInfoReqs.getPayTime()));
            }
            if (orderInfoReqs.getReceiveTime() != null) {
                data.setGmtCompleteTime(Long.parseLong(orderInfoReqs.getReceiveTime()));
                data.setGmtReceiveTime(Long.parseLong(orderInfoReqs.getReceiveTime()));
            }
            if (orderInfoReqs.getDeliveryTime() != null) {
                data.setGmtDelivery(Long.decode(orderInfoReqs.getDeliveryTime()));
            }
            if (null != orderInfoReqs.getAfterSalesOrderList() && orderInfoReqs.getAfterSalesOrderList().size() > 0) {
                AfterSalesOrderResp afterSalesOrderResp = orderInfoReqs.getAfterSalesOrderList().get(0);
                if (AfterSalesStatus.COMPLETE.getIndex() == afterSalesOrderResp.getAfterSalesStatus()) {
                    data.setGmtRefundFinish(Long.parseLong(afterSalesOrderResp.getUpdateTime()));
                }
            }

        } catch (Exception e) {
            e.printStackTrace();
        }

        if (orderInfoReqs.getAfterSalesOrderList() != null && orderInfoReqs.getAfterSalesOrderList().size() != 0) {
            data.setHasRefund(true);
        } else {
            data.setHasRefund(false);
        }
        data.setInvoiceInfo("");
        data.setOtherCode(orderInfoReqs.getPickUpGoodsNo());
        data.setPartition("");
        data.setPayChannel(orderInfoReqs.getPayChannel());
        data.setPayChannelName(orderInfoReqs.getPayChannelName());
        //1:未支付 2:已支付 3:已退款 4:部分退款
        data.setPayStatus(orderInfoReqs.getPayState());
        data.setPayType(orderInfoReqs.getPayType());
        data.setPayVoucher(orderInfoReqs.getPayRequestNo());
        data.setPosId(orderInfoReqs.getPosCode());
        data.setDaySeq(orderInfoReqs.getDaySeq());
        data.setSource(OrderSourceV1.getCodeByClientType(orderInfoReqs.getOrderClient()));
        data.setSourceName(OrderSourceV1.getDescByClientType(orderInfoReqs.getOrderClient()));
        data.setStatus(OrderStatusV1.getOldCode(orderInfoReqs.getOrderState()));
        data.setStatusV2(orderInfoReqs.getOrderState());
        data.setQueueIndex("");
        data.setUserType("");
        data.setOperateTakeOrderTime(null);
        data.setOperateWaitPayTime(null);
        data.setOperateReceiptTime(null);
        data.setOperateDistributionTime(null);
        data.setOperateCompleteTime(null);
        data.setOperateCalcelTime(null);
        data.setOperatePefuseTime(null);
        data.setOperateCompleteMakeTime(null);

        //运单相关信息
        data.setDeliverStatus(orderInfoReqs.getDeliveryState() != null ? orderInfoReqs.getDeliveryState() : 0);
        data.setReceiveTime("");
        data.setDepatchTime("");
        data.setArriveShopTime("");
        data.setSendTime("");
        data.setCompleteTime("");
        data.setParentCode(orderInfoReqs.getParentCode());
        data.setIsParent(orderInfoReqs.getIsParent());
        data.setBizType(orderInfoReqs.getBizType());

        data.setAbnormalDesc(orderInfoReqs.getAbnormalDesc());
        data.setAbnormalState(orderInfoReqs.getAbnormalState());

        data.setWeight(orderInfoReqs.getWeight());
        List<ProductBeanV1> productList = getOldOrderProductList(orderInfoReqs.getOrderSettlementDetailList(), orderInfoReqs.getOrderItemList());
        data.setProductList(productList);

        List<AccountBeanV1> accountList = getOldOrderAccountList(orderInfoReqs.getOrderSettlementDetailList(), orderInfoReqs.getOrderCostDetailList());
        data.setAccountList(accountList);

        if (orderInfoReqs.getAfterSalesOrderList() != null && orderInfoReqs.getAfterSalesOrderList().size() != 0) {
            List<RefundBeanV1> refundList = getOldOrderRefundList(orderInfoReqs.getAfterSalesOrderList());
            refundList.sort(Comparator.comparing(RefundBeanV1 :: getCreateTime));
            data.setRefundList(refundList);
        }
        data.setOrderOperationHistoryList(getOrderOperationHistory(orderInfoReqs.getOrderOperationHistoryList()));
        data.setApportionDetails(getApportionDetails(orderInfoReqs));
        data.setOrderSettlementDetailList(orderInfoReqs.getOrderSettlementDetailList());
        if (Objects.nonNull(orderInfoReqs.getOrderSettlementDetailList())) {
            orderInfoReqs.getOrderSettlementDetailList().stream()
                    .filter(e -> Objects.equals(OrderSettlementType.SPELL_GROUP.getIndex(), e.getSettlementType())).findFirst().ifPresent(e -> data.setSpellGroupActivityCode(e.getExternalObjectId()));
        }
        //费用信息
        data.setOrderCostDetailList(orderInfoReqs.getOrderCostDetailList());
        data.setExpressChannelName(orderInfoReqs.getExpressChannelName());
        data.setExpressNo(orderInfoReqs.getExpressNo());
        data.setExpressChannelCode(orderInfoReqs.getExpressChannelCode());
        //发票信息
        data.setOrderInvoice(orderInfoReqs.getOrderInvoice());
        data.setPayChannelType(orderInfoReqs.getPayChannelType());
        data.setPickUpGoodsNo(orderInfoReqs.getPickUpGoodsNo());
        //todo:混合支付
        if (CollectionUtils.isNotEmpty(orderInfoReqs.getOrderPayItemCreateReqList())) {
            data.setOrderPayItem(this.getOrderItemPayList(orderInfoReqs.getOrderPayItemCreateReqList()));
        }

        //订单类型回传
        if (orderInfoReqs.getMarketingType() != null) {
            data.setMarketingType(ClassUtils.toByte(orderInfoReqs.getMarketingType()));
        }
        data.setExpressType(orderInfoReqs.getExpressType() == null ? 0 : orderInfoReqs.getExpressType());

        // 买一赠一寄件信息
        data.setOrderSendCouponRespList(orderInfoReqs.getOrderSendCouponRespList());

        // 设置 额外拓展字段信息
        OrderExtendedReq orderExtended = this.getOrderExtendedObj(orderInfoReqs.getOrderExtended());
        data.setOrderExtended(orderExtended);
        data.setNeedInvoice(orderInfoReqs.getNeedInvoice());
        return data;
    }


    /**
     * 老订单服务商品信息转化 order_product 和produce_discount 表
     */
    private List<ProductBeanV1> getOldOrderProductList(List<OrderSettlementResp> orderSettlementResps, List<OrderItemResp> orderItemList) {
        List<ProductBeanV1> productList = new ArrayList<>();
        List<OrderItemResp> parentOrderItemList = orderItemList == null ? new ArrayList<>() : orderItemList.stream()
                .filter(item -> StringUtils.isEmpty(item.getParentProductId()) || ObjectUtils.equals("0", item.getParentProductId()))
                .collect(Collectors.toList());
        for (OrderItemResp orderItem : parentOrderItemList) {
            ProductBeanV1 productBean = getOldOrderProduct(orderSettlementResps, orderItem);
            if (ObjectUtils.equals(ProductTypeEnum.SETMEAL_PRODUCT.getCode(), orderItem.getProductType()) || ObjectUtils.equals(ProductTypeEnum.SETMEAL_UPPRICE_PRODUCT.getCode(), orderItem.getProductType())) {
                // 获取套餐子商品列表
                productBean.setComboProduct(new ArrayList<>());
                String partnerProductId = orderItem.getProductId() + "_" + orderItem.getProductSeq();
                List<OrderItemResp> comboProducts = orderItemList.stream().filter(item -> ObjectUtils.equals(partnerProductId, item.getParentProductId())).collect(Collectors.toList());
                comboProducts.forEach(combo -> productBean.getComboProduct().add(getOldOrderProduct(orderSettlementResps, combo)));
                if (CollectionUtils.isNotEmpty(productBean.getComboProduct())) {
                    for (ProductBeanV1 comboProductBean : productBean.getComboProduct()) {
                        if (ObjectUtils.equals(ProductTypeEnum.MATERIAL_PRODUCT.getCode(), comboProductBean.getProductType())) {
                            comboProductBean.setMaterialProduct(new ArrayList<>());
                            String addProductId = comboProductBean.getProductId() + "_" + comboProductBean.getOpid();
                            List<OrderItemResp> materialProducts = orderItemList.stream().filter(item -> ObjectUtils.equals(addProductId, item.getParentProductId())).collect(Collectors.toList());
                            materialProducts.forEach(material -> comboProductBean.getMaterialProduct().add(getOldOrderProduct(new ArrayList<>(), material)));
                        }
                    }
                }
            }
            if (ObjectUtils.equals(ProductTypeEnum.MATERIAL_PRODUCT.getCode(), orderItem.getProductType())) {
                // 获取加料子商品列表
                productBean.setMaterialProduct(new ArrayList<>());
                String partnerProductId = orderItem.getProductId() + "_" + orderItem.getProductSeq();
                List<OrderItemResp> materialProducts = orderItemList.stream().filter(item -> ObjectUtils.equals(partnerProductId, item.getParentProductId())).collect(Collectors.toList());
                materialProducts.forEach(material -> productBean.getMaterialProduct().add(getOldOrderProduct(orderSettlementResps, material)));
            }

            if (StringUtils.isNotEmpty(productBean.getExtInfo())) {
                OrderProductExtInfo extInfo = JSONObject.parseObject(productBean.getExtInfo(), OrderProductExtInfo.class);
                productBean.setIsSendGoods(null == extInfo.getIsSendGoods() ? false : extInfo.getIsSendGoods());
                productBean.setCartGoodsUid(StringUtils.isEmpty(extInfo.getCartGoodsUid()) ? "" : extInfo.getCartGoodsUid());
                productBean.setOriginalGoodsUid(StringUtils.isEmpty(extInfo.getOriginalGoodsUid()) ? "" : extInfo.getOriginalGoodsUid());
            }

            productList.add(productBean);
        }
        if (null != productList && productList.size() > 0) {
            List<ProductBeanV1> originalProductLists = productList;

            for (ProductBeanV1 sendProductBean : productList) {
                sendProductBean.setIsPrint(true);
                if (null != sendProductBean.getIsSendGoods() && sendProductBean.getIsSendGoods() && StringUtils.isNotEmpty(sendProductBean.getOriginalGoodsUid())) {
                    sendProductBean.setIsPrint(false);
                }
                if (StringUtils.isNotEmpty(sendProductBean.getCartGoodsUid()) && null != sendProductBean.getIsSendGoods() && !sendProductBean.getIsSendGoods()) {
                    sendProductBean.setSendProduct(
                            originalProductLists.stream().filter(productBean -> productBean.getOriginalGoodsUid().equalsIgnoreCase(sendProductBean.getCartGoodsUid()) && productBean.getIsSendGoods() == true)
                                    .map(o -> JSON.parseObject(JSON.toJSONString(o), ProductBeanV1.class))
                                    .collect(Collectors.toList()));
                }
            }
        }
        return productList;
    }


    private ProductBeanV1 getOldOrderProduct(List<OrderSettlementResp> orderSettlementResps, OrderItemResp orderItemResp) {
        ProductBeanV1 productBean = new ProductBeanV1();
        productBean.setWeight(orderItemResp.getWeight());
        productBean.setCustomerCode(orderItemResp.getThirdProductId());
        productBean.setProductCode(orderItemResp.getProductCode());
        productBean.setNumber(orderItemResp.getProductQuantity());
        productBean.setOpid(orderItemResp.getProductSeq() == null ? null : orderItemResp.getProductSeq().toString());
        productBean.setSequence(orderItemResp.getProductSeq() == null ? 0 : orderItemResp.getProductSeq());
        productBean.setOrderId(orderItemResp.getOrderCode());
        productBean.setProductId(orderItemResp.getProductId());
        productBean.setParentProductId("");
        productBean.setPicture(orderItemResp.getProductPicUrl());
        productBean.setPrice(orderItemResp.getProductPrice().longValue());
        productBean.setSalePrice(orderItemResp.getSalePrice().longValue());
        productBean.setProductName(orderItemResp.getProductName());
        productBean.setProductForeignName(orderItemResp.getProductForeignName());
        productBean.setSpecification(orderItemResp.getProductSpec());
        productBean.setSpecificationName(orderItemResp.getProductSpecName());
        productBean.setSpecificationForeignName(orderItemResp.getProductForeignSpecName());
        productBean.setProductSharePrice(orderItemResp.getProductSharePrice());
        productBean.setSettlementPrice(orderItemResp.getSettlementPrice().longValue());
        productBean.setUnit(orderItemResp.getProductUnit());
        Map<String, String> map = new HashMap<String, String>();
        map.put("attributeNames", orderItemResp.getProductProperty());
        map.put("attributeForeignNames", orderItemResp.getProductForeignProperty());
        productBean.setAddInfo(JSONObject.toJSONString(map));
        productBean.setProductProperty(orderItemResp.getProductProperty());
        productBean.setProductForeignProperty(orderItemResp.getProductForeignProperty());
        productBean.setExtInfo(orderItemResp.getExtInfo());
        productBean.setNote(orderItemResp.getNote());

        // 套餐
        productBean.setParentProductId(orderItemResp.getParentProductId());
        productBean.setProductType(orderItemResp.getProductType());
        productBean.setId(orderItemResp.getId());

        // 拼单类型商品加购人相关信息
        productBean.setUserId(orderItemResp.getUserId());
        productBean.setOpenId(orderItemResp.getOpenId());
        productBean.setNickName(orderItemResp.getNickName());
        productBean.setPhotoUrl(orderItemResp.getPhotoUrl());
        productBean.setPackPrice(orderItemResp.getPackPrice());

        List<ProductDiscountV1> discountList = new ArrayList<>();
        List<OrderSettlementResp> orderSettlementResps1 = orderSettlementResps == null ? new ArrayList<>() : orderSettlementResps;
        for (OrderSettlementResp orderSettlementResp : orderSettlementResps1) {
            if (ObjectUtils.equals(orderItemResp.getProductSeq(), orderSettlementResp.getProductSeq()) && orderItemResp.getProductSpec().equals(orderSettlementResp.getProductId())) {
                ProductDiscountV1 productDiscount = new ProductDiscountV1();
                productDiscount.setDiscountId(orderSettlementResp.getExternalObjectId());
                productDiscount.setDiscountDesc(orderSettlementResp.getNote());
                productDiscount.setDiscountType(OrderAccountTypeV1.getOldCode(orderSettlementResp.getSettlementType()));
                productDiscount.setDiscountPrice(orderSettlementResp.getSettlementAmount().longValue());
                productDiscount.setDiscountQty(orderSettlementResp.getNumber());
                productDiscount.setDiscountAmount(orderSettlementResp.getShopDiscountAmount());
                //无数据
                productDiscount.setCustomerCode("");
                productDiscount.setAddInfo(orderSettlementResp.getExtInfo());
                productDiscount.setProductId(orderSettlementResp.getProductId());
                productDiscount.setExtInfo(orderSettlementResp.getExtInfo());
                discountList.add(productDiscount);
            }
        }
        productBean.setDiscountList(discountList);
        return productBean;
    }


    /**
     * 老订单服务结算信息转化 order_account表
     */
    private List<AccountBeanV1> getOldOrderAccountList(List<OrderSettlementResp> orderSettlementResps, List<OrderCostResp> orderCostResps) {
        List<AccountBeanV1> accountList = new ArrayList<>();

        //新订单服务优惠信息集合
        List<OrderSettlementResp> orderSettlementResps1 = orderSettlementResps == null ? new ArrayList<>() : orderSettlementResps;
        for (OrderSettlementResp orderSettlementResp : orderSettlementResps1) {
            if ("0".equals(orderSettlementResp.getProductId()) || StringUtils.isBlank(orderSettlementResp.getProductId())) {
                //第三方外卖订单会保存优惠总金额，不计为单个类型优惠
                if (OrderSettlementType.DISCOUNT_FEE.getIndex() == orderSettlementResp.getSettlementType().intValue()) {
                    continue;
                }
                AccountBeanV1 accountBean = new AccountBeanV1();
                accountBean.setAccountId(orderSettlementResp.getExternalObjectId());
                accountBean.setOrderId("");
                accountBean.setName(orderSettlementResp.getNote());
                accountBean.setNumber(1);
                accountBean.setPrice(orderSettlementResp.getSettlementAmount() == null ? 0L : orderSettlementResp.getSettlementAmount().longValue());
                //处理第三方外卖单优惠金额信息
                if (orderSettlementResp.getSettlementAmount() != null && orderSettlementResp.getSettlementAmount().intValue() > 0) {
                    long discountFee = 0 - Math.abs(orderSettlementResp.getSettlementAmount().longValue());
                    accountBean.setPrice(discountFee);
                }
                accountBean.setSequence(orderSettlementResp.getProductSeq());
                accountBean.setType(OrderAccountTypeV1.getOldCode(orderSettlementResp.getSettlementType()));
                accountBean.setAddInfo(orderSettlementResp.getExtInfo());
                accountBean.setPlatformDiscountAmount(orderSettlementResp.getPlatformDiscountAmount());
                accountBean.setShopDiscountAmount(orderSettlementResp.getShopDiscountAmount());
                accountList.add(accountBean);
            }
        }

        //新订单 订单费用信息集合 餐盒费和包装费
        List<OrderCostResp> orderCostResps1 = orderCostResps == null ? new ArrayList<>() : orderCostResps;
        for (OrderCostResp orderCostResp : orderCostResps1) {
            AccountBeanV1 accountBean = new AccountBeanV1();
            accountBean.setAccountId(orderCostResp.getProductId());
            accountBean.setOrderId("");
            accountBean.setName(orderCostResp.getCostName());
            accountBean.setNumber(1);
            accountBean.setPrice(orderCostResp.getCostAmount().longValue());
            accountBean.setActualCostAmount(null != orderCostResp.getActualCostAmount() ? orderCostResp.getActualCostAmount().longValue() : 0);
            accountBean.setSequence(orderCostResp.getProductSeq());
            //新订单服务  1=包装费，2=运费，5=会员卡费用
            if (orderCostResp.getCostType() == 2) {
                accountBean.setType(OrderAccountTypeV1.DELIVERY_AMOUNT.getV1code());
            }
            if (orderCostResp.getCostType() == 1) {
                accountBean.setType(OrderAccountTypeV1.PACK_AMOUNT.getV1code());
            }
            if (orderCostResp.getCostType() == 5) {
                accountBean.setType(OrderAccountTypeV1.CARD_ORIGINAL_AMOUNT.getV1code());
            }
            if (orderCostResp.getCostType() == 7) {
                accountBean.setType(OrderAccountTypeV1.DRIVER_FEE.getV1code());
            }
            if (orderCostResp.getCostType() == 10) {
                accountBean.setType(OrderAccountTypeV1.WITH_ORDER_BUY_COUPON_FEE.getV1code());
            }
            accountBean.setAddInfo("");
            accountList.add(accountBean);
        }
        return accountList;
    }


    private List<RefundBeanV1> getOldOrderRefundList(List<AfterSalesOrderResp> afterSalesOrderRespList) {
        List<RefundBeanV1> refundBeans = new ArrayList<>();
        for (AfterSalesOrderResp afterSalesOrderResp : afterSalesOrderRespList) {
            RefundBeanV1 refundBean = new RefundBeanV1();
            refundBean.setOrderId(afterSalesOrderResp.getOrderCode());
            refundBean.setPrice(afterSalesOrderResp.getReqAmount() == null ? null : afterSalesOrderResp.getReqAmount().longValue());
            refundBean.setReason(afterSalesOrderResp.getAfterSalesReason());
            refundBean.setRemark(afterSalesOrderResp.getReqRemark());
            refundBean.setDecisionReason(afterSalesOrderResp.getAdultRemark());
            refundBean.setRid(afterSalesOrderResp.getAfterSalesCode());
            //售后单状态 1:待处理 2:退货中 3:拒绝退款 4:已退货 5:完成 6:取消
//            refundBean.setStatus(getOldOrderRefundStatus(afterSalesOrderResp.getAfterSalesStatus()));
            refundBean.setStatus(RefundStatusV1.getOldCodeByCodeV2(afterSalesOrderResp.getAfterSalesStatus()));
            refundBean.setCreateTime(afterSalesOrderResp.getCreateTime());
            refundBean.setExtInfo(afterSalesOrderResp.getExtInfo());
            if (StringUtils.isNotBlank(afterSalesOrderResp.getExtInfo())) {
                AfterOrderExtInfoDto extInfoDto = JSONObject.parseObject(afterSalesOrderResp.getExtInfo(), new TypeReference<AfterOrderExtInfoDto>() {
                }.getType());
                if (extInfoDto != null) {
                    RefundModeEnum refundModeEnum;
                    if ((refundModeEnum = RefundModeEnum.getByIndex(extInfoDto.getRefundMode())) != null) {
                        refundBean.setRefundMode(refundModeEnum.getIndex());
                        refundBean.setRefundModeDesc(refundModeEnum.getName());
                    }
                    refundBean.setBatchRefundId(extInfoDto.getBatchRefundId());
                }

            }

            refundBeans.add(refundBean);
        }
        return refundBeans;
    }


    private List<OperationHistoryV1> getOrderOperationHistory(List<OrderOperationHistoryResp> orderOperationHistoryResps) {
        List<OperationHistoryV1> operationHistories = new ArrayList<>();
        if (orderOperationHistoryResps == null) {
            return operationHistories;
        }
        for (OrderOperationHistoryResp operationHistoryResp : orderOperationHistoryResps) {
            OperationHistoryV1 operationHistory = new OperationHistoryV1();
            operationHistory.setCreateTime(operationHistoryResp.getCreateTime());
            operationHistory.setOperationDesc(operationHistoryResp.getOperationDesc());
            operationHistory.setOperationMethod(operationHistoryResp.getOperationMethod());
            operationHistory.setOrderCode(operationHistoryResp.getOrderCode());
            operationHistory.setOperationType(operationHistoryResp.getOperationType());
            operationHistory.setPartnerId(operationHistoryResp.getPartnerId());
            operationHistory.setStoreId(operationHistoryResp.getStoreId());
            operationHistory.setOperator(operationHistoryResp.getOperator());
            operationHistory.setUpdateTime(operationHistoryResp.getUpdateTime());
            operationHistory.setUpdateTimestamp(operationHistoryResp.getUpdateTimestamp());
            operationHistories.add(operationHistory);
        }
        return operationHistories;
    }


    /**
     * 均摊明细
     *
     * @param orderInfoReqs
     * @return
     */
    private List<OrderSettlementResp> getApportionDetails(OrderInfoReqs orderInfoReqs) {
        List<OrderSettlementResp> orderSettlementList = new ArrayList<>();

        List<OrderSettlementResp> orderSettlements = orderInfoReqs.getOrderSettlementDetailList();
        if (CollectionUtils.isNotEmpty(orderSettlements)) {
            Map<String, OrderItemResp> orderItemMap = orderInfoReqs.getOrderItemList().stream().collect(Collectors.toMap(OrderItemResp::getPartnerId, orderItemResp -> orderItemResp, (key1, key2) -> key2));
            for (OrderSettlementResp orderSettlementResp : orderSettlements) {
                OrderSettlementResp orderSettlement = new OrderSettlementResp();
                orderSettlement.setProductId(orderSettlementResp.getProductId());
                if (orderItemMap.get(orderSettlementResp.getProductId()) != null) {
                    orderSettlement.setProductName(orderItemMap.get(orderSettlementResp.getProductId()).getProductName());
                }
                orderSettlement.setProductSeq(orderSettlementResp.getProductSeq());
                orderSettlement.setExternalObjectId(orderSettlementResp.getExternalObjectId());
                orderSettlement.setExternalObjectName(orderSettlementResp.getExternalObjectName());
                orderSettlement.setExternalObjectSubId(null);
                orderSettlement.setIgnoreInDiscountAmount(orderSettlementResp.getIgnoreInDiscountAmount());
                orderSettlement.setSettlementType(orderSettlementResp.getSettlementType());
                if(orderSettlementResp.getSettlementType() == null){
                    orderSettlement.setSettlementTypeName("");
                }else if ( Objects.equals(orderSettlementResp.getSettlementType(), 23) && "setMeal".equals(orderSettlementResp.getExternalObjectId())) {
                    orderSettlement.setSettlementTypeName("套餐");
                } else {
                    orderSettlement.setSettlementTypeName(OrderSettlementType.getNameByIndex(orderSettlementResp.getSettlementType()));
                }
                orderSettlement.setSettlementAmount(orderSettlementResp.getSettlementAmount());
                orderSettlement.setNote(orderSettlementResp.getNote());
                orderSettlement.setNumber(orderSettlementResp.getNumber());
                orderSettlement.setPlatformDiscountAmount(orderSettlementResp.getPlatformDiscountAmount());
                orderSettlement.setShopDiscountAmount(orderSettlementResp.getShopDiscountAmount());
                orderSettlement.setAgentDiscountAmount(orderSettlementResp.getAgentDiscountAmount());
                orderSettlement.setCarrierDiscountAmount(orderSettlementResp.getCarrierDiscountAmount());
                orderSettlement.setShopAmount(orderSettlementResp.getShopAmount());
                orderSettlement.setPlatformServiceAmount(orderSettlementResp.getPlatformServiceAmount());
                if (orderSettlementResp.getProspectiveAmount() != null) {
                    orderSettlement.setProspectiveAmount(orderSettlementResp.getProspectiveAmount());
                } else {
                    orderSettlement.setProspectiveAmount(new BigDecimal(0));
                }
                orderSettlementList.add(orderSettlement);
            }
        }
        return orderSettlementList;
    }



    /**
     * 混合支付转换
     *
     * @param OrderPayItemReqs
     */
    private List<OrderPayItemResp> getOrderItemPayList(List<OrderPayItemResp> OrderPayItemReqs) {
        List<OrderPayItemResp> OrderPayItemList = new ArrayList<>(2);
        for (OrderPayItemResp orderPayItemReq : OrderPayItemReqs) {
            OrderPayItemResp orderPayItem = new OrderPayItemResp();
            orderPayItem.setOrderCode(orderPayItemReq.getOrderCode());
            orderPayItem.setOrderPayItemCode(orderPayItemReq.getOrderPayItemCode());
            orderPayItem.setPayAmount(orderPayItemReq.getPayAmount());
            orderPayItem.setPayChannelName(orderPayItemReq.getPayChannelName());
            orderPayItem.setPayChannelType(orderPayItemReq.getPayChannelType());
            orderPayItem.setTransId(orderPayItemReq.getTransId());
            OrderPayItemList.add(orderPayItem);
        }
        return OrderPayItemList;
    }






    /**
     * 新订单类型转换老订单类型
     */
    public Integer getOldOrderType(Integer type) {
        //订单服务订单类型 1=外卖 4=自提，5=堂食
        //外卖平台订单类型 1=常规堂食，2=预约堂食，3=常规外送，4=预约外送，5=常规自取，6=预约自取
        switch (type) {
            case 1:
                type = OrderTypeV1.EAT_IN.getCode();
                break;
            case 2:
                type = OrderTypeV1.EAT_IN.getCode();
                break;
            case 3:
                type = OrderTypeV1.TAKE_OUT.getCode();
                break;
            case 4:
                type = OrderTypeV1.TAKE_OUT.getCode();
                break;
            case 5:
                type = OrderTypeV1.COLLECT_GOODS.getCode();
                break;
            case 6:
                type = OrderTypeV1.COLLECT_GOODS.getCode();
                break;
            default:
                break;
        }

        return type;
    }

//    /**
//     * 优惠类型描述
//     *
//     * @param settlementType
//     * @return
//     */
//    private String getOrderSettlementTypeName(int settlementType) {
//        // 新订单服务枚举 OrderSettlementType
//        String name = "";
//        switch (settlementType) {
//            case 2:
//                name = OrderSettlementType.FULL_REDUCTION.getName();
//                break;
//            case 3:
//                name = OrderSettlementType.COUPON.getName();
//                break;
//            case 4:
//                name = OrderSettlementType.GIFT_GIVING.getName();
//                break;
//            case 5:
//                name = OrderSettlementType.FULL_GIFTS.getName();
//                break;
//            case 10:
//                name = OrderSettlementType.CASH_COUPON.getName();
//                break;
//            case 12:
//                name = OrderSettlementType.INCREASE_PURCHASE.getName();
//                break;
//            case 20:
//                name = OrderSettlementType.ITEM_DISCOUNT.getName();
//                break;
//            case 23:
//                name = OrderSettlementType.ONE_BY_ONE.getName();
//                break;
//            case 46:
//                name = OrderSettlementType.INCREASE_PURCHASE.getName();
//                break;
//            case 118:
//                name = OrderSettlementType.PRODUCT_COUPON.getName();
//                break;
//            case 200:
//                name = OrderSettlementType.POINTS.getName();
//                break;
//            case 206:
//                name = OrderSettlementType.ITEM_SPECIAL_PRICE.getName();
//                break;
//            case 207:
//                name = OrderSettlementType.ONE_BY_ONE.getName();
//                break;
//            case 208:
//                name = OrderSettlementType.DISCOUNT_COUPON.getName();
//                break;
//            case 1014:
//                name = OrderSettlementType.FULL_DISTRIBUTION_FEE.getName();
//                break;
//            default:
//                break;
//        }
//        return name;
//    }


    private OrderExtendedReq getOrderExtendedObj(OrderExtendedReq orderExtended) {
        if (Objects.isNull(orderExtended)) {
            return null;
        }
        return OrderExtendedReq.builder().orderClientGroup(orderExtended.getOrderClientGroup())
                .orderClientGroupCode(orderExtended.getOrderClientGroupCode())
                .storeNameEn(orderExtended.getStoreNameEn())
                .spellGroupCode(orderExtended.getSpellGroupCode())
                .userPhone(orderExtended.getUserPhone())
                .sendWord(orderExtended.getSendWord())
                .agentPayerId(orderExtended.getAgentPayerId())
                .agentPayerName(orderExtended.getAgentPayerName())
                .build();
    }

}
