package cn.freemud.adapter;

import cn.freemud.base.util.DateUtil;
import cn.freemud.entities.dto.QueryOrdersResponseDto;
import cn.freemud.entities.vo.CreateDeliveryPreferentialVo;
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.enums.OldOrderAccountType;
import com.freemud.sdk.api.assortment.order.enums.QueryOrderAccountType;
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;

import static java.util.stream.Collectors.toList;

@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'T'HH:mm:ss'Z'");

        CreateDeliveryVo deliveryOrderRequestDto = new CreateDeliveryVo();
        OrderExtInfoDto orderExtInfoDto = JSON.parseObject(order.getExtInfo(), OrderExtInfoDto.class);
        deliveryOrderRequestDto.setInvoiceTitle(orderExtInfoDto.getInvoiceTitle());
        deliveryOrderRequestDto.setDepatchWeight(order.getWeight());
        //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(DateUtil.addHours(new Date(order.getGmtCreate()), -8));
        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(1);
        if (CollectionUtils.isNotEmpty(order.getAccountList())) {
            List<QueryOrdersResponseDto.DataBean.OrderBean.AccountBean> collect = order.getAccountList().stream().filter(account -> account != null && OldOrderAccountType.DELIVERY_AMOUNT.getCode().equals(account.getType())).collect(Collectors.toList());
            if (CollectionUtils.isNotEmpty(collect)) {
                //配送费
                deliveryOrderRequestDto.setDeliveryTotal(collect.get(0).getPrice().intValue());
            }
        }else {
            deliveryOrderRequestDto.setDeliveryTotal(0);
        }
        deliveryOrderRequestDto.setIsPayed(1);
        deliveryOrderRequestDto.setTenderType("WeChat");
        deliveryOrderRequestDto.setIsLargeOrder(0);
        if (deliveryOrderRequestDto.getIsPre()== 1 && deliveryOrderRequestDto.getExpectTime() !=null){
            deliveryOrderRequestDto.setIsImmediateDelivery(0);
            deliveryOrderRequestDto.setExpectDeliveryTimeByUTC(simpleDateFormat.format(DateUtil.addHours(deliveryOrderRequestDto.getExpectTime(), -8)));
        }else {
            deliveryOrderRequestDto.setIsImmediateDelivery(1);
            String expectDeliveryTimeByUTC = order.getGmtCreate() !=null ?
                    simpleDateFormat.format(DateUtil.addHours(DateUtil.addMinutes(new Date(order.getGmtCreate()),storeInfo.getBizVO().getServiceTime()), -8)) :null;
            deliveryOrderRequestDto.setExpectDeliveryTimeByUTC(expectDeliveryTimeByUTC);
        }
        //---麦咖啡餐道专用---

        List<ProductInfo> productInfos = new ArrayList<>();
        if (CollectionUtils.isNotEmpty(order.getProductList())) {
            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(StringUtils.isNotEmpty(orderProductAddInfoDto.getTaxId()) ? orderProductAddInfoDto.getTaxId() : "10");
                    deliveryProductInfo.setTaxRate(orderProductAddInfoDto.getTax() > 0 ? orderProductAddInfoDto.getTax() : 6);
                    deliveryProductInfo.setParentCode(Long.valueOf(productList.getParentProductId()) == 0l ? -1l : Long.valueOf(productList.getParentProductId()));

                    productInfos.add(deliveryProductInfo);

                    if(CollectionUtils.isNotEmpty(productList.getComboProduct())) {
                        productList.getComboProduct().forEach(comboProduct -> {
                            ProductInfo deliveryComboProductInfo = new ProductInfo();
                            deliveryComboProductInfo.setProductCode(comboProduct.getProductId());
                            deliveryComboProductInfo.setProductName(comboProduct.getProductName());
                            deliveryComboProductInfo.setProductNumber(comboProduct.getNumber());
                            deliveryComboProductInfo.setProductPrice(comboProduct.getPrice().intValue());
                            //餐道使用
                            deliveryComboProductInfo.setCumulatedTotal(comboProduct.getNumber() * comboProduct.getPrice().intValue());
                            OrderProductAddInfoDto orderComboProductAddInfoDto = JSON.parseObject(comboProduct.getAddInfo(), OrderProductAddInfoDto.class);
                            deliveryComboProductInfo.setTaxId(StringUtils.isNotEmpty(orderComboProductAddInfoDto.getTaxId()) ? orderComboProductAddInfoDto.getTaxId() : "10");
                            deliveryComboProductInfo.setTaxRate(orderComboProductAddInfoDto.getTax() > 0 ? orderComboProductAddInfoDto.getTax() : 6);
                            deliveryComboProductInfo.setParentCode(Long.valueOf(comboProduct.getParentProductId()) == 0l ? -1l : Long.valueOf(comboProduct.getParentProductId()));

                            productInfos.add(deliveryComboProductInfo);
                        });
                    }
                }
            });
            deliveryOrderRequestDto.setProductTotal(productInfos.stream().mapToInt(t -> t.getCumulatedTotal()).sum());
        }
        deliveryOrderRequestDto.setProductInfos(productInfos);
        deliveryOrderRequestDto.setOrderSource(OrderSourceType.ALIPAY.getCode().equals(order.getSource())?"Alipay":"freemud");
        if(CollectionUtils.isNotEmpty(order.getAccountList())) {
            List<CreateDeliveryPreferentialVo> createDeliveryPreferentialVos = new ArrayList<>();
            order.getAccountList().stream().forEach(accountBean -> {
                if (!OldOrderAccountType.DELIVERY_AMOUNT.getCode().equals(accountBean.getType())
                        && !OldOrderAccountType.PACK_AMOUNT.getCode().equals(accountBean.getType())
                        && !OldOrderAccountType.CARD_ORIGINAL_AMOUNT.getCode().equals(accountBean.getType())
                        && !OldOrderAccountType.DRIVER_FEE.getCode().equals(accountBean.getType())) {
                    CreateDeliveryPreferentialVo createDeliveryPreferentialVo = new CreateDeliveryPreferentialVo();
                    createDeliveryPreferentialVo.setPreferentialContent(accountBean.getName());
                    createDeliveryPreferentialVo.setPreferentialPrice(accountBean.getPrice());
                    createDeliveryPreferentialVos.add(createDeliveryPreferentialVo);
                }
            });
            deliveryOrderRequestDto.setPreferentials(createDeliveryPreferentialVos);
        }
        return deliveryOrderRequestDto;
    }

}


