package cn.freemud.service.impl;

import cn.freemud.adapter.ShoppingCartConvertAdapter;
import cn.freemud.entities.dto.ActivityCalculationDiscountResponseDto;
import cn.freemud.entities.dto.UserLoginInfoDto;
import cn.freemud.entities.dto.activity.ActivityDiscountsDto;
import cn.freemud.entities.dto.activity.ActivityQueryDto;
import cn.freemud.entities.dto.shoppingCart.ShoppingCartGoodsDto;
import cn.freemud.entities.vo.*;
import cn.freemud.enums.GoodsTypeEnum;
import cn.freemud.service.IPromotionService;
import lombok.Data;
import org.apache.commons.collections4.CollectionUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

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

/**
 * All rights Reserved, Designed By www.freemud.cn
 *
 * @Title: cn.freemud.service.impl MaterialPromotionImpl
 * @Description: TDO 描述....
 * @author: family
 * @date: 2020/7/29
 * @Copyright: www.freemud.cn Inc. All rights reserved.
 * 注意：本内容仅限于上海非码科技内部传阅，禁止外泄以及用于其他的商业目
 */
@Service("MaterialPromotionService")
public class MaterialPromotionService implements IPromotionService {
    @Autowired
    private ShoppingCartConvertAdapter shoppingCartConvertAdapter;
    /**
     * 总优惠和总原价促进已经计算过了，这里只需要累积行记录
     * 加料优惠金额
     *
     * @param couponPromotionVO
     * @param activityQueryDto
     * @param calculationDiscountResult
     * @param cartGoodsList
     * @param shoppingCartGoodsResponseVo
     * @param userLoginInfoDto
     * @param shoppingCartInfoRequestVo
     */
    @Override
    public void updateShoppingCartGoodsDiscount(CouponPromotionVO couponPromotionVO, ActivityQueryDto activityQueryDto, ActivityCalculationDiscountResponseDto.CalculationDiscountResult calculationDiscountResult, List<CartGoods> cartGoodsList, ShoppingCartGoodsResponseVo shoppingCartGoodsResponseVo, UserLoginInfoDto userLoginInfoDto, ShoppingCartInfoRequestVo shoppingCartInfoRequestVo) {

        long materialAmount = 0L, materialOriginal = 0L;
        //todo : 加料和商品成交价不需要累计 分开显示
        for (CartGoods cartGoods : cartGoodsList) {
            if (CollectionUtils.isEmpty(cartGoods.getProductMaterialList())) continue;
            materialAmount = 0L;
            materialOriginal = 0L;
            for (CartGoods.MaterialGoods materialGoods : cartGoods.getProductMaterialList()) {
                //materialAmount += materialGoods.getFinalPrice()*cartGoods.getQty();
                //materialOriginal += materialGoods.getOriginalPrice() * cartGoods.getQty();
                materialGoods.setAmount(materialGoods.getFinalPrice() * cartGoods.getQty());
                materialGoods.setOriginalAmount(materialGoods.getOriginalPrice() * cartGoods.getQty());
            }
            //设置商品行现总价\行原价 商品总价+小料商品总价
            //cartGoods.setAmount(cartGoods.getAmount() + materialAmount);
            //cartGoods.setOriginalAmount(cartGoods.getOriginalAmount() + materialOriginal);
        }
    }

    /**
     * 加料商品设置行均摊记录
     *
     * @param shoppingCartGoodsResponseVo
     * @param calculationDiscountResult
     * @param shoppingCartGoodsDto
     * @param premiumExchangeActivity
     * @param shoppingCartInfoRequestVo
     */
    @Override
    public void updateShoppingCartGoodsApportion(ShoppingCartGoodsResponseVo shoppingCartGoodsResponseVo, ActivityCalculationDiscountResponseDto.CalculationDiscountResult calculationDiscountResult, ShoppingCartGoodsDto shoppingCartGoodsDto, CreateOrderVo.PremiumExchangeActivity premiumExchangeActivity, ShoppingCartInfoRequestVo shoppingCartInfoRequestVo) {
        HashMap<String, MaterialApportion> map = getApportionGoodsDetail(calculationDiscountResult);
        List<ShoppingCartGoodsDto.CartGoodsDetailDto> products = shoppingCartGoodsDto.getProducts();
        if (map.size() > 0) {
            String pk = "";
            for (ShoppingCartGoodsDto.CartGoodsDetailDto product : products) {
                if (CollectionUtils.isEmpty(product.getMaterialList())) continue;
                for (ShoppingCartGoodsDto.CartGoodsDetailDto.MaterialGoods materialGoods : product.getMaterialList()) {
                    pk = shoppingCartConvertAdapter.jointPk(product.getCartGoodsUid(), materialGoods.getSpuId());
                    MaterialApportion material = map.get(pk);
                    if (material != null && material.getApportionAmount().intValue() == 0) continue;
                    List<ActivityDiscountsDto> activityDiscountsDtos = materialGoods.getActivityDiscountsDtos();
                    if (CollectionUtils.isEmpty(activityDiscountsDtos)) {
                        activityDiscountsDtos = new ArrayList<>();
                    }
                    //设置行记录参加的活动及总优惠
                    ActivityDiscountsDto activityDiscountsDto = new ActivityDiscountsDto();
                    activityDiscountsDto.setActivityCode(material.getDetails().activityCode);
                    activityDiscountsDto.setActivityName(material.getDetails().activityName);
                    activityDiscountsDto.setActivityType(material.getDetails().activityType);
                    activityDiscountsDto.setDiscountAmount(material.getApportionAmount());
                    activityDiscountsDtos.add(activityDiscountsDto);

                    materialGoods.setActivityDiscountsDtos(activityDiscountsDtos);
                    //materialGoods.setTotalDiscountAmount((materialGoods.getOriginalPrice().intValue() - materialGoods.getSalePrice().intValue()) * product.getQty());
                    materialGoods.setTotalDiscountAmount(material.getTotalDiscountAmount());
                    product.setProductType(GoodsTypeEnum.MATERIAL.getGoodsType());
                }
            }
        }
        //将小料的价格累加到商品行上
        for (ShoppingCartGoodsDto.CartGoodsDetailDto product : products) {
            if (CollectionUtils.isEmpty(product.getMaterialList())) continue;
            for (ShoppingCartGoodsDto.CartGoodsDetailDto.MaterialGoods materialGoods : product.getMaterialList()) {
                product.setSalePrice(product.getSalePrice() + materialGoods.getSalePrice());//现金
                product.setOriginalPrice(product.getOriginalPrice() + materialGoods.getOriginalPrice());
                product.setTotalDiscountAmount(product.getTotalDiscountAmount() + materialGoods.getTotalDiscountAmount() * product.getQty());
                product.setProductType(GoodsTypeEnum.MATERIAL.getGoodsType());
            }
        }
    }

    /**
     * 提取促销均摊
     *
     * @param calculationDiscountResult
     * @return
     */
    private HashMap<String, MaterialApportion> getApportionGoodsDetail(ActivityCalculationDiscountResponseDto.CalculationDiscountResult calculationDiscountResult) {
        HashMap<String, MaterialApportion> mApportion = new HashMap<>();
        // 遍历促销
        if (calculationDiscountResult == null || CollectionUtils.isEmpty(calculationDiscountResult.getApportionGoods())) {
            return mApportion;
        }
        String pk = "";
        for (ActivityCalculationDiscountResponseDto.CalculationDiscountResult.ApportionGoods apportionGood : calculationDiscountResult.getApportionGoods()) {
            if (CollectionUtils.isEmpty(apportionGood.getSmallMaterial())) continue;
            for (ActivityCalculationDiscountResponseDto.CalculationDiscountResult.ApportionGoods.Material material : apportionGood.getSmallMaterial()) {

                if (material.getApportionAmount() == 0) continue;
                pk = shoppingCartConvertAdapter.jointPk(apportionGood.getCartGoodsUid(), material.getGoodsId());
                if (mApportion.get(pk) == null) {
                    MaterialApportion materialApportion = new MaterialApportion();
                    //materialApportion.setSalePrice(material.getNowPrice());
                    //materialApportion.setAmount(material.getNowPrice() * material.getGoodsQuantity());
                    materialApportion.setApportionAmount(material.getApportionAmount() * material.getGoodsQuantity());
                    materialApportion.setGoodsId(material.getGoodsId());
                    materialApportion.setTotalDiscountAmount(material.getApportionAmount() * material.getGoodsQuantity());
                    materialApportion.setPk(pk);
                    ApportionDetails apportionDetails = new ApportionDetails();
                    if (CollectionUtils.isNotEmpty(material.getApportionDetails())) {
                        apportionDetails.setActivityCode(material.getApportionDetails().get(0).getActivityCode());
                        apportionDetails.setActivityName(material.getApportionDetails().get(0).getActivityName());
                        apportionDetails.setActivityType(material.getApportionDetails().get(0).getActivityType());
                        materialApportion.setDetails(apportionDetails);
                    }
                    mApportion.put(pk, materialApportion);
                    continue;
                }
                MaterialApportion apportion = mApportion.get(pk);
                //apportion.setSalePrice(apportion.getSalePrice() + material.getNowPrice());
                //apportion.setAmount(apportion.getAmount() + material.getNowPrice() * material.getGoodsQuantity());
                apportion.setApportionAmount(apportion.getApportionAmount() + material.getApportionAmount() * material.getGoodsQuantity());
                apportion.setTotalDiscountAmount(apportion.getTotalDiscountAmount() + material.getApportionAmount() * material.getGoodsQuantity());
                mApportion.put(pk, apportion);
            }
        }
        return mApportion;
    }

    @Data
    private class MaterialApportion {
        private String goodsId;
        private Long salePrice;
        private Long amount;
        private Integer apportionAmount;
        //优惠金额
        private Integer totalDiscountAmount;
        private ApportionDetails details;
        private String pk;
    }

    @Data
    public class ApportionDetails {
        private String activityCode;
        private String activityName;
        private Integer activityType;
    }
}
