package cn.freemud.adapter;

import cn.freemud.base.util.DateUtil;
import cn.freemud.entities.dto.OrderPrintDto;
import cn.freemud.enums.CostTypeEnum;
import com.alibaba.fastjson.JSON;
import com.freemud.application.sdk.api.ordercenter.enums.ProductTypeEnum;
import com.freemud.application.sdk.api.ordercenter.response.orderInfo.OrderCostResp;
import com.freemud.application.sdk.api.ordercenter.response.orderInfo.OrderInfoReqs;
import com.freemud.application.sdk.api.ordercenter.response.orderInfo.OrderItemResp;
import com.freemud.sdk.api.assortment.order.enums.StoreDeliveryMethod;
import com.google.common.collect.Lists;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.lang.StringUtils;

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

/**
 * @author Clover.z
 * @version 1.0.0
 * @since 1.0.0
 */
public class OrderPrintDtoAdapter {

    public static OrderPrintDto convert(OrderInfoReqs order, String reason) {
        OrderPrintDto orderPrintDto = new OrderPrintDto();
        orderPrintDto.setPartnerId(order.getPartnerId());
        orderPrintDto.setStoreId(order.getStoreId());
        //确定日订单序号
        orderPrintDto.setType(order.getOrderType());
        orderPrintDto.setOid(order.getOrderCode());
        orderPrintDto.setUserName(order.getUserName());
        orderPrintDto.setDaySeq(order.getDaySeq() == null ? "" : order.getDaySeq().toString());
        orderPrintDto.setPhone(order.getUserMobile());
        if (CollectionUtils.isNotEmpty(order.getDeliveryContactInfoList())) {
            order.getDeliveryContactInfoList().stream().filter(c -> Objects.equals(c.getRelateObjectType(), 1))
                    .findFirst().ifPresent(c -> orderPrintDto.setAddress(c.getAddressDetail()));
            order.getDeliveryContactInfoList().stream().filter(c -> Objects.equals(c.getRelateObjectType(), 3))
                    .findFirst().ifPresent(c -> {
                        if (Objects.equals(c.getAddressDetail(), StoreDeliveryMethod.THIRD.getCode())) {
                            orderPrintDto.setDeliveryTypeDesc("第三方配送");
                            if (StringUtils.isNotBlank(order.getExpressChannelName())) {
                                orderPrintDto.setDeliveryTypeDesc(order.getExpressChannelName());
                            }
                        } else {
                            orderPrintDto.setDeliveryTypeDesc("自配送");
                        }
            });
        }
        orderPrintDto.setGmtExpect(order.getExpectTime() == null
                ? "立即送出"
                : (DateUtil.convert2String(new Date(Long.parseLong(order.getExpectTime())), DateUtil.FORMAT_YYYY_MM_DD_HHMMSS)));
        orderPrintDto.setRemark(order.getNote());
        Integer count = order.getOrderItemList().stream().map(OrderItemResp::getProductQuantity).reduce(Integer::sum).get();
        orderPrintDto.setProductTotalAmount(count);
        Long packageFee = 0L;
        long sendFee = 0L;
        if (CollectionUtils.isNotEmpty(order.getOrderCostDetailList())) {
            for (OrderCostResp cost : order.getOrderCostDetailList()) {
                if (CostTypeEnum.PACK_AMOUNT.getCode().equals(cost.getCostType())) {
                    packageFee = cost.getActualCostAmount().longValue();
                } else if (CostTypeEnum.DELIVERY_AMOUNT.getCode().equals(cost.getCostType())) {
                    sendFee = cost.getActualCostAmount().longValue();
                }
            }
        }
        orderPrintDto.setPackageFee(packageFee);
        orderPrintDto.setProductAmount(order.getSettlementAmount().longValue() - sendFee);
        orderPrintDto.setSendFee(sendFee);
        orderPrintDto.setDiscountFee(order.getOriginalAmount().longValue() - order.getSettlementAmount().longValue());
        orderPrintDto.setUserFee(order.getActualPayAmount().longValue());
        orderPrintDto.setGmtCreate(DateUtil.convert2String(new Date(Long.parseLong(order.getCreateTime())), DateUtil.FORMAT_YYYY_MM_DD_HHMMSS));
        orderPrintDto.setShopName(order.getStoreName());
        orderPrintDto.setOtherCode(order.getPickUpGoodsNo());
        List<OrderPrintDto.ProductsBean> productsBeans = getProducts(order.getOrderItemList());
        orderPrintDto.setProducts(productsBeans);
        orderPrintDto.setBarCounter(order.getBarCounter());
        orderPrintDto.setRemark(reason);
        return orderPrintDto;
    }


    public static List<OrderPrintDto.ProductsBean> getProducts(List<OrderItemResp> itemList) {
        if (CollectionUtils.isEmpty(itemList)) {
            return Collections.emptyList();
        }
        List<OrderPrintDto.ProductsBean> products = Lists.newArrayList();
        // 将订单里同一商品下的所有子商品放到一个集合中  key：父商品id， value为子商品集合
        Map<String, List<OrderItemResp>> sItemMap = itemList
                .stream()
                .filter(item -> !item.getParentProductId().equals("0"))
                .collect(Collectors.groupingBy(OrderItemResp::getParentProductId));
        for (OrderItemResp item : itemList) {
            //非主商品跳过
            if (!item.getParentProductId().equals("0")) continue;
            OrderPrintDto.ProductsBean productVO = getProductBean(item);
            //匹配子商品
            List<OrderItemResp> sList = sItemMap.get(item.getProductId() + "_" + item.getProductSeq());
            List<OrderPrintDto.ProductsBean> comboProductVOs = new ArrayList<>();
            List<OrderPrintDto.ProductsBean> materialProductVOs = new ArrayList<>();
            if (CollectionUtils.isNotEmpty(sList)) {
                sList.forEach(sItem -> {
                    OrderPrintDto.ProductsBean son = getProductBean(sItem);
                    if (ProductTypeEnum.MATERIAL_PRODUCT.getCode().equals(sItem.getProductType())) {
                        materialProductVOs.add(son);
                    } else {
                        comboProductVOs.add(son);
                    }
                });
            }
            productVO.setSonProducts(comboProductVOs);
            productVO.setMaterialProducts(materialProductVOs);
            products.add(productVO);
        }
        return products;
    }

    private static OrderPrintDto.ProductsBean getProductBean(OrderItemResp item) {
        OrderPrintDto.ProductsBean productBean1 = new OrderPrintDto.ProductsBean();
        productBean1.setParentProductId(item.getParentProductId());
        productBean1.setSequence(item.getProductSeq());
        productBean1.setProductId(item.getProductSpec());
        productBean1.setProductName(item.getProductSpecName());
        productBean1.setNumber(item.getProductQuantity());
        String extraName = "";
        if (StringUtils.isNotBlank(item.getExtInfo())) {
            OrderItemResp.ExtInfo itemExt = JSON.parseObject(item.getExtInfo(), OrderItemResp.ExtInfo.class);
            if (CollectionUtils.isNotEmpty(itemExt.getSpecialAttrs())) {
                extraName = StringUtils.join(itemExt.getSpecialAttrs().stream()
                        .map(OrderItemResp.ExtAttr::getExtraName)
                        .collect(Collectors.toList()), "/");
            }
        }
        productBean1.setPrice(item.getProductPrice().longValue());
        productBean1.setProductOtherInfo(extraName);
        productBean1.setParentType(item.getProductType());
        productBean1.setSonProducts(new ArrayList<>());
        productBean1.setUnit(item.getProductUnit());
        productBean1.setProductSpuQuantity(item.getProductSpuQuantity());
        return productBean1;
    }
}
