package com.ym.mec.biz.service.impl;

import com.alibaba.fastjson.JSON;
import com.ym.mec.biz.dal.dao.HfMemberDao;
import com.ym.mec.biz.dal.dao.StudentPaymentRouteOrderDao;
import com.ym.mec.biz.dal.dao.SysConfigDao;
import com.ym.mec.biz.dal.dto.AmountChannelDto;
import com.ym.mec.biz.dal.dto.RouteScaleDto;
import com.ym.mec.biz.dal.entity.*;
import com.ym.mec.biz.dal.enums.FeeTypeEnum;
import com.ym.mec.biz.dal.enums.PaymentChannelEnum;
import com.ym.mec.biz.service.*;
import com.ym.mec.common.exception.BizException;
import com.ym.mec.common.redis.service.RedisCache;
import com.ym.mec.thirdparty.adapay.ConfigInit;
import com.ym.mec.thirdparty.adapay.Payment;
import com.ym.mec.thirdparty.yqpay.YqPayUtil;
import com.ym.mec.util.date.DateUtil;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.ValueOperations;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.util.*;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;

/**
 * 支付服务类
 */
@Service
public class PayServiceImpl implements PayService {
    @Autowired
    private StudentPaymentOrderService studentPaymentOrderService;
    @Autowired
    private SysConfigDao sysConfigDao;
    @Autowired
    private SysPaymentConfigService sysPaymentConfigService;
    @Autowired
    private StudentPaymentRouteOrderDao studentPaymentRouteOrderDao;
    @Autowired
    private SellOrderService sellOrderService;
    @Autowired
    private HfMemberDao hfMemberDao;
    @Autowired
    private RedisCache<String, Object> redisCache;

    @Override
    public Map<String, Object> getPayMap(BigDecimal amount, BigDecimal balanceAmount, String orderNo, String notifyUrl, String returnUrl, String orderSubject, String orderBody, Integer organId, String receiver) throws Exception {
        String usePaymentConfig = sysConfigDao.findConfigValue("use_payment_config");
        List<RouteScaleDto> routeScaleDtos = null;
        //使用配置开关
        if (usePaymentConfig.equals("0")) {
            routeScaleDtos = noUsePaymentConfig(amount);
        }

        //根据费用类型
        if (routeScaleDtos == null) {
            routeScaleDtos = getTypeRouteChannel(organId, orderNo, amount, balanceAmount);
        }

        //根据金额获取分润
        if (routeScaleDtos == null) {
            routeScaleDtos = getAmountChannel(organId, amount, receiver);
        }
        //零星支付，收到指定
        if (routeScaleDtos == null) {
            routeScaleDtos = getSporadicChannel(amount, receiver);
        }
        //比例或者笔数分佣
        if (routeScaleDtos == null) {
            routeScaleDtos = getPaymentConfigChannel(organId, amount);
        }

        //验证最大收款金额
        for (RouteScaleDto routeScaleDto : routeScaleDtos) {
            checkMaxReceipt(routeScaleDto, routeScaleDto.getMerNo());
        }

        return getPayRoute(amount, balanceAmount, orderNo, notifyUrl, returnUrl, orderSubject, orderBody, routeScaleDtos);
    }

    private List<RouteScaleDto> noUsePaymentConfig(BigDecimal amount) {
        String paymentChannel = sysConfigDao.findConfigValue("payment_channel");
        List<RouteScaleDto> routeScaleDtos = new ArrayList<>();
        RouteScaleDto routeScaleDto = new RouteScaleDto();
        routeScaleDto.setAmount(amount);
        routeScaleDto.setOrganId(ConfigInit.organId);
        routeScaleDto.setScale(100);
        if (paymentChannel.equals("YQPAY")) {
            routeScaleDto.setMerNo(YqPayUtil.merNo);
            routeScaleDto.setPayType(PaymentChannelEnum.YQPAY);
        } else {
            routeScaleDto.setMerNo(ConfigInit.merNo);
            routeScaleDto.setPayType(PaymentChannelEnum.ADAPAY);
        }
        routeScaleDto.setFeeFlag("Y");
        routeScaleDtos.add(routeScaleDto);
        return routeScaleDtos;
    }

    private List<RouteScaleDto> getPaymentConfigChannel(Integer organId, BigDecimal amount) {
        SysPaymentConfig paymentConfig = sysPaymentConfigService.findPaymentConfigByOrganId(organId);
        if (paymentConfig == null) {
            return noUsePaymentConfig(amount);
        }
        if (StringUtils.isBlank(paymentConfig.getRouteScale())) {
            List<RouteScaleDto> routeScaleDtos = new ArrayList<>();
            RouteScaleDto routeScaleDto = new RouteScaleDto();
            routeScaleDto.setAmount(amount);
            routeScaleDto.setOrganId(organId);
            routeScaleDto.setScale(100);
            routeScaleDto.setPayType(paymentConfig.getPayType());
            if (paymentConfig.getPayType().equals(PaymentChannelEnum.YQPAY)) {
                routeScaleDto.setMerNo(paymentConfig.getYqMerNo());
            } else {
                routeScaleDto.setMerNo(paymentConfig.getHfMerNo());
            }
            routeScaleDto.setFeeFlag("Y");
            routeScaleDtos.add(routeScaleDto);
            return routeScaleDtos;
        }

        String routeScale = paymentConfig.getRouteScale();
        List<RouteScaleDto> routeScaleDtos = JSON.parseArray(routeScale, RouteScaleDto.class);
        List<Integer> organIds = routeScaleDtos.stream().map(RouteScaleDto::getOrganId).collect(Collectors.toList());
        List<SysPaymentConfig> paymentConfigByOrganIds = sysPaymentConfigService.findPaymentConfigByOrganIds(organIds);
        for (RouteScaleDto routeScaleDto : routeScaleDtos) {
            routeScaleDto.setPayType(paymentConfig.getPayType());
            routeScaleDto.setAmount(amount);
            for (SysPaymentConfig paymentConfigByOrganId : paymentConfigByOrganIds) {
                if (!paymentConfigByOrganId.getOrganId().equals(routeScaleDto.getOrganId())) continue;
                if (paymentConfig.getPayType().equals(PaymentChannelEnum.YQPAY)) {
                    routeScaleDto.setMerNo(paymentConfigByOrganId.getYqMerNo());
                } else {
                    routeScaleDto.setMerNo(paymentConfigByOrganId.getHfMerNo());
                }
            }
        }

        //笔数比例
        if (paymentConfig.getType().equals(1)) {
            int payOrderNums = studentPaymentOrderService.findOrganPayOrderNum(organId); //获取支付中和成功的订单数
            int rem = payOrderNums % 10;
            rem = rem == 0 ? 10 : rem;

            int scale = 0;
            Iterator<RouteScaleDto> iterator = routeScaleDtos.iterator();
            while (iterator.hasNext()) {
                RouteScaleDto routeScaleDto = iterator.next();
                Integer num = routeScaleDto.getScale();
                boolean flag = false;
                if (rem > scale && rem <= scale + num) {
                    routeScaleDto.setScale(100);
                    flag = true;
                }
                scale += num;
                if (!flag) {
                    iterator.remove();
                }
            }
        }
        return routeScaleDtos;
    }


    /**
     * 根据金额获取渠道
     *
     * @param amount 金额
     */
    private List<RouteScaleDto> getAmountChannel(Integer organId, BigDecimal amount, String receiver) {
        String amountChannel = sysConfigDao.findConfigValue("amount_channel");
        if (StringUtils.isBlank(amountChannel)) {
            return null;
        }
        Set<String> musicGroupType = new HashSet<>();
        musicGroupType.add("renew");
        musicGroupType.add("register");
        if (musicGroupType.contains(receiver)) {
            receiver = "musicGroupBuy";
        }

        Integer routeOrganId = null;
        List<AmountChannelDto> amountChannelDtoList = JSON.parseArray(amountChannel, AmountChannelDto.class);
        for (AmountChannelDto amountChannelDto : amountChannelDtoList) {
            if (amountChannelDto.getOrganId().equals(organId) &&
                    //0的时候不限定金额
                    (amountChannelDto.getAmount().compareTo(BigDecimal.ZERO) == 0 || amount.compareTo(amountChannelDto.getAmount()) == 0) &&
                    receiver.equals(amountChannelDto.getType())
            ) {
                routeOrganId = amountChannelDto.getRouteOrganId();
                break;
            }
        }

        if (routeOrganId == null) {
            return null;
        }

        //调度到 鎏逸乐器经营部 检测限定金额
        if (checkHasMaxReceipt(routeOrganId, amount)) {
            return null;
        }

        SysPaymentConfig paymentConfig = sysPaymentConfigService.findPaymentConfigByOrganId(routeOrganId);

        RouteScaleDto routeScaleDto = new RouteScaleDto();
        List<RouteScaleDto> routeScaleDtos = new ArrayList<>();
        routeScaleDto.setAmount(amount);
        routeScaleDto.setOrganId(paymentConfig.getOrganId());
        routeScaleDto.setPayType(paymentConfig.getPayType());
        routeScaleDto.setScale(100);
        if (paymentConfig.getPayType().equals(PaymentChannelEnum.YQPAY)) {
            routeScaleDto.setMerNo(paymentConfig.getYqMerNo());
        } else {
            routeScaleDto.setMerNo(paymentConfig.getHfMerNo());
        }
        routeScaleDto.setFeeFlag("Y");
        routeScaleDtos.add(routeScaleDto);
        return routeScaleDtos;
    }

    /**
     * 零星支付获取渠道
     *
     * @param amount
     * @return
     */
    private List<RouteScaleDto> getSporadicChannel(BigDecimal amount, String receiver) {
        if (receiver == null || !receiver.equals("sporadic")) {
            return null;
        }
        String SporadicChannel = sysConfigDao.findConfigValue("sporadic_channel");
        if (StringUtils.isBlank(SporadicChannel)) {
            return null;
        }

        Map<String, Object> channel = (Map<String, Object>) JSON.parseObject(SporadicChannel, Map.class);

        BigDecimal minReceiptMoney = new BigDecimal(channel.get("minReceipt").toString()); //最小接收的金额(不包含)
        if (amount.compareTo(minReceiptMoney) <= 0) {
            return null;
        }

        Integer organId = Integer.parseInt(channel.get("organId").toString());
        if (checkHasMaxReceipt(organId, amount)) {
            return null;
        }

        SysPaymentConfig paymentConfig = sysPaymentConfigService.findPaymentConfigByOrganId(organId);

        RouteScaleDto routeScaleDto = new RouteScaleDto();
        List<RouteScaleDto> routeScaleDtos = new ArrayList<>();
        routeScaleDto.setAmount(amount);
        routeScaleDto.setOrganId(paymentConfig.getOrganId());
        routeScaleDto.setPayType(paymentConfig.getPayType());
        routeScaleDto.setScale(100);
        if (paymentConfig.getPayType().equals(PaymentChannelEnum.YQPAY)) {
            routeScaleDto.setMerNo(paymentConfig.getYqMerNo());
        } else {
            routeScaleDto.setMerNo(paymentConfig.getHfMerNo());
        }
        routeScaleDto.setFeeFlag("Y");
        routeScaleDtos.add(routeScaleDto);
        return routeScaleDtos;
    }

    //按金额和零星支付（调度到 鎏逸乐器经营部 检测限定金额）
    private Boolean checkHasMaxReceipt(Integer organId, BigDecimal amount) {
        SysPaymentConfig paymentConfig = sysPaymentConfigService.findPaymentConfigByOrganId(organId);

        if (!paymentConfig.getHfMerNo().equals("H004217")) {
            return false;
        }
        BigDecimal monthMaxReceipt = new BigDecimal(75000); //每月限定金额
        BigDecimal totalMaxReceipt = new BigDecimal(5000000); //总限定金额（500W）

        Date monthStartTime = DateUtil.getFirstDayOfMonth(new Date());

        //已收金额
        List<PaymentChannelEnum> paymentChannelList = new ArrayList<>();
        paymentChannelList.add(PaymentChannelEnum.YQPAY);
        paymentChannelList.add(PaymentChannelEnum.ADAPAY);

        BigDecimal monthHasReceipt = studentPaymentRouteOrderDao.getRouteOrderAmount(organId, paymentChannelList, monthStartTime);
        monthHasReceipt = monthHasReceipt == null ? BigDecimal.ZERO : monthHasReceipt;
        if (amount.add(monthHasReceipt).compareTo(monthMaxReceipt) >= 0) {
            return true;
        }
        BigDecimal totalHasReceipt = studentPaymentRouteOrderDao.getRouteOrderAmount(organId, paymentChannelList, null);
        totalHasReceipt = totalHasReceipt == null ? BigDecimal.ZERO : totalHasReceipt;
        return amount.add(totalHasReceipt).compareTo(totalMaxReceipt) >= 0;
    }

    private Map<String, Object> getPayRoute(BigDecimal amount, BigDecimal balanceAmount, String orderNo, String notifyUrl, String returnUrl, String orderSubject, String orderBody, List<RouteScaleDto> routeScaleDtos) throws Exception {
        Map<String, List<RouteScaleDto>> routeScaleDtosMap = routeScaleDtos.stream().collect(Collectors.groupingBy(RouteScaleDto::getMerNo));

        //合并同账号的数据
        List<RouteScaleDto> newRouteScaleDtos = new ArrayList<>();
        for (Map.Entry<String, List<RouteScaleDto>> groupRouteScaleDtos : routeScaleDtosMap.entrySet()) {
            RouteScaleDto routeScaleDto = null;
            for (RouteScaleDto scaleDto : groupRouteScaleDtos.getValue()) {
                if (routeScaleDto == null) {
                    routeScaleDto = scaleDto;
                } else {
                    routeScaleDto.setAmount(routeScaleDto.getAmount().add(scaleDto.getAmount()));
                    routeScaleDto.setBalance(routeScaleDto.getBalance().add(scaleDto.getBalance()));
                }
            }
            newRouteScaleDtos.add(routeScaleDto);
        }
        routeScaleDtos = newRouteScaleDtos;

        Map<String, Object> unionPay = new HashMap<>();
        Map<String, Object> payMap = null;

        List<StudentPaymentRouteOrder> RouteOrders = new ArrayList<>();

        BigDecimal yqAmount = amount.subtract((amount.multiply(new BigDecimal("0.28")).divide(new BigDecimal(100), 2, BigDecimal.ROUND_HALF_UP)));
        int i = 0;
        BigDecimal hasRouteAmount = BigDecimal.ZERO;
        BigDecimal hasRouteBalanceAmount = BigDecimal.ZERO;
        BigDecimal hasRouteMoney = BigDecimal.ZERO;
        List<Map<String, Object>> tempRoutingList = new ArrayList<>();

        PaymentChannelEnum payType = null;
        boolean feeFlag = false;
        Set<String> routingMerNoSet = new HashSet<>();
        for (RouteScaleDto routeScaleDto : routeScaleDtos) {
            payType = routeScaleDto.getPayType();
            Map<String, Object> routingList = new HashMap<>();
            i++;

            BigDecimal routingAmount = amount;
            if (routeScaleDto.getPayType().equals(PaymentChannelEnum.YQPAY)) {
                routingAmount = yqAmount;
            }

            BigDecimal routingFee = null;
            BigDecimal routeBalanceAmount = null;
            BigDecimal routingMoney = null;

            if (routeScaleDto.getFeeType() == null) {
                routingFee = routingAmount.multiply(new BigDecimal(routeScaleDto.getScale())).divide(new BigDecimal(100), 2, BigDecimal.ROUND_DOWN);
                routeBalanceAmount = balanceAmount.multiply(new BigDecimal(routeScaleDto.getScale())).divide(new BigDecimal(100), 2, BigDecimal.ROUND_DOWN);
                routingMoney = amount.multiply(new BigDecimal(routeScaleDto.getScale())).divide(new BigDecimal(100), 2, BigDecimal.ROUND_DOWN);
            } else {
                routingFee = routeScaleDto.getAmount();
                routeBalanceAmount = routeScaleDto.getBalance();
                routingMoney = routeScaleDto.getAmount();
            }
            if (i == routeScaleDtos.size()) {
                routingFee = routingAmount.subtract(hasRouteAmount).setScale(2, BigDecimal.ROUND_HALF_UP);
                routeBalanceAmount = balanceAmount.subtract(hasRouteBalanceAmount).setScale(2, BigDecimal.ROUND_HALF_UP);
                routingMoney = amount.subtract(hasRouteMoney).setScale(2, BigDecimal.ROUND_HALF_UP);
            }

            if (routingFee.compareTo(BigDecimal.ZERO) <= 0) {
                continue;
            }

            hasRouteAmount = hasRouteAmount.add(routingFee);
            hasRouteBalanceAmount = hasRouteBalanceAmount.add(routeBalanceAmount);
            hasRouteMoney = hasRouteMoney.add(routingMoney);

            routingList.put("routingMerNo", routeScaleDto.getMerNo());//分佣账户
            routingList.put("routingFee", routingFee); //分佣金额
            tempRoutingList.add(routingList);

            //ADAPAY 采用延迟分账模式，手续费各自承担(2021-01-01号正式执行)
            if (routeScaleDto.getPayType().equals(PaymentChannelEnum.ADAPAY)) {
                routeScaleDto.setFeeFlag("Y");
            }

            StudentPaymentRouteOrder studentPaymentRouteOrder = new StudentPaymentRouteOrder();
            studentPaymentRouteOrder.setOrderNo(orderNo);
            studentPaymentRouteOrder.setRouteOrganId(routeScaleDto.getOrganId());
            studentPaymentRouteOrder.setFeeFlag(routeScaleDto.getFeeFlag());
            studentPaymentRouteOrder.setRouteAmount(routingMoney);
            studentPaymentRouteOrder.setRouteBalanceAmount(routeBalanceAmount);
            studentPaymentRouteOrder.setMerNo(routeScaleDto.getMerNo());
            RouteOrders.add(studentPaymentRouteOrder);
            routingMerNoSet.add(routeScaleDto.getMerNo());
        }

        if (studentPaymentRouteOrderDao.batchAdd(RouteOrders) <= 0) {
            throw new BizException("调用支付接口失败");
        }

        if (payType.equals(PaymentChannelEnum.YQPAY)) {
            if (tempRoutingList.size() == 1 && YqPayUtil.merNo.equals(tempRoutingList.get(0).get("routingMerNo").toString())) {
                tempRoutingList = null;
            }
            payMap = YqPayUtil.getPayMap(amount, orderNo, notifyUrl, returnUrl, orderSubject, orderBody, YqPayUtil.merNo, tempRoutingList);
        } else {
            payMap = Payment.getPayMap(amount, orderNo, notifyUrl, returnUrl, orderSubject, orderBody, ConfigInit.merNo, tempRoutingList);
        }
        String routingMerNos = String.join(",", routingMerNoSet);

        unionPay.put("orderNo", orderNo);
        unionPay.put("type", payType.getCode());
        unionPay.put("payMap", payMap);
        unionPay.put("routingMerNos", routingMerNos);
        return unionPay;
    }

    /**
     * @param organId
     * @param orderNo
     * @param amount
     * @return
     */
    private List<RouteScaleDto> getTypeRouteChannel(Integer organId, String orderNo, BigDecimal amount, BigDecimal balanceAmount) {
        SysPaymentConfig paymentConfig = sysPaymentConfigService.findPaymentConfigByOrganId(organId);
        if (paymentConfig == null || StringUtils.isBlank(paymentConfig.getTypeRouteScale())) {
            return null;
        }

        Map<String, BigDecimal> sellAmount = sellOrderService.getSellAmount(orderNo);
        if (sellAmount == null) {
            return null;
        }

        String typeRouteScale = paymentConfig.getTypeRouteScale();
        List<RouteScaleDto> routeScaleDtos = JSON.parseArray(typeRouteScale, RouteScaleDto.class);
        List<Integer> organIds = routeScaleDtos.stream().map(RouteScaleDto::getOrganId).collect(Collectors.toList());
        List<SysPaymentConfig> paymentConfigByOrganIds = sysPaymentConfigService.findPaymentConfigByOrganIds(organIds);

        long serviceCount = routeScaleDtos.stream().filter(e -> e.getFeeType().equals(FeeTypeEnum.SERVICE)).count();
        long sellCount = routeScaleDtos.stream().filter(e -> e.getFeeType().equals(FeeTypeEnum.SELL)).count();

        BigDecimal routeAmount = sellAmount.get("actualAmount");
        BigDecimal routeBalance = sellAmount.get("balance");

        BigDecimal serviceHasRouteMoney = BigDecimal.ZERO;
        BigDecimal serviceHasRouteBalance = BigDecimal.ZERO;
        BigDecimal sellHasRouteMoney = BigDecimal.ZERO;
        BigDecimal sellHasRouteBalance = BigDecimal.ZERO;

        Iterator<RouteScaleDto> iterator = routeScaleDtos.iterator();
        while (iterator.hasNext()) {
            RouteScaleDto routeScaleDto = iterator.next();
            routeScaleDto.setPayType(paymentConfig.getPayType());
            if (routeScaleDto.getFeeType().equals(FeeTypeEnum.SERVICE)) {
                routeAmount = amount.subtract(sellAmount.get("actualAmount"));
                routeBalance = balanceAmount.subtract(sellAmount.get("balance"));
                serviceCount--;
            } else {
                routeAmount = sellAmount.get("actualAmount");
                routeBalance = sellAmount.get("balance");
                sellCount--;
            }

            BigDecimal routingMoney = routeAmount.multiply(new BigDecimal(routeScaleDto.getScale())).divide(new BigDecimal(100), 2, BigDecimal.ROUND_DOWN);
            BigDecimal routingBalance = routeBalance.multiply(new BigDecimal(routeScaleDto.getScale())).divide(new BigDecimal(100), 2, BigDecimal.ROUND_DOWN);

            if (routeScaleDto.getFeeType().equals(FeeTypeEnum.SERVICE) && serviceCount == 0) {
                routingMoney = routeAmount.subtract(serviceHasRouteMoney);
                routingBalance = routeBalance.subtract(serviceHasRouteBalance);
            } else if (routeScaleDto.getFeeType().equals(FeeTypeEnum.SELL) && sellCount == 0) {
                routingMoney = routeAmount.subtract(sellHasRouteMoney);
                routingBalance = routeBalance.subtract(sellHasRouteBalance);
            }
            routeScaleDto.setAmount(routingMoney);
            routeScaleDto.setBalance(routingBalance);

            if (routeScaleDto.getFeeType().equals(FeeTypeEnum.SERVICE)) {
                serviceHasRouteMoney = serviceHasRouteMoney.add(routingMoney);
                serviceHasRouteBalance = serviceHasRouteBalance.add(routingBalance);
            } else {
                sellHasRouteMoney = sellHasRouteMoney.add(routingMoney);
                sellHasRouteBalance = sellHasRouteBalance.add(routingBalance);
            }

            if (routeScaleDto.getAmount().compareTo(BigDecimal.ZERO) <= 0) {
                iterator.remove();
                continue;
            }

            for (SysPaymentConfig paymentConfigByOrganId : paymentConfigByOrganIds) {
                if (!paymentConfigByOrganId.getOrganId().equals(routeScaleDto.getOrganId())) continue;
                if (paymentConfig.getPayType().equals(PaymentChannelEnum.YQPAY)) {
                    routeScaleDto.setMerNo(paymentConfigByOrganId.getYqMerNo());
                } else {
                    routeScaleDto.setMerNo(paymentConfigByOrganId.getHfMerNo());
                }
            }
        }
        Map<String, List<RouteScaleDto>> routeScaleDtosMap = routeScaleDtos.stream().collect(Collectors.groupingBy(RouteScaleDto::getMerNo));

        //合并同账号的数据
        BigDecimal maxAmount = BigDecimal.ZERO;
        List<RouteScaleDto> newRouteScaleDtos = new ArrayList<>();
        for (Map.Entry<String, List<RouteScaleDto>> groupRouteScaleDtos : routeScaleDtosMap.entrySet()) {
            RouteScaleDto routeScaleDto = null;
            for (RouteScaleDto scaleDto : groupRouteScaleDtos.getValue()) {
                if (routeScaleDto == null) {
                    routeScaleDto = scaleDto;
                } else {
                    routeScaleDto.setAmount(routeScaleDto.getAmount().add(scaleDto.getAmount()));
                    routeScaleDto.setBalance(routeScaleDto.getBalance().add(scaleDto.getBalance()));
                }
            }
            if (routeScaleDto != null && routeScaleDto.getAmount().compareTo(maxAmount) > 0) {
                maxAmount = routeScaleDto.getAmount();
            }
            newRouteScaleDtos.add(routeScaleDto);
        }

        //金额最大的账号承担手续费
        boolean hasFeeFlag = false;
        for (RouteScaleDto routeScaleDto : newRouteScaleDtos) {
            if (!hasFeeFlag && routeScaleDto.getAmount().compareTo(maxAmount) == 0) {
                routeScaleDto.setFeeFlag("Y");
                hasFeeFlag = true;
            } else {
                routeScaleDto.setFeeFlag("N");
            }
        }
        return newRouteScaleDtos;
    }


    /**
     * 收款已满转到其他收款账户
     *
     * @param routeScaleDto
     * @param merNo
     * @return
     */
    private RouteScaleDto checkMaxReceipt(RouteScaleDto routeScaleDto, String merNo) {
        HfMember hfmember = hfMemberDao.getByMemberId(routeScaleDto.getMerNo());
        if (hfmember == null || hfmember.getMonthMaxReceipt().compareTo(BigDecimal.ZERO) <= 0) {
            return routeScaleDto;
        }

        BigDecimal monthMaxReceipt = hfmember.getMonthMaxReceipt(); //每月限定金额
        Date dayStartTime = DateUtil.trunc(new Date());

        //已收金额
        List<PaymentChannelEnum> paymentChannelList = new ArrayList<>();
        paymentChannelList.add(PaymentChannelEnum.ADAPAY);

//        String key = "month_max_receipt_"+routeScaleDto.getOrganId();
//        if(redisCache.exists(key)){
//            RedisTemplate<String, Object> redisTemplate = redisCache.getRedisTemplate();
//            try {
//                ValueOperations<String, Object> valueOper = redisTemplate.opsForValue();
//                Long index = valueOper.increment(key, 1);
//            } catch (Exception ex) {
//                log.error("分布式订单号生成失败异常。。。。。", ex);
//            } finally {
//                redisTemplate.expire(key, 600, TimeUnit.SECONDS);// 保留10分钟内的key
//            }
//        }else {
            BigDecimal monthHasReceipt = studentPaymentRouteOrderDao.getRouteOrderAmount(routeScaleDto.getOrganId(), paymentChannelList, dayStartTime);
            monthHasReceipt = monthHasReceipt == null ? BigDecimal.ZERO : monthHasReceipt;
//            monthHasReceipt.multiply(new BigDecimal(100));
//
//        }



        if (routeScaleDto.getAmount().add(monthHasReceipt).compareTo(monthMaxReceipt) > 0) {
            routeScaleDto.setMerNo(hfmember.getRouteMemberId());
            routeScaleDto.setOrganId(hfmember.getRouteOrganId());
            if (routeScaleDto.getMerNo().equals(merNo)) {
                return routeScaleDto;
            }
            return checkMaxReceipt(routeScaleDto, merNo);
        }
        return routeScaleDto;
    }
}
