package cn.freemud.adapter;

import cn.freemud.entities.dto.ActivityCalculationDiscountResponseDto;
import cn.freemud.entities.dto.CreateSpellGroupOrderDto;
import cn.freemud.entities.dto.delivery.QueryDeliveryTemplateRequest;
import cn.freemud.entities.dto.order.CreatePrepayRequestDto;
import cn.freemud.entities.dto.product.ProductInfo;
import cn.freemud.entities.dto.promotion.CalculationDiscountGoodsDto;
import cn.freemud.entities.dto.promotion.CalculationDiscountRequestDto;
import cn.freemud.entities.dto.promotion.GroupWorkQueryRequest;
import cn.freemud.enums.OrderType;
import cn.freemud.enums.PayType;
import cn.freemud.management.entities.dto.request.activity.GroupWorkRefundRequest;
import com.alibaba.fastjson.JSONObject;
import com.freemud.api.assortment.datamanager.entity.vo.AssortmentCustomerInfoVo;
import com.freemud.application.sdk.api.ordercenter.entities.v1.OrderBeanV1;
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.PayChannelType;
import com.freemud.application.sdk.api.ordercenter.request.OrderExtInfoDto;
import com.freemud.application.sdk.api.ordercenter.request.OrderExtendedReq;
import com.freemud.application.sdk.api.ordercenter.request.create.*;
import com.freemud.application.sdk.api.promotioncenter.request.promotion.ActivityUpdateStockRequest;
import com.freemud.application.sdk.api.storecenter.response.StoreResponse;
import com.freemud.application.sdk.api.util.DateUtil;
import org.springframework.stereotype.Component;

import java.util.ArrayList;
import java.util.List;

/**
 * @author wanghanghang
 * @title: SpellGroupOrderAdapter
 * @projectName order-group
 * @description: 创建拼团订单转换类
 * @date 2021/4/15上午11:54
 */
@Component
public class SpellGroupOrderAdapter {

    /**
     * 转换创建订单request
     *
     * @param createSpellGroupOrderDto
     * @return
     */
    public CreateOrderRequest convertToCreateOrderRequest(CreateSpellGroupOrderDto createSpellGroupOrderDto, AssortmentCustomerInfoVo userLoginInfoDto) {
        CreateOrderRequest createOrderRequest = new CreateOrderRequest();
        //初始化订单基础信息
        createOrderRequest.setPartnerId(createSpellGroupOrderDto.getPartnerId());
        createOrderRequest.setStoreId(createSpellGroupOrderDto.getStoreId());
        createOrderRequest.setThirdStoreId(createSpellGroupOrderDto.getStoreId());
        StoreResponse.BizVO storeInfo = createSpellGroupOrderDto.getStore();
        createOrderRequest.setStoreName(storeInfo.getStoreName());
        createOrderRequest.setStoreNameEn(storeInfo.getStoreNameEn());
        createOrderRequest.setUserId(createSpellGroupOrderDto.getUserId());
        createOrderRequest.setUserName(createSpellGroupOrderDto.getNickName());
        createOrderRequest.setOrderType(OrderType.MALL.getCode());
        createOrderRequest.setPayType(PayType.ONLINE_PAY.getCode());
        PayChannelType payChannelType = PayChannelType.getByIndex(createSpellGroupOrderDto.getPayChannelType());
        if (payChannelType != null) {
            createOrderRequest.setPayChannel(payChannelType.getEbcode());
            createOrderRequest.setPayChannelName(payChannelType.getName());
            createOrderRequest.setPayChannelType(payChannelType.getIndex());
        }
        //运费
        long freight = 0 ;
        //判断是否包邮，包邮的话运费为0
        if (createSpellGroupOrderDto.getDeliveryTemplateInfo().getIsDispatchFree() == false) {
            freight = createSpellGroupOrderDto.getDeliveryTemplateInfo().getFreight();
        }
        ActivityCalculationDiscountResponseDto.CalculationDiscountResult calculationDiscount = createSpellGroupOrderDto.getCalculationDiscount();
        createOrderRequest.setActualPayAmount(calculationDiscount.getTotalAmount().longValue() + freight); //加配送费
        createOrderRequest.setSettlementAmount(calculationDiscount.getTotalAmount().longValue() + freight);
        createOrderRequest.setOriginalAmount(calculationDiscount.getOriginalTotalAmount().longValue() + freight);
        createOrderRequest.setOrderClient(OrderClientType.SAASMALL.getIndex());
        createOrderRequest.setMarketingType(createSpellGroupOrderDto.getMarketingType());
        createOrderRequest.setExpressType(null);
        createOrderRequest.setExpressChannelName("");
        createOrderRequest.setExpressChannelCode("");
        createOrderRequest.setExpressNo("");
        createOrderRequest.setCanRefund(true);
        createOrderRequest.setBizType(1);
        createOrderRequest.setSuspendState((byte) 0);
        createOrderRequest.setSuspendDesc("");
        createOrderRequest.setOperator(userLoginInfoDto.getNickName());
        createOrderRequest.setAppId(userLoginInfoDto.getAppId());
        createOrderRequest.setPayChannelType(createSpellGroupOrderDto.getPayChannelType());
        createOrderRequest.setSpellGroupCode(createSpellGroupOrderDto.getSpellGroupCode());
        OrderExtendedReq orderExtendedReq = new OrderExtendedReq();
        orderExtendedReq.setStoreNameEn(storeInfo.getStoreNameEn());
        orderExtendedReq.setSpellGroupCode(createSpellGroupOrderDto.getSpellGroupCode());
        createOrderRequest.setOrderExtended(orderExtendedReq);

        OrderExtInfoDto orderExtInfoDto = new OrderExtInfoDto();
        orderExtInfoDto.setSessionId(createSpellGroupOrderDto.getSessionId());
        createOrderRequest.setExtInfo(JSONObject.toJSONString(orderExtInfoDto));
        /**
         * 处理商品优惠信息  OrderItemCreateReq
         * 现阶段拼单商品只有一个，直接取0.后面拓展需要写循环。基本不会动
         */
        ProductInfo productInfo = createSpellGroupOrderDto.getProducts().get(0);
        ActivityCalculationDiscountResponseDto.CalculationDiscountResult.Goods goods = calculationDiscount.getGoods().get(0);
        this.convertToOrderItemReq(productInfo, goods, createOrderRequest, createSpellGroupOrderDto, userLoginInfoDto);
        /**
         * 处理配送费
         */
        this.convertOrderCostCreateReq(productInfo, freight, createOrderRequest);
        /**
         * 处理结算信息
         */
        this.convertOrderSettlementCreateReq(goods.getGoodsId(), goods.getRealAmount(),goods.getDiscountAmount(), createSpellGroupOrderDto.getActivityCode(), createOrderRequest);
        /**
         * 处理快递信息
         */
        createOrderRequest.setDeliveryContactInfoList(createSpellGroupOrderDto.getDeliveryContactInfoCreateReqList());
        return createOrderRequest;
    }

    /**
     * 转换促销算价request
     *
     * @param createSpellGroupOrderDto
     * @param userLoginInfoDto
     * @return
     */
    public CalculationDiscountRequestDto convertToCalculationDiscountRequestDto(CreateSpellGroupOrderDto createSpellGroupOrderDto, AssortmentCustomerInfoVo userLoginInfoDto) {
        CalculationDiscountRequestDto calculationDiscountRequestDto = new CalculationDiscountRequestDto();
        calculationDiscountRequestDto.setStoreId(createSpellGroupOrderDto.getStoreId());
        calculationDiscountRequestDto.setPartnerCode(createSpellGroupOrderDto.getPartnerId());
        calculationDiscountRequestDto.setUserId(userLoginInfoDto.getMemberId());
        List<CalculationDiscountGoodsDto> discountGoodsDtoList = new ArrayList<>();
        createSpellGroupOrderDto.getProducts().forEach(productInfo -> {
            CalculationDiscountGoodsDto discountGoodsDto = new CalculationDiscountGoodsDto();
            discountGoodsDto.setGoodsId(productInfo.getPid());
            //拼团订单，数量默认1
            discountGoodsDto.setGoodsQuantity(1);
            discountGoodsDto.setOriginalPrice(productInfo.getOriginalPrice().intValue());
            discountGoodsDtoList.add(discountGoodsDto);
        });
        calculationDiscountRequestDto.setGoods(discountGoodsDtoList);

        List<String> activityCodes = new ArrayList<>();
        activityCodes.add(createSpellGroupOrderDto.getActivityCode());

        calculationDiscountRequestDto.setGroupActivityCode(activityCodes);
        calculationDiscountRequestDto.setVer(1);
        return calculationDiscountRequestDto;
    }

    public CreatePrepayRequestDto convertToCreatePrepayRequest(
            AssortmentCustomerInfoVo userLoginInfoDto, OrderBeanV1 data, String trackingNo, String province
    ) {
        CreatePrepayRequestDto requestDto = new CreatePrepayRequestDto();
        requestDto.setPartnerId(data.getParentCode());
        requestDto.setWxAppId(userLoginInfoDto.getWxAppId());
        requestDto.setOpenId(userLoginInfoDto.getOpenId());
        requestDto.setTotalAmount(data.getActualPayAmount().longValue());
        requestDto.setCardAmount(0);
        OrderExtInfoDto orderExtInfoDto = new OrderExtInfoDto();
        orderExtInfoDto.setSessionId(userLoginInfoDto.getSessionId());
        orderExtInfoDto.setProvince(province);
        requestDto.setOrderExtInfoDTO(orderExtInfoDto);
        requestDto.setTransId(data.getOid());
        requestDto.setOrderClient(OrderClientType.getOrderClientType(Integer.valueOf(data.getOrderClient())));
        requestDto.setProductOrderBean(data);
        requestDto.setFatherOrderBean(data);
        requestDto.setStoreId(data.getShopId());
        requestDto.setChannel("");
        return requestDto;
    }

    public void convertToOrderItemReq(ProductInfo productInfo, ActivityCalculationDiscountResponseDto.CalculationDiscountResult.Goods goods,
                                      CreateOrderRequest createOrderRequest, CreateSpellGroupOrderDto createSpellGroupOrderDto, AssortmentCustomerInfoVo userLoginInfoDto) {
        OrderItemCreateReq orderItemCreateReq = new OrderItemCreateReq();
        orderItemCreateReq.setPartnerId(createSpellGroupOrderDto.getPartnerId());
        orderItemCreateReq.setProductId(productInfo.getPid());
        orderItemCreateReq.setThirdProductId(productInfo.getPid());
        orderItemCreateReq.setProductCode(productInfo.getProductCode());
        orderItemCreateReq.setProductName(productInfo.getName());
        orderItemCreateReq.setProductSeq(productInfo.getSequence());
        //此处由于库存冲正。需要加上此字段
        orderItemCreateReq.setProductSpec(productInfo.getPid());
        orderItemCreateReq.setProductQuantity(1);
        orderItemCreateReq.setProductUnit(productInfo.getUnit());
        orderItemCreateReq.setProductPrice(goods.getOriginalPrice());
        orderItemCreateReq.setSettlementPrice(goods.getRealAmount());
        orderItemCreateReq.setSalePrice(productInfo.getFinalPrice());
        orderItemCreateReq.setProductSharePrice(goods.getDiscountAmount());
        orderItemCreateReq.setProductPicUrl(productInfo.getPicture());
        orderItemCreateReq.setMarketingType(createSpellGroupOrderDto.getMarketingType().byteValue());
        orderItemCreateReq.setMarketingCode(createSpellGroupOrderDto.getActivityCode());
        orderItemCreateReq.setCategoryId(productInfo.getCategory());
        orderItemCreateReq.setCategoryName(productInfo.getCategoryName());
        orderItemCreateReq.setProductType(productInfo.getType());
        orderItemCreateReq.setUserId(userLoginInfoDto.getMemberId());
        orderItemCreateReq.setOpenId(userLoginInfoDto.getOpenId());
        orderItemCreateReq.setNickName(userLoginInfoDto.getNickName());
        orderItemCreateReq.setPhotoUrl(userLoginInfoDto.getPhotoUrl());
        List<OrderItemCreateReq> orderItemList = new ArrayList<>();
        orderItemList.add(orderItemCreateReq);
        createOrderRequest.setOrderItemList(orderItemList);
    }

    //快递费用信息
    public void convertOrderCostCreateReq(ProductInfo productInfo, Long freight, CreateOrderRequest createOrderRequest) {
        OrderCostCreateReq orderCostCreateReq = new OrderCostCreateReq();
        orderCostCreateReq.setCostName("快递费用");
        //新订单服务  1=包装费,2=运费,3=餐盒单价,4=餐盒数量
        orderCostCreateReq.setCostType(2);
        orderCostCreateReq.setActualCostAmount(freight);
        orderCostCreateReq.setCostAmount(freight);
        orderCostCreateReq.setProductSeq(1);
        //1=订单,2=订单商品,3=售后单
        orderCostCreateReq.setBillType(1);
        orderCostCreateReq.setProductId(productInfo.getPid());
        orderCostCreateReq.setNote("拼团订单快递费用");
        List<OrderCostCreateReq> orderCostCreateReqList = new ArrayList<>();
        orderCostCreateReqList.add(orderCostCreateReq);
        createOrderRequest.setOrderCostDetailList(orderCostCreateReqList);
    }

    //优惠信息
    public void convertOrderSettlementCreateReq(String goodId, Long realAmount, Long discountAmount,String activityCode, CreateOrderRequest createOrderRequest) {
        OrderSettlementCreateReq orderSettlementCreateReq = new OrderSettlementCreateReq();
        orderSettlementCreateReq.setProductId(goodId);
        orderSettlementCreateReq.setSettlementType(OrderSettlementType.SPELL_GROUP.getIndex());
        orderSettlementCreateReq.setSettlementAmount(realAmount);
        orderSettlementCreateReq.setShopDiscountAmount(discountAmount);
        orderSettlementCreateReq.setNumber(1);
        orderSettlementCreateReq.setShopAmount(realAmount);
        orderSettlementCreateReq.setExternalObjectId(activityCode);
        orderSettlementCreateReq.setIsOnline(true);
        List<OrderSettlementCreateReq> orderSettlementCreateReqList = new ArrayList<>();
        orderSettlementCreateReqList.add(orderSettlementCreateReq);
        createOrderRequest.setOrderSettlementDetailList(orderSettlementCreateReqList);

    }


    public ActivityUpdateStockRequest convert2ActivityUpdateStockRequest(OrderBeanV1 orderBean, CreateSpellGroupOrderDto createSpellGroupOrderDto) {
        if (orderBean == null || createSpellGroupOrderDto.getCalculationDiscount() == null) {
            return null;
        }
        ActivityUpdateStockRequest activityUpdateStockRequest = new ActivityUpdateStockRequest();
        activityUpdateStockRequest.setOrderId(orderBean.getOid());
        activityUpdateStockRequest.setPartnerCode(orderBean.getCompanyId());
        activityUpdateStockRequest.setStoreId(orderBean.getShopId());
        activityUpdateStockRequest.setVer("1");
        activityUpdateStockRequest.setUserId(orderBean.getUserId());
        activityUpdateStockRequest.setOrderCreateTime(DateUtil.getCurrentDate(DateUtil.FORMAT_yyyyMMdd_date));
        List<String> activityList = new ArrayList<>();
        activityList.add(createSpellGroupOrderDto.getActivityCode());
        activityUpdateStockRequest.setActivityList(activityList);
        activityUpdateStockRequest.setStock(createSpellGroupOrderDto.getCalculationDiscount().getStocks());
        return activityUpdateStockRequest;
    }


    public GroupWorkQueryRequest groupWorkQueryRequest(CreateSpellGroupOrderDto createSpellGroupOrderDto) {
        GroupWorkQueryRequest groupWorkQueryRequest = new GroupWorkQueryRequest();
        groupWorkQueryRequest.setActivityCode(createSpellGroupOrderDto.getActivityCode());
        groupWorkQueryRequest.setGroupId(createSpellGroupOrderDto.getSpellGroupCode());
        groupWorkQueryRequest.setPartnerId(createSpellGroupOrderDto.getPartnerId());
        groupWorkQueryRequest.setUserId(createSpellGroupOrderDto.getUserId());
        groupWorkQueryRequest.setOrderId("");
        return groupWorkQueryRequest;
    }

    public QueryDeliveryTemplateRequest convertToQueryDeliveryTemplateRequest(CreateSpellGroupOrderDto createSpellGroupOrderDto) {
        QueryDeliveryTemplateRequest  queryDeliveryTemplateRequest = new QueryDeliveryTemplateRequest();
        queryDeliveryTemplateRequest.setPartnerId(createSpellGroupOrderDto.getPartnerId());
        queryDeliveryTemplateRequest.setProvince(createSpellGroupOrderDto.getProvince());
        queryDeliveryTemplateRequest.setOrderAmount(createSpellGroupOrderDto.getCalculationDiscount().getTotalAmount().intValue());
        queryDeliveryTemplateRequest.setCount(createSpellGroupOrderDto.getProducts().size());
        return queryDeliveryTemplateRequest;
    }

    public GroupWorkRefundRequest convertToGroupWorkRefundRequest(String activityCode, String partnerCode, String groupId, String orderId, String userId) {
        return new GroupWorkRefundRequest(activityCode,partnerCode, groupId, orderId, userId);
    }

    /*------------------下方转换返回信息------------------------*/

    /**
     * 转换拼团订单收货地址reps
     */
    public void convertToReceiveAddress(CreateSpellGroupOrderDto createSpellGroupOrderDto) {
        DeliveryContactInfoCreateReq deliveryContactInfoCreateReq = new DeliveryContactInfoCreateReq();
        deliveryContactInfoCreateReq.setRelateObjectType(1);
        deliveryContactInfoCreateReq.setAddressDetail(createSpellGroupOrderDto.getReceiveAddress());
        deliveryContactInfoCreateReq.setInfoType(1);
        deliveryContactInfoCreateReq.setMobile(createSpellGroupOrderDto.getReceiveMobile());
        deliveryContactInfoCreateReq.setContactsName(createSpellGroupOrderDto.getReceiveUsername());
        List<DeliveryContactInfoCreateReq> list = new ArrayList<>();
        list.add(deliveryContactInfoCreateReq);
        createSpellGroupOrderDto.setDeliveryContactInfoCreateReqList(list);
    }

}
