package com.yami.shop.user.api.listener;

import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.yami.shop.bean.app.dto.*;
import com.yami.shop.bean.app.param.OrderParam;
import com.yami.shop.bean.event.PlatformConfirmOrderEvent;
import com.yami.shop.bean.event.ScoreConfirmOrderEvent;
import com.yami.shop.bean.model.Category;
import com.yami.shop.bean.model.UserExtension;
import com.yami.shop.bean.order.ConfirmOrderOrder;
import com.yami.shop.bean.param.ScoreConfigParam;
import com.yami.shop.common.config.Constant;
import com.yami.shop.common.util.Arith;
import com.yami.shop.security.api.util.SecurityUtils;
import com.yami.shop.service.CategoryService;
import com.yami.shop.service.SysConfigService;
import com.yami.shop.service.UserExtensionService;
import com.yami.shop.user.comment.dao.UserLevelMapper;
import com.yami.shop.user.comment.model.UserLevel;
import com.yami.shop.user.comment.util.CategoryScale;
import lombok.AllArgsConstructor;
import org.apache.commons.collections.CollectionUtils;
import org.springframework.context.event.EventListener;
import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Component;

import javax.swing.text.StyledEditorKit;
import java.util.*;
import java.util.stream.Collectors;

/**
 * 计算订单时的积分及成长值抵现和折扣信息
 */
@Component("userConfirmOrderListener")
@AllArgsConstructor
public class ConfirmOrderListener {

    private final UserExtensionService userExtensionService;
    private final SysConfigService sysConfigService;
    private final UserLevelMapper userLevelMapper;
    private final CategoryService categoryService;

    /**
     * 计算积分抵现和分摊
     */
    @EventListener(ScoreConfirmOrderEvent.class)
    @Order(ConfirmOrderOrder.SCORE)
    public void scoreSubmitOrderListener(ScoreConfirmOrderEvent event) {
        System.out.println(JSONObject.toJSONString(event));
//        //获取用户等级积分详细表
//        UserExtension extension = userExtensionService.getOne(
//                new LambdaQueryWrapper<UserExtension>().eq(UserExtension::getUserId, SecurityUtils.getUser().getUserId()));
//        //获取配置信息
//        ScoreConfigParam scoreParam = sysConfigService.getSysConfigObject(Constant.SCORE_CONFIG,ScoreConfigParam.class);
//        if(Objects.nonNull(scoreParam)  && scoreParam.getShopScoreSwitch() != null && !scoreParam.getShopScoreSwitch()){
//            return;
//        }
//        ShopCartOrderMergerDto shopCartOrderMergerDto = event.getShopCartOrderMergerDto();
//        OrderParam orderParam = event.getOrderParam();
//        if(orderParam.getUserUseScore() != null && orderParam.getUserUseScore() < 0 && extension.getScore() < 0){
//            return;
//        }
//        //计算积分最多抵现金额
//        double totalScoreAmount = 0.0;
//        List<Category> categories = categoryService.listByShopId(Constant.PLATFORM_SHOP_ID);
//        Map<Long, Double> categoryMap = CategoryScale.getScaleByCategory(categories,scoreParam,0);
//        // 积分抵现金额可用上限 = 订单可使用积分比例 * ((实际总值)/100）
//        if(scoreParam.getUseDiscountRange() == 0){
//            // 如果有等级优惠金额，还需减去等级的优惠金额、运费才是实际金额，包邮时运费为0
//            double actualTotal = Arith.sub(shopCartOrderMergerDto.getActualTotal(),shopCartOrderMergerDto.getTotalTransfee());
//            totalScoreAmount = Arith.div(Arith.mul(actualTotal, scoreParam.getUseDiscount()), 100);
//        }else{
//            //获取大类的比例并转成map
//            for (ShopCartItemDto shopCartItem : event.getAllCartItem()) {
//                if(!categoryMap.containsKey(shopCartItem.getCategoryId())) {
//                    continue;
//                }
//                // 商品总额减去商家优惠、平台优惠，就是商品项的实际金额
//                double actualTotal = Arith.sub(Arith.sub(shopCartItem.getProductTotalAmount(), shopCartItem.getShareReduce()),shopCartItem.getPlatformShareReduce());
//                double scoreReduce = Arith.div(Arith.mul(actualTotal, categoryMap.get(shopCartItem.getCategoryId())),100);
//                totalScoreAmount = Arith.add(totalScoreAmount,scoreReduce);
//            }
//        }
//        //计算用户可用积分 如果大于总共的积分使用比例直接使用，如果小于根据比例使用
//        int canUseScore = (int) Arith.mul(totalScoreAmount, scoreParam.getShopUseScore());
////        totalScoreAmount = Arith.div(canUseScore, scoreParam.getShopUseScore(),2);
//        Integer userUseScore = extension.getScore();
//        Integer totalUsableScore = extension.getScore();
//        //如果是用户选择的积分数额，则用此积分数额
//        if(orderParam.getUserUseScore() != null && orderParam.getIsScorePay() == 1 && orderParam.getUserUseScore() >= 0){
//            userUseScore = Math.min(orderParam.getUserUseScore(),userUseScore);
//        }else{
//            userUseScore = 0;
//        }
//        double scale = 1.0;
//        if(userUseScore < canUseScore){
//            scale = Arith.div(userUseScore, canUseScore);
//        }
//        int maxScore = Math.min(totalUsableScore,canUseScore);
//        userUseScore = Math.min(userUseScore, canUseScore);
//        // 如果为大于100的比例，则积分需要整10使用
//        if(scoreParam.getShopUseScore() > 100){
//            userUseScore = userUseScore - userUseScore % 10;
//            maxScore = maxScore - maxScore % 10;
//        }
//        // 计算最大可抵扣金额，并且如果小数大于两位四舍五入，还需在计算一遍实际使用积分
//        totalScoreAmount = Arith.div(userUseScore,scoreParam.getShopUseScore(),2);
//        userUseScore = (int) Arith.mul(totalScoreAmount, scoreParam.getShopUseScore());
//        //用户选择积分抵现，组装积分信息
//        List<ShopCartOrderDto> shopCartOrders = shopCartOrderMergerDto.getShopCartOrders();
//        double totalScoreReduce = 0.0;
//        int totalScore = 0;
//        //通过for i找出最后一项，将计算偏差的1积分给最后的最大的一项
//        for (int shopIndex = 0; shopIndex < shopCartOrders.size(); shopIndex++) {
//            ShopCartOrderDto shopCartOrder = shopCartOrders.get(shopIndex);
//            double reduceSum = 0.0;
//            int shopScore = 0;
//            List<ShopCartItemDiscountDto> shopCartItemDiscounts = shopCartOrder.getShopCartItemDiscounts();
//            for (int discountIndex = 0; discountIndex < shopCartItemDiscounts.size(); discountIndex++) {
//                List<ShopCartItemDto> shopCartItems = shopCartItemDiscounts.get(discountIndex).getShopCartItems();
//                for (int itemIndex = 0; itemIndex< shopCartItems.size(); itemIndex++) {
//                    ShopCartItemDto shopCartItem = shopCartItems.get(itemIndex);
//                    double scoreReduceProd = 0.0;
//                    //判断是否最后一项
//                    boolean isEnd =  shopIndex == shopCartOrders.size() - 1 && discountIndex ==shopCartItemDiscounts.size() - 1 && itemIndex == shopCartItems.size() - 1;
//                    //计算商品分摊的金额，需要乘以比例
//                    if(scoreParam.getUseDiscountRange() == 0){
//                        scoreReduceProd = Arith.div(Arith.mul(shopCartItem.getActualTotal(),scoreParam.getUseDiscount()),100,2);
//                    }else if(categoryMap.containsKey(shopCartItem.getCategoryId())){
//                        scoreReduceProd = Arith.div(Arith.mul(shopCartItem.getActualTotal(),categoryMap.get(shopCartItem.getCategoryId())),100,2);
//                    }
//                    int useScore = (int) Arith.mul(Arith.round(Arith.mul(scoreReduceProd,scale),2), scoreParam.getShopUseScore());
//                    scoreReduceProd = Arith.div(useScore, scoreParam.getShopUseScore(),2);
//                    //如果大于可用上限则直接等于，或者如果是最后一项直接将剩余的抵扣金额全部赋予最后一个，积分和金额直接等于 使用的 - 已经抵扣的
//                    if(Arith.add(totalScoreReduce,scoreReduceProd) > totalScoreAmount || isEnd){
//                        //减去当前总共的积分，减去店铺已分摊的积分
//                        useScore = userUseScore - totalScore - shopScore;
//                        scoreReduceProd = Arith.sub(totalScoreAmount ,totalScoreReduce);
//                    }
//
//                    totalScoreReduce = Arith.add(totalScoreReduce, scoreReduceProd);
//                    reduceSum = Arith.add(reduceSum, scoreReduceProd);
//                    shopScore += useScore;
//                    if (orderParam.getIsScorePay() != null && orderParam.getIsScorePay() == 1) {
//                        double platformReduce = shopCartItem.getPlatformShareReduce() == null?0:shopCartItem.getPlatformShareReduce();
//                        shopCartItem.setPlatformShareReduce(Arith.add(platformReduce, scoreReduceProd));
//                        shopCartItem.setScorePayReduce(scoreReduceProd);
//                        shopCartItem.setScorePrice(useScore);
//                        shopCartItem.setShareReduce(Arith.add(Arith.round(shopCartItem.getShareReduce(),2),scoreReduceProd));
//                        shopCartItem.setActualTotal(Arith.sub(shopCartItem.getActualTotal(),scoreReduceProd));
//                    }
//                }
//            }
//            //设置店铺的实际总值、积分优惠金额和订单优惠金额
//            shopCartOrder.setScoreReduce(reduceSum);
//            shopCartOrder.setActualTotal(Arith.sub(shopCartOrder.getActualTotal(),reduceSum));
//            //放入优惠金额
//            shopCartOrder.setShopReduce(Arith.add(shopCartOrder.getShopReduce(),reduceSum));
//            //放入平台优惠金额,如果用户等级免自营店运费也要放进去
//            shopCartOrder.setPlatformAmount(Arith.add(shopCartOrder.getPlatformAmount(),reduceSum));
//            totalScore += shopScore;
//            if (orderParam.getIsScorePay() != null && orderParam.getIsScorePay() == 1) {
//                shopCartOrder.setUseScore(shopScore);
//            }
//        }
//        //设置订单的实际总值和订单优惠金额
//        shopCartOrderMergerDto.setTotalScoreAmount(totalScoreReduce);
//        shopCartOrderMergerDto.setShopUseScore(scoreParam.getShopUseScore());
//        shopCartOrderMergerDto.setTotalUsableScore(totalScore);
//        shopCartOrderMergerDto.setActualTotal(Arith.sub(shopCartOrderMergerDto.getActualTotal(),totalScoreReduce));
//        shopCartOrderMergerDto.setOrderReduce(Arith.add(shopCartOrderMergerDto.getOrderReduce(),totalScoreReduce));
//        shopCartOrderMergerDto.setMaxUsableScore(maxScore);
//        if (orderParam.getIsScorePay() != null && orderParam.getIsScorePay() == 1) {
//            shopCartOrderMergerDto.setScorePrice(totalScore);
//        }
    }

    /**
     * 计算等级折扣比例和分摊比例
     */
    @EventListener(PlatformConfirmOrderEvent.class)
    @Order(ConfirmOrderOrder.LEVEL)
    public void levelSubmitOrderListener(PlatformConfirmOrderEvent event) {
        UserExtension extension = userExtensionService.getOne(
                new LambdaQueryWrapper<UserExtension>().eq(UserExtension::getUserId, SecurityUtils.getUser().getUserId()));
        if (extension == null) {
            return;
        }
        UserLevel level = userLevelMapper.selectOneAndCategory(extension);
        if (level == null || level.getDiscount() > 10) {
            return;
        }
        ShopCartOrderMergerDto shopCartOrderMergerDto = event.getShopCartOrderMergerDto();
        List<ShopCartOrderDto> shopCartOrders = shopCartOrderMergerDto.getShopCartOrders();
        //获取分类比例
        //最后计算成长值折扣
        if (extension.getLevel() == null) {
            extension.setLevel(Constant.USER_LEVEL_INIT);
        }
        double levelDiscount = 0.0;
        double freeTransfee = 0.0;
//        double levelDiscountActualTotal= 0.0;
        double discount = Arith.sub(10, level.getDiscount());

        //将分类转成map
        List<Long> categoryIds = level.getCategoryIds();
        Map<Long, Long> categoryMap = new HashMap<>(100);
        if (CollectionUtils.isNotEmpty(categoryIds)) {
            categoryIds.forEach(categoryId -> categoryMap.put(categoryId, categoryId));
        }
        //计算折扣总额
        double maxlevelFeeTotal = getLevelFeeTotal(shopCartOrders, level, categoryMap);
        //通过for i找出最后一项，将计算偏差的1积分给最后的最大的一项
        for (int shopIndex = 0; shopIndex < shopCartOrders.size(); shopIndex++) {
            ShopCartOrderDto shopCartOrder = shopCartOrders.get(shopIndex);
            //如果可用范围为自营店不为当前店铺直接下一次循环
            if (level.getDiscountRange() == 1 && !Objects.equals(shopCartOrder.getShopId(), 1L)) {
                continue;
            }
            double reduceSum = 0.0;
            List<ShopCartItemDiscountDto> shopCartItemDiscounts = shopCartOrder.getShopCartItemDiscounts();
            for (int discountIndex = 0; discountIndex < shopCartItemDiscounts.size(); discountIndex++) {
                List<ShopCartItemDto> shopCartItems = shopCartItemDiscounts.get(discountIndex).getShopCartItems();
                for (int itemIndex = 0; itemIndex < shopCartItems.size(); itemIndex++) {
                    ShopCartItemDto shopCartItem = shopCartItems.get(itemIndex);
                    double prodDiscount = 0.0;
                    //判断是否最后一项
                    boolean isEnd = shopIndex == shopCartOrders.size() - 1 && discountIndex == shopCartItemDiscounts.size() - 1 && itemIndex == shopCartItems.size() - 1;
                    //折扣
                    if (level.getDiscountType() == 0 || categoryMap.containsKey(shopCartItem.getCategoryId())) {
                        prodDiscount = Arith.div(Arith.mul(shopCartItem.getActualTotal(), discount), 10, 2);
                        if (isEnd || Arith.add(Arith.add(levelDiscount, reduceSum), prodDiscount) > maxlevelFeeTotal) {
                            //总折扣金额减去当前累计的折扣金额，就为最后一件商品分摊的等级优惠金额
                            prodDiscount = Arith.sub(Arith.sub(maxlevelFeeTotal, levelDiscount), reduceSum);
                        }
                    }
                    //计算商品分摊的金额
                    shopCartItem.setPlatformShareReduce(Arith.add(shopCartItem.getPlatformShareReduce(), prodDiscount));
                    reduceSum = Arith.add(reduceSum, Arith.round(prodDiscount, 2));
                }
            }
            //设置店铺的实际总值、积分优惠金额和订单优惠金额
            shopCartOrder.setLevelReduce(reduceSum);
            levelDiscount = Arith.add(levelDiscount, reduceSum);
            //判断用户等级是否自营店包邮
            //&& level.getCategoryIds()
            if (Objects.equals(shopCartOrder.getShopId(), Constant.MAIN_SHOP) && level.getIsFreeFee() == 1) {
                freeTransfee = shopCartOrder.getTransfee();
                shopCartOrder.setFreeTransfee(shopCartOrder.getTransfee());
                shopCartOrder.setTransfee(0.0);
            }
        }
        shopCartOrderMergerDto.setTotalLevelAmount(levelDiscount);
        //设置运费优惠金额
        shopCartOrderMergerDto.setFreeTransfee(freeTransfee);
    }

    /**
     * 计算出总共可以折扣的金额
     *
     * @param shopCartOrders 全部商品项
     * @param level          等级
     * @param categoryMap    分类
     * @return 总折扣金额
     */
    private double getLevelFeeTotal(List<ShopCartOrderDto> shopCartOrders, UserLevel level, Map<Long, Long> categoryMap) {
        double totalFee = 0.0;
        for (ShopCartOrderDto shopCartOrder : shopCartOrders) {
            //如果可用范围为自营店不为当前店铺直接下一次循环
            if (level.getDiscountRange() == 1 && !Objects.equals(shopCartOrder.getShopId(), 1L)) {
                continue;
            }
            List<ShopCartItemDiscountDto> shopCartItemDiscounts = shopCartOrder.getShopCartItemDiscounts();
            for (ShopCartItemDiscountDto shopCartItemDiscount : shopCartItemDiscounts) {
                List<ShopCartItemDto> shopCartItems = shopCartItemDiscount.getShopCartItems();
                for (ShopCartItemDto shopCartItem : shopCartItems) {
                    //折扣
                    if (level.getDiscountType() == 0 || categoryMap.containsKey(shopCartItem.getCategoryId())) {
                        totalFee = Arith.add(totalFee, shopCartItem.getActualTotal());
                    }
                }
            }
        }
//        return Arith.div(totalFee,level.getDiscount(),2);
        return Arith.div(Arith.mul(totalFee, Arith.sub(10, level.getDiscount())), 10, 2);
    }
}
