package cn.freemud.adapter;

import cn.freemud.base.util.DateUtil;
import cn.freemud.entities.Active;
import cn.freemud.entities.dto.delivery.WeixinDeliveryAddressDto;
import cn.freemud.entities.dto.order.UnifiedPayResponseDto;
import cn.freemud.entities.dto.pay.PayOrderDto;
import cn.freemud.entities.dto.pay.PayProductDto;
import cn.freemud.entities.dto.pay.UnifiedOrderRequestDto;
import cn.freemud.entities.dto.product.pointsmall.IntegralProductType;
import cn.freemud.entities.dto.product.pointsmall.PointMallListProductInfoRequest;
import cn.freemud.entities.dto.product.pointsmall.ProductStockRequest;
import cn.freemud.entities.dto.product.pointsmall.UpdatePointsMallStocksRequest;
import cn.freemud.entities.dto.user.UseScoreRequest;
import cn.freemud.entities.vo.CreateOrderResponseVo;
import com.alibaba.fastjson.JSONObject;
import com.freemud.api.assortment.datamanager.entity.vo.AssortmentCustomerInfoVo;
import com.freemud.application.sdk.api.log.LogThreadLocal;
import com.freemud.application.sdk.api.ordercenter.enums.OrderClientType;
import com.freemud.application.sdk.api.ordercenter.enums.OrderSettlementType;
import com.freemud.application.sdk.api.ordercenter.enums.OrderType;
import com.freemud.application.sdk.api.ordercenter.request.create.CreateOrderRequest;
import com.freemud.application.sdk.api.ordercenter.request.create.DeliveryContactInfoCreateReq;
import com.freemud.application.sdk.api.ordercenter.request.create.OrderItemCreateReq;
import com.freemud.application.sdk.api.ordercenter.request.create.OrderSettlementCreateReq;
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.request.order.OrderProductAddInfoDto;
import com.freemud.sdk.api.assortment.order.request.order.ProductBindingCouponType;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang.StringUtils;
import org.springframework.stereotype.Component;

import java.util.*;

@Component
public class PointsMallOrderAdapter {


    public PointMallListProductInfoRequest convent2PointMallListProductInfoRequest(String partnerId, String memberId, String skuId) {
        PointMallListProductInfoRequest productInfoRequest = new PointMallListProductInfoRequest();
        productInfoRequest.setPartnerId(partnerId);
        productInfoRequest.setMemberId(memberId);
        productInfoRequest.setProductIdList(Arrays.asList(skuId));
        productInfoRequest.setValidateMember(true);
        productInfoRequest.setValidateStock(true);
        productInfoRequest.setValidateTime(true);
        productInfoRequest.setValidateLimitNum(true);
        return productInfoRequest;
    }


    public CreateOrderRequest convent2NEWCreateOrderRequest(Integer orderClient, AssortmentCustomerInfoVo userLoginInfoDto,
                                                            String shopId, String cardCode,
                                                            String channel, Integer bizType,
                                                            IntegralProductType productBean, String skuId,
                                                            Active active, WeixinDeliveryAddressDto weixinDeliveryAddress) {
        CreateOrderRequest request = new CreateOrderRequest();
        String partnerId = userLoginInfoDto.getPartnerId();
        request.setOrderClient(orderClient);
        request.setPartnerId(partnerId);
        request.setStoreId(shopId);
        request.setStoreName("虚拟门店");
        request.setThirdStoreId("");
        //买券虚拟订单  不管APP卖券还是平台，依旧保留传入6
        request.setBizType(bizType);
        //1:线上支付 2:线下支付
        request.setPayType(1);
        request.setUserId(userLoginInfoDto.getMemberId());
        request.setUserName(userLoginInfoDto.getNickName());
        request.setOrderState(1);
        request.setPayState(1);
        if (StringUtils.isNotBlank(cardCode)) {
            request.setPayChannel("10102");
            request.setPayChannelName("储值卡支付");
        }
        //积分价格
        Integer integralPrice = productBean.getIntegralPrice() == null ? 0 : productBean.getIntegralPrice();
        //现金价格（分）
        Integer cashPrice = productBean.getCashPrice() == null ? 0 : productBean.getCashPrice();
//        Integer settlementAmount = integralPrice + cashPrice;
        //订单原始金额，单位分
        //用户在界面上看到的支付金额
        request.setSettlementAmount(cashPrice.longValue());
        //实际支付现金金额，扣除支付自生优惠，单位分`
        request.setActualPayAmount(cashPrice.longValue());
        request.setOriginalAmount(cashPrice.longValue());
        request.setOrderType(OrderType.GENERAL_DINE_IN.getIndex());
        //商品信息赋值
        OrderItemCreateReq orderItemCreateReq = convent2OrderItemCreateReq(productBean, partnerId, skuId, active);
        request.setOrderItemList(Arrays.asList(orderItemCreateReq));
        //积分优惠
        OrderSettlementCreateReq orderSettlementCreateReq = convent2OrderSettlementCreateReq(productBean);
        request.setOrderSettlementDetailList(Arrays.asList(orderSettlementCreateReq));
        //收货人信息转换
        List<DeliveryContactInfoCreateReq> deliveryContactInfoList = new ArrayList<>();
        DeliveryContactInfoCreateReq deliveryContactInfoCreateReq = new DeliveryContactInfoCreateReq();
        //地址类型 1:订单地址 2:售后单地址 3:配送员信息
        deliveryContactInfoCreateReq.setRelateObjectType(1);
        //联系方式类型 1:取件 2:收件
        deliveryContactInfoCreateReq.setInfoType(1);
        deliveryContactInfoCreateReq.setContactsName(userLoginInfoDto.getNickName());
        deliveryContactInfoCreateReq.setMobile(userLoginInfoDto.getMobile());
        deliveryContactInfoCreateReq.setLatitude(null);
        deliveryContactInfoCreateReq.setLongitude(null);
        deliveryContactInfoCreateReq.setAddressDetail(null);
        deliveryContactInfoCreateReq.setProvince(null);
        deliveryContactInfoCreateReq.setCity(null);
        deliveryContactInfoCreateReq.setRegion(null);
        if (weixinDeliveryAddress != null) {
            deliveryContactInfoCreateReq.setContactsName(weixinDeliveryAddress.getUserName());
            deliveryContactInfoCreateReq.setMobile(weixinDeliveryAddress.getTelNumber());
            deliveryContactInfoCreateReq.setProvince(weixinDeliveryAddress.getProvinceName());
            deliveryContactInfoCreateReq.setCity(weixinDeliveryAddress.getCityName());
            deliveryContactInfoCreateReq.setRegion(weixinDeliveryAddress.getCountyName());
            deliveryContactInfoCreateReq.setAddressDetail(weixinDeliveryAddress.getDetailInfo());
        }
        deliveryContactInfoList.add(deliveryContactInfoCreateReq);
        request.setDeliveryContactInfoList(deliveryContactInfoList);
        request.setOperator(userLoginInfoDto.getNickName());
        request.setAppId(userLoginInfoDto.getWxAppId());
        request.setPayChannel(channel);
        return request;

    }

    private OrderItemCreateReq convent2OrderItemCreateReq(IntegralProductType productBean, String partnerId, String skuId,
                                                          Active active) {
        boolean isCoupon = productBean.getProductType() == 1;
        //积分价格
        Integer integralPrice = productBean.getIntegralPrice() == null ? 0 : productBean.getIntegralPrice();
        //现金价格（分）
        Integer cashPrice = productBean.getCashPrice() == null ? 0 : productBean.getCashPrice();
//        Integer settlementAmount = integralPrice + cashPrice;
        OrderItemCreateReq orderItemCreateReq = new OrderItemCreateReq();
        orderItemCreateReq.setPartnerId(partnerId);
        orderItemCreateReq.setSalePrice(cashPrice.longValue());
        orderItemCreateReq.setProductPrice(integralPrice.longValue());
        orderItemCreateReq.setSettlementPrice(cashPrice.longValue());
        orderItemCreateReq.setProductId(skuId);
        orderItemCreateReq.setProductSpec(skuId);
        orderItemCreateReq.setProductName(productBean.getProductName());
        orderItemCreateReq.setProductSpecName(productBean.getProductName());
        orderItemCreateReq.setProductType(productBean.getProductType());
        if (CollectionUtils.isNotEmpty(productBean.getPictureList())) {
            orderItemCreateReq.setProductPicUrl(productBean.getPictureList().get(0));
        }
        orderItemCreateReq.setProductSeq(1);
        if (productBean.getEntityProductInfo() != null) {
            orderItemCreateReq.setProductCode(productBean.getEntityProductInfo().getProductId());
            orderItemCreateReq.setThirdProductId(productBean.getEntityProductInfo().getProductId());
            orderItemCreateReq.setProductPicUrl(productBean.getEntityProductInfo().getPicture());
        }
        if (isCoupon) {
            //添加商品绑定的券
            OrderProductAddInfoDto orderProductAddInfoDto = new OrderProductAddInfoDto();
            List<ProductBindingCouponType> productBindingCoupons = new ArrayList<>();
            productBindingCoupons.add(convent2ProductBindingCouponType(active));
            orderProductAddInfoDto.setProductBindingCoupons(productBindingCoupons);
            orderItemCreateReq.setExtInfo(JSONObject.toJSONString(orderProductAddInfoDto));
        }
        orderItemCreateReq.setProductQuantity(1);
        return orderItemCreateReq;
    }

    private OrderSettlementCreateReq convent2OrderSettlementCreateReq(IntegralProductType productBean) {
        OrderSettlementCreateReq orderSettlementCreateReq = new OrderSettlementCreateReq();
        orderSettlementCreateReq.setNumber(productBean.getIntegralPrice());
        orderSettlementCreateReq.setProductSeq(1);
        orderSettlementCreateReq.setExternalObjectId("");
        //商家优惠
        orderSettlementCreateReq.setShopDiscountAmount(0L);
        //结算金额
        orderSettlementCreateReq.setSettlementAmount(productBean.getIntegralPrice().longValue());
        //是否线上 false:不是 true:是
        orderSettlementCreateReq.setIsOnline(true);
        orderSettlementCreateReq.setSettlementType(OrderSettlementType.POINTS.getIndex());
        return orderSettlementCreateReq;
    }

    private ProductBindingCouponType convent2ProductBindingCouponType(Active active) {
        ProductBindingCouponType productBindingCouponType2 = new ProductBindingCouponType();
        productBindingCouponType2.setActivityCode(active.getActiveCode());
        productBindingCouponType2.setNum(1);
        productBindingCouponType2.setActivityName(active.getActiveName());
        return productBindingCouponType2;
    }

    public UnifiedOrderRequestDto convert2UnifiedOrderRequestDto(OrderInfoReqs orderInfo, String openId, Integer cashPrice,
                                                                 Long clientCode, String reverseNotifyiDcUrl, String payTimeOutTime) {

        String partnerId = orderInfo.getPartnerId();
        String storeId = orderInfo.getStoreId();
        String appId = orderInfo.getAppId();

        //现金支付唤起线上支付
        UnifiedOrderRequestDto requestDto = new UnifiedOrderRequestDto();
        requestDto.setTransId(orderInfo.getOrderCode());
        requestDto.setPartnerId(partnerId);
        requestDto.setStoreId(storeId);
        requestDto.setAmount(cashPrice.longValue());

        String businessDate = DateUtil.convert2String(new Date(), "yyyyMMdd");
        requestDto.setBusinessDate(businessDate);
        requestDto.setClientCode(clientCode);
        requestDto.setFoodOrderType(getFoodOrderType(1));
        requestDto.setNotifyUrl(reverseNotifyiDcUrl);
        requestDto.setOpenId(openId);
        requestDto.setPayTimeOutTime(payTimeOutTime);
        List<PayProductDto> productBeans = new ArrayList<>();
        String payProductName = "";
        if (CollectionUtils.isNotEmpty(orderInfo.getOrderItemList())) {

            for (OrderItemResp orderProductBean : orderInfo.getOrderItemList()) {
                PayProductDto productBean = new PayProductDto();
                productBean.setId(orderProductBean.getProductId());
                productBean.setQuantity(orderProductBean.getProductQuantity());
//                productBean.setSeq(orderProductBean.getProductSeq());
//                productBean.setSalesType("NORMAL");
                productBean.setPrice(orderProductBean.getProductPrice().longValue());
                if (StringUtils.isNotBlank(payProductName)) {
                    payProductName = orderProductBean.getProductName();
                } else if (payProductName.endsWith("...")) {
                    //不处理
                } else {
                    payProductName = payProductName + "...";
                }
                productBean.setName(orderProductBean.getProductName());
                productBeans.add(productBean);
            }
        }
        requestDto.setProducts(productBeans);
        requestDto.setBody(payProductName);

        requestDto.setSubAppid(orderInfo.getAppId());
        requestDto.setPayTypeCode(convertPayTypeCode(orderInfo.getOrderClient().toString()));
        return requestDto;
    }

    /**
     * 支付类型编码 TWX:微信 TZFB:支付宝
     */
    public String convertPayTypeCode(String orderClient) {
        String payTypeCode = "";
        switch (orderClient) {
            case "2":
                payTypeCode = "TWX";
                break;
            case "3":
                payTypeCode = "TZFB";
                break;
            default:
                break;
        }
        return payTypeCode;
    }

    /**
     * 预支付接口获取类型
     *
     * @return
     */
    private String getFoodOrderType(Integer orderType) {
        //1=外卖 4=自提，5=堂食
        //qr_order（店内扫码点餐）,pre_order（预点到店自提）,home_delivery （外送到家）
        String foodOrderType;
        switch (orderType) {
            case 1:
                foodOrderType = "home_delivery";
                break;
            case 4:
                foodOrderType = "pre_order";
                break;
            case 5:
            default:
                foodOrderType = "qr_order";
                break;
        }
        return foodOrderType;
    }


    public UpdatePointsMallStocksRequest convent2UpdatePointsMallStocksRequest(String partnerId, String memberId, String skuId, String orderCode) {
        UpdatePointsMallStocksRequest updatePointsMallStocksRequest = new UpdatePointsMallStocksRequest();
        updatePointsMallStocksRequest.setPartnerId(partnerId);
        updatePointsMallStocksRequest.setMemberId(memberId);
        updatePointsMallStocksRequest.setChangeType(2);
        updatePointsMallStocksRequest.setRemark("积分商城兑换");
        updatePointsMallStocksRequest.setTransTime(DateUtil.convert2String(new Date(), DateUtil.FORMAT_YYYY_MM_DD_HHMMSS));
        updatePointsMallStocksRequest.setTransNo(orderCode);
        ProductStockRequest productStockRequest = new ProductStockRequest();
        productStockRequest.setProductId(skuId);
        productStockRequest.setExchangeNumber(1);
        productStockRequest.setStockNumber(1);
        updatePointsMallStocksRequest.setProductStocks(Arrays.asList(productStockRequest));

        return updatePointsMallStocksRequest;
    }


    public UseScoreRequest convent2UseScoreRequest(String partnerId, String memberId, String appId, String orderCode, Integer points) {
        UseScoreRequest userScoreRequest = new UseScoreRequest();
        userScoreRequest.setMemberId(memberId);
        userScoreRequest.setPartnerId(partnerId);
        userScoreRequest.setChangeScore(points);
        userScoreRequest.setOperationType(12);
        userScoreRequest.setOperationName("积分兑换");
        userScoreRequest.setChangeType(2);
        userScoreRequest.setOrderId(orderCode);
        userScoreRequest.setOrgCode("");
        userScoreRequest.setOrgType(1);
        userScoreRequest.setIdempotencyBussinessId(LogThreadLocal.getTrackingNo());
        userScoreRequest.setIdempotencyBussinessType("5");
        userScoreRequest.setAppId(appId);
        return userScoreRequest;
    }

    public void convent2CreateOrderResponseVo(CreateOrderResponseVo createOrderResponseVo, String appId, UnifiedPayResponseDto response){
        createOrderResponseVo.setWxappId(appId);
        createOrderResponseVo.setFmId(response.getFmId());
        createOrderResponseVo.setPaySuccess(false);
        String payOrderDto = response.getPayOrder();
        PayOrderDto payOrder = JSONObject.parseObject(payOrderDto, PayOrderDto.class);
        if (payOrder != null) {
            createOrderResponseVo.setTimestamp(payOrder.getTimestamp());
            createOrderResponseVo.setNonceStr(payOrder.getNonceStr());
            createOrderResponseVo.setPackageX(payOrder.getPackageX());
            createOrderResponseVo.setSignType(payOrder.getSignType());
            createOrderResponseVo.setSign(payOrder.getPaySign());
            createOrderResponseVo.setOrderStr(payOrder.getAliPayOrder());
        }
    }
}
