/**
 * All rights Reserved, Designed By www.freemud.cn
 *
 * @Title:
 * @Package cn.freemud.adapter
 * @Description:
 * @author: liming.guo
 * @date: 2018/5/21 20:34
 * @version V1.0
 * @Copyright: 2018 www.freemud.cn Inc. All rights reserved.
 * 注意：本内容仅限于上海非码科技内部传阅，禁止外泄以及用于其他的商业目
 */
package cn.freemud.adapter;

import cn.freemud.base.constant.Version;
import cn.freemud.entities.dto.*;
import cn.freemud.entities.dto.activity.ActivityQueryDto;
import cn.freemud.entities.dto.order.CreateOrderDto;
import cn.freemud.entities.vo.CreateOrderVo;
import cn.freemud.entities.vo.PremiumExchangeResponseVo;
import cn.freemud.enums.*;
import cn.freemud.utils.PropertyConvertUtil;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.lang.StringUtils;
import org.springframework.stereotype.Component;

import java.util.ArrayList;
import java.util.List;
import java.util.Objects;
import java.util.stream.Collectors;

@Component
public class ActivityAdapter {

    /**
     * 扣减库存数量
      */
    private static final int STACK_SUB = 1;

    public ActivityQueryRequestDto convert2ActivityQueryRequestDto(CreateOrderVo createOrderVo) {
        if (createOrderVo == null || createOrderVo.getPremiumExchangeActivity() == null
                || CollectionUtils.isEmpty(createOrderVo.getPremiumExchangeActivity().getProducts())) {
            return null;
        }
        ActivityQueryRequestDto activityQueryRequestDto = new ActivityQueryRequestDto();
        activityQueryRequestDto.setVer(Version.VERSION_1);
        activityQueryRequestDto.setPartnerCode(createOrderVo.getPartnerId());
        activityQueryRequestDto.setStoreId(createOrderVo.getShopId());
        activityQueryRequestDto.setActivityType(ActivityTypeEnum.TYPE_81.getCode());
        List<ActivityQueryRequestDto.QueryGoodsBeanDto> goodsBeanDtoList = new ArrayList<>();
        for (CreateOrderVo.PremiumExchangeActivity.Product skuProduct : createOrderVo.getPremiumExchangeActivity().getProducts()) {
            ActivityQueryRequestDto.QueryGoodsBeanDto queryGoodsBeanDto = new ActivityQueryRequestDto.QueryGoodsBeanDto(skuProduct.getSkuId(),
                    skuProduct.getQty(),
                    skuProduct.getOriginalPrice());
            goodsBeanDtoList.add(queryGoodsBeanDto);
        }
        activityQueryRequestDto.setGoods(goodsBeanDtoList);
        return activityQueryRequestDto;
    }

    public ActivityCalculationDiscountRequestDto convert2ActivityCalculationDiscountRequestDto(ShoppingCartInfoDto shoppingCartInfoDto
            , String partnerCode, String storeId, String appid, Integer orderType, CouponListResponseDto.CouponBean couponBean, Long promotionAmount) {
        if (shoppingCartInfoDto == null || CollectionUtils.isEmpty(shoppingCartInfoDto.getData())) {
            return null;
        }
        ActivityCalculationDiscountRequestDto result = new ActivityCalculationDiscountRequestDto();
        result.setVer(Integer.valueOf(Version.VERSION_1));
        result.setPartnerCode(partnerCode);
        result.setStoreId(storeId);
        ActivityChannelEnum activityChannelEnum = PropertyConvertUtil.orderTypeConvert2ActivityChannel(orderType);
        if(!Objects.isNull(activityChannelEnum)) {
            result.setChannel(activityChannelEnum.getCode());
        }
        result.setAppId(appid);
        result.setIsShowActivities(1);
        result.setIsShowGoodsActivity(1);
        List<ActivityCalculationDiscountRequestDto.CalculationDiscountGoods> goods = new ArrayList<>();
        // TODO 暂时指定成一个商品，后期优化
        ActivityCalculationDiscountRequestDto.CalculationDiscountGoods calculationDiscountGoods = new ActivityCalculationDiscountRequestDto.CalculationDiscountGoods();
        calculationDiscountGoods.setGoodsId("1");
        calculationDiscountGoods.setCategory("1");
        calculationDiscountGoods.setGoodsQuantity(1);
        Long amount = 0L;
        if (shoppingCartInfoDto.getAmount() != null) {
            amount = shoppingCartInfoDto.getAmount();
        }
        Long packAmount = 0L;
        // 外卖才有打包费
        if (shoppingCartInfoDto.getPackAmount() != null && Objects.equals(CreateOrderType.TAKE_OUT.getCode(), orderType)) {
            packAmount = shoppingCartInfoDto.getPackAmount();
        }
        Long couponAmount = 0L;
        if (couponBean != null && couponBean.getDiscountAmount() != null) {
            couponAmount = Long.valueOf(couponBean.getDiscountAmount());
        }
        if (promotionAmount == null) {
            promotionAmount = 0L;
        }
        calculationDiscountGoods.setOriginalPrice(amount + packAmount - couponAmount - promotionAmount);
        goods.add(calculationDiscountGoods);
        result.setGoods(goods);
        return result;
    }

    public PremiumExchangeResponseVo convert2PremiumExchange(ActivityCalculationDiscountResponseDto.CalculationDiscountResult.SendActivity sendActivity) {
        if (sendActivity == null) {
            return null;
        }
        PremiumExchangeResponseVo premiumExchangeResponseVo = new PremiumExchangeResponseVo();
        premiumExchangeResponseVo.setResultCode(ActivityResultCodeEnum.PARTICIPATE.getCode());
        premiumExchangeResponseVo.setActivityCode(sendActivity.getActivityCode());
        premiumExchangeResponseVo.setActivityName(sendActivity.getActivityName());
        premiumExchangeResponseVo.setMaxNum(sendActivity.getMaxNum());
        List<PremiumExchangeResponseVo.PremiumExchangeProduct> products = new ArrayList<>();
        sendActivity.getSendGoods().forEach(sendGoods -> {
            PremiumExchangeResponseVo.PremiumExchangeProduct product = new PremiumExchangeResponseVo.PremiumExchangeProduct();
            product.setSpuId(sendGoods.getCategory());
            product.setSkuId(sendGoods.getGoodsId());
            product.setSkuName(sendGoods.getGoodsName());
            product.setOriginalPrice(sendGoods.getOriginalPrice());
            product.setNowPrice(sendGoods.getNowPrice());
            product.setNumber(sendGoods.getSendNumber());
            products.add(product);
        });
        premiumExchangeResponseVo.setProducts(products);
        return premiumExchangeResponseVo;
    }

    public ActivityUpdateStockRequestDto convert2ActivityUpdateStockRequestDto(CreateOrderVo createOrderVo, String orderId, CreateOrderDto createOrderDto) {
        ActivityUpdateStockRequestDto activityUpdateStockRequestDto = new ActivityUpdateStockRequestDto();
        activityUpdateStockRequestDto.setVer(Version.VERSION_1);
        activityUpdateStockRequestDto.setOrderId(orderId);
        activityUpdateStockRequestDto.setPartnerCode(createOrderVo.getPartnerId());
        activityUpdateStockRequestDto.setStoreId(createOrderVo.getShopId());

        List<ActivityUpdateStockRequestDto.StockBeanDto> stock = new ArrayList<>();
        // 加价购
        if (createOrderVo.getPremiumExchangeActivity() != null && CollectionUtils.isNotEmpty(createOrderVo.getPremiumExchangeActivity().getProducts())) {
            ActivityUpdateStockRequestDto.StockBeanDto stockBeanDto = new ActivityUpdateStockRequestDto.StockBeanDto();
            stockBeanDto.setActivityCode(createOrderVo.getPremiumExchangeActivity().getActivityCode());
            stockBeanDto.setActivityStock(STACK_SUB);
            List<ActivityUpdateStockRequestDto.StockBeanDto.GoodsStock> goodsStocks = new ArrayList<>();
            createOrderVo.getPremiumExchangeActivity().getProducts().forEach(product -> {
                ActivityUpdateStockRequestDto.StockBeanDto.GoodsStock goodsStock = new ActivityUpdateStockRequestDto.StockBeanDto.GoodsStock();
                goodsStock.setGoodsId(product.getSkuId());
                goodsStock.setStock(product.getQty());
                goodsStocks.add(goodsStock);
            });
            stockBeanDto.setGoodsStock(goodsStocks);
            stock.add(stockBeanDto);
        }
        // 满减活动和限时特价
        if (createOrderDto != null && CollectionUtils.isNotEmpty(createOrderDto.getAccounts())) {
            createOrderDto.getAccounts().forEach(createOrderAccountDto -> {
                if (Objects.equals(createOrderAccountDto.getType(), OrderAccountType.BUY_DISCOUNT.getCode())
                        || Objects.equals(createOrderAccountDto.getType(), OrderAccountType.DISCOUNT_AMOUNT.getCode())
                        || Objects.equals(createOrderAccountDto.getType(), OrderAccountType.BUYM_SENDN.getCode())) {
                    ActivityUpdateStockRequestDto.StockBeanDto stockBeanDto = new ActivityUpdateStockRequestDto.StockBeanDto();
                    stockBeanDto.setActivityCode(createOrderAccountDto.getAccountId());
                    stockBeanDto.setActivityStock(STACK_SUB);
                    List<ActivityUpdateStockRequestDto.StockBeanDto.GoodsStock> goodsStocks = new ArrayList<>();
                    // 满减活动没有商品库存
                    if (CollectionUtils.isNotEmpty(createOrderAccountDto.getAccountProducts())
                            && !Objects.equals(createOrderAccountDto.getType(), OrderAccountType.BUY_DISCOUNT.getCode())
                            && !Objects.equals(createOrderAccountDto.getType(), OrderAccountType.BUYM_SENDN.getCode())) {
                        createOrderAccountDto.getAccountProducts().forEach(createAccountProductDto -> {
                            ActivityUpdateStockRequestDto.StockBeanDto.GoodsStock goodsStock = new ActivityUpdateStockRequestDto.StockBeanDto.GoodsStock();
                            goodsStock.setGoodsId(createAccountProductDto.getProductId());
                            goodsStock.setStock(createAccountProductDto.getDiscountQty());
                            goodsStocks.add(goodsStock);
                        });
                    }
                    stockBeanDto.setGoodsStock(goodsStocks);
                    stock.add(stockBeanDto);
                }
            });
        }
        activityUpdateStockRequestDto.setStock(stock);
        return activityUpdateStockRequestDto;
    }

    public ActivityCancelStockRequestDto convert2ActivityCancelStockRequestDto(QueryOrdersResponseDto.DataBean.OrderBean orderBean, List<Integer> transType) {
        ActivityCancelStockRequestDto activityCancelStockRequestDto = new ActivityCancelStockRequestDto();
        activityCancelStockRequestDto.setVer(Version.VERSION_1);
        activityCancelStockRequestDto.setPartnerCode(orderBean.getCompanyId());
        activityCancelStockRequestDto.setStoreId(orderBean.getShopId());
        activityCancelStockRequestDto.setOrderId(orderBean.getOid());
        activityCancelStockRequestDto.setTransType(transType);
        activityCancelStockRequestDto.setUserId(orderBean.getUserId());
        List<ActivityCancelStockRequestDto.ProductVo> orderProducts = new ArrayList<>();
        if(CollectionUtils.isNotEmpty(orderBean.getProductList())) {
            orderBean.getProductList().forEach(productBean -> {
                ActivityCancelStockRequestDto.ProductVo productStock = new ActivityCancelStockRequestDto.ProductVo();
                productStock.setSkuId(productBean.getSpecification() );
                productStock.setQty(productBean.getNumber());
                orderProducts.add(productStock);
            });
        }
        activityCancelStockRequestDto.setProducts(orderProducts);
        //优惠券冲正
        List<QueryOrdersResponseDto.DataBean.OrderBean.AccountBean> accountList = orderBean.getAccountList();
        if (!CollectionUtils.isEmpty(accountList) && !CollectionUtils.isEmpty(orderBean.getProductList())) {
            for (QueryOrdersResponseDto.DataBean.OrderBean.AccountBean accountBean : accountList) {
                List<CouponCodeVerificationProductDto> products = new ArrayList<>();
                //订单中存储的6代表商品券
                if (Objects.equals(accountBean.getType(), OrderAccountType.PRODUCT_COUPON.getCode())) {
                    for (int i = 0; i < orderBean.getProductList().size(); i++) {
                        QueryOrdersResponseDto.DataBean.OrderBean.ProductBean productBean = orderBean.getProductList().get(i);
                        String pid = StringUtils.isNotBlank(productBean.getSpecification()) ? productBean.getSpecification() : productBean.getProductId();
                        if (!org.springframework.util.CollectionUtils.isEmpty(orderBean.getProductList().get(i).getDiscountList())) {
                            List<QueryOrdersResponseDto.DataBean.OrderBean.ProductBean.ProductDiscount> discounts = orderBean.getProductList().get(i).getDiscountList().stream().
                                    filter(productDiscount -> productDiscount.getDiscountId().equals(accountBean.getAccountId())).collect(Collectors.toList());
                            for (QueryOrdersResponseDto.DataBean.OrderBean.ProductBean.ProductDiscount productDiscount : discounts) {
                                CouponCodeVerificationProductDto couponCodeVerificationProductDto = new CouponCodeVerificationProductDto();
                                couponCodeVerificationProductDto.setPID(pid);
                                couponCodeVerificationProductDto.setConsume_num(productDiscount.getDiscountQty());
                                couponCodeVerificationProductDto.setSeq(i + 1);
                                products.add(couponCodeVerificationProductDto);
                            }
                        }
                    }
                }
                if (OrderAccountType.COUPON.getCode().equals(accountBean.getType())
                        || OrderAccountType.PRODUCT_COUPON.getCode().equals(accountBean.getType())
                        || OrderAccountType.DISCOUNT_COUPON.getCode().equals(accountBean.getType())) {
                    activityCancelStockRequestDto.setCouponCode(accountBean.getAccountId());
                    activityCancelStockRequestDto.setCouponProducts(products);
                }
            }
        }

        return activityCancelStockRequestDto;
    }

    /**
     * 组装ActivityQueryDto对象
     *
     * @param partnerId
     * @param storeId
     * @param userId
     * @param appId
     * @param orderType
     * @return
     */
    public ActivityQueryDto getActivityQueryDto(String partnerId, String storeId, String userId, String appId, Integer orderType) {
        return ActivityQueryDto.builder()
                .partnerId(partnerId)
                .storeId(storeId)
                .userId(userId)
                .appId(appId)
                .orderType(orderType)
                .build();
    }



}
