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.ConfirmOrderEvent;
import com.yami.shop.bean.event.PlatformConfirmOrderEvent;
import com.yami.shop.bean.event.ScoreConfirmOrderEvent;
import com.yami.shop.bean.dto.XsbMemberDiscountInfo;
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.service.XsbMemberSupportService;
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.math.BigDecimal;
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;
    private final XsbMemberSupportService xsbMemberSupportService;

    /**
     * 閻犱緤绱曢悾鑽ょ矓椤栨艾鐎婚柟鍓佹暩楠炲洭宕仦钘夌€婚柟?
     */
    @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){
//            // 濠碘€冲€归悘澶愬嫉婢跺瞼鎼肩紒鐙欏倻鍠橀柟顖滃█閸ｇ偓锛愬┑鎾剁閺夆晜锕㈠〒鍫曞礄韫囨挸绠电紒娑橆槺妤犲洭鎯冮崟顏嗗枠闁诡垳濞€閸ｇ偓锛愬┑鍕ㄥ亾娴ｇ晫绠ラ悹鎰潐婢х娀寮伴姘辨澖闂傚嫬鎳橀崳鐐紣濠垫挾绀夐柛鏍ф嚇閸嬫牠寮幆鎵閻犳劙鈧稖绀?
//            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);
//        // 濠碘€冲€归悘澶嬬▔閸濆嫨浜ｅù?00闁汇劌瀚惁顔界瑹鐎ｅ墎绀夐柛鎺撶懅琚ч柛鎺戞濞撳墎鎲版担瑙勬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;
//        //闂侇偅淇虹换鍍╫r i闁瑰灚鍎抽崵顓㈠嫉閳ь剟宕ユ惔婵堫伇濡炪倗娅㈢槐婵堜焊閸℃凹鍚€缂佺姵顨呮禍绋款啅椤旂偓鐣?缂佸鍨伴崹搴ｇ磼濞嗘劖浠橀柛姘捣濞堟垿寮甸埀顒佸緞瑜忓▓鎴炵▔閳ь剚銇?
//        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);
//        }
    }

    /**
     * Apply member discount for XSB mall items only.
     */
    @EventListener(ConfirmOrderEvent.class)
    @Order(ConfirmOrderOrder.MEMBER)
    public void memberDiscountConfirmOrderListener(ConfirmOrderEvent event) {
        ShopCartOrderDto shopCartOrderDto = event.getShopCartOrderDto();
        List<ShopCartItemDto> xsbItems = event.getShopCartItems().stream()
                .filter(xsbMemberSupportService::isXsbItem)
                .filter(item -> Boolean.TRUE.equals(item.getIsMember()))
                .filter(item -> item.getMemberPrice() != null)
                .collect(Collectors.toList());
        if (CollectionUtils.isEmpty(xsbItems)) {
            return;
        }
        Double memberDiscountRate = resolveMemberDiscountRate();
        double memberReduce = 0.0;
        for (ShopCartItemDto shopCartItem : xsbItems) {
            double productTotal = shopCartItem.getProductTotalAmount() == null ? 0.0 : shopCartItem.getProductTotalAmount();
            double memberTotal = Arith.mul(shopCartItem.getMemberPrice(), shopCartItem.getProdCount());
            double reduceAmount = Arith.round(Arith.sub(productTotal, memberTotal), 2);
            if (reduceAmount < 0) {
                reduceAmount = 0.0;
            }
            if (reduceAmount > productTotal) {
                reduceAmount = productTotal;
            }
            if (reduceAmount <= 0) {
                shopCartItem.setMemberDiscountShareAmount(0.0);
                continue;
            }
            shopCartItem.setMemberDiscountShareAmount(reduceAmount);
            shopCartItem.setShareReduce(Arith.add(shopCartItem.getShareReduce(), reduceAmount));
            shopCartItem.setActualTotal(Arith.sub(shopCartItem.getActualTotal(), reduceAmount));
            memberReduce = Arith.add(memberReduce, reduceAmount);
        }
        if (memberReduce <= 0) {
            return;
        }
        shopCartOrderDto.setMemberDiscountAmount(memberReduce);
        shopCartOrderDto.setMemberDiscountDesc("Member discount");
        shopCartOrderDto.setMemberDiscountRate(memberDiscountRate);
        shopCartOrderDto.setMemberBenefitDesc(buildMemberBenefitDesc(memberDiscountRate));
        shopCartOrderDto.setActualTotal(Arith.sub(shopCartOrderDto.getActualTotal(), memberReduce));
        shopCartOrderDto.setShopReduce(Arith.add(shopCartOrderDto.getShopReduce(), memberReduce));
    }

    private Double resolveMemberDiscountRate() {
        XsbMemberDiscountInfo memberInfo = xsbMemberSupportService.getMemberDiscountInfo(SecurityUtils.getUser().getUserId());
        if (memberInfo == null || !Boolean.TRUE.equals(memberInfo.getMember())) {
            return null;
        }
        Double discountRate = memberInfo.getDiscountRate();
        if (discountRate == null || discountRate <= 0 || discountRate >= 1) {
            return null;
        }
        return discountRate;
    }

    private String buildMemberBenefitDesc(Double memberDiscountRate) {
        if (memberDiscountRate == null) {
            return "会员权益";
        }
        BigDecimal discountValue = BigDecimal.valueOf(memberDiscountRate).multiply(BigDecimal.TEN).stripTrailingZeros();
        return "会员权益（" + discountValue.toPlainString() + "折）";
    }

    /**
     * Apply original level discount logic.
     */
    @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());

        //閻忓繐妫楅崹搴ｇ尵閺勫繑绁柟瀛樹粣ap
        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);
        //闂侇偅淇虹换鍍╫r i闁瑰灚鍎抽崵顓㈠嫉閳ь剟宕ユ惔婵堫伇濡炪倗娅㈢槐婵堜焊閸℃凹鍚€缂佺姵顨呮禍绋款啅椤旂偓鐣?缂佸鍨伴崹搴ｇ磼濞嗘劖浠橀柛姘捣濞堟垿寮甸埀顒佸緞瑜忓▓鎴炵▔閳ь剚銇?
        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);
    }
}
