package cn.freemud.adapter;

import cn.freemud.base.util.DateUtil;
import cn.freemud.entities.dto.QueryOrdersResponseDto;
import cn.freemud.entities.vo.CreateDeliveryVo;
import cn.freemud.entities.vo.ProductInfo;
import cn.freemud.enums.DeliveryChannelEnum;
import cn.freemud.enums.OrderSourceType;
import cn.freemud.enums.OrderType;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.freemud.application.sdk.api.deliverycenter.dto.CreateDeliveryOrderRequestDto;
import com.freemud.application.sdk.api.ordercenter.request.OrderExtInfoDto;
import com.freemud.application.sdk.api.storecenter.response.StoreResponse;
import com.freemud.sdk.api.assortment.order.request.order.CreateOrderProductRequest;
import com.freemud.sdk.api.assortment.order.request.order.OrderProductAddInfoDto;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.lang.StringUtils;
import org.springframework.stereotype.Component;

import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;

@Component
public class DeliveryAdapter {




    public CreateDeliveryOrderRequestDto convertToWeixinDeliveryOrderRequestDto(QueryOrdersResponseDto.DataBean.OrderBean orderBean, StoreResponse storeInfo, String accessToken, String deliveryCallBackUrl) {
        CreateDeliveryOrderRequestDto deliveryOrderRequestDto = new CreateDeliveryOrderRequestDto();

        OrderExtInfoDto orderExtInfoDto = JSONObject.parseObject(orderBean.getExtInfo(), OrderExtInfoDto.class) == null ? new OrderExtInfoDto() : JSONObject.parseObject(orderBean.getExtInfo(), OrderExtInfoDto.class);

        deliveryOrderRequestDto.setDeliveryChannel(DeliveryChannelEnum.WEIXIN.getCode());
        deliveryOrderRequestDto.setAccessToken(accessToken);
        deliveryOrderRequestDto.setOpenId(orderExtInfoDto.getOpenid());
        deliveryOrderRequestDto.setWxAppId(orderExtInfoDto.getAppid());
        BigDecimal weight = (orderBean.getWeight() == null || new BigDecimal("0").compareTo(orderBean.getWeight()) == 0) ? new BigDecimal("1") : orderBean.getWeight();
        deliveryOrderRequestDto.setDepatchWeight(weight.divide(new BigDecimal("1000"))); //克转化为千克
        deliveryOrderRequestDto.setSerialNumber(orderBean.getDaySeq().toString());
        deliveryOrderRequestDto.setOrderId(orderBean.getOid());
        deliveryOrderRequestDto.setOrderRemark(orderBean.getRemark());
        deliveryOrderRequestDto.setOrderTotalAmount(orderBean.getAmount().intValue() == 0 ? 1 : orderBean.getAmount().intValue());
        deliveryOrderRequestDto.setOrderActualAmount(orderBean.getAmount().intValue() == 0 ? 1 : orderBean.getAmount().intValue());
        deliveryOrderRequestDto.setPartnerId(orderBean.getCompanyId());
        deliveryOrderRequestDto.setOrderChannel(orderBean.getSource());
        deliveryOrderRequestDto.setIsPre(0);
        deliveryOrderRequestDto.setStoreId(storeInfo.getBizVO().getStoreId());
        deliveryOrderRequestDto.setStoreCode(storeInfo.getBizVO().getStoreCode());
        deliveryOrderRequestDto.setStoreAddress(storeInfo.getBizVO().getAddress());
        deliveryOrderRequestDto.setStoreLng(new BigDecimal(storeInfo.getBizVO().getLongitude()));
        deliveryOrderRequestDto.setStoreLat(new BigDecimal(storeInfo.getBizVO().getLatitude()));
        deliveryOrderRequestDto.setStorePhone(storeInfo.getBizVO().getPhone());
        deliveryOrderRequestDto.setStoreName(orderBean.getShopName());
        deliveryOrderRequestDto.setStoreProvince(storeInfo.getBizVO().getProvince());
        deliveryOrderRequestDto.setStoreCity(storeInfo.getBizVO().getCity());
        deliveryOrderRequestDto.setStoreArea(storeInfo.getBizVO().getRegion());
        deliveryOrderRequestDto.setStoreContact(StringUtils.isEmpty(storeInfo.getBizVO().getStoreContacts()) ? storeInfo.getBizVO().getStoreName() : storeInfo.getBizVO().getStoreContacts());

        deliveryOrderRequestDto.setReceiverName(orderBean.getUserName());
        deliveryOrderRequestDto.setReceiverPrimaryPhone(orderBean.getPhone());
        deliveryOrderRequestDto.setReceiverAddress(orderBean.getAddress());
        deliveryOrderRequestDto.setReceiverLng(new BigDecimal(orderBean.getLongitude()));
        deliveryOrderRequestDto.setReceiverLat(new BigDecimal(orderBean.getLatitude()));
        deliveryOrderRequestDto.setProvinceName(orderBean.getReceiveProvince());
        deliveryOrderRequestDto.setCityName(orderBean.getReceiveCity());
        deliveryOrderRequestDto.setAreaName(orderBean.getReceiveRegion());
        deliveryOrderRequestDto.setOrderTime(new Date(orderBean.getGmtCreate()));
        deliveryOrderRequestDto.setCallbackUrl(deliveryCallBackUrl);
        deliveryOrderRequestDto.setWxaPath("pages/index");

        List<CreateDeliveryOrderRequestDto.DeliveryProductInfo> productInfos = new ArrayList<>();
        orderBean.getProductList().forEach(productList -> {
            CreateDeliveryOrderRequestDto.DeliveryProductInfo deliveryProductInfo = new CreateDeliveryOrderRequestDto.DeliveryProductInfo();
            deliveryProductInfo.setProductCode(productList.getProductId());
            deliveryProductInfo.setProductName(productList.getProductName());
            deliveryProductInfo.setProductNumber(productList.getNumber());
            deliveryProductInfo.setProductPrice(productList.getPrice().intValue());
            deliveryProductInfo.setProductImg(productList.getPicture());
            productInfos.add(deliveryProductInfo);
        });
        deliveryOrderRequestDto.setProductInfos(productInfos);

        return deliveryOrderRequestDto;
    }


    /**
     * 创建配送单请求对象
     *
     * @param order
     * @param storeInfo
     * @return
     */
    public CreateDeliveryVo buildDeliveryOrderRequestDto(QueryOrdersResponseDto.DataBean.OrderBean order
            , StoreResponse storeInfo, String deliveryCallBackUrl, String displayOrderId ) {

        SimpleDateFormat simpleDateFormat =new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");

        CreateDeliveryVo deliveryOrderRequestDto = new CreateDeliveryVo();
        OrderExtInfoDto orderExtInfoDto = JSON.parseObject(order.getExtInfo(), OrderExtInfoDto.class);
        deliveryOrderRequestDto.setInvoiceTitle(orderExtInfoDto.getInvoiceTitle());
        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);
        // 预约单预计送到时间
        if (order.getGmtExpect() != null && order.getGmtExpect() != 0) {
            deliveryOrderRequestDto.setExpectTime(new Date(order.getGmtExpect()));
        }
        deliveryOrderRequestDto.setIsPre(order.getType() == OrderType.PRE_ORDER.getCode() ? 1 : 0);

        //---麦咖啡餐道专用---
        deliveryOrderRequestDto.setDisplayOrderId(displayOrderId);
        deliveryOrderRequestDto.setTaxFlag(0);
        if (CollectionUtils.isNotEmpty(order.getAccountList())) {
            List<QueryOrdersResponseDto.DataBean.OrderBean.AccountBean> collect = order.getAccountList().stream().filter(type -> type != null && !type.equals(1)).collect(Collectors.toList());
            if (CollectionUtils.isNotEmpty(collect)) {
                //配送费
                deliveryOrderRequestDto.setDeliveryTotal(collect.get(0).getPrice().intValue());
            }
        }
        deliveryOrderRequestDto.setIsPayed(1);
        deliveryOrderRequestDto.setTenderType("WeChat");
        deliveryOrderRequestDto.setIsLargeOrder(0);
        if (deliveryOrderRequestDto.getIsPre()== 1 && deliveryOrderRequestDto.getExpectTime() !=null){
            deliveryOrderRequestDto.setIsImmediateDelivery(0);
            deliveryOrderRequestDto.setExpectDeliveryTimeByUTC(simpleDateFormat.format(deliveryOrderRequestDto.getExpectTime()));
        }else {
            deliveryOrderRequestDto.setIsImmediateDelivery(1);
            String expectDeliveryTimeByUTC = order.getGmtCreate() !=null ? simpleDateFormat.format(DateUtil.addMinutes(new Date(order.getGmtCreate()),30)) :null;
            deliveryOrderRequestDto.setExpectDeliveryTimeByUTC(expectDeliveryTimeByUTC);
        }
        //---麦咖啡餐道专用---

        List<ProductInfo> productInfos = new ArrayList<>();
        order.getProductList().forEach(productList -> {
            if (productList.getPrice() > 0) {
                ProductInfo deliveryProductInfo = new ProductInfo();
                deliveryProductInfo.setProductCode(productList.getProductId());
                deliveryProductInfo.setProductName(productList.getProductName());
                deliveryProductInfo.setProductNumber(productList.getNumber());
                deliveryProductInfo.setProductPrice(productList.getPrice().intValue());
                //餐道使用
                deliveryProductInfo.setCumulatedTotal(productList.getNumber() * productList.getPrice().intValue());
                OrderProductAddInfoDto orderProductAddInfoDto = JSON.parseObject(productList.getAddInfo(), OrderProductAddInfoDto.class);
                deliveryProductInfo.setTaxId(orderProductAddInfoDto.getTaxId());
                deliveryProductInfo.setTaxRate(orderProductAddInfoDto.getTax());
                deliveryProductInfo.setParentCode(Long.valueOf(productList.getParentProductId()));

                productInfos.add(deliveryProductInfo);
            }
        });
        deliveryOrderRequestDto.setProductInfos(productInfos);
        deliveryOrderRequestDto.setOrderSource(OrderSourceType.ALIPAY.getCode().equals(order.getSource())?"Alipay":"freemud");
        return deliveryOrderRequestDto;
    }

}


