package cn.freemud.management.adapter;

import cn.freemud.management.entities.dto.request.order.OrderManagerRequest;
import cn.freemud.management.enums.DeliveryStatus;
import com.freemud.application.sdk.api.deliverycenter.dto.CreateDeliveryOrderRequestDto;
import com.freemud.application.sdk.api.ordercenter.enums.OrderType;
import com.freemud.application.sdk.api.ordercenter.request.OrderExpressReq;
import com.freemud.application.sdk.api.storecenter.response.StoreResponse;
import com.freemud.sdk.api.assortment.order.enums.QueryDeliveryType;
import com.freemud.sdk.api.assortment.order.response.order.QueryOrdersResponse;
import org.apache.commons.lang.math.NumberUtils;
import org.springframework.stereotype.Component;

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

@Component
public class DeliverySdkAdapter {
    /**
     * 创建配送单请求对象
     *
     * @param order
     * @param storeInfo
     * @param deliveryCallBackUrl
     * @return
     */
    public CreateDeliveryOrderRequestDto buildDeliveryOrderRequestDto(QueryOrdersResponse.DataBean.OrderBean order
            , StoreResponse storeInfo, String deliveryCallBackUrl) {

        CreateDeliveryOrderRequestDto deliveryOrderRequestDto = new CreateDeliveryOrderRequestDto();
        deliveryOrderRequestDto.setDepatchWeight(new BigDecimal(1));
        deliveryOrderRequestDto.setSerialNumber(order.getOtherCode());
        deliveryOrderRequestDto.setOrderId(order.getOid());
        deliveryOrderRequestDto.setOrderRemark(order.getRemark());
        deliveryOrderRequestDto.setOrderTotalAmount(order.getAmount().intValue());
        deliveryOrderRequestDto.setOrderActualAmount(order.getAmount().intValue());
        deliveryOrderRequestDto.setPartnerId(order.getCompanyId());
        deliveryOrderRequestDto.setOrderChannel(order.getSource());
        deliveryOrderRequestDto.setStoreId(storeInfo.getBizVO().getStoreId());
        deliveryOrderRequestDto.setStoreCode(storeInfo.getBizVO().getStoreCode());
        StringBuffer address = new StringBuffer(storeInfo.getBizVO().getCity())
                .append(storeInfo.getBizVO().getProvince())
                .append(storeInfo.getBizVO().getRegion())
                .append(storeInfo.getBizVO().getAddress());
        deliveryOrderRequestDto.setStoreAddress(address.toString());
        deliveryOrderRequestDto.setStoreLng(new BigDecimal(storeInfo.getBizVO().getLongitude()));
        deliveryOrderRequestDto.setStoreLat(new BigDecimal(storeInfo.getBizVO().getLatitude()));
        deliveryOrderRequestDto.setStorePhone(storeInfo.getBizVO().getPhone());
        deliveryOrderRequestDto.setStoreName(order.getShopName());
        deliveryOrderRequestDto.setCityName(storeInfo.getBizVO().getCity());
        deliveryOrderRequestDto.setReceiverName(order.getUserName());
        deliveryOrderRequestDto.setReceiverPrimaryPhone(order.getPhone());
        deliveryOrderRequestDto.setReceiverAddress(order.getAddress());
        deliveryOrderRequestDto.setReceiverLng(new BigDecimal(order.getLongitude()));
        deliveryOrderRequestDto.setReceiverLat(new BigDecimal(order.getLatitude()));
        deliveryOrderRequestDto.setOrderTime(new Date(order.getGmtCreate()));
        deliveryOrderRequestDto.setCallbackUrl(deliveryCallBackUrl);
        deliveryOrderRequestDto.setOrderClient(NumberUtils.toInt(order.getOrderClient()));
        // 预约单预计送到时间
        if (order.getGmtExpect() != null && order.getGmtExpect() != 0) {
            deliveryOrderRequestDto.setExpectTime(new Date(order.getGmtExpect()));
        }
        deliveryOrderRequestDto.setIsPre(order.getNewOrderType() == OrderType.RESERVED_EXPRESS.getIndex() ? 1 : 0);
        Optional.ofNullable(order.getProductList())
                .ifPresent(productList ->
                        deliveryOrderRequestDto.setProductInfos(productList.stream()
                                .filter(productBean -> Objects.nonNull(productBean.getPrice()))
                                .filter(productBean -> productBean.getPrice() > 0)
                                .map(productBean -> {
                                    CreateDeliveryOrderRequestDto.DeliveryProductInfo deliveryProductInfo = new CreateDeliveryOrderRequestDto.DeliveryProductInfo();
                                    deliveryProductInfo.setProductCode(productBean.getProductId());
                                    deliveryProductInfo.setProductName(productBean.getProductName());
                                    deliveryProductInfo.setProductNumber(productBean.getNumber());
                                    deliveryProductInfo.setProductPrice(productBean.getPrice().intValue());
                                    return deliveryProductInfo;
                                }).collect(Collectors.toCollection(LinkedList::new))));
        return deliveryOrderRequestDto;
    }

    /**
     * 构建配送状态和信息
     *
     * @param request
     * @param deliveryStatus
     * @return
     */
    public OrderExpressReq buildOrderExpressReq(OrderManagerRequest request, DeliveryStatus deliveryStatus) {
        OrderExpressReq expressReq = new OrderExpressReq();
        expressReq.setOrderCode(request.getOrderId());
        //设置自配送--三方订单（美团、饿了么）使用订单表中 expressTyp， saas订单根据delivery_info表中 配送员 的 addressDetail字段为self
        expressReq.setOrderSubState(deliveryStatus.getCode());
        expressReq.setOperator(request.getOperator());
        expressReq.setRemark(request.getReason());

        //修改配送员  为infoType=0,address_detail为self，
        switch (deliveryStatus) {
            case RIDERSTARTDELIVERY:
                expressReq.setOpType(1);
                expressReq.setContactsName("");
                expressReq.setMobile("");
                expressReq.setAddressDetail(QueryDeliveryType.SELF.getCode());

                break;
            default:
                break;
        }

        return expressReq;
    }
}
